File:
[LON-CAPA] /
loncom /
lonnet /
perl /
lonnet.pm
Revision
1.1176:
download - view:
text,
annotated -
select for diffs
Wed May 30 20:29:45 2012 UTC (12 years, 2 months ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD
- Dedicated loadbalancer.
- If a session for a specific user is being hosted on a loadbalancer server
call to lonnet::check_loadbalancing() only made for an authenticated
user, once 10 minutes have elapsed since last call.
(user.loadbalexempt and user.loadbalcheck.time stored in %env).
1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.1176 2012/05/30 20:29:45 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: use Encode;
79:
80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
81: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
82: %managerstab);
83:
84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
85: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
86: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
87: %courseownerbuf, %coursetypebuf,$locknum);
88:
89: use IO::Socket;
90: use GDBM_File;
91: use HTML::LCParser;
92: use Fcntl qw(:flock);
93: use Storable qw(thaw nfreeze);
94: use Time::HiRes qw( gettimeofday tv_interval );
95: use Cache::Memcached;
96: use Digest::MD5;
97: use Math::Random;
98: use File::MMagic;
99: use LONCAPA qw(:DEFAULT :match);
100: use LONCAPA::Configuration;
101: use LONCAPA::lonmetadata;
102: use LONCAPA::Lond;
103:
104: use File::Copy;
105:
106: my $readit;
107: my $max_connection_retries = 10; # Or some such value.
108:
109: require Exporter;
110:
111: our @ISA = qw (Exporter);
112: our @EXPORT = qw(%env);
113:
114:
115: # --------------------------------------------------------------------- Logging
116: {
117: my $logid;
118: sub instructor_log {
119: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
120: if (($cnum eq '') || ($cdom eq '')) {
121: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
122: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
123: }
124: $logid++;
125: my $now = time();
126: my $id=$now.'00000'.$$.'00000'.$logid;
127: return &Apache::lonnet::put('nohist_'.$hash_name,
128: { $id => {
129: 'exe_uname' => $env{'user.name'},
130: 'exe_udom' => $env{'user.domain'},
131: 'exe_time' => $now,
132: 'exe_ip' => $ENV{'REMOTE_ADDR'},
133: 'delflag' => $delflag,
134: 'logentry' => $storehash,
135: 'uname' => $uname,
136: 'udom' => $udom,
137: }
138: },$cdom,$cnum);
139: }
140: }
141:
142: sub logtouch {
143: my $execdir=$perlvar{'lonDaemons'};
144: unless (-e "$execdir/logs/lonnet.log") {
145: open(my $fh,">>$execdir/logs/lonnet.log");
146: close $fh;
147: }
148: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
149: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
150: }
151:
152: sub logthis {
153: my $message=shift;
154: my $execdir=$perlvar{'lonDaemons'};
155: my $now=time;
156: my $local=localtime($now);
157: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
158: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
159: print $fh $logstring;
160: close($fh);
161: }
162: return 1;
163: }
164:
165: sub logperm {
166: my $message=shift;
167: my $execdir=$perlvar{'lonDaemons'};
168: my $now=time;
169: my $local=localtime($now);
170: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
171: print $fh "$now:$message:$local\n";
172: close($fh);
173: }
174: return 1;
175: }
176:
177: sub create_connection {
178: my ($hostname,$lonid) = @_;
179: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
180: Type => SOCK_STREAM,
181: Timeout => 10);
182: return 0 if (!$client);
183: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
184: my $result = <$client>;
185: chomp($result);
186: return 1 if ($result eq 'done');
187: return 0;
188: }
189:
190: sub get_server_timezone {
191: my ($cnum,$cdom) = @_;
192: my $home=&homeserver($cnum,$cdom);
193: if ($home ne 'no_host') {
194: my $cachetime = 24*3600;
195: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
196: if (defined($cached)) {
197: return $timezone;
198: } else {
199: my $timezone = &reply('servertimezone',$home);
200: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
201: }
202: }
203: }
204:
205: sub get_server_distarch {
206: my ($lonhost,$ignore_cache) = @_;
207: if (defined($lonhost)) {
208: if (!defined(&hostname($lonhost))) {
209: return;
210: }
211: my $cachetime = 12*3600;
212: if (!$ignore_cache) {
213: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
214: if (defined($cached)) {
215: return $distarch;
216: }
217: }
218: my $rep = &reply('serverdistarch',$lonhost);
219: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
220: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
221: $rep eq '') {
222: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
223: }
224: }
225: return;
226: }
227:
228: sub get_server_loncaparev {
229: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
230: if (defined($lonhost)) {
231: if (!defined(&hostname($lonhost))) {
232: undef($lonhost);
233: }
234: }
235: if (!defined($lonhost)) {
236: if (defined(&domain($dom,'primary'))) {
237: $lonhost=&domain($dom,'primary');
238: if ($lonhost eq 'no_host') {
239: undef($lonhost);
240: }
241: }
242: }
243: if (defined($lonhost)) {
244: my $cachetime = 12*3600;
245: if (!$ignore_cache) {
246: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
247: if (defined($cached)) {
248: return $loncaparev;
249: }
250: }
251: my ($answer,$loncaparev);
252: my @ids=¤t_machine_ids();
253: if (grep(/^\Q$lonhost\E$/,@ids)) {
254: $answer = $perlvar{'lonVersion'};
255: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
256: $loncaparev = $1;
257: }
258: } else {
259: $answer = &reply('serverloncaparev',$lonhost);
260: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
261: if ($caller eq 'loncron') {
262: my $ua=new LWP::UserAgent;
263: $ua->timeout(4);
264: my $protocol = $protocol{$lonhost};
265: $protocol = 'http' if ($protocol ne 'https');
266: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
267: my $request=new HTTP::Request('GET',$url);
268: my $response=$ua->request($request);
269: unless ($response->is_error()) {
270: my $content = $response->content;
271: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
272: $loncaparev = $1;
273: }
274: }
275: } else {
276: $loncaparev = $loncaparevs{$lonhost};
277: }
278: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
279: $loncaparev = $1;
280: }
281: }
282: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
283: }
284: }
285:
286: sub get_server_homeID {
287: my ($hostname,$ignore_cache,$caller) = @_;
288: unless ($ignore_cache) {
289: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
290: if (defined($cached)) {
291: return $serverhomeID;
292: }
293: }
294: my $cachetime = 12*3600;
295: my $serverhomeID;
296: if ($caller eq 'loncron') {
297: my @machine_ids = &machine_ids($hostname);
298: foreach my $id (@machine_ids) {
299: my $response = &reply('serverhomeID',$id);
300: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
301: $serverhomeID = $response;
302: last;
303: }
304: }
305: if ($serverhomeID eq '') {
306: $serverhomeID = $machine_ids[-1];
307: }
308: } else {
309: $serverhomeID = $serverhomeIDs{$hostname};
310: }
311: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
312: }
313:
314: sub get_remote_globals {
315: my ($lonhost,$whathash,$ignore_cache) = @_;
316: my ($result,%returnhash,%whatneeded);
317: if (ref($whathash) eq 'HASH') {
318: foreach my $what (sort(keys(%{$whathash}))) {
319: my $hashid = $lonhost.'-'.$what;
320: my ($response,$cached);
321: unless ($ignore_cache) {
322: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
323: }
324: if (defined($cached)) {
325: $returnhash{$what} = $response;
326: } else {
327: $whatneeded{$what} = 1;
328: }
329: }
330: if (keys(%whatneeded) == 0) {
331: $result = 'ok';
332: } else {
333: my $requested = &freeze_escape(\%whatneeded);
334: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
335: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
336: ($rep eq 'unknown_cmd')) {
337: $result = $rep;
338: } else {
339: $result = 'ok';
340: my @pairs=split(/\&/,$rep);
341: foreach my $item (@pairs) {
342: my ($key,$value)=split(/=/,$item,2);
343: my $what = &unescape($key);
344: my $hashid = $lonhost.'-'.$what;
345: $returnhash{$what}=&thaw_unescape($value);
346: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
347: }
348: }
349: }
350: }
351: return ($result,\%returnhash);
352: }
353:
354: sub remote_devalidate_cache {
355: my ($lonhost,$name,$id) = @_;
356: my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
357: return $response;
358: }
359:
360: # -------------------------------------------------- Non-critical communication
361: sub subreply {
362: my ($cmd,$server)=@_;
363: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
364: #
365: # With loncnew process trimming, there's a timing hole between lonc server
366: # process exit and the master server picking up the listen on the AF_UNIX
367: # socket. In that time interval, a lock file will exist:
368:
369: my $lockfile=$peerfile.".lock";
370: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
371: sleep(1);
372: }
373: # At this point, either a loncnew parent is listening or an old lonc
374: # or loncnew child is listening so we can connect or everything's dead.
375: #
376: # We'll give the connection a few tries before abandoning it. If
377: # connection is not possible, we'll con_lost back to the client.
378: #
379: my $client;
380: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
381: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
382: Type => SOCK_STREAM,
383: Timeout => 10);
384: if ($client) {
385: last; # Connected!
386: } else {
387: &create_connection(&hostname($server),$server);
388: }
389: sleep(1); # Try again later if failed connection.
390: }
391: my $answer;
392: if ($client) {
393: print $client "sethost:$server:$cmd\n";
394: $answer=<$client>;
395: if (!$answer) { $answer="con_lost"; }
396: chomp($answer);
397: } else {
398: $answer = 'con_lost'; # Failed connection.
399: }
400: return $answer;
401: }
402:
403: sub reply {
404: my ($cmd,$server)=@_;
405: unless (defined(&hostname($server))) { return 'no_such_host'; }
406: my $answer=subreply($cmd,$server);
407: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
408: &logthis("<font color=\"blue\">WARNING:".
409: " $cmd to $server returned $answer</font>");
410: }
411: return $answer;
412: }
413:
414: # ----------------------------------------------------------- Send USR1 to lonc
415:
416: sub reconlonc {
417: my ($lonid) = @_;
418: my $hostname = &hostname($lonid);
419: if ($lonid) {
420: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
421: if ($hostname && -e $peerfile) {
422: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
423: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
424: Type => SOCK_STREAM,
425: Timeout => 10);
426: if ($client) {
427: print $client ("reset_retries\n");
428: my $answer=<$client>;
429: #reset just this one.
430: }
431: }
432: return;
433: }
434:
435: &logthis("Trying to reconnect lonc");
436: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
437: if (open(my $fh,"<$loncfile")) {
438: my $loncpid=<$fh>;
439: chomp($loncpid);
440: if (kill 0 => $loncpid) {
441: &logthis("lonc at pid $loncpid responding, sending USR1");
442: kill USR1 => $loncpid;
443: sleep 1;
444: } else {
445: &logthis(
446: "<font color=\"blue\">WARNING:".
447: " lonc at pid $loncpid not responding, giving up</font>");
448: }
449: } else {
450: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
451: }
452: }
453:
454: # ------------------------------------------------------ Critical communication
455:
456: sub critical {
457: my ($cmd,$server)=@_;
458: unless (&hostname($server)) {
459: &logthis("<font color=\"blue\">WARNING:".
460: " Critical message to unknown server ($server)</font>");
461: return 'no_such_host';
462: }
463: my $answer=reply($cmd,$server);
464: if ($answer eq 'con_lost') {
465: &reconlonc("$perlvar{'lonSockDir'}/$server");
466: my $answer=reply($cmd,$server);
467: if ($answer eq 'con_lost') {
468: my $now=time;
469: my $middlename=$cmd;
470: $middlename=substr($middlename,0,16);
471: $middlename=~s/\W//g;
472: my $dfilename=
473: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
474: $dumpcount++;
475: {
476: my $dfh;
477: if (open($dfh,">$dfilename")) {
478: print $dfh "$cmd\n";
479: close($dfh);
480: }
481: }
482: sleep 2;
483: my $wcmd='';
484: {
485: my $dfh;
486: if (open($dfh,"<$dfilename")) {
487: $wcmd=<$dfh>;
488: close($dfh);
489: }
490: }
491: chomp($wcmd);
492: if ($wcmd eq $cmd) {
493: &logthis("<font color=\"blue\">WARNING: ".
494: "Connection buffer $dfilename: $cmd</font>");
495: &logperm("D:$server:$cmd");
496: return 'con_delayed';
497: } else {
498: &logthis("<font color=\"red\">CRITICAL:"
499: ." Critical connection failed: $server $cmd</font>");
500: &logperm("F:$server:$cmd");
501: return 'con_failed';
502: }
503: }
504: }
505: return $answer;
506: }
507:
508: # ------------------------------------------- check if return value is an error
509:
510: sub error {
511: my ($result) = @_;
512: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
513: if ($2 == 2) { return undef; }
514: return $1;
515: }
516: return undef;
517: }
518:
519: sub convert_and_load_session_env {
520: my ($lonidsdir,$handle)=@_;
521: my @profile;
522: {
523: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
524: if (!$opened) {
525: return 0;
526: }
527: flock($idf,LOCK_SH);
528: @profile=<$idf>;
529: close($idf);
530: }
531: my %temp_env;
532: foreach my $line (@profile) {
533: if ($line !~ m/=/) {
534: return 0;
535: }
536: chomp($line);
537: my ($envname,$envvalue)=split(/=/,$line,2);
538: $temp_env{&unescape($envname)} = &unescape($envvalue);
539: }
540: unlink("$lonidsdir/$handle.id");
541: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
542: 0640)) {
543: %disk_env = %temp_env;
544: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
545: untie(%disk_env);
546: }
547: return 1;
548: }
549:
550: # ------------------------------------------- Transfer profile into environment
551: my $env_loaded;
552: sub transfer_profile_to_env {
553: my ($lonidsdir,$handle,$force_transfer) = @_;
554: if (!$force_transfer && $env_loaded) { return; }
555:
556: if (!defined($lonidsdir)) {
557: $lonidsdir = $perlvar{'lonIDsDir'};
558: }
559: if (!defined($handle)) {
560: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
561: }
562:
563: my $convert;
564: {
565: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
566: if (!$opened) {
567: return;
568: }
569: flock($idf,LOCK_SH);
570: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
571: &GDBM_READER(),0640)) {
572: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
573: untie(%disk_env);
574: } else {
575: $convert = 1;
576: }
577: }
578: if ($convert) {
579: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
580: &logthis("Failed to load session, or convert session.");
581: }
582: }
583:
584: my %remove;
585: while ( my $envname = each(%env) ) {
586: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
587: if ($time < time-300) {
588: $remove{$key}++;
589: }
590: }
591: }
592:
593: $env{'user.environment'} = "$lonidsdir/$handle.id";
594: $env_loaded=1;
595: foreach my $expired_key (keys(%remove)) {
596: &delenv($expired_key);
597: }
598: }
599:
600: # ---------------------------------------------------- Check for valid session
601: sub check_for_valid_session {
602: my ($r,$name) = @_;
603: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
604: if ($name eq '') {
605: $name = 'lonID';
606: }
607: my $lonid=$cookies{$name};
608: return undef if (!$lonid);
609:
610: my $handle=&LONCAPA::clean_handle($lonid->value);
611: my $lonidsdir;
612: if ($name eq 'lonDAV') {
613: $lonidsdir=$r->dir_config('lonDAVsessDir');
614: } else {
615: $lonidsdir=$r->dir_config('lonIDsDir');
616: }
617: return undef if (!-e "$lonidsdir/$handle.id");
618:
619: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
620: return undef if (!$opened);
621:
622: flock($idf,LOCK_SH);
623: my %disk_env;
624: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
625: &GDBM_READER(),0640)) {
626: return undef;
627: }
628:
629: if (!defined($disk_env{'user.name'})
630: || !defined($disk_env{'user.domain'})) {
631: return undef;
632: }
633: return $handle;
634: }
635:
636: sub timed_flock {
637: my ($file,$lock_type) = @_;
638: my $failed=0;
639: eval {
640: local $SIG{__DIE__}='DEFAULT';
641: local $SIG{ALRM}=sub {
642: $failed=1;
643: die("failed lock");
644: };
645: alarm(13);
646: flock($file,$lock_type);
647: alarm(0);
648: };
649: if ($failed) {
650: return undef;
651: } else {
652: return 1;
653: }
654: }
655:
656: # ---------------------------------------------------------- Append Environment
657:
658: sub appenv {
659: my ($newenv,$roles) = @_;
660: if (ref($newenv) eq 'HASH') {
661: foreach my $key (keys(%{$newenv})) {
662: my $refused = 0;
663: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
664: $refused = 1;
665: if (ref($roles) eq 'ARRAY') {
666: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
667: if (grep(/^\Q$role\E$/,@{$roles})) {
668: $refused = 0;
669: }
670: }
671: }
672: if ($refused) {
673: &logthis("<font color=\"blue\">WARNING: ".
674: "Attempt to modify environment ".$key." to ".$newenv->{$key}
675: .'</font>');
676: delete($newenv->{$key});
677: } else {
678: $env{$key}=$newenv->{$key};
679: }
680: }
681: my $opened = open(my $env_file,'+<',$env{'user.environment'});
682: if ($opened
683: && &timed_flock($env_file,LOCK_EX)
684: &&
685: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
686: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
687: while (my ($key,$value) = each(%{$newenv})) {
688: $disk_env{$key} = $value;
689: }
690: untie(%disk_env);
691: }
692: }
693: return 'ok';
694: }
695: # ----------------------------------------------------- Delete from Environment
696:
697: sub delenv {
698: my ($delthis,$regexp,$roles) = @_;
699: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
700: my $refused = 1;
701: if (ref($roles) eq 'ARRAY') {
702: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
703: if (grep(/^\Q$role\E$/,@{$roles})) {
704: $refused = 0;
705: }
706: }
707: if ($refused) {
708: &logthis("<font color=\"blue\">WARNING: ".
709: "Attempt to delete from environment ".$delthis);
710: return 'error';
711: }
712: }
713: my $opened = open(my $env_file,'+<',$env{'user.environment'});
714: if ($opened
715: && &timed_flock($env_file,LOCK_EX)
716: &&
717: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
718: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
719: foreach my $key (keys(%disk_env)) {
720: if ($regexp) {
721: if ($key=~/^$delthis/) {
722: delete($env{$key});
723: delete($disk_env{$key});
724: }
725: } else {
726: if ($key=~/^\Q$delthis\E/) {
727: delete($env{$key});
728: delete($disk_env{$key});
729: }
730: }
731: }
732: untie(%disk_env);
733: }
734: return 'ok';
735: }
736:
737: sub get_env_multiple {
738: my ($name) = @_;
739: my @values;
740: if (defined($env{$name})) {
741: # exists is it an array
742: if (ref($env{$name})) {
743: @values=@{ $env{$name} };
744: } else {
745: $values[0]=$env{$name};
746: }
747: }
748: return(@values);
749: }
750:
751: # ------------------------------------------------------------------- Locking
752:
753: sub set_lock {
754: my ($text)=@_;
755: $locknum++;
756: my $id=$$.'-'.$locknum;
757: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
758: 'session.lock.'.$id => $text});
759: return $id;
760: }
761:
762: sub get_locks {
763: my $num=0;
764: my %texts=();
765: foreach my $lock (split(/\,/,$env{'session.locks'})) {
766: if ($lock=~/\w/) {
767: $num++;
768: $texts{$lock}=$env{'session.lock.'.$lock};
769: }
770: }
771: return ($num,%texts);
772: }
773:
774: sub remove_lock {
775: my ($id)=@_;
776: my $newlocks='';
777: foreach my $lock (split(/\,/,$env{'session.locks'})) {
778: if (($lock=~/\w/) && ($lock ne $id)) {
779: $newlocks.=','.$lock;
780: }
781: }
782: &appenv({'session.locks' => $newlocks});
783: &delenv('session.lock.'.$id);
784: }
785:
786: sub remove_all_locks {
787: my $activelocks=$env{'session.locks'};
788: foreach my $lock (split(/\,/,$env{'session.locks'})) {
789: if ($lock=~/\w/) {
790: &remove_lock($lock);
791: }
792: }
793: }
794:
795:
796: # ------------------------------------------ Find out current server userload
797: sub userload {
798: my $numusers=0;
799: {
800: opendir(LONIDS,$perlvar{'lonIDsDir'});
801: my $filename;
802: my $curtime=time;
803: while ($filename=readdir(LONIDS)) {
804: next if ($filename eq '.' || $filename eq '..');
805: next if ($filename =~ /publicuser_\d+\.id/);
806: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
807: if ($curtime-$mtime < 1800) { $numusers++; }
808: }
809: closedir(LONIDS);
810: }
811: my $userloadpercent=0;
812: my $maxuserload=$perlvar{'lonUserLoadLim'};
813: if ($maxuserload) {
814: $userloadpercent=100*$numusers/$maxuserload;
815: }
816: $userloadpercent=sprintf("%.2f",$userloadpercent);
817: return $userloadpercent;
818: }
819:
820: # ------------------------------ Find server with least workload from spare.tab
821:
822: sub spareserver {
823: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
824: my $spare_server;
825: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
826: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
827: : $userloadpercent;
828: my ($uint_dom,$remotesessions);
829: if (($udom ne '') && (&domain($udom) ne '')) {
830: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
831: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
832: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
833: $remotesessions = $udomdefaults{'remotesessions'};
834: }
835: my $spareshash = &this_host_spares($udom);
836: if (ref($spareshash) eq 'HASH') {
837: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
838: foreach my $try_server (@{ $spareshash->{'primary'} }) {
839: if ($uint_dom) {
840: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
841: $try_server));
842: }
843: ($spare_server, $lowest_load) =
844: &compare_server_load($try_server, $spare_server, $lowest_load);
845: }
846: }
847:
848: my $found_server = ($spare_server ne '' && $lowest_load < 100);
849:
850: if (!$found_server) {
851: if (ref($spareshash->{'default'}) eq 'ARRAY') {
852: foreach my $try_server (@{ $spareshash->{'default'} }) {
853: if ($uint_dom) {
854: next unless (&spare_can_host($udom,$uint_dom,
855: $remotesessions,$try_server));
856: }
857: ($spare_server, $lowest_load) =
858: &compare_server_load($try_server, $spare_server, $lowest_load);
859: }
860: }
861: }
862: }
863:
864: if (!$want_server_name) {
865: my $protocol = 'http';
866: if ($protocol{$spare_server} eq 'https') {
867: $protocol = $protocol{$spare_server};
868: }
869: if (defined($spare_server)) {
870: my $hostname = &hostname($spare_server);
871: if (defined($hostname)) {
872: $spare_server = $protocol.'://'.$hostname;
873: }
874: }
875: }
876: return $spare_server;
877: }
878:
879: sub compare_server_load {
880: my ($try_server, $spare_server, $lowest_load) = @_;
881:
882: my $loadans = &reply('load', $try_server);
883: my $userloadans = &reply('userload',$try_server);
884:
885: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
886: return ($spare_server, $lowest_load); #didn't get a number from the server
887: }
888:
889: my $load;
890: if ($loadans =~ /\d/) {
891: if ($userloadans =~ /\d/) {
892: #both are numbers, pick the bigger one
893: $load = ($loadans > $userloadans) ? $loadans
894: : $userloadans;
895: } else {
896: $load = $loadans;
897: }
898: } else {
899: $load = $userloadans;
900: }
901:
902: if (($load =~ /\d/) && ($load < $lowest_load)) {
903: $spare_server = $try_server;
904: $lowest_load = $load;
905: }
906: return ($spare_server,$lowest_load);
907: }
908:
909: # --------------------------- ask offload servers if user already has a session
910: sub find_existing_session {
911: my ($udom,$uname) = @_;
912: my $spareshash = &this_host_spares($udom);
913: if (ref($spareshash) eq 'HASH') {
914: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
915: foreach my $try_server (@{ $spareshash->{'primary'} }) {
916: return $try_server if (&has_user_session($try_server, $udom, $uname));
917: }
918: }
919: if (ref($spareshash->{'default'}) eq 'ARRAY') {
920: foreach my $try_server (@{ $spareshash->{'default'} }) {
921: return $try_server if (&has_user_session($try_server, $udom, $uname));
922: }
923: }
924: }
925: return;
926: }
927:
928: # -------------------------------- ask if server already has a session for user
929: sub has_user_session {
930: my ($lonid,$udom,$uname) = @_;
931: my $result = &reply(join(':','userhassession',
932: map {&escape($_)} ($udom,$uname)),$lonid);
933: return 1 if ($result eq 'ok');
934:
935: return 0;
936: }
937:
938: # --------- determine least loaded server in a user's domain which allows login
939:
940: sub choose_server {
941: my ($udom,$checkloginvia) = @_;
942: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
943: my %servers = &get_servers($udom);
944: my $lowest_load = 30000;
945: my ($login_host,$hostname,$portal_path,$isredirect);
946: foreach my $lonhost (keys(%servers)) {
947: my $loginvia;
948: if ($checkloginvia) {
949: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
950: if ($loginvia) {
951: my ($server,$path) = split(/:/,$loginvia);
952: ($login_host, $lowest_load) =
953: &compare_server_load($server, $login_host, $lowest_load);
954: if ($login_host eq $server) {
955: $portal_path = $path;
956: $isredirect = 1;
957: }
958: } else {
959: ($login_host, $lowest_load) =
960: &compare_server_load($lonhost, $login_host, $lowest_load);
961: if ($login_host eq $lonhost) {
962: $portal_path = '';
963: $isredirect = '';
964: }
965: }
966: } else {
967: ($login_host, $lowest_load) =
968: &compare_server_load($lonhost, $login_host, $lowest_load);
969: }
970: }
971: if ($login_host ne '') {
972: $hostname = &hostname($login_host);
973: }
974: return ($login_host,$hostname,$portal_path,$isredirect);
975: }
976:
977: # --------------------------------------------- Try to change a user's password
978:
979: sub changepass {
980: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
981: $currentpass = &escape($currentpass);
982: $newpass = &escape($newpass);
983: my $lonhost = $perlvar{'lonHostID'};
984: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
985: $server);
986: if (! $answer) {
987: &logthis("No reply on password change request to $server ".
988: "by $uname in domain $udom.");
989: } elsif ($answer =~ "^ok") {
990: &logthis("$uname in $udom successfully changed their password ".
991: "on $server.");
992: } elsif ($answer =~ "^pwchange_failure") {
993: &logthis("$uname in $udom was unable to change their password ".
994: "on $server. The action was blocked by either lcpasswd ".
995: "or pwchange");
996: } elsif ($answer =~ "^non_authorized") {
997: &logthis("$uname in $udom did not get their password correct when ".
998: "attempting to change it on $server.");
999: } elsif ($answer =~ "^auth_mode_error") {
1000: &logthis("$uname in $udom attempted to change their password despite ".
1001: "not being locally or internally authenticated on $server.");
1002: } elsif ($answer =~ "^unknown_user") {
1003: &logthis("$uname in $udom attempted to change their password ".
1004: "on $server but were unable to because $server is not ".
1005: "their home server.");
1006: } elsif ($answer =~ "^refused") {
1007: &logthis("$server refused to change $uname in $udom password because ".
1008: "it was sent an unencrypted request to change the password.");
1009: } elsif ($answer =~ "invalid_client") {
1010: &logthis("$server refused to change $uname in $udom password because ".
1011: "it was a reset by e-mail originating from an invalid server.");
1012: }
1013: return $answer;
1014: }
1015:
1016: # ----------------------- Try to determine user's current authentication scheme
1017:
1018: sub queryauthenticate {
1019: my ($uname,$udom)=@_;
1020: my $uhome=&homeserver($uname,$udom);
1021: if (!$uhome) {
1022: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1023: return 'no_host';
1024: }
1025: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1026: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1027: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1028: }
1029: return $answer;
1030: }
1031:
1032: # --------- Try to authenticate user from domain's lib servers (first this one)
1033:
1034: sub authenticate {
1035: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1036: $upass=&escape($upass);
1037: $uname= &LONCAPA::clean_username($uname);
1038: my $uhome=&homeserver($uname,$udom,1);
1039: my $newhome;
1040: if ((!$uhome) || ($uhome eq 'no_host')) {
1041: # Maybe the machine was offline and only re-appeared again recently?
1042: &reconlonc();
1043: # One more
1044: $uhome=&homeserver($uname,$udom,1);
1045: if (($uhome eq 'no_host') && $checkdefauth) {
1046: if (defined(&domain($udom,'primary'))) {
1047: $newhome=&domain($udom,'primary');
1048: }
1049: if ($newhome ne '') {
1050: $uhome = $newhome;
1051: }
1052: }
1053: if ((!$uhome) || ($uhome eq 'no_host')) {
1054: &logthis("User $uname at $udom is unknown in authenticate");
1055: return 'no_host';
1056: }
1057: }
1058: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1059: if ($answer eq 'authorized') {
1060: if ($newhome) {
1061: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1062: return 'no_account_on_host';
1063: } else {
1064: &logthis("User $uname at $udom authorized by $uhome");
1065: return $uhome;
1066: }
1067: }
1068: if ($answer eq 'non_authorized') {
1069: &logthis("User $uname at $udom rejected by $uhome");
1070: return 'no_host';
1071: }
1072: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1073: return 'no_host';
1074: }
1075:
1076: sub can_host_session {
1077: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1078: my $canhost = 1;
1079: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1080: if (ref($remotesessions) eq 'HASH') {
1081: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1082: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1083: $canhost = 0;
1084: } else {
1085: $canhost = 1;
1086: }
1087: }
1088: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1089: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1090: $canhost = 1;
1091: } else {
1092: $canhost = 0;
1093: }
1094: }
1095: if ($canhost) {
1096: if ($remotesessions->{'version'} ne '') {
1097: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1098: if ($reqmajor ne '' && $reqminor ne '') {
1099: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1100: my $major = $1;
1101: my $minor = $2;
1102: if (($major < $reqmajor ) ||
1103: (($major == $reqmajor) && ($minor < $reqminor))) {
1104: $canhost = 0;
1105: }
1106: } else {
1107: $canhost = 0;
1108: }
1109: }
1110: }
1111: }
1112: }
1113: if ($canhost) {
1114: if (ref($hostedsessions) eq 'HASH') {
1115: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1116: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1117: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1118: if (($uint_dom ne '') &&
1119: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1120: $canhost = 0;
1121: } else {
1122: $canhost = 1;
1123: }
1124: }
1125: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1126: if (($uint_dom ne '') &&
1127: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1128: $canhost = 1;
1129: } else {
1130: $canhost = 0;
1131: }
1132: }
1133: }
1134: }
1135: return $canhost;
1136: }
1137:
1138: sub spare_can_host {
1139: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1140: my $canhost=1;
1141: my @intdoms;
1142: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1143: if (ref($internet_names) eq 'ARRAY') {
1144: @intdoms = @{$internet_names};
1145: }
1146: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1147: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1148: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1149: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1150: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1151: $canhost = &can_host_session($udom,$try_server,$remoterev,
1152: $remotesessions,
1153: $defdomdefaults{'hostedsessions'});
1154: }
1155: return $canhost;
1156: }
1157:
1158: sub this_host_spares {
1159: my ($dom) = @_;
1160: my ($dom_in_use,$lonhost_in_use,$result);
1161: my @hosts = ¤t_machine_ids();
1162: foreach my $lonhost (@hosts) {
1163: if (&host_domain($lonhost) eq $dom) {
1164: $dom_in_use = $dom;
1165: $lonhost_in_use = $lonhost;
1166: last;
1167: }
1168: }
1169: if ($dom_in_use ne '') {
1170: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1171: }
1172: if (ref($result) ne 'HASH') {
1173: $lonhost_in_use = $perlvar{'lonHostID'};
1174: $dom_in_use = &host_domain($lonhost_in_use);
1175: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1176: if (ref($result) ne 'HASH') {
1177: $result = \%spareid;
1178: }
1179: }
1180: return $result;
1181: }
1182:
1183: sub spares_for_offload {
1184: my ($dom_in_use,$lonhost_in_use) = @_;
1185: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1186: if (defined($cached)) {
1187: return $result;
1188: } else {
1189: my $cachetime = 60*60*24;
1190: my %domconfig =
1191: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1192: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1193: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1194: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1195: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1196: }
1197: }
1198: }
1199: }
1200: return;
1201: }
1202:
1203: sub get_lonbalancer_config {
1204: my ($servers) = @_;
1205: my ($currbalancer,$currtargets);
1206: if (ref($servers) eq 'HASH') {
1207: foreach my $server (keys(%{$servers})) {
1208: my %what = (
1209: spareid => 1,
1210: perlvar => 1,
1211: );
1212: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1213: if ($result eq 'ok') {
1214: if (ref($returnhash) eq 'HASH') {
1215: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1216: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1217: $currbalancer = $server;
1218: $currtargets = {};
1219: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1220: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1221: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1222: }
1223: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1224: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1225: }
1226: }
1227: last;
1228: }
1229: }
1230: }
1231: }
1232: }
1233: }
1234: return ($currbalancer,$currtargets);
1235: }
1236:
1237: sub check_loadbalancing {
1238: my ($uname,$udom) = @_;
1239: my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
1240: $offloadto,$otherserver);
1241: my $lonhost = $perlvar{'lonHostID'};
1242: my @hosts = ¤t_machine_ids();
1243: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1244: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1245: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1246: my $serverhomedom = &host_domain($lonhost);
1247:
1248: my $cachetime = 60*60*24;
1249:
1250: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1251: $dom_in_use = $udom;
1252: $homeintdom = 1;
1253: } else {
1254: $dom_in_use = $serverhomedom;
1255: }
1256: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1257: unless (defined($cached)) {
1258: my %domconfig =
1259: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1260: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1261: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1262: }
1263: }
1264: if (ref($result) eq 'HASH') {
1265: my $currbalancer = $result->{'lonhost'};
1266: my $currtargets = $result->{'targets'};
1267: my $currrules = $result->{'rules'};
1268: if ($currbalancer ne '') {
1269: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1270: $is_balancer = 1;
1271: }
1272: }
1273: if ($is_balancer) {
1274: if (ref($currrules) eq 'HASH') {
1275: if ($homeintdom) {
1276: if ($uname ne '') {
1277: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1278: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1279: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1280: $rule_in_effect = $currrules->{'_LC_author'};
1281: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1282: $rule_in_effect = $currrules->{'_LC_adv'}
1283: }
1284: }
1285: if ($rule_in_effect eq '') {
1286: my %userenv = &userenvironment($udom,$uname,'inststatus');
1287: if ($userenv{'inststatus'} ne '') {
1288: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1289: my ($othertitle,$usertypes,$types) =
1290: &Apache::loncommon::sorted_inst_types($udom);
1291: if (ref($types) eq 'ARRAY') {
1292: foreach my $type (@{$types}) {
1293: if (grep(/^\Q$type\E$/,@statuses)) {
1294: if (exists($currrules->{$type})) {
1295: $rule_in_effect = $currrules->{$type};
1296: }
1297: }
1298: }
1299: }
1300: } else {
1301: if (exists($currrules->{'default'})) {
1302: $rule_in_effect = $currrules->{'default'};
1303: }
1304: }
1305: }
1306: } else {
1307: if (exists($currrules->{'default'})) {
1308: $rule_in_effect = $currrules->{'default'};
1309: }
1310: }
1311: } else {
1312: if ($currrules->{'_LC_external'} ne '') {
1313: $rule_in_effect = $currrules->{'_LC_external'};
1314: }
1315: }
1316: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1317: $uname,$udom);
1318: }
1319: }
1320: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1321: my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1322: unless (defined($cached)) {
1323: my %domconfig =
1324: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1325: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1326: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1327: }
1328: }
1329: if (ref($result) eq 'HASH') {
1330: my $currbalancer = $result->{'lonhost'};
1331: my $currtargets = $result->{'targets'};
1332: my $currrules = $result->{'rules'};
1333:
1334: if ($currbalancer eq $lonhost) {
1335: $is_balancer = 1;
1336: if (ref($currrules) eq 'HASH') {
1337: if ($currrules->{'_LC_internetdom'} ne '') {
1338: $rule_in_effect = $currrules->{'_LC_internetdom'};
1339: }
1340: }
1341: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1342: $uname,$udom);
1343: }
1344: } else {
1345: if ($perlvar{'lonBalancer'} eq 'yes') {
1346: $is_balancer = 1;
1347: $offloadto = &this_host_spares($dom_in_use);
1348: }
1349: }
1350: } else {
1351: if ($perlvar{'lonBalancer'} eq 'yes') {
1352: $is_balancer = 1;
1353: $offloadto = &this_host_spares($dom_in_use);
1354: }
1355: }
1356: if ($is_balancer) {
1357: my $lowest_load = 30000;
1358: if (ref($offloadto) eq 'HASH') {
1359: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1360: foreach my $try_server (@{$offloadto->{'primary'}}) {
1361: ($otherserver,$lowest_load) =
1362: &compare_server_load($try_server,$otherserver,$lowest_load);
1363: }
1364: }
1365: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1366:
1367: if (!$found_server) {
1368: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1369: foreach my $try_server (@{$offloadto->{'default'}}) {
1370: ($otherserver,$lowest_load) =
1371: &compare_server_load($try_server,$otherserver,$lowest_load);
1372: }
1373: }
1374: }
1375: } elsif (ref($offloadto) eq 'ARRAY') {
1376: if (@{$offloadto} == 1) {
1377: $otherserver = $offloadto->[0];
1378: } elsif (@{$offloadto} > 1) {
1379: foreach my $try_server (@{$offloadto}) {
1380: ($otherserver,$lowest_load) =
1381: &compare_server_load($try_server,$otherserver,$lowest_load);
1382: }
1383: }
1384: }
1385: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1386: $is_balancer = 0;
1387: if ($uname ne '' && $udom ne '') {
1388: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1389:
1390: &appenv({'user.loadbalexempt' => $lonhost,
1391: 'user.loadbalcheck.time' => time});
1392: }
1393: }
1394: }
1395: }
1396: return ($is_balancer,$otherserver);
1397: }
1398:
1399: sub get_loadbalancer_targets {
1400: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1401: my $offloadto;
1402: if ($rule_in_effect eq 'none') {
1403: return [$perlvar{'lonHostID'}];
1404: } elsif ($rule_in_effect eq '') {
1405: $offloadto = $currtargets;
1406: } else {
1407: if ($rule_in_effect eq 'homeserver') {
1408: my $homeserver = &homeserver($uname,$udom);
1409: if ($homeserver ne 'no_host') {
1410: $offloadto = [$homeserver];
1411: }
1412: } elsif ($rule_in_effect eq 'externalbalancer') {
1413: my %domconfig =
1414: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1415: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1416: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1417: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1418: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1419: }
1420: }
1421: } else {
1422: my %servers = &dom_servers($udom);
1423: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1424: if (&hostname($remotebalancer) ne '') {
1425: $offloadto = [$remotebalancer];
1426: }
1427: }
1428: } elsif (&hostname($rule_in_effect) ne '') {
1429: $offloadto = [$rule_in_effect];
1430: }
1431: }
1432: return $offloadto;
1433: }
1434:
1435: sub internet_dom_servers {
1436: my ($dom) = @_;
1437: my (%uniqservers,%servers);
1438: my $primaryserver = &hostname(&domain($dom,'primary'));
1439: my @machinedoms = &machine_domains($primaryserver);
1440: foreach my $mdom (@machinedoms) {
1441: my %currservers = %servers;
1442: my %server = &get_servers($mdom);
1443: %servers = (%currservers,%server);
1444: }
1445: my %by_hostname;
1446: foreach my $id (keys(%servers)) {
1447: push(@{$by_hostname{$servers{$id}}},$id);
1448: }
1449: foreach my $hostname (sort(keys(%by_hostname))) {
1450: if (@{$by_hostname{$hostname}} > 1) {
1451: my $match = 0;
1452: foreach my $id (@{$by_hostname{$hostname}}) {
1453: if (&host_domain($id) eq $dom) {
1454: $uniqservers{$id} = $hostname;
1455: $match = 1;
1456: }
1457: }
1458: unless ($match) {
1459: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1460: }
1461: } else {
1462: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1463: }
1464: }
1465: return %uniqservers;
1466: }
1467:
1468: # ---------------------- Find the homebase for a user from domain's lib servers
1469:
1470: my %homecache;
1471: sub homeserver {
1472: my ($uname,$udom,$ignoreBadCache)=@_;
1473: my $index="$uname:$udom";
1474:
1475: if (exists($homecache{$index})) { return $homecache{$index}; }
1476:
1477: my %servers = &get_servers($udom,'library');
1478: foreach my $tryserver (keys(%servers)) {
1479: next if ($ignoreBadCache ne 'true' &&
1480: exists($badServerCache{$tryserver}));
1481:
1482: my $answer=reply("home:$udom:$uname",$tryserver);
1483: if ($answer eq 'found') {
1484: delete($badServerCache{$tryserver});
1485: return $homecache{$index}=$tryserver;
1486: } elsif ($answer eq 'no_host') {
1487: $badServerCache{$tryserver}=1;
1488: }
1489: }
1490: return 'no_host';
1491: }
1492:
1493: # ------------------------------------- Find the usernames behind a list of IDs
1494:
1495: sub idget {
1496: my ($udom,@ids)=@_;
1497: my %returnhash=();
1498:
1499: my %servers = &get_servers($udom,'library');
1500: foreach my $tryserver (keys(%servers)) {
1501: my $idlist=join('&',@ids);
1502: $idlist=~tr/A-Z/a-z/;
1503: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1504: my @answer=();
1505: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1506: @answer=split(/\&/,$reply);
1507: } ;
1508: my $i;
1509: for ($i=0;$i<=$#ids;$i++) {
1510: if ($answer[$i]) {
1511: $returnhash{$ids[$i]}=$answer[$i];
1512: }
1513: }
1514: }
1515: return %returnhash;
1516: }
1517:
1518: # ------------------------------------- Find the IDs behind a list of usernames
1519:
1520: sub idrget {
1521: my ($udom,@unames)=@_;
1522: my %returnhash=();
1523: foreach my $uname (@unames) {
1524: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1525: }
1526: return %returnhash;
1527: }
1528:
1529: # ------------------------------- Store away a list of names and associated IDs
1530:
1531: sub idput {
1532: my ($udom,%ids)=@_;
1533: my %servers=();
1534: foreach my $uname (keys(%ids)) {
1535: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1536: my $uhom=&homeserver($uname,$udom);
1537: if ($uhom ne 'no_host') {
1538: my $id=&escape($ids{$uname});
1539: $id=~tr/A-Z/a-z/;
1540: my $esc_unam=&escape($uname);
1541: if ($servers{$uhom}) {
1542: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1543: } else {
1544: $servers{$uhom}=$id.'='.$esc_unam;
1545: }
1546: }
1547: }
1548: foreach my $server (keys(%servers)) {
1549: &critical('idput:'.$udom.':'.$servers{$server},$server);
1550: }
1551: }
1552:
1553: # ------------------------------dump from db file owned by domainconfig user
1554: sub dump_dom {
1555: my ($namespace, $udom, $regexp) = @_;
1556:
1557: $udom ||= $env{'user.domain'};
1558:
1559: return () unless $udom;
1560:
1561: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1562: }
1563:
1564: # ------------------------------------------ get items from domain db files
1565:
1566: sub get_dom {
1567: my ($namespace,$storearr,$udom,$uhome)=@_;
1568: my $items='';
1569: foreach my $item (@$storearr) {
1570: $items.=&escape($item).'&';
1571: }
1572: $items=~s/\&$//;
1573: if (!$udom) {
1574: $udom=$env{'user.domain'};
1575: if (defined(&domain($udom,'primary'))) {
1576: $uhome=&domain($udom,'primary');
1577: } else {
1578: undef($uhome);
1579: }
1580: } else {
1581: if (!$uhome) {
1582: if (defined(&domain($udom,'primary'))) {
1583: $uhome=&domain($udom,'primary');
1584: }
1585: }
1586: }
1587: if ($udom && $uhome && ($uhome ne 'no_host')) {
1588: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1589: my %returnhash;
1590: if ($rep eq '' || $rep =~ /^error: 2 /) {
1591: return %returnhash;
1592: }
1593: my @pairs=split(/\&/,$rep);
1594: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1595: return @pairs;
1596: }
1597: my $i=0;
1598: foreach my $item (@$storearr) {
1599: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1600: $i++;
1601: }
1602: return %returnhash;
1603: } else {
1604: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1605: }
1606: }
1607:
1608: # -------------------------------------------- put items in domain db files
1609:
1610: sub put_dom {
1611: my ($namespace,$storehash,$udom,$uhome)=@_;
1612: if (!$udom) {
1613: $udom=$env{'user.domain'};
1614: if (defined(&domain($udom,'primary'))) {
1615: $uhome=&domain($udom,'primary');
1616: } else {
1617: undef($uhome);
1618: }
1619: } else {
1620: if (!$uhome) {
1621: if (defined(&domain($udom,'primary'))) {
1622: $uhome=&domain($udom,'primary');
1623: }
1624: }
1625: }
1626: if ($udom && $uhome && ($uhome ne 'no_host')) {
1627: my $items='';
1628: foreach my $item (keys(%$storehash)) {
1629: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1630: }
1631: $items=~s/\&$//;
1632: return &reply("putdom:$udom:$namespace:$items",$uhome);
1633: } else {
1634: &logthis("put_dom failed - no homeserver and/or domain");
1635: }
1636: }
1637:
1638: # --------------------- newput for items in db file owned by domainconfig user
1639: sub newput_dom {
1640: my ($namespace,$storehash,$udom) = @_;
1641: my $result;
1642: if (!$udom) {
1643: $udom=$env{'user.domain'};
1644: }
1645: if ($udom) {
1646: my $uname = &get_domainconfiguser($udom);
1647: $result = &newput($namespace,$storehash,$udom,$uname);
1648: }
1649: return $result;
1650: }
1651:
1652: # --------------------- delete for items in db file owned by domainconfig user
1653: sub del_dom {
1654: my ($namespace,$storearr,$udom)=@_;
1655: if (ref($storearr) eq 'ARRAY') {
1656: if (!$udom) {
1657: $udom=$env{'user.domain'};
1658: }
1659: if ($udom) {
1660: my $uname = &get_domainconfiguser($udom);
1661: return &del($namespace,$storearr,$udom,$uname);
1662: }
1663: }
1664: }
1665:
1666: # ----------------------------------construct domainconfig user for a domain
1667: sub get_domainconfiguser {
1668: my ($udom) = @_;
1669: return $udom.'-domainconfig';
1670: }
1671:
1672: sub retrieve_inst_usertypes {
1673: my ($udom) = @_;
1674: my (%returnhash,@order);
1675: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1676: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1677: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1678: %returnhash = %{$domdefs{'inststatustypes'}};
1679: @order = @{$domdefs{'inststatusorder'}};
1680: } else {
1681: if (defined(&domain($udom,'primary'))) {
1682: my $uhome=&domain($udom,'primary');
1683: my $rep=&reply("inst_usertypes:$udom",$uhome);
1684: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1685: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1686: return (\%returnhash,\@order);
1687: }
1688: my ($hashitems,$orderitems) = split(/:/,$rep);
1689: my @pairs=split(/\&/,$hashitems);
1690: foreach my $item (@pairs) {
1691: my ($key,$value)=split(/=/,$item,2);
1692: $key = &unescape($key);
1693: next if ($key =~ /^error: 2 /);
1694: $returnhash{$key}=&thaw_unescape($value);
1695: }
1696: my @esc_order = split(/\&/,$orderitems);
1697: foreach my $item (@esc_order) {
1698: push(@order,&unescape($item));
1699: }
1700: } else {
1701: &logthis("get_dom failed - no primary domain server for $udom");
1702: }
1703: }
1704: return (\%returnhash,\@order);
1705: }
1706:
1707: sub is_domainimage {
1708: my ($url) = @_;
1709: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1710: if (&domain($1) ne '') {
1711: return '1';
1712: }
1713: }
1714: return;
1715: }
1716:
1717: sub inst_directory_query {
1718: my ($srch) = @_;
1719: my $udom = $srch->{'srchdomain'};
1720: my %results;
1721: my $homeserver = &domain($udom,'primary');
1722: my $outcome;
1723: if ($homeserver ne '') {
1724: my $queryid=&reply("querysend:instdirsearch:".
1725: &escape($srch->{'srchby'}).':'.
1726: &escape($srch->{'srchterm'}).':'.
1727: &escape($srch->{'srchtype'}),$homeserver);
1728: my $host=&hostname($homeserver);
1729: if ($queryid !~/^\Q$host\E\_/) {
1730: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1731: return;
1732: }
1733: my $response = &get_query_reply($queryid);
1734: my $maxtries = 5;
1735: my $tries = 1;
1736: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1737: $response = &get_query_reply($queryid);
1738: $tries ++;
1739: }
1740:
1741: if (!&error($response) && $response ne 'refused') {
1742: if ($response eq 'unavailable') {
1743: $outcome = $response;
1744: } else {
1745: $outcome = 'ok';
1746: my @matches = split(/\n/,$response);
1747: foreach my $match (@matches) {
1748: my ($key,$value) = split(/=/,$match);
1749: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1750: }
1751: }
1752: }
1753: }
1754: return ($outcome,%results);
1755: }
1756:
1757: sub usersearch {
1758: my ($srch) = @_;
1759: my $dom = $srch->{'srchdomain'};
1760: my %results;
1761: my %libserv = &all_library();
1762: my $query = 'usersearch';
1763: foreach my $tryserver (keys(%libserv)) {
1764: if (&host_domain($tryserver) eq $dom) {
1765: my $host=&hostname($tryserver);
1766: my $queryid=
1767: &reply("querysend:".&escape($query).':'.
1768: &escape($srch->{'srchby'}).':'.
1769: &escape($srch->{'srchtype'}).':'.
1770: &escape($srch->{'srchterm'}),$tryserver);
1771: if ($queryid !~/^\Q$host\E\_/) {
1772: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1773: next;
1774: }
1775: my $reply = &get_query_reply($queryid);
1776: my $maxtries = 1;
1777: my $tries = 1;
1778: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1779: $reply = &get_query_reply($queryid);
1780: $tries ++;
1781: }
1782: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1783: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1784: } else {
1785: my @matches;
1786: if ($reply =~ /\n/) {
1787: @matches = split(/\n/,$reply);
1788: } else {
1789: @matches = split(/\&/,$reply);
1790: }
1791: foreach my $match (@matches) {
1792: my ($uname,$udom,%userhash);
1793: foreach my $entry (split(/:/,$match)) {
1794: my ($key,$value) =
1795: map {&unescape($_);} split(/=/,$entry);
1796: $userhash{$key} = $value;
1797: if ($key eq 'username') {
1798: $uname = $value;
1799: } elsif ($key eq 'domain') {
1800: $udom = $value;
1801: }
1802: }
1803: $results{$uname.':'.$udom} = \%userhash;
1804: }
1805: }
1806: }
1807: }
1808: return %results;
1809: }
1810:
1811: sub get_instuser {
1812: my ($udom,$uname,$id) = @_;
1813: my $homeserver = &domain($udom,'primary');
1814: my ($outcome,%results);
1815: if ($homeserver ne '') {
1816: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1817: &escape($id).':'.&escape($udom),$homeserver);
1818: my $host=&hostname($homeserver);
1819: if ($queryid !~/^\Q$host\E\_/) {
1820: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1821: return;
1822: }
1823: my $response = &get_query_reply($queryid);
1824: my $maxtries = 5;
1825: my $tries = 1;
1826: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1827: $response = &get_query_reply($queryid);
1828: $tries ++;
1829: }
1830: if (!&error($response) && $response ne 'refused') {
1831: if ($response eq 'unavailable') {
1832: $outcome = $response;
1833: } else {
1834: $outcome = 'ok';
1835: my @matches = split(/\n/,$response);
1836: foreach my $match (@matches) {
1837: my ($key,$value) = split(/=/,$match);
1838: $results{&unescape($key)} = &thaw_unescape($value);
1839: }
1840: }
1841: }
1842: }
1843: my %userinfo;
1844: if (ref($results{$uname}) eq 'HASH') {
1845: %userinfo = %{$results{$uname}};
1846: }
1847: return ($outcome,%userinfo);
1848: }
1849:
1850: sub inst_rulecheck {
1851: my ($udom,$uname,$id,$item,$rules) = @_;
1852: my %returnhash;
1853: if ($udom ne '') {
1854: if (ref($rules) eq 'ARRAY') {
1855: @{$rules} = map {&escape($_);} (@{$rules});
1856: my $rulestr = join(':',@{$rules});
1857: my $homeserver=&domain($udom,'primary');
1858: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1859: my $response;
1860: if ($item eq 'username') {
1861: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1862: ':'.&escape($uname).':'.$rulestr,
1863: $homeserver));
1864: } elsif ($item eq 'id') {
1865: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1866: ':'.&escape($id).':'.$rulestr,
1867: $homeserver));
1868: } elsif ($item eq 'selfcreate') {
1869: $response=&unescape(&reply('instselfcreatecheck:'.
1870: &escape($udom).':'.&escape($uname).
1871: ':'.$rulestr,$homeserver));
1872: }
1873: if ($response ne 'refused') {
1874: my @pairs=split(/\&/,$response);
1875: foreach my $item (@pairs) {
1876: my ($key,$value)=split(/=/,$item,2);
1877: $key = &unescape($key);
1878: next if ($key =~ /^error: 2 /);
1879: $returnhash{$key}=&thaw_unescape($value);
1880: }
1881: }
1882: }
1883: }
1884: }
1885: return %returnhash;
1886: }
1887:
1888: sub inst_userrules {
1889: my ($udom,$check) = @_;
1890: my (%ruleshash,@ruleorder);
1891: if ($udom ne '') {
1892: my $homeserver=&domain($udom,'primary');
1893: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1894: my $response;
1895: if ($check eq 'id') {
1896: $response=&reply('instidrules:'.&escape($udom),
1897: $homeserver);
1898: } elsif ($check eq 'email') {
1899: $response=&reply('instemailrules:'.&escape($udom),
1900: $homeserver);
1901: } else {
1902: $response=&reply('instuserrules:'.&escape($udom),
1903: $homeserver);
1904: }
1905: if (($response ne 'refused') && ($response ne 'error') &&
1906: ($response ne 'unknown_cmd') &&
1907: ($response ne 'no_such_host')) {
1908: my ($hashitems,$orderitems) = split(/:/,$response);
1909: my @pairs=split(/\&/,$hashitems);
1910: foreach my $item (@pairs) {
1911: my ($key,$value)=split(/=/,$item,2);
1912: $key = &unescape($key);
1913: next if ($key =~ /^error: 2 /);
1914: $ruleshash{$key}=&thaw_unescape($value);
1915: }
1916: my @esc_order = split(/\&/,$orderitems);
1917: foreach my $item (@esc_order) {
1918: push(@ruleorder,&unescape($item));
1919: }
1920: }
1921: }
1922: }
1923: return (\%ruleshash,\@ruleorder);
1924: }
1925:
1926: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1927:
1928: sub get_domain_defaults {
1929: my ($domain) = @_;
1930: my $cachetime = 60*60*24;
1931: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1932: if (defined($cached)) {
1933: if (ref($result) eq 'HASH') {
1934: return %{$result};
1935: }
1936: }
1937: my %domdefaults;
1938: my %domconfig =
1939: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1940: 'requestcourses','inststatus',
1941: 'coursedefaults','usersessions'],$domain);
1942: if (ref($domconfig{'defaults'}) eq 'HASH') {
1943: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1944: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1945: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1946: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1947: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1948: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1949: } else {
1950: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1951: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1952: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1953: }
1954: if (ref($domconfig{'quotas'}) eq 'HASH') {
1955: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1956: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1957: } else {
1958: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1959: }
1960: my @usertools = ('aboutme','blog','portfolio');
1961: foreach my $item (@usertools) {
1962: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1963: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1964: }
1965: }
1966: }
1967: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1968: foreach my $item ('official','unofficial','community') {
1969: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1970: }
1971: }
1972: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1973: foreach my $item ('inststatustypes','inststatusorder') {
1974: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1975: }
1976: }
1977: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1978: foreach my $item ('canuse_pdfforms') {
1979: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1980: }
1981: }
1982: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1983: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1984: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1985: }
1986: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1987: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1988: }
1989: }
1990: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1991: $cachetime);
1992: return %domdefaults;
1993: }
1994:
1995: # --------------------------------------------------- Assign a key to a student
1996:
1997: sub assign_access_key {
1998: #
1999: # a valid key looks like uname:udom#comments
2000: # comments are being appended
2001: #
2002: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2003: $kdom=
2004: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
2005: $knum=
2006: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
2007: $cdom=
2008: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2009: $cnum=
2010: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2011: $udom=$env{'user.name'} unless (defined($udom));
2012: $uname=$env{'user.domain'} unless (defined($uname));
2013: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
2014: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
2015: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
2016: # assigned to this person
2017: # - this should not happen,
2018: # unless something went wrong
2019: # the first time around
2020: # ready to assign
2021: $logentry=$1.'; '.$logentry;
2022: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
2023: $kdom,$knum) eq 'ok') {
2024: # key now belongs to user
2025: my $envkey='key.'.$cdom.'_'.$cnum;
2026: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
2027: &appenv({'environment.'.$envkey => $ckey});
2028: return 'ok';
2029: } else {
2030: return
2031: 'error: Count not permanently assign key, will need to be re-entered later.';
2032: }
2033: } else {
2034: return 'error: Could not assign key, try again later.';
2035: }
2036: } elsif (!$existing{$ckey}) {
2037: # the key does not exist
2038: return 'error: The key does not exist';
2039: } else {
2040: # the key is somebody else's
2041: return 'error: The key is already in use';
2042: }
2043: }
2044:
2045: # ------------------------------------------ put an additional comment on a key
2046:
2047: sub comment_access_key {
2048: #
2049: # a valid key looks like uname:udom#comments
2050: # comments are being appended
2051: #
2052: my ($ckey,$cdom,$cnum,$logentry)=@_;
2053: $cdom=
2054: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2055: $cnum=
2056: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2057: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2058: if ($existing{$ckey}) {
2059: $existing{$ckey}.='; '.$logentry;
2060: # ready to assign
2061: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
2062: $cdom,$cnum) eq 'ok') {
2063: return 'ok';
2064: } else {
2065: return 'error: Count not store comment.';
2066: }
2067: } else {
2068: # the key does not exist
2069: return 'error: The key does not exist';
2070: }
2071: }
2072:
2073: # ------------------------------------------------------ Generate a set of keys
2074:
2075: sub generate_access_keys {
2076: my ($number,$cdom,$cnum,$logentry)=@_;
2077: $cdom=
2078: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2079: $cnum=
2080: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2081: unless (&allowed('mky',$cdom)) { return 0; }
2082: unless (($cdom) && ($cnum)) { return 0; }
2083: if ($number>10000) { return 0; }
2084: sleep(2); # make sure don't get same seed twice
2085: srand(time()^($$+($$<<15))); # from "Programming Perl"
2086: my $total=0;
2087: for (my $i=1;$i<=$number;$i++) {
2088: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2089: sprintf("%lx",int(100000*rand)).'-'.
2090: sprintf("%lx",int(100000*rand));
2091: $newkey=~s/1/g/g; # folks mix up 1 and l
2092: $newkey=~s/0/h/g; # and also 0 and O
2093: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2094: if ($existing{$newkey}) {
2095: $i--;
2096: } else {
2097: if (&put('accesskeys',
2098: { $newkey => '# generated '.localtime().
2099: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
2100: '; '.$logentry },
2101: $cdom,$cnum) eq 'ok') {
2102: $total++;
2103: }
2104: }
2105: }
2106: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
2107: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2108: return $total;
2109: }
2110:
2111: # ------------------------------------------------------- Validate an accesskey
2112:
2113: sub validate_access_key {
2114: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2115: $cdom=
2116: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2117: $cnum=
2118: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2119: $udom=$env{'user.domain'} unless (defined($udom));
2120: $uname=$env{'user.name'} unless (defined($uname));
2121: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2122: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
2123: }
2124:
2125: # ------------------------------------- Find the section of student in a course
2126: sub devalidate_getsection_cache {
2127: my ($udom,$unam,$courseid)=@_;
2128: my $hashid="$udom:$unam:$courseid";
2129: &devalidate_cache_new('getsection',$hashid);
2130: }
2131:
2132: sub courseid_to_courseurl {
2133: my ($courseid) = @_;
2134: #already url style courseid
2135: return $courseid if ($courseid =~ m{^/});
2136:
2137: if (exists($env{'course.'.$courseid.'.num'})) {
2138: my $cnum = $env{'course.'.$courseid.'.num'};
2139: my $cdom = $env{'course.'.$courseid.'.domain'};
2140: return "/$cdom/$cnum";
2141: }
2142:
2143: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2144: if (exists($courseinfo{'num'})) {
2145: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2146: }
2147:
2148: return undef;
2149: }
2150:
2151: sub getsection {
2152: my ($udom,$unam,$courseid)=@_;
2153: my $cachetime=1800;
2154:
2155: my $hashid="$udom:$unam:$courseid";
2156: my ($result,$cached)=&is_cached_new('getsection',$hashid);
2157: if (defined($cached)) { return $result; }
2158:
2159: my %Pending;
2160: my %Expired;
2161: #
2162: # Each role can either have not started yet (pending), be active,
2163: # or have expired.
2164: #
2165: # If there is an active role, we are done.
2166: #
2167: # If there is more than one role which has not started yet,
2168: # choose the one which will start sooner
2169: # If there is one role which has not started yet, return it.
2170: #
2171: # If there is more than one expired role, choose the one which ended last.
2172: # If there is a role which has expired, return it.
2173: #
2174: $courseid = &courseid_to_courseurl($courseid);
2175: my %roleshash = &dump('roles',$udom,$unam,$courseid);
2176: foreach my $key (keys(%roleshash)) {
2177: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
2178: my $section=$1;
2179: if ($key eq $courseid.'_st') { $section=''; }
2180: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
2181: my $now=time;
2182: if (defined($end) && $end && ($now > $end)) {
2183: $Expired{$end}=$section;
2184: next;
2185: }
2186: if (defined($start) && $start && ($now < $start)) {
2187: $Pending{$start}=$section;
2188: next;
2189: }
2190: return &do_cache_new('getsection',$hashid,$section,$cachetime);
2191: }
2192: #
2193: # Presumedly there will be few matching roles from the above
2194: # loop and the sorting time will be negligible.
2195: if (scalar(keys(%Pending))) {
2196: my ($time) = sort {$a <=> $b} keys(%Pending);
2197: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
2198: }
2199: if (scalar(keys(%Expired))) {
2200: my @sorted = sort {$a <=> $b} keys(%Expired);
2201: my $time = pop(@sorted);
2202: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
2203: }
2204: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
2205: }
2206:
2207: sub save_cache {
2208: &purge_remembered();
2209: #&Apache::loncommon::validate_page();
2210: undef(%env);
2211: undef($env_loaded);
2212: }
2213:
2214: my $to_remember=-1;
2215: my %remembered;
2216: my %accessed;
2217: my $kicks=0;
2218: my $hits=0;
2219: sub make_key {
2220: my ($name,$id) = @_;
2221: if (length($id) > 65
2222: && length(&escape($id)) > 200) {
2223: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2224: }
2225: return &escape($name.':'.$id);
2226: }
2227:
2228: sub devalidate_cache_new {
2229: my ($name,$id,$debug) = @_;
2230: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
2231: $id=&make_key($name,$id);
2232: $memcache->delete($id);
2233: delete($remembered{$id});
2234: delete($accessed{$id});
2235: }
2236:
2237: sub is_cached_new {
2238: my ($name,$id,$debug) = @_;
2239: $id=&make_key($name,$id);
2240: if (exists($remembered{$id})) {
2241: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
2242: $accessed{$id}=[&gettimeofday()];
2243: $hits++;
2244: return ($remembered{$id},1);
2245: }
2246: my $value = $memcache->get($id);
2247: if (!(defined($value))) {
2248: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
2249: return (undef,undef);
2250: }
2251: if ($value eq '__undef__') {
2252: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2253: $value=undef;
2254: }
2255: &make_room($id,$value,$debug);
2256: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2257: return ($value,1);
2258: }
2259:
2260: sub do_cache_new {
2261: my ($name,$id,$value,$time,$debug) = @_;
2262: $id=&make_key($name,$id);
2263: my $setvalue=$value;
2264: if (!defined($setvalue)) {
2265: $setvalue='__undef__';
2266: }
2267: if (!defined($time) ) {
2268: $time=600;
2269: }
2270: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
2271: my $result = $memcache->set($id,$setvalue,$time);
2272: if (! $result) {
2273: &logthis("caching of id -> $id failed");
2274: $memcache->disconnect_all();
2275: }
2276: # need to make a copy of $value
2277: &make_room($id,$value,$debug);
2278: return $value;
2279: }
2280:
2281: sub make_room {
2282: my ($id,$value,$debug)=@_;
2283:
2284: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2285: : $value;
2286: if ($to_remember<0) { return; }
2287: $accessed{$id}=[&gettimeofday()];
2288: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2289: my $to_kick;
2290: my $max_time=0;
2291: foreach my $other (keys(%accessed)) {
2292: if (&tv_interval($accessed{$other}) > $max_time) {
2293: $to_kick=$other;
2294: $max_time=&tv_interval($accessed{$other});
2295: }
2296: }
2297: delete($remembered{$to_kick});
2298: delete($accessed{$to_kick});
2299: $kicks++;
2300: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
2301: return;
2302: }
2303:
2304: sub purge_remembered {
2305: #&logthis("Tossing ".scalar(keys(%remembered)));
2306: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
2307: undef(%remembered);
2308: undef(%accessed);
2309: }
2310: # ------------------------------------- Read an entry from a user's environment
2311:
2312: sub userenvironment {
2313: my ($udom,$unam,@what)=@_;
2314: my $items;
2315: foreach my $item (@what) {
2316: $items.=&escape($item).'&';
2317: }
2318: $items=~s/\&$//;
2319: my %returnhash=();
2320: my $uhome = &homeserver($unam,$udom);
2321: unless ($uhome eq 'no_host') {
2322: my @answer=split(/\&/,
2323: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
2324: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2325: return %returnhash;
2326: }
2327: my $i;
2328: for ($i=0;$i<=$#what;$i++) {
2329: $returnhash{$what[$i]}=&unescape($answer[$i]);
2330: }
2331: }
2332: return %returnhash;
2333: }
2334:
2335: # ---------------------------------------------------------- Get a studentphoto
2336: sub studentphoto {
2337: my ($udom,$unam,$ext) = @_;
2338: my $home=&Apache::lonnet::homeserver($unam,$udom);
2339: if (defined($env{'request.course.id'})) {
2340: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
2341: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2342: return(&retrievestudentphoto($udom,$unam,$ext));
2343: } else {
2344: my ($result,$perm_reqd)=
2345: &Apache::lonnet::auto_photo_permission($unam,$udom);
2346: if ($result eq 'ok') {
2347: if (!($perm_reqd eq 'yes')) {
2348: return(&retrievestudentphoto($udom,$unam,$ext));
2349: }
2350: }
2351: }
2352: }
2353: } else {
2354: my ($result,$perm_reqd) =
2355: &Apache::lonnet::auto_photo_permission($unam,$udom);
2356: if ($result eq 'ok') {
2357: if (!($perm_reqd eq 'yes')) {
2358: return(&retrievestudentphoto($udom,$unam,$ext));
2359: }
2360: }
2361: }
2362: return '/adm/lonKaputt/lonlogo_broken.gif';
2363: }
2364:
2365: sub retrievestudentphoto {
2366: my ($udom,$unam,$ext,$type) = @_;
2367: my $home=&Apache::lonnet::homeserver($unam,$udom);
2368: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2369: if ($ret eq 'ok') {
2370: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2371: if ($type eq 'thumbnail') {
2372: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2373: }
2374: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2375: return $tokenurl;
2376: } else {
2377: if ($type eq 'thumbnail') {
2378: return '/adm/lonKaputt/genericstudent_tn.gif';
2379: } else {
2380: return '/adm/lonKaputt/lonlogo_broken.gif';
2381: }
2382: }
2383: }
2384:
2385: # -------------------------------------------------------------------- New chat
2386:
2387: sub chatsend {
2388: my ($newentry,$anon,$group)=@_;
2389: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2390: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2391: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
2392: &reply('chatsend:'.$cdom.':'.$cnum.':'.
2393: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
2394: &escape($newentry)).':'.$group,$chome);
2395: }
2396:
2397: # ------------------------------------------ Find current version of a resource
2398:
2399: sub getversion {
2400: my $fname=&clutter(shift);
2401: unless ($fname=~/^\/res\//) { return -1; }
2402: return ¤tversion(&filelocation('',$fname));
2403: }
2404:
2405: sub currentversion {
2406: my $fname=shift;
2407: my $author=$fname;
2408: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2409: my ($udom,$uname)=split(/\//,$author);
2410: my $home=&homeserver($uname,$udom);
2411: if ($home eq 'no_host') {
2412: return -1;
2413: }
2414: my $answer=&reply("currentversion:$fname",$home);
2415: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2416: return -1;
2417: }
2418: return $answer;
2419: }
2420:
2421: #
2422: # Return special version number of resource if set by override, empty otherwise
2423: #
2424: sub usedversion {
2425: my $fname=shift;
2426: unless ($fname) { $fname=$env{'request.uri'}; }
2427: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2428: if ($urlversion) { return $urlversion; }
2429: return '';
2430: }
2431:
2432: # ----------------------------- Subscribe to a resource, return URL if possible
2433:
2434: sub subscribe {
2435: my $fname=shift;
2436: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
2437: $fname=~s/[\n\r]//g;
2438: my $author=$fname;
2439: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2440: my ($udom,$uname)=split(/\//,$author);
2441: my $home=homeserver($uname,$udom);
2442: if ($home eq 'no_host') {
2443: return 'not_found';
2444: }
2445: my $answer=reply("sub:$fname",$home);
2446: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2447: $answer.=' by '.$home;
2448: }
2449: return $answer;
2450: }
2451:
2452: # -------------------------------------------------------------- Replicate file
2453:
2454: sub repcopy {
2455: my $filename=shift;
2456: $filename=~s/\/+/\//g;
2457: my $londocroot = $perlvar{'lonDocRoot'};
2458: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
2459: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
2460: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2461: $filename=~m{^/*(uploaded|editupload)/}) {
2462: return &repcopy_userfile($filename);
2463: }
2464: $filename=~s/[\n\r]//g;
2465: my $transname="$filename.in.transfer";
2466: # FIXME: this should flock
2467: if ((-e $filename) || (-e $transname)) { return 'ok'; }
2468: my $remoteurl=subscribe($filename);
2469: if ($remoteurl =~ /^con_lost by/) {
2470: &logthis("Subscribe returned $remoteurl: $filename");
2471: return 'unavailable';
2472: } elsif ($remoteurl eq 'not_found') {
2473: #&logthis("Subscribe returned not_found: $filename");
2474: return 'not_found';
2475: } elsif ($remoteurl =~ /^rejected by/) {
2476: &logthis("Subscribe returned $remoteurl: $filename");
2477: return 'forbidden';
2478: } elsif ($remoteurl eq 'directory') {
2479: return 'ok';
2480: } else {
2481: my $author=$filename;
2482: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2483: my ($udom,$uname)=split(/\//,$author);
2484: my $home=homeserver($uname,$udom);
2485: unless ($home eq $perlvar{'lonHostID'}) {
2486: my @parts=split(/\//,$filename);
2487: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2488: if ($path ne "$londocroot/res") {
2489: &logthis("Malconfiguration for replication: $filename");
2490: return 'bad_request';
2491: }
2492: my $count;
2493: for ($count=5;$count<$#parts;$count++) {
2494: $path.="/$parts[$count]";
2495: if ((-e $path)!=1) {
2496: mkdir($path,0777);
2497: }
2498: }
2499: my $ua=new LWP::UserAgent;
2500: my $request=new HTTP::Request('GET',"$remoteurl");
2501: my $response=$ua->request($request,$transname);
2502: if ($response->is_error()) {
2503: unlink($transname);
2504: my $message=$response->status_line;
2505: &logthis("<font color=\"blue\">WARNING:"
2506: ." LWP get: $message: $filename</font>");
2507: return 'unavailable';
2508: } else {
2509: if ($remoteurl!~/\.meta$/) {
2510: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2511: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2512: if ($mresponse->is_error()) {
2513: unlink($filename.'.meta');
2514: &logthis(
2515: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
2516: }
2517: }
2518: rename($transname,$filename);
2519: return 'ok';
2520: }
2521: }
2522: }
2523: }
2524:
2525: # ------------------------------------------------ Get server side include body
2526: sub ssi_body {
2527: my ($filelink,%form)=@_;
2528: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2529: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2530: }
2531: my $output='';
2532: my $response;
2533: if ($filelink=~/^https?\:/) {
2534: ($output,$response)=&externalssi($filelink);
2535: } else {
2536: $filelink .= $filelink=~/\?/ ? '&' : '?';
2537: $filelink .= 'inhibitmenu=yes';
2538: ($output,$response)=&ssi($filelink,%form);
2539: }
2540: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
2541: $output=~s/^.*?\<body[^\>]*\>//si;
2542: $output=~s/\<\/body\s*\>.*?$//si;
2543: if (wantarray) {
2544: return ($output, $response);
2545: } else {
2546: return $output;
2547: }
2548: }
2549:
2550: # --------------------------------------------------------- Server Side Include
2551:
2552: sub absolute_url {
2553: my ($host_name) = @_;
2554: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2555: if ($host_name eq '') {
2556: $host_name = $ENV{'SERVER_NAME'};
2557: }
2558: return $protocol.$host_name;
2559: }
2560:
2561: #
2562: # Server side include.
2563: # Parameters:
2564: # fn Possibly encrypted resource name/id.
2565: # form Hash that describes how the rendering should be done
2566: # and other things.
2567: # Returns:
2568: # Scalar context: The content of the response.
2569: # Array context: 2 element list of the content and the full response object.
2570: #
2571: sub ssi {
2572:
2573: my ($fn,%form)=@_;
2574: my $ua=new LWP::UserAgent;
2575: my $request;
2576:
2577: $form{'no_update_last_known'}=1;
2578: &Apache::lonenc::check_encrypt(\$fn);
2579: if (%form) {
2580: $request=new HTTP::Request('POST',&absolute_url().$fn);
2581: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
2582: } else {
2583: $request=new HTTP::Request('GET',&absolute_url().$fn);
2584: }
2585:
2586: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2587: my $response= $ua->request($request);
2588: my $content = Encode::decode_utf8($response->content);
2589: if (wantarray) {
2590: return ($content, $response);
2591: } else {
2592: return $content;
2593: }
2594: }
2595:
2596: sub externalssi {
2597: my ($url)=@_;
2598: my $ua=new LWP::UserAgent;
2599: my $request=new HTTP::Request('GET',$url);
2600: my $response=$ua->request($request);
2601: if (wantarray) {
2602: return ($response->content, $response);
2603: } else {
2604: return $response->content;
2605: }
2606: }
2607:
2608: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2609:
2610: sub allowuploaded {
2611: my ($srcurl,$url)=@_;
2612: $url=&clutter(&declutter($url));
2613: my $dir=$url;
2614: $dir=~s/\/[^\/]+$//;
2615: my %httpref=();
2616: my $httpurl=&hreflocation('',$url);
2617: $httpref{'httpref.'.$httpurl}=$srcurl;
2618: &Apache::lonnet::appenv(\%httpref);
2619: }
2620:
2621: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
2622: # input: action, courseID, current domain, intended
2623: # path to file, source of file, instruction to parse file for objects,
2624: # ref to hash for embedded objects,
2625: # ref to hash for codebase of java objects.
2626: # reference to scalar to accommodate mime type determined
2627: # from File::MMagic if $parser = parse.
2628: #
2629: # output: url to file (if action was uploaddoc),
2630: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
2631: #
2632: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2633: # course.
2634: #
2635: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2636: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2637: # course's home server.
2638: #
2639: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2640: # be copied from $source (current location) to
2641: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2642: # and will then be copied to
2643: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2644: # course's home server.
2645: #
2646: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2647: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
2648: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2649: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2650: # in course's home server.
2651: #
2652:
2653: sub process_coursefile {
2654: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2655: $mimetype)=@_;
2656: my $fetchresult;
2657: my $home=&homeserver($docuname,$docudom);
2658: if ($action eq 'propagate') {
2659: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2660: $home);
2661: } else {
2662: my $fpath = '';
2663: my $fname = $file;
2664: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2665: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2666: my $filepath = &build_filepath($fpath);
2667: if ($action eq 'copy') {
2668: if ($source eq '') {
2669: $fetchresult = 'no source file';
2670: return $fetchresult;
2671: } else {
2672: my $destination = $filepath.'/'.$fname;
2673: rename($source,$destination);
2674: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2675: $home);
2676: }
2677: } elsif ($action eq 'uploaddoc') {
2678: open(my $fh,'>'.$filepath.'/'.$fname);
2679: print $fh $env{'form.'.$source};
2680: close($fh);
2681: if ($parser eq 'parse') {
2682: my $mm = new File::MMagic;
2683: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2684: if ($type eq 'text/html') {
2685: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2686: unless ($parse_result eq 'ok') {
2687: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2688: }
2689: }
2690: if (ref($mimetype)) {
2691: $$mimetype = $type;
2692: }
2693: }
2694: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2695: $home);
2696: if ($fetchresult eq 'ok') {
2697: return '/uploaded/'.$fpath.'/'.$fname;
2698: } else {
2699: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2700: ' to host '.$home.': '.$fetchresult);
2701: return '/adm/notfound.html';
2702: }
2703: }
2704: }
2705: unless ( $fetchresult eq 'ok') {
2706: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2707: ' to host '.$home.': '.$fetchresult);
2708: }
2709: return $fetchresult;
2710: }
2711:
2712: sub build_filepath {
2713: my ($fpath) = @_;
2714: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2715: unless ($fpath eq '') {
2716: my @parts=split('/',$fpath);
2717: foreach my $part (@parts) {
2718: $filepath.= '/'.$part;
2719: if ((-e $filepath)!=1) {
2720: mkdir($filepath,0777);
2721: }
2722: }
2723: }
2724: return $filepath;
2725: }
2726:
2727: sub store_edited_file {
2728: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
2729: my $file = $primary_url;
2730: $file =~ s#^/uploaded/$docudom/$docuname/##;
2731: my $fpath = '';
2732: my $fname = $file;
2733: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2734: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2735: my $filepath = &build_filepath($fpath);
2736: open(my $fh,'>'.$filepath.'/'.$fname);
2737: print $fh $content;
2738: close($fh);
2739: my $home=&homeserver($docuname,$docudom);
2740: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2741: $home);
2742: if ($$fetchresult eq 'ok') {
2743: return '/uploaded/'.$fpath.'/'.$fname;
2744: } else {
2745: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2746: ' to host '.$home.': '.$$fetchresult);
2747: return '/adm/notfound.html';
2748: }
2749: }
2750:
2751: sub clean_filename {
2752: my ($fname,$args)=@_;
2753: # Replace Windows backslashes by forward slashes
2754: $fname=~s/\\/\//g;
2755: if (!$args->{'keep_path'}) {
2756: # Get rid of everything but the actual filename
2757: $fname=~s/^.*\/([^\/]+)$/$1/;
2758: }
2759: # Replace spaces by underscores
2760: $fname=~s/\s+/\_/g;
2761: # Replace all other weird characters by nothing
2762: $fname=~s{[^/\w\.\-]}{}g;
2763: # Replace all .\d. sequences with _\d. so they no longer look like version
2764: # numbers
2765: $fname=~s/\.(\d+)(?=\.)/_$1/g;
2766: return $fname;
2767: }
2768: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2769: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2770: # image with the same aspect ratio as the original, but with dimensions which do
2771: # not exceed $resizewidth and $resizeheight.
2772:
2773: sub resizeImage {
2774: my ($img_path,$resizewidth,$resizeheight) = @_;
2775: my $ima = Image::Magick->new;
2776: my $resized;
2777: if (-e $img_path) {
2778: $ima->Read($img_path);
2779: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2780: my $width = $ima->Get('width');
2781: my $height = $ima->Get('height');
2782: if ($width > $resizewidth) {
2783: my $factor = $width/$resizewidth;
2784: my $newheight = $height/$factor;
2785: $ima->Scale(width=>$resizewidth,height=>$newheight);
2786: $resized = 1;
2787: }
2788: }
2789: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2790: my $width = $ima->Get('width');
2791: my $height = $ima->Get('height');
2792: if ($height > $resizeheight) {
2793: my $factor = $height/$resizeheight;
2794: my $newwidth = $width/$factor;
2795: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2796: $resized = 1;
2797: }
2798: }
2799: if ($resized) {
2800: $ima->Write($img_path);
2801: }
2802: }
2803: return;
2804: }
2805:
2806: # --------------- Take an uploaded file and put it into the userfiles directory
2807: # input: $formname - the contents of the file are in $env{"form.$formname"}
2808: # the desired filename is in $env{"form.$formname.filename"}
2809: # $context - possible values: coursedoc, existingfile, overwrite,
2810: # canceloverwrite, or ''.
2811: # if 'coursedoc': upload to the current course
2812: # if 'existingfile': write file to tmp/overwrites directory
2813: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2814: # $context is passed as argument to &finishuserfileupload
2815: # $subdir - directory in userfile to store the file into
2816: # $parser - instruction to parse file for objects ($parser = parse)
2817: # $allfiles - reference to hash for embedded objects
2818: # $codebase - reference to hash for codebase of java objects
2819: # $desuname - username for permanent storage of uploaded file
2820: # $dsetudom - domain for permanaent storage of uploaded file
2821: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2822: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
2823: # $resizewidth - width (pixels) to which to resize uploaded image
2824: # $resizeheight - height (pixels) to which to resize uploaded image
2825: # $mimetype - reference to scalar to accommodate mime type determined
2826: # from File::MMagic.
2827: #
2828: # output: url of file in userspace, or error: <message>
2829: # or /adm/notfound.html if failure to upload occurse
2830:
2831: sub userfileupload {
2832: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
2833: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
2834: if (!defined($subdir)) { $subdir='unknown'; }
2835: my $fname=$env{'form.'.$formname.'.filename'};
2836: $fname=&clean_filename($fname);
2837: # See if there is anything left
2838: unless ($fname) { return 'error: no uploaded file'; }
2839: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2840: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2841: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2842: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2843: my $now = time;
2844: my $filepath;
2845: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
2846: $filepath = 'tmp/helprequests/'.$now;
2847: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2848: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2849: '_'.$env{'user.domain'}.'/pending';
2850: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2851: my ($docuname,$docudom);
2852: if ($destudom) {
2853: $docudom = $destudom;
2854: } else {
2855: $docudom = $env{'user.domain'};
2856: }
2857: if ($destuname) {
2858: $docuname = $destuname;
2859: } else {
2860: $docuname = $env{'user.name'};
2861: }
2862: if (exists($env{'form.group'})) {
2863: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2864: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2865: }
2866: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2867: if ($context eq 'canceloverwrite') {
2868: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2869: if (-e $tempfile) {
2870: my @info = stat($tempfile);
2871: if ($info[9] eq $env{'form.timestamp'}) {
2872: unlink($tempfile);
2873: }
2874: }
2875: return;
2876: }
2877: }
2878: # Create the directory if not present
2879: my @parts=split(/\//,$filepath);
2880: my $fullpath = $perlvar{'lonDaemons'};
2881: for (my $i=0;$i<@parts;$i++) {
2882: $fullpath .= '/'.$parts[$i];
2883: if ((-e $fullpath)!=1) {
2884: mkdir($fullpath,0777);
2885: }
2886: }
2887: open(my $fh,'>'.$fullpath.'/'.$fname);
2888: print $fh $env{'form.'.$formname};
2889: close($fh);
2890: if ($context eq 'existingfile') {
2891: my @info = stat($fullpath.'/'.$fname);
2892: return ($fullpath.'/'.$fname,$info[9]);
2893: } else {
2894: return $fullpath.'/'.$fname;
2895: }
2896: }
2897: if ($subdir eq 'scantron') {
2898: $fname = 'scantron_orig_'.$fname;
2899: } else {
2900: $fname="$subdir/$fname";
2901: }
2902: if ($context eq 'coursedoc') {
2903: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2904: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2905: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
2906: return &finishuserfileupload($docuname,$docudom,
2907: $formname,$fname,$parser,$allfiles,
2908: $codebase,$thumbwidth,$thumbheight,
2909: $resizewidth,$resizeheight,$context,$mimetype);
2910: } else {
2911: $fname=$env{'form.folder'}.'/'.$fname;
2912: return &process_coursefile('uploaddoc',$docuname,$docudom,
2913: $fname,$formname,$parser,
2914: $allfiles,$codebase,$mimetype);
2915: }
2916: } elsif (defined($destuname)) {
2917: my $docuname=$destuname;
2918: my $docudom=$destudom;
2919: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2920: $parser,$allfiles,$codebase,
2921: $thumbwidth,$thumbheight,
2922: $resizewidth,$resizeheight,$context,$mimetype);
2923: } else {
2924: my $docuname=$env{'user.name'};
2925: my $docudom=$env{'user.domain'};
2926: if (exists($env{'form.group'})) {
2927: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2928: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2929: }
2930: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2931: $parser,$allfiles,$codebase,
2932: $thumbwidth,$thumbheight,
2933: $resizewidth,$resizeheight,$context,$mimetype);
2934: }
2935: }
2936:
2937: sub finishuserfileupload {
2938: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
2939: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
2940: my $path=$docudom.'/'.$docuname.'/';
2941: my $filepath=$perlvar{'lonDocRoot'};
2942:
2943: my ($fnamepath,$file,$fetchthumb);
2944: $file=$fname;
2945: if ($fname=~m|/|) {
2946: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2947: $path.=$fnamepath.'/';
2948: }
2949: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
2950: my $count;
2951: for ($count=4;$count<=$#parts;$count++) {
2952: $filepath.="/$parts[$count]";
2953: if ((-e $filepath)!=1) {
2954: mkdir($filepath,0777);
2955: }
2956: }
2957:
2958: # Save the file
2959: {
2960: if (!open(FH,'>'.$filepath.'/'.$file)) {
2961: &logthis('Failed to create '.$filepath.'/'.$file);
2962: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2963: return '/adm/notfound.html';
2964: }
2965: if ($context eq 'overwrite') {
2966: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
2967: my $target = $filepath.'/'.$file;
2968: if (-e $source) {
2969: my @info = stat($source);
2970: if ($info[9] eq $env{'form.timestamp'}) {
2971: unless (&File::Copy::move($source,$target)) {
2972: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2973: return "Moving from $source failed";
2974: }
2975: } else {
2976: return "Temporary file: $source had unexpected date/time for last modification";
2977: }
2978: } else {
2979: return "Temporary file: $source missing";
2980: }
2981: } elsif (!print FH ($env{'form.'.$formname})) {
2982: &logthis('Failed to write to '.$filepath.'/'.$file);
2983: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2984: return '/adm/notfound.html';
2985: }
2986: close(FH);
2987: if ($resizewidth && $resizeheight) {
2988: my $mm = new File::MMagic;
2989: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2990: if ($mime_type =~ m{^image/}) {
2991: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2992: }
2993: }
2994: }
2995: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
2996: if (ref($mimetype)) {
2997: if ($$mimetype eq '') {
2998: my $mm = new File::MMagic;
2999: my $type = $mm->checktype_filename($filepath.'/'.$file);
3000: $$mimetype = $type;
3001: }
3002: }
3003: }
3004: if ($parser eq 'parse') {
3005: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
3006: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3007: $allfiles,$codebase);
3008: unless ($parse_result eq 'ok') {
3009: &logthis('Failed to parse '.$filepath.$file.
3010: ' for embedded media: '.$parse_result);
3011: }
3012: }
3013: }
3014: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3015: my $input = $filepath.'/'.$file;
3016: my $output = $filepath.'/'.'tn-'.$file;
3017: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3018: system("convert -sample $thumbsize $input $output");
3019: if (-e $filepath.'/'.'tn-'.$file) {
3020: $fetchthumb = 1;
3021: }
3022: }
3023:
3024: # Notify homeserver to grep it
3025: #
3026: my $docuhome=&homeserver($docuname,$docudom);
3027: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
3028: if ($fetchresult eq 'ok') {
3029: if ($fetchthumb) {
3030: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3031: if ($thumbresult ne 'ok') {
3032: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3033: $docuhome.': '.$thumbresult);
3034: }
3035: }
3036: #
3037: # Return the URL to it
3038: return '/uploaded/'.$path.$file;
3039: } else {
3040: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3041: ': '.$fetchresult);
3042: return '/adm/notfound.html';
3043: }
3044: }
3045:
3046: sub extract_embedded_items {
3047: my ($fullpath,$allfiles,$codebase,$content) = @_;
3048: my @state = ();
3049: my (%lastids,%related,%shockwave,%flashvars);
3050: my %javafiles = (
3051: codebase => '',
3052: code => '',
3053: archive => ''
3054: );
3055: my %mediafiles = (
3056: src => '',
3057: movie => '',
3058: );
3059: my $p;
3060: if ($content) {
3061: $p = HTML::LCParser->new($content);
3062: } else {
3063: $p = HTML::LCParser->new($fullpath);
3064: }
3065: while (my $t=$p->get_token()) {
3066: if ($t->[0] eq 'S') {
3067: my ($tagname, $attr) = ($t->[1],$t->[2]);
3068: push(@state, $tagname);
3069: if (lc($tagname) eq 'allow') {
3070: &add_filetype($allfiles,$attr->{'src'},'src');
3071: }
3072: if (lc($tagname) eq 'img') {
3073: &add_filetype($allfiles,$attr->{'src'},'src');
3074: }
3075: if (lc($tagname) eq 'a') {
3076: &add_filetype($allfiles,$attr->{'href'},'href');
3077: }
3078: if (lc($tagname) eq 'script') {
3079: my $src;
3080: if ($attr->{'archive'} =~ /\.jar$/i) {
3081: &add_filetype($allfiles,$attr->{'archive'},'archive');
3082: } else {
3083: if ($attr->{'src'} ne '') {
3084: $src = $attr->{'src'};
3085: &add_filetype($allfiles,$src,'src');
3086: }
3087: }
3088: my $text = $p->get_trimmed_text();
3089: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3090: my @swfargs = split(/,/,$1);
3091: foreach my $item (@swfargs) {
3092: $item =~ s/["']//g;
3093: $item =~ s/^\s+//;
3094: $item =~ s/\s+$//;
3095: }
3096: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3097: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3098: push(@{$related{$swfargs[0]}},$swfargs[2]);
3099: } else {
3100: $related{$swfargs[0]} = [$swfargs[2]];
3101: }
3102: }
3103: }
3104: }
3105: if (lc($tagname) eq 'link') {
3106: if (lc($attr->{'rel'}) eq 'stylesheet') {
3107: &add_filetype($allfiles,$attr->{'href'},'href');
3108: }
3109: }
3110: if (lc($tagname) eq 'object' ||
3111: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3112: foreach my $item (keys(%javafiles)) {
3113: $javafiles{$item} = '';
3114: }
3115: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3116: $lastids{lc($tagname)} = $attr->{'id'};
3117: }
3118: }
3119: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3120: my $name = lc($attr->{'name'});
3121: foreach my $item (keys(%javafiles)) {
3122: if ($name eq $item) {
3123: $javafiles{$item} = $attr->{'value'};
3124: last;
3125: }
3126: }
3127: my $pathfrom;
3128: foreach my $item (keys(%mediafiles)) {
3129: if ($name eq $item) {
3130: $pathfrom = $attr->{'value'};
3131: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3132: &add_filetype($allfiles,$pathfrom,$name);
3133: last;
3134: }
3135: }
3136: if ($name eq 'flashvars') {
3137: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3138: }
3139: if ($pathfrom ne '') {
3140: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3141: $pathfrom);
3142: }
3143: }
3144: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3145: foreach my $item (keys(%javafiles)) {
3146: if ($attr->{$item}) {
3147: $javafiles{$item} = $attr->{$item};
3148: last;
3149: }
3150: }
3151: foreach my $item (keys(%mediafiles)) {
3152: if ($attr->{$item}) {
3153: &add_filetype($allfiles,$attr->{$item},$item);
3154: last;
3155: }
3156: }
3157: if (lc($tagname) eq 'embed') {
3158: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3159: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3160: $attr->{'src'});
3161: }
3162: }
3163: }
3164: if ($t->[4] =~ m{/>$}) {
3165: pop(@state);
3166: }
3167: } elsif ($t->[0] eq 'E') {
3168: my ($tagname) = ($t->[1]);
3169: if ($javafiles{'codebase'} ne '') {
3170: $javafiles{'codebase'} .= '/';
3171: }
3172: if (lc($tagname) eq 'applet' ||
3173: lc($tagname) eq 'object' ||
3174: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3175: ) {
3176: foreach my $item (keys(%javafiles)) {
3177: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3178: my $file=$javafiles{'codebase'}.$javafiles{$item};
3179: &add_filetype($allfiles,$file,$item);
3180: }
3181: }
3182: }
3183: pop @state;
3184: }
3185: }
3186: foreach my $id (sort(keys(%flashvars))) {
3187: if ($shockwave{$id} ne '') {
3188: my @pairs = split(/\&/,$flashvars{$id});
3189: foreach my $pair (@pairs) {
3190: my ($key,$value) = split(/\=/,$pair);
3191: if ($key eq 'thumb') {
3192: &add_filetype($allfiles,$value,$key);
3193: } elsif ($key eq 'content') {
3194: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3195: my ($ext) = ($value =~ /\.([^.]+)$/);
3196: if ($ext ne '') {
3197: &add_filetype($allfiles,$path.$value,$ext);
3198: }
3199: }
3200: }
3201: }
3202: }
3203: return 'ok';
3204: }
3205:
3206: sub add_filetype {
3207: my ($allfiles,$file,$type)=@_;
3208: if (exists($allfiles->{$file})) {
3209: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3210: push(@{$allfiles->{$file}}, &escape($type));
3211: }
3212: } else {
3213: @{$allfiles->{$file}} = (&escape($type));
3214: }
3215: }
3216:
3217: sub embedded_dependency {
3218: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3219: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3220: if (($identifier ne '') &&
3221: (ref($related->{$identifier}) eq 'ARRAY') &&
3222: ($pathfrom ne '')) {
3223: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3224: foreach my $dep (@{$related->{$identifier}}) {
3225: &add_filetype($allfiles,$path.$dep,'object');
3226: }
3227: }
3228: }
3229: return;
3230: }
3231:
3232: sub removeuploadedurl {
3233: my ($url)=@_;
3234: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
3235: return &removeuserfile($uname,$udom,$fname);
3236: }
3237:
3238: sub removeuserfile {
3239: my ($docuname,$docudom,$fname)=@_;
3240: my $home=&homeserver($docuname,$docudom);
3241: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
3242: if ($result eq 'ok') {
3243: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3244: my $metafile = $fname.'.meta';
3245: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
3246: my $url = "/uploaded/$docudom/$docuname/$fname";
3247: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
3248: my $sqlresult =
3249: &update_portfolio_table($docuname,$docudom,$file,
3250: 'portfolio_metadata',$group,
3251: 'delete');
3252: }
3253: }
3254: return $result;
3255: }
3256:
3257: sub mkdiruserfile {
3258: my ($docuname,$docudom,$dir)=@_;
3259: my $home=&homeserver($docuname,$docudom);
3260: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3261: }
3262:
3263: sub renameuserfile {
3264: my ($docuname,$docudom,$old,$new)=@_;
3265: my $home=&homeserver($docuname,$docudom);
3266: my $result = &reply("renameuserfile:$docudom:$docuname:".
3267: &escape("$old").':'.&escape("$new"),$home);
3268: if ($result eq 'ok') {
3269: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3270: my $oldmeta = $old.'.meta';
3271: my $newmeta = $new.'.meta';
3272: my $metaresult =
3273: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
3274: my $url = "/uploaded/$docudom/$docuname/$old";
3275: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
3276: my $sqlresult =
3277: &update_portfolio_table($docuname,$docudom,$file,
3278: 'portfolio_metadata',$group,
3279: 'delete');
3280: }
3281: }
3282: return $result;
3283: }
3284:
3285: # ------------------------------------------------------------------------- Log
3286:
3287: sub log {
3288: my ($dom,$nam,$hom,$what)=@_;
3289: return critical("log:$dom:$nam:$what",$hom);
3290: }
3291:
3292: # ------------------------------------------------------------------ Course Log
3293: #
3294: # This routine flushes several buffers of non-mission-critical nature
3295: #
3296:
3297: sub flushcourselogs {
3298: &logthis('Flushing log buffers');
3299: #
3300: # course logs
3301: # This is a log of all transactions in a course, which can be used
3302: # for data mining purposes
3303: #
3304: # It also collects the courseid database, which lists last transaction
3305: # times and course titles for all courseids
3306: #
3307: my %courseidbuffer=();
3308: foreach my $crsid (keys(%courselogs)) {
3309: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
3310: &escape($courselogs{$crsid}),
3311: $coursehombuf{$crsid}) eq 'ok') {
3312: delete $courselogs{$crsid};
3313: } else {
3314: &logthis('Failed to flush log buffer for '.$crsid);
3315: if (length($courselogs{$crsid})>40000) {
3316: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
3317: " exceeded maximum size, deleting.</font>");
3318: delete $courselogs{$crsid};
3319: }
3320: }
3321: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
3322: 'description' => $coursedescrbuf{$crsid},
3323: 'inst_code' => $courseinstcodebuf{$crsid},
3324: 'type' => $coursetypebuf{$crsid},
3325: 'owner' => $courseownerbuf{$crsid},
3326: };
3327: }
3328: #
3329: # Write course id database (reverse lookup) to homeserver of courses
3330: # Is used in pickcourse
3331: #
3332: foreach my $crs_home (keys(%courseidbuffer)) {
3333: my $response = &courseidput(&host_domain($crs_home),
3334: $courseidbuffer{$crs_home},
3335: $crs_home,'timeonly');
3336: }
3337: #
3338: # File accesses
3339: # Writes to the dynamic metadata of resources to get hit counts, etc.
3340: #
3341: foreach my $entry (keys(%accesshash)) {
3342: if ($entry =~ /___count$/) {
3343: my ($dom,$name);
3344: ($dom,$name,undef)=
3345: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
3346: if (! defined($dom) || $dom eq '' ||
3347: ! defined($name) || $name eq '') {
3348: my $cid = $env{'request.course.id'};
3349: $dom = $env{'request.'.$cid.'.domain'};
3350: $name = $env{'request.'.$cid.'.num'};
3351: }
3352: my $value = $accesshash{$entry};
3353: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3354: my %temphash=($url => $value);
3355: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3356: if ($result eq 'ok') {
3357: delete $accesshash{$entry};
3358: }
3359: } else {
3360: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
3361: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
3362: my %temphash=($entry => $accesshash{$entry});
3363: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3364: delete $accesshash{$entry};
3365: }
3366: }
3367: }
3368: #
3369: # Roles
3370: # Reverse lookup of user roles for course faculty/staff and co-authorship
3371: #
3372: foreach my $entry (keys(%userrolehash)) {
3373: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
3374: split(/\:/,$entry);
3375: if (&Apache::lonnet::put('nohist_userroles',
3376: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
3377: $rudom,$runame) eq 'ok') {
3378: delete $userrolehash{$entry};
3379: }
3380: }
3381: #
3382: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3383: #
3384: my %domrolebuffer = ();
3385: foreach my $entry (keys(%domainrolehash)) {
3386: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
3387: if ($domrolebuffer{$rudom}) {
3388: $domrolebuffer{$rudom}.='&'.&escape($entry).
3389: '='.&escape($domainrolehash{$entry});
3390: } else {
3391: $domrolebuffer{$rudom}.=&escape($entry).
3392: '='.&escape($domainrolehash{$entry});
3393: }
3394: delete $domainrolehash{$entry};
3395: }
3396: foreach my $dom (keys(%domrolebuffer)) {
3397: my %servers = &get_servers($dom,'library');
3398: foreach my $tryserver (keys(%servers)) {
3399: unless (&reply('domroleput:'.$dom.':'.
3400: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3401: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3402: }
3403: }
3404: }
3405: $dumpcount++;
3406: }
3407:
3408: sub courselog {
3409: my $what=shift;
3410: $what=time.':'.$what;
3411: unless ($env{'request.course.id'}) { return ''; }
3412: $coursedombuf{$env{'request.course.id'}}=
3413: $env{'course.'.$env{'request.course.id'}.'.domain'};
3414: $coursenumbuf{$env{'request.course.id'}}=
3415: $env{'course.'.$env{'request.course.id'}.'.num'};
3416: $coursehombuf{$env{'request.course.id'}}=
3417: $env{'course.'.$env{'request.course.id'}.'.home'};
3418: $coursedescrbuf{$env{'request.course.id'}}=
3419: $env{'course.'.$env{'request.course.id'}.'.description'};
3420: $courseinstcodebuf{$env{'request.course.id'}}=
3421: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3422: $courseownerbuf{$env{'request.course.id'}}=
3423: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
3424: $coursetypebuf{$env{'request.course.id'}}=
3425: $env{'course.'.$env{'request.course.id'}.'.type'};
3426: if (defined $courselogs{$env{'request.course.id'}}) {
3427: $courselogs{$env{'request.course.id'}}.='&'.$what;
3428: } else {
3429: $courselogs{$env{'request.course.id'}}.=$what;
3430: }
3431: if (length($courselogs{$env{'request.course.id'}})>4048) {
3432: &flushcourselogs();
3433: }
3434: }
3435:
3436: sub courseacclog {
3437: my $fnsymb=shift;
3438: unless ($env{'request.course.id'}) { return ''; }
3439: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
3440: if ($fnsymb=~/$LONCAPA::assess_re/) {
3441: $what.=':POST';
3442: # FIXME: Probably ought to escape things....
3443: foreach my $key (keys(%env)) {
3444: if ($key=~/^form\.(.*)/) {
3445: my $formitem = $1;
3446: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3447: $what.=':'.$formitem.'='.$env{$key};
3448: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3449: $what.=':'.$formitem.'='.$env{$key};
3450: }
3451: }
3452: }
3453: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3454: # FIXME: We should not be depending on a form parameter that someone
3455: # editing lonsearchcat.pm might change in the future.
3456: if ($env{'form.phase'} eq 'course_search') {
3457: $what.= ':POST';
3458: # FIXME: Probably ought to escape things....
3459: foreach my $element ('courseexp','crsfulltext','crsrelated',
3460: 'crsdiscuss') {
3461: $what.=':'.$element.'='.$env{'form.'.$element};
3462: }
3463: }
3464: }
3465: &courselog($what);
3466: }
3467:
3468: sub countacc {
3469: my $url=&declutter(shift);
3470: return if (! defined($url) || $url eq '');
3471: unless ($env{'request.course.id'}) { return ''; }
3472: #
3473: # Mark that this url was used in this course
3474: #
3475: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
3476: #
3477: # Increase the access count for this resource in this child process
3478: #
3479: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
3480: $accesshash{$key}++;
3481: }
3482:
3483: sub linklog {
3484: my ($from,$to)=@_;
3485: $from=&declutter($from);
3486: $to=&declutter($to);
3487: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3488: $accesshash{$to.'___'.$from.'___goto'}=1;
3489: }
3490:
3491: sub statslog {
3492: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3493: if ($users<2) { return; }
3494: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3495: 'course' => $env{'request.course.id'},
3496: 'sections' => '"all"',
3497: 'num_students' => $users,
3498: 'part' => $part,
3499: 'symb' => $symb,
3500: 'mean_tries' => $av_attempts,
3501: 'deg_of_diff' => $degdiff});
3502: foreach my $key (keys(%dynstore)) {
3503: $accesshash{$key}=$dynstore{$key};
3504: }
3505: }
3506:
3507: sub userrolelog {
3508: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
3509: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
3510: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3511: $userrolehash
3512: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3513: =$tend.':'.$tstart;
3514: }
3515: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
3516: $userrolehash
3517: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3518: =$tend.':'.$tstart;
3519: }
3520: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
3521: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3522: $domainrolehash
3523: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3524: = $tend.':'.$tstart;
3525: }
3526: }
3527:
3528: sub courserolelog {
3529: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3530: if (($trole eq 'cc') || ($trole eq 'in') ||
3531: ($trole eq 'ep') || ($trole eq 'ad') ||
3532: ($trole eq 'ta') || ($trole eq 'st') ||
3533: ($trole=~/^cr/) || ($trole eq 'gr') ||
3534: ($trole eq 'co')) {
3535: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3536: my $cdom = $1;
3537: my $cnum = $2;
3538: my $sec = $3;
3539: my $namespace = 'rolelog';
3540: my %storehash = (
3541: role => $trole,
3542: start => $tstart,
3543: end => $tend,
3544: selfenroll => $selfenroll,
3545: context => $context,
3546: );
3547: if ($trole eq 'gr') {
3548: $namespace = 'groupslog';
3549: $storehash{'group'} = $sec;
3550: } else {
3551: $storehash{'section'} = $sec;
3552: }
3553: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
3554: if (($trole ne 'st') || ($sec ne '')) {
3555: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3556: }
3557: }
3558: }
3559: return;
3560: }
3561:
3562: sub get_course_adv_roles {
3563: my ($cid,$codes) = @_;
3564: $cid=$env{'request.course.id'} unless (defined($cid));
3565: my %coursehash=&coursedescription($cid);
3566: my $crstype = &Apache::loncommon::course_type($cid);
3567: my %nothide=();
3568: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3569: if ($user !~ /:/) {
3570: $nothide{join(':',split(/[\@]/,$user))}=1;
3571: } else {
3572: $nothide{$user}=1;
3573: }
3574: }
3575: my %returnhash=();
3576: my %dumphash=
3577: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3578: my $now=time;
3579: my %privileged;
3580: foreach my $entry (keys(%dumphash)) {
3581: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3582: if (($tstart) && ($tstart<0)) { next; }
3583: if (($tend) && ($tend<$now)) { next; }
3584: if (($tstart) && ($now<$tstart)) { next; }
3585: my ($role,$username,$domain,$section)=split(/\:/,$entry);
3586: if ($username eq '' || $domain eq '') { next; }
3587: unless (ref($privileged{$domain}) eq 'HASH') {
3588: my %dompersonnel =
3589: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3590: $privileged{$domain} = {};
3591: foreach my $server (keys(%dompersonnel)) {
3592: if (ref($dompersonnel{$server}) eq 'HASH') {
3593: foreach my $user (keys(%{$dompersonnel{$server}})) {
3594: my ($trole,$uname,$udom) = split(/:/,$user);
3595: $privileged{$udom}{$uname} = 1;
3596: }
3597: }
3598: }
3599: }
3600: if ((exists($privileged{$domain}{$username})) &&
3601: (!$nothide{$username.':'.$domain})) { next; }
3602: if ($role eq 'cr') { next; }
3603: if ($codes) {
3604: if ($section) { $role .= ':'.$section; }
3605: if ($returnhash{$role}) {
3606: $returnhash{$role}.=','.$username.':'.$domain;
3607: } else {
3608: $returnhash{$role}=$username.':'.$domain;
3609: }
3610: } else {
3611: my $key=&plaintext($role,$crstype);
3612: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
3613: if ($returnhash{$key}) {
3614: $returnhash{$key}.=','.$username.':'.$domain;
3615: } else {
3616: $returnhash{$key}=$username.':'.$domain;
3617: }
3618: }
3619: }
3620: return %returnhash;
3621: }
3622:
3623: sub get_my_roles {
3624: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
3625: unless (defined($uname)) { $uname=$env{'user.name'}; }
3626: unless (defined($udom)) { $udom=$env{'user.domain'}; }
3627: my (%dumphash,%nothide);
3628: if ($context eq 'userroles') {
3629: %dumphash = &dump('roles',$udom,$uname);
3630: } else {
3631: %dumphash=
3632: &dump('nohist_userroles',$udom,$uname);
3633: if ($hidepriv) {
3634: my %coursehash=&coursedescription($udom.'_'.$uname);
3635: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3636: if ($user !~ /:/) {
3637: $nothide{join(':',split(/[\@]/,$user))} = 1;
3638: } else {
3639: $nothide{$user} = 1;
3640: }
3641: }
3642: }
3643: }
3644: my %returnhash=();
3645: my $now=time;
3646: my %privileged;
3647: foreach my $entry (keys(%dumphash)) {
3648: my ($role,$tend,$tstart);
3649: if ($context eq 'userroles') {
3650: next if ($entry =~ /^rolesdef/);
3651: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3652: } else {
3653: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3654: }
3655: if (($tstart) && ($tstart<0)) { next; }
3656: my $status = 'active';
3657: if (($tend) && ($tend<=$now)) {
3658: $status = 'previous';
3659: }
3660: if (($tstart) && ($now<$tstart)) {
3661: $status = 'future';
3662: }
3663: if (ref($types) eq 'ARRAY') {
3664: if (!grep(/^\Q$status\E$/,@{$types})) {
3665: next;
3666: }
3667: } else {
3668: if ($status ne 'active') {
3669: next;
3670: }
3671: }
3672: my ($rolecode,$username,$domain,$section,$area);
3673: if ($context eq 'userroles') {
3674: ($area,$rolecode) = split(/_/,$entry);
3675: (undef,$domain,$username,$section) = split(/\//,$area);
3676: } else {
3677: ($role,$username,$domain,$section) = split(/\:/,$entry);
3678: }
3679: if (ref($roledoms) eq 'ARRAY') {
3680: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3681: next;
3682: }
3683: }
3684: if (ref($roles) eq 'ARRAY') {
3685: if (!grep(/^\Q$role\E$/,@{$roles})) {
3686: if ($role =~ /^cr\//) {
3687: if (!grep(/^cr$/,@{$roles})) {
3688: next;
3689: }
3690: } elsif ($role =~ /^gr\//) {
3691: if (!grep(/^gr$/,@{$roles})) {
3692: next;
3693: }
3694: } else {
3695: next;
3696: }
3697: }
3698: }
3699: if ($hidepriv) {
3700: if ($context eq 'userroles') {
3701: if ((&privileged($username,$domain)) &&
3702: (!$nothide{$username.':'.$domain})) {
3703: next;
3704: }
3705: } else {
3706: unless (ref($privileged{$domain}) eq 'HASH') {
3707: my %dompersonnel =
3708: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3709: $privileged{$domain} = {};
3710: if (keys(%dompersonnel)) {
3711: foreach my $server (keys(%dompersonnel)) {
3712: if (ref($dompersonnel{$server}) eq 'HASH') {
3713: foreach my $user (keys(%{$dompersonnel{$server}})) {
3714: my ($trole,$uname,$udom) = split(/:/,$user);
3715: $privileged{$udom}{$uname} = $trole;
3716: }
3717: }
3718: }
3719: }
3720: }
3721: if (exists($privileged{$domain}{$username})) {
3722: if (!$nothide{$username.':'.$domain}) {
3723: next;
3724: }
3725: }
3726: }
3727: }
3728: if ($withsec) {
3729: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3730: $tstart.':'.$tend;
3731: } else {
3732: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3733: }
3734: }
3735: return %returnhash;
3736: }
3737:
3738: # ----------------------------------------------------- Frontpage Announcements
3739: #
3740: #
3741:
3742: sub postannounce {
3743: my ($server,$text)=@_;
3744: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
3745: unless ($text=~/\w/) { $text=''; }
3746: return &reply('setannounce:'.&escape($text),$server);
3747: }
3748:
3749: sub getannounce {
3750:
3751: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
3752: my $announcement='';
3753: while (my $line = <$fh>) { $announcement .= $line; }
3754: close($fh);
3755: if ($announcement=~/\w/) {
3756: return
3757: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
3758: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
3759: } else {
3760: return '';
3761: }
3762: } else {
3763: return '';
3764: }
3765: }
3766:
3767: # ---------------------------------------------------------- Course ID routines
3768: # Deal with domain's nohist_courseid.db files
3769: #
3770:
3771: sub courseidput {
3772: my ($domain,$storehash,$coursehome,$caller) = @_;
3773: return unless (ref($storehash) eq 'HASH');
3774: my $outcome;
3775: if ($caller eq 'timeonly') {
3776: my $cids = '';
3777: foreach my $item (keys(%$storehash)) {
3778: $cids.=&escape($item).'&';
3779: }
3780: $cids=~s/\&$//;
3781: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3782: $coursehome);
3783: } else {
3784: my $items = '';
3785: foreach my $item (keys(%$storehash)) {
3786: $items.= &escape($item).'='.
3787: &freeze_escape($$storehash{$item}).'&';
3788: }
3789: $items=~s/\&$//;
3790: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3791: $coursehome);
3792: }
3793: if ($outcome eq 'unknown_cmd') {
3794: my $what;
3795: foreach my $cid (keys(%$storehash)) {
3796: $what .= &escape($cid).'=';
3797: foreach my $item ('description','inst_code','owner','type') {
3798: $what .= &escape($storehash->{$cid}{$item}).':';
3799: }
3800: $what =~ s/\:$/&/;
3801: }
3802: $what =~ s/\&$//;
3803: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3804: } else {
3805: return $outcome;
3806: }
3807: }
3808:
3809: sub courseiddump {
3810: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
3811: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
3812: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
3813: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
3814: my $as_hash = 1;
3815: my %returnhash;
3816: if (!$domfilter) { $domfilter=''; }
3817: my %libserv = &all_library();
3818: foreach my $tryserver (keys(%libserv)) {
3819: if ( ( $hostidflag == 1
3820: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3821: || (!defined($hostidflag)) ) {
3822:
3823: if (($domfilter eq '') ||
3824: (&host_domain($tryserver) eq $domfilter)) {
3825: my $rep =
3826: &reply('courseiddump:'.&host_domain($tryserver).':'.
3827: $sincefilter.':'.&escape($descfilter).':'.
3828: &escape($instcodefilter).':'.&escape($ownerfilter).
3829: ':'.&escape($coursefilter).':'.&escape($typefilter).
3830: ':'.&escape($regexp_ok).':'.$as_hash.':'.
3831: &escape($selfenrollonly).':'.&escape($catfilter).':'.
3832: $showhidden.':'.$caller.':'.&escape($cloner).':'.
3833: &escape($cc_clone).':'.$cloneonly.':'.
3834: &escape($createdbefore).':'.&escape($createdafter).':'.
3835: &escape($creationcontext).':'.$domcloner,
3836: $tryserver);
3837: my @pairs=split(/\&/,$rep);
3838: foreach my $item (@pairs) {
3839: my ($key,$value)=split(/\=/,$item,2);
3840: $key = &unescape($key);
3841: next if ($key =~ /^error: 2 /);
3842: my $result = &thaw_unescape($value);
3843: if (ref($result) eq 'HASH') {
3844: $returnhash{$key}=$result;
3845: } else {
3846: my @responses = split(/:/,$value);
3847: my @items = ('description','inst_code','owner','type');
3848: for (my $i=0; $i<@responses; $i++) {
3849: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
3850: }
3851: }
3852: }
3853: }
3854: }
3855: }
3856: return %returnhash;
3857: }
3858:
3859: sub courselastaccess {
3860: my ($cdom,$cnum,$hostidref) = @_;
3861: my %returnhash;
3862: if ($cdom && $cnum) {
3863: my $chome = &homeserver($cnum,$cdom);
3864: if ($chome ne 'no_host') {
3865: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3866: &extract_lastaccess(\%returnhash,$rep);
3867: }
3868: } else {
3869: if (!$cdom) { $cdom=''; }
3870: my %libserv = &all_library();
3871: foreach my $tryserver (keys(%libserv)) {
3872: if (ref($hostidref) eq 'ARRAY') {
3873: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3874: }
3875: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3876: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3877: &extract_lastaccess(\%returnhash,$rep);
3878: }
3879: }
3880: }
3881: return %returnhash;
3882: }
3883:
3884: sub extract_lastaccess {
3885: my ($returnhash,$rep) = @_;
3886: if (ref($returnhash) eq 'HASH') {
3887: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3888: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3889: $rep eq '') {
3890: my @pairs=split(/\&/,$rep);
3891: foreach my $item (@pairs) {
3892: my ($key,$value)=split(/\=/,$item,2);
3893: $key = &unescape($key);
3894: next if ($key =~ /^error: 2 /);
3895: $returnhash->{$key} = &thaw_unescape($value);
3896: }
3897: }
3898: }
3899: return;
3900: }
3901:
3902: # ---------------------------------------------------------- DC e-mail
3903:
3904: sub dcmailput {
3905: my ($domain,$msgid,$message,$server)=@_;
3906: my $status = &Apache::lonnet::critical(
3907: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3908: &escape($message),$server);
3909: return $status;
3910: }
3911:
3912: sub dcmaildump {
3913: my ($dom,$startdate,$enddate,$senders) = @_;
3914: my %returnhash=();
3915:
3916: if (defined(&domain($dom,'primary'))) {
3917: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3918: &escape($enddate).':';
3919: my @esc_senders=map { &escape($_)} @$senders;
3920: $cmd.=&escape(join('&',@esc_senders));
3921: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
3922: my ($key,$value) = split(/\=/,$line,2);
3923: if (($key) && ($value)) {
3924: $returnhash{&unescape($key)} = &unescape($value);
3925: }
3926: }
3927: }
3928: return %returnhash;
3929: }
3930: # ---------------------------------------------------------- Domain roles
3931:
3932: sub get_domain_roles {
3933: my ($dom,$roles,$startdate,$enddate)=@_;
3934: if ((!defined($startdate)) || ($startdate eq '')) {
3935: $startdate = '.';
3936: }
3937: if ((!defined($enddate)) || ($enddate eq '')) {
3938: $enddate = '.';
3939: }
3940: my $rolelist;
3941: if (ref($roles) eq 'ARRAY') {
3942: $rolelist = join(':',@{$roles});
3943: }
3944: my %personnel = ();
3945:
3946: my %servers = &get_servers($dom,'library');
3947: foreach my $tryserver (keys(%servers)) {
3948: %{$personnel{$tryserver}}=();
3949: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3950: &escape($startdate).':'.
3951: &escape($enddate).':'.
3952: &escape($rolelist), $tryserver))) {
3953: my ($key,$value) = split(/\=/,$line,2);
3954: if (($key) && ($value)) {
3955: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3956: }
3957: }
3958: }
3959: return %personnel;
3960: }
3961:
3962: # ----------------------------------------------------------- Interval timing
3963:
3964: {
3965: # Caches needed for speedup of navmaps
3966: # We don't want to cache this for very long at all (5 seconds at most)
3967: #
3968: # The user for whom we cache
3969: my $cachedkey='';
3970: # The cached times for this user
3971: my %cachedtimes=();
3972: # When this was last done
3973: my $cachedtime=();
3974:
3975: sub load_all_first_access {
3976: my ($uname,$udom)=@_;
3977: if (($cachedkey eq $uname.':'.$udom) &&
3978: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
3979: return;
3980: }
3981: $cachedtime=time;
3982: $cachedkey=$uname.':'.$udom;
3983: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
3984: }
3985:
3986: sub get_first_access {
3987: my ($type,$argsymb,$argmap)=@_;
3988: my ($symb,$courseid,$udom,$uname)=&whichuser();
3989: if ($argsymb) { $symb=$argsymb; }
3990: my ($map,$id,$res)=&decode_symb($symb);
3991: if ($argmap) { $map = $argmap; }
3992: if ($type eq 'course') {
3993: $res='course';
3994: } elsif ($type eq 'map') {
3995: $res=&symbread($map);
3996: } else {
3997: $res=$symb;
3998: }
3999: &load_all_first_access($uname,$udom);
4000: return $cachedtimes{"$courseid\0$res"};
4001: }
4002:
4003: sub set_first_access {
4004: my ($type,$interval)=@_;
4005: my ($symb,$courseid,$udom,$uname)=&whichuser();
4006: my ($map,$id,$res)=&decode_symb($symb);
4007: if ($type eq 'course') {
4008: $res='course';
4009: } elsif ($type eq 'map') {
4010: $res=&symbread($map);
4011: } else {
4012: $res=$symb;
4013: }
4014: $cachedkey='';
4015: my $firstaccess=&get_first_access($type,$symb,$map);
4016: if (!$firstaccess) {
4017: my $start = time;
4018: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4019: $udom,$uname);
4020: if ($putres eq 'ok') {
4021: &put('timerinterval',{"$courseid\0$res"=>$interval},
4022: $udom,$uname);
4023: &appenv(
4024: {
4025: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4026: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4027: }
4028: );
4029: }
4030: return $putres;
4031: }
4032: return 'already_set';
4033: }
4034: }
4035: # --------------------------------------------- Set Expire Date for Spreadsheet
4036:
4037: sub expirespread {
4038: my ($uname,$udom,$stype,$usymb)=@_;
4039: my $cid=$env{'request.course.id'};
4040: if ($cid) {
4041: my $now=time;
4042: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
4043: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4044: $env{'course.'.$cid.'.num'}.
4045: ':nohist_expirationdates:'.
4046: &escape($key).'='.$now,
4047: $env{'course.'.$cid.'.home'})
4048: }
4049: return 'ok';
4050: }
4051:
4052: # ----------------------------------------------------- Devalidate Spreadsheets
4053:
4054: sub devalidate {
4055: my ($symb,$uname,$udom)=@_;
4056: my $cid=$env{'request.course.id'};
4057: if ($cid) {
4058: # delete the stored spreadsheets for
4059: # - the student level sheet of this user in course's homespace
4060: # - the assessment level sheet for this resource
4061: # for this user in user's homespace
4062: # - current conditional state info
4063: my $key=$uname.':'.$udom.':';
4064: my $status=
4065: &del('nohist_calculatedsheets',
4066: [$key.'studentcalc:'],
4067: $env{'course.'.$cid.'.domain'},
4068: $env{'course.'.$cid.'.num'})
4069: .' '.
4070: &del('nohist_calculatedsheets_'.$cid,
4071: [$key.'assesscalc:'.$symb],$udom,$uname);
4072: unless ($status eq 'ok ok') {
4073: &logthis('Could not devalidate spreadsheet '.
4074: $uname.' at '.$udom.' for '.
4075: $symb.': '.$status);
4076: }
4077: &delenv('user.state.'.$cid);
4078: }
4079: }
4080:
4081: sub get_scalar {
4082: my ($string,$end) = @_;
4083: my $value;
4084: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4085: $value = $1;
4086: } elsif ($$string =~ s/^([^&]*?)&//) {
4087: $value = $1;
4088: }
4089: return &unescape($value);
4090: }
4091:
4092: sub array2str {
4093: my (@array) = @_;
4094: my $result=&arrayref2str(\@array);
4095: $result=~s/^__ARRAY_REF__//;
4096: $result=~s/__END_ARRAY_REF__$//;
4097: return $result;
4098: }
4099:
4100: sub arrayref2str {
4101: my ($arrayref) = @_;
4102: my $result='__ARRAY_REF__';
4103: foreach my $elem (@$arrayref) {
4104: if(ref($elem) eq 'ARRAY') {
4105: $result.=&arrayref2str($elem).'&';
4106: } elsif(ref($elem) eq 'HASH') {
4107: $result.=&hashref2str($elem).'&';
4108: } elsif(ref($elem)) {
4109: #print("Got a ref of ".(ref($elem))." skipping.");
4110: } else {
4111: $result.=&escape($elem).'&';
4112: }
4113: }
4114: $result=~s/\&$//;
4115: $result .= '__END_ARRAY_REF__';
4116: return $result;
4117: }
4118:
4119: sub hash2str {
4120: my (%hash) = @_;
4121: my $result=&hashref2str(\%hash);
4122: $result=~s/^__HASH_REF__//;
4123: $result=~s/__END_HASH_REF__$//;
4124: return $result;
4125: }
4126:
4127: sub hashref2str {
4128: my ($hashref)=@_;
4129: my $result='__HASH_REF__';
4130: foreach my $key (sort(keys(%$hashref))) {
4131: if (ref($key) eq 'ARRAY') {
4132: $result.=&arrayref2str($key).'=';
4133: } elsif (ref($key) eq 'HASH') {
4134: $result.=&hashref2str($key).'=';
4135: } elsif (ref($key)) {
4136: $result.='=';
4137: #print("Got a ref of ".(ref($key))." skipping.");
4138: } else {
4139: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
4140: }
4141:
4142: if(ref($hashref->{$key}) eq 'ARRAY') {
4143: $result.=&arrayref2str($hashref->{$key}).'&';
4144: } elsif(ref($hashref->{$key}) eq 'HASH') {
4145: $result.=&hashref2str($hashref->{$key}).'&';
4146: } elsif(ref($hashref->{$key})) {
4147: $result.='&';
4148: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
4149: } else {
4150: $result.=&escape($hashref->{$key}).'&';
4151: }
4152: }
4153: $result=~s/\&$//;
4154: $result .= '__END_HASH_REF__';
4155: return $result;
4156: }
4157:
4158: sub str2hash {
4159: my ($string)=@_;
4160: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4161: return %$hash;
4162: }
4163:
4164: sub str2hashref {
4165: my ($string) = @_;
4166:
4167: my %hash;
4168:
4169: if($string !~ /^__HASH_REF__/) {
4170: if (! ($string eq '' || !defined($string))) {
4171: $hash{'error'}='Not hash reference';
4172: }
4173: return (\%hash, $string);
4174: }
4175:
4176: $string =~ s/^__HASH_REF__//;
4177:
4178: while($string !~ /^__END_HASH_REF__/) {
4179: #key
4180: my $key='';
4181: if($string =~ /^__HASH_REF__/) {
4182: ($key, $string)=&str2hashref($string);
4183: if(defined($key->{'error'})) {
4184: $hash{'error'}='Bad data';
4185: return (\%hash, $string);
4186: }
4187: } elsif($string =~ /^__ARRAY_REF__/) {
4188: ($key, $string)=&str2arrayref($string);
4189: if($key->[0] eq 'Array reference error') {
4190: $hash{'error'}='Bad data';
4191: return (\%hash, $string);
4192: }
4193: } else {
4194: $string =~ s/^(.*?)=//;
4195: $key=&unescape($1);
4196: }
4197: $string =~ s/^=//;
4198:
4199: #value
4200: my $value='';
4201: if($string =~ /^__HASH_REF__/) {
4202: ($value, $string)=&str2hashref($string);
4203: if(defined($value->{'error'})) {
4204: $hash{'error'}='Bad data';
4205: return (\%hash, $string);
4206: }
4207: } elsif($string =~ /^__ARRAY_REF__/) {
4208: ($value, $string)=&str2arrayref($string);
4209: if($value->[0] eq 'Array reference error') {
4210: $hash{'error'}='Bad data';
4211: return (\%hash, $string);
4212: }
4213: } else {
4214: $value=&get_scalar(\$string,'__END_HASH_REF__');
4215: }
4216: $string =~ s/^&//;
4217:
4218: $hash{$key}=$value;
4219: }
4220:
4221: $string =~ s/^__END_HASH_REF__//;
4222:
4223: return (\%hash, $string);
4224: }
4225:
4226: sub str2array {
4227: my ($string)=@_;
4228: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4229: return @$array;
4230: }
4231:
4232: sub str2arrayref {
4233: my ($string) = @_;
4234: my @array;
4235:
4236: if($string !~ /^__ARRAY_REF__/) {
4237: if (! ($string eq '' || !defined($string))) {
4238: $array[0]='Array reference error';
4239: }
4240: return (\@array, $string);
4241: }
4242:
4243: $string =~ s/^__ARRAY_REF__//;
4244:
4245: while($string !~ /^__END_ARRAY_REF__/) {
4246: my $value='';
4247: if($string =~ /^__HASH_REF__/) {
4248: ($value, $string)=&str2hashref($string);
4249: if(defined($value->{'error'})) {
4250: $array[0] ='Array reference error';
4251: return (\@array, $string);
4252: }
4253: } elsif($string =~ /^__ARRAY_REF__/) {
4254: ($value, $string)=&str2arrayref($string);
4255: if($value->[0] eq 'Array reference error') {
4256: $array[0] ='Array reference error';
4257: return (\@array, $string);
4258: }
4259: } else {
4260: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4261: }
4262: $string =~ s/^&//;
4263:
4264: push(@array, $value);
4265: }
4266:
4267: $string =~ s/^__END_ARRAY_REF__//;
4268:
4269: return (\@array, $string);
4270: }
4271:
4272: # -------------------------------------------------------------------Temp Store
4273:
4274: sub tmpreset {
4275: my ($symb,$namespace,$domain,$stuname) = @_;
4276: if (!$symb) {
4277: $symb=&symbread();
4278: if (!$symb) { $symb= $env{'request.url'}; }
4279: }
4280: $symb=escape($symb);
4281:
4282: if (!$namespace) { $namespace=$env{'request.state'}; }
4283: $namespace=~s/\//\_/g;
4284: $namespace=~s/\W//g;
4285:
4286: if (!$domain) { $domain=$env{'user.domain'}; }
4287: if (!$stuname) { $stuname=$env{'user.name'}; }
4288: if ($domain eq 'public' && $stuname eq 'public') {
4289: $stuname=$ENV{'REMOTE_ADDR'};
4290: }
4291: my $path=LONCAPA::tempdir();
4292: my %hash;
4293: if (tie(%hash,'GDBM_File',
4294: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4295: &GDBM_WRCREAT(),0640)) {
4296: foreach my $key (keys(%hash)) {
4297: if ($key=~ /:$symb/) {
4298: delete($hash{$key});
4299: }
4300: }
4301: }
4302: }
4303:
4304: sub tmpstore {
4305: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4306:
4307: if (!$symb) {
4308: $symb=&symbread();
4309: if (!$symb) { $symb= $env{'request.url'}; }
4310: }
4311: $symb=escape($symb);
4312:
4313: if (!$namespace) {
4314: # I don't think we would ever want to store this for a course.
4315: # it seems this will only be used if we don't have a course.
4316: #$namespace=$env{'request.course.id'};
4317: #if (!$namespace) {
4318: $namespace=$env{'request.state'};
4319: #}
4320: }
4321: $namespace=~s/\//\_/g;
4322: $namespace=~s/\W//g;
4323: if (!$domain) { $domain=$env{'user.domain'}; }
4324: if (!$stuname) { $stuname=$env{'user.name'}; }
4325: if ($domain eq 'public' && $stuname eq 'public') {
4326: $stuname=$ENV{'REMOTE_ADDR'};
4327: }
4328: my $now=time;
4329: my %hash;
4330: my $path=LONCAPA::tempdir();
4331: if (tie(%hash,'GDBM_File',
4332: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4333: &GDBM_WRCREAT(),0640)) {
4334: $hash{"version:$symb"}++;
4335: my $version=$hash{"version:$symb"};
4336: my $allkeys='';
4337: foreach my $key (keys(%$storehash)) {
4338: $allkeys.=$key.':';
4339: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
4340: }
4341: $hash{"$version:$symb:timestamp"}=$now;
4342: $allkeys.='timestamp';
4343: $hash{"$version:keys:$symb"}=$allkeys;
4344: if (untie(%hash)) {
4345: return 'ok';
4346: } else {
4347: return "error:$!";
4348: }
4349: } else {
4350: return "error:$!";
4351: }
4352: }
4353:
4354: # -----------------------------------------------------------------Temp Restore
4355:
4356: sub tmprestore {
4357: my ($symb,$namespace,$domain,$stuname) = @_;
4358:
4359: if (!$symb) {
4360: $symb=&symbread();
4361: if (!$symb) { $symb= $env{'request.url'}; }
4362: }
4363: $symb=escape($symb);
4364:
4365: if (!$namespace) { $namespace=$env{'request.state'}; }
4366:
4367: if (!$domain) { $domain=$env{'user.domain'}; }
4368: if (!$stuname) { $stuname=$env{'user.name'}; }
4369: if ($domain eq 'public' && $stuname eq 'public') {
4370: $stuname=$ENV{'REMOTE_ADDR'};
4371: }
4372: my %returnhash;
4373: $namespace=~s/\//\_/g;
4374: $namespace=~s/\W//g;
4375: my %hash;
4376: my $path=LONCAPA::tempdir();
4377: if (tie(%hash,'GDBM_File',
4378: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4379: &GDBM_READER(),0640)) {
4380: my $version=$hash{"version:$symb"};
4381: $returnhash{'version'}=$version;
4382: my $scope;
4383: for ($scope=1;$scope<=$version;$scope++) {
4384: my $vkeys=$hash{"$scope:keys:$symb"};
4385: my @keys=split(/:/,$vkeys);
4386: my $key;
4387: $returnhash{"$scope:keys"}=$vkeys;
4388: foreach $key (@keys) {
4389: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4390: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4391: }
4392: }
4393: if (!(untie(%hash))) {
4394: return "error:$!";
4395: }
4396: } else {
4397: return "error:$!";
4398: }
4399: return %returnhash;
4400: }
4401:
4402: # ----------------------------------------------------------------------- Store
4403:
4404: sub store {
4405: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4406: my $home='';
4407:
4408: if ($stuname) { $home=&homeserver($stuname,$domain); }
4409:
4410: $symb=&symbclean($symb);
4411: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4412:
4413: if (!$domain) { $domain=$env{'user.domain'}; }
4414: if (!$stuname) { $stuname=$env{'user.name'}; }
4415:
4416: &devalidate($symb,$stuname,$domain);
4417:
4418: $symb=escape($symb);
4419: if (!$namespace) {
4420: unless ($namespace=$env{'request.course.id'}) {
4421: return '';
4422: }
4423: }
4424: if (!$home) { $home=$env{'user.home'}; }
4425:
4426: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4427: $$storehash{'host'}=$perlvar{'lonHostID'};
4428:
4429: my $namevalue='';
4430: foreach my $key (keys(%$storehash)) {
4431: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4432: }
4433: $namevalue=~s/\&$//;
4434: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
4435: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4436: }
4437:
4438: # -------------------------------------------------------------- Critical Store
4439:
4440: sub cstore {
4441: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4442: my $home='';
4443:
4444: if ($stuname) { $home=&homeserver($stuname,$domain); }
4445:
4446: $symb=&symbclean($symb);
4447: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4448:
4449: if (!$domain) { $domain=$env{'user.domain'}; }
4450: if (!$stuname) { $stuname=$env{'user.name'}; }
4451:
4452: &devalidate($symb,$stuname,$domain);
4453:
4454: $symb=escape($symb);
4455: if (!$namespace) {
4456: unless ($namespace=$env{'request.course.id'}) {
4457: return '';
4458: }
4459: }
4460: if (!$home) { $home=$env{'user.home'}; }
4461:
4462: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4463: $$storehash{'host'}=$perlvar{'lonHostID'};
4464:
4465: my $namevalue='';
4466: foreach my $key (keys(%$storehash)) {
4467: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4468: }
4469: $namevalue=~s/\&$//;
4470: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
4471: return critical
4472: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4473: }
4474:
4475: # --------------------------------------------------------------------- Restore
4476:
4477: sub restore {
4478: my ($symb,$namespace,$domain,$stuname) = @_;
4479: my $home='';
4480:
4481: if ($stuname) { $home=&homeserver($stuname,$domain); }
4482:
4483: if (!$symb) {
4484: unless ($symb=escape(&symbread())) { return ''; }
4485: } else {
4486: $symb=&escape(&symbclean($symb));
4487: }
4488: if (!$namespace) {
4489: unless ($namespace=$env{'request.course.id'}) {
4490: return '';
4491: }
4492: }
4493: if (!$domain) { $domain=$env{'user.domain'}; }
4494: if (!$stuname) { $stuname=$env{'user.name'}; }
4495: if (!$home) { $home=$env{'user.home'}; }
4496: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4497:
4498: my %returnhash=();
4499: foreach my $line (split(/\&/,$answer)) {
4500: my ($name,$value)=split(/\=/,$line);
4501: $returnhash{&unescape($name)}=&thaw_unescape($value);
4502: }
4503: my $version;
4504: for ($version=1;$version<=$returnhash{'version'};$version++) {
4505: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4506: $returnhash{$item}=$returnhash{$version.':'.$item};
4507: }
4508: }
4509: return %returnhash;
4510: }
4511:
4512: # ---------------------------------------------------------- Course Description
4513: #
4514: #
4515:
4516: sub coursedescription {
4517: my ($courseid,$args)=@_;
4518: $courseid=~s/^\///;
4519: $courseid=~s/\_/\//g;
4520: my ($cdomain,$cnum)=split(/\//,$courseid);
4521: my $chome=&homeserver($cnum,$cdomain);
4522: my $normalid=$cdomain.'_'.$cnum;
4523: # need to always cache even if we get errors otherwise we keep
4524: # trying and trying and trying to get the course description.
4525: my %envhash=();
4526: my %returnhash=();
4527:
4528: my $expiretime=600;
4529: if ($env{'request.course.id'} eq $normalid) {
4530: $expiretime=120;
4531: }
4532:
4533: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4534: if (!$args->{'freshen_cache'}
4535: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4536: foreach my $key (keys(%env)) {
4537: next if ($key !~ /^\Q$prefix\E(.*)/);
4538: my ($setting) = $1;
4539: $returnhash{$setting} = $env{$key};
4540: }
4541: return %returnhash;
4542: }
4543:
4544: # get the data again
4545:
4546: if (!$args->{'one_time'}) {
4547: $envhash{'course.'.$normalid.'.last_cache'}=time;
4548: }
4549:
4550: if ($chome ne 'no_host') {
4551: %returnhash=&dump('environment',$cdomain,$cnum);
4552: if (!exists($returnhash{'con_lost'})) {
4553: my $username = $env{'user.name'}; # Defult username
4554: if(defined $args->{'user'}) {
4555: $username = $args->{'user'};
4556: }
4557: $returnhash{'home'}= $chome;
4558: $returnhash{'domain'} = $cdomain;
4559: $returnhash{'num'} = $cnum;
4560: if (!defined($returnhash{'type'})) {
4561: $returnhash{'type'} = 'Course';
4562: }
4563: while (my ($name,$value) = each %returnhash) {
4564: $envhash{'course.'.$normalid.'.'.$name}=$value;
4565: }
4566: $returnhash{'url'}=&clutter($returnhash{'url'});
4567: $returnhash{'fn'}=LONCAPA::tempdir() .
4568: $username.'_'.$cdomain.'_'.$cnum;
4569: $envhash{'course.'.$normalid.'.home'}=$chome;
4570: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4571: $envhash{'course.'.$normalid.'.num'}=$cnum;
4572: }
4573: }
4574: if (!$args->{'one_time'}) {
4575: &appenv(\%envhash);
4576: }
4577: return %returnhash;
4578: }
4579:
4580: sub update_released_required {
4581: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4582: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4583: $cid = $env{'request.course.id'};
4584: $cdom = $env{'course.'.$cid.'.domain'};
4585: $cnum = $env{'course.'.$cid.'.num'};
4586: $chome = $env{'course.'.$cid.'.home'};
4587: }
4588: if ($needsrelease) {
4589: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4590: my $needsupdate;
4591: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4592: $needsupdate = 1;
4593: } else {
4594: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4595: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4596: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4597: $needsupdate = 1;
4598: }
4599: }
4600: if ($needsupdate) {
4601: my %needshash = (
4602: 'internal.releaserequired' => $needsrelease,
4603: );
4604: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4605: if ($putresult eq 'ok') {
4606: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4607: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4608: if (ref($crsinfo{$cid}) eq 'HASH') {
4609: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4610: &courseidput($cdom,\%crsinfo,$chome,'notime');
4611: }
4612: }
4613: }
4614: }
4615: return;
4616: }
4617:
4618: # -------------------------------------------------See if a user is privileged
4619:
4620: sub privileged {
4621: my ($username,$domain)=@_;
4622:
4623: my %rolesdump = &dump("roles", $domain, $username) or return 0;
4624: my $now = time;
4625:
4626: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
4627: my ($trole, $tend, $tstart) = split(/_/, $role);
4628: if (($trole eq 'dc') || ($trole eq 'su')) {
4629: return 1 unless ($tend && $tend < $now)
4630: or ($tstart && $tstart > $now);
4631: }
4632: }
4633:
4634: return 0;
4635: }
4636:
4637: # -------------------------------------------------------- Get user privileges
4638:
4639: sub rolesinit {
4640: my ($domain, $username) = @_;
4641: my %userroles = ('user.login.time' => time);
4642: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
4643:
4644: # firstaccess and timerinterval are related to timed maps/resources.
4645: # also, blocking can be triggered by an activating timer
4646: # it's saved in the user's %env.
4647: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
4648: my %timerinterval = &dump('timerinterval', $domain, $username);
4649: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
4650: %timerintchk, %timerintenv);
4651:
4652: foreach my $key (keys(%firstaccess)) {
4653: my ($cid, $rest) = split(/\0/, $key);
4654: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
4655: }
4656:
4657: foreach my $key (keys(%timerinterval)) {
4658: my ($cid,$rest) = split(/\0/,$key);
4659: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
4660: }
4661:
4662: my %allroles=();
4663: my %allgroups=();
4664:
4665: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
4666: my $role = $rolesdump{$area};
4667: $area =~ s/\_\w\w$//;
4668:
4669: my ($trole, $tend, $tstart, $group_privs);
4670:
4671: if ($role =~ /^cr/) {
4672: # Custom role, defined by a user
4673: # e.g., user.role.cr/msu/smith/mynewrole
4674: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4675: $trole = $1;
4676: ($tend, $tstart) = split('_', $2);
4677: } else {
4678: $trole = $role;
4679: }
4680: } elsif ($role =~ m|^gr/|) {
4681: # Role of member in a group, defined within a course/community
4682: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
4683: ($trole, $tend, $tstart) = split(/_/, $role);
4684: next if $tstart eq '-1';
4685: ($trole, $group_privs) = split(/\//, $trole);
4686: $group_privs = &unescape($group_privs);
4687: } else {
4688: # Just a normal role, defined in roles.tab
4689: ($trole, $tend, $tstart) = split(/_/,$role);
4690: }
4691:
4692: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4693: $username);
4694: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
4695:
4696: # role expired or not available yet?
4697: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
4698: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
4699:
4700: next if $area eq '' or $trole eq '';
4701:
4702: my $spec = "$trole.$area";
4703: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
4704:
4705: if ($trole =~ /^cr\//) {
4706: # Custom role, defined by a user
4707: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4708: } elsif ($trole eq 'gr') {
4709: # Role of a member in a group, defined within a course/community
4710: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
4711: next;
4712: } else {
4713: # Normal role, defined in roles.tab
4714: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4715: }
4716:
4717: my $cid = $tdomain.'_'.$trest;
4718: unless ($firstaccchk{$cid}) {
4719: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
4720: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
4721: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
4722: $coursetimerstarts{$cid}{$item};
4723: }
4724: }
4725: $firstaccchk{$cid} = 1;
4726: }
4727: unless ($timerintchk{$cid}) {
4728: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
4729: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
4730: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
4731: $coursetimerintervals{$cid}{$item};
4732: }
4733: }
4734: $timerintchk{$cid} = 1;
4735: }
4736: }
4737:
4738: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
4739: \%allroles, \%allgroups);
4740: $env{'user.adv'} = $userroles{'user.adv'};
4741:
4742: return (\%userroles,\%firstaccenv,\%timerintenv);
4743: }
4744:
4745: sub set_arearole {
4746: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4747: # log the associated role with the area
4748: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
4749: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
4750: }
4751:
4752: sub custom_roleprivs {
4753: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4754: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4755: my $homsvr=homeserver($rauthor,$rdomain);
4756: if (&hostname($homsvr) ne '') {
4757: my ($rdummy,$roledef)=
4758: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4759: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4760: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4761: if (defined($syspriv)) {
4762: if ($trest =~ /^$match_community$/) {
4763: $syspriv =~ s/bre\&S//;
4764: }
4765: $$allroles{'cm./'}.=':'.$syspriv;
4766: $$allroles{$spec.'./'}.=':'.$syspriv;
4767: }
4768: if ($tdomain ne '') {
4769: if (defined($dompriv)) {
4770: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4771: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4772: }
4773: if (($trest ne '') && (defined($coursepriv))) {
4774: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4775: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4776: }
4777: }
4778: }
4779: }
4780: }
4781:
4782: sub group_roleprivs {
4783: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4784: my $access = 1;
4785: my $now = time;
4786: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4787: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4788: if ($access) {
4789: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
4790: $$allgroups{$course}{$group} .=':'.$group_privs;
4791: }
4792: }
4793:
4794: sub standard_roleprivs {
4795: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4796: if (defined($pr{$trole.':s'})) {
4797: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4798: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4799: }
4800: if ($tdomain ne '') {
4801: if (defined($pr{$trole.':d'})) {
4802: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4803: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4804: }
4805: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4806: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4807: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4808: }
4809: }
4810: }
4811:
4812: sub set_userprivs {
4813: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
4814: my $author=0;
4815: my $adv=0;
4816: my %grouproles = ();
4817: if (keys(%{$allgroups}) > 0) {
4818: my @groupkeys;
4819: foreach my $role (keys(%{$allroles})) {
4820: push(@groupkeys,$role);
4821: }
4822: if (ref($groups_roles) eq 'HASH') {
4823: foreach my $key (keys(%{$groups_roles})) {
4824: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4825: push(@groupkeys,$key);
4826: }
4827: }
4828: }
4829: if (@groupkeys > 0) {
4830: foreach my $role (@groupkeys) {
4831: my ($trole,$area,$sec,$extendedarea);
4832: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4833: $trole = $1;
4834: $area = $2;
4835: $sec = $3;
4836: $extendedarea = $area.$sec;
4837: if (exists($$allgroups{$area})) {
4838: foreach my $group (keys(%{$$allgroups{$area}})) {
4839: my $spec = $trole.'.'.$extendedarea;
4840: $grouproles{$spec.'.'.$area.'/'.$group} =
4841: $$allgroups{$area}{$group};
4842: }
4843: }
4844: }
4845: }
4846: }
4847: }
4848: foreach my $group (keys(%grouproles)) {
4849: $$allroles{$group} = $grouproles{$group};
4850: }
4851: foreach my $role (keys(%{$allroles})) {
4852: my %thesepriv;
4853: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
4854: foreach my $item (split(/:/,$$allroles{$role})) {
4855: if ($item ne '') {
4856: my ($privilege,$restrictions)=split(/&/,$item);
4857: if ($restrictions eq '') {
4858: $thesepriv{$privilege}='F';
4859: } elsif ($thesepriv{$privilege} ne 'F') {
4860: $thesepriv{$privilege}.=$restrictions;
4861: }
4862: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4863: }
4864: }
4865: my $thesestr='';
4866: foreach my $priv (sort(keys(%thesepriv))) {
4867: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4868: }
4869: $userroles->{'user.priv.'.$role} = $thesestr;
4870: }
4871: return ($author,$adv);
4872: }
4873:
4874: sub role_status {
4875: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
4876: my @pwhere = ();
4877: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4878: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4879: unless (!defined($$role) || $$role eq '') {
4880: $$where=join('.',@pwhere);
4881: $$trolecode=$$role.'.'.$$where;
4882: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4883: $$tstatus='is';
4884: if ($$tstart && $$tstart>$update) {
4885: $$tstatus='future';
4886: if ($$tstart<$now) {
4887: if ($$tstart && $$tstart>$refresh) {
4888: if (($$where ne '') && ($$role ne '')) {
4889: my (%allroles,%allgroups,$group_privs,
4890: %groups_roles,@rolecodes);
4891: my %userroles = (
4892: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4893: );
4894: @rolecodes = ('cm');
4895: my $spec=$$role.'.'.$$where;
4896: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4897: if ($$role =~ /^cr\//) {
4898: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
4899: push(@rolecodes,'cr');
4900: } elsif ($$role eq 'gr') {
4901: push(@rolecodes,$$role);
4902: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4903: $env{'user.name'});
4904: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
4905: (undef,my $group_privs) = split(/\//,$trole);
4906: $group_privs = &unescape($group_privs);
4907: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
4908: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4909: &get_groups_roles($tdomain,$trest,
4910: \%course_roles,\@rolecodes,
4911: \%groups_roles);
4912: } else {
4913: push(@rolecodes,$$role);
4914: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4915: }
4916: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4917: &appenv(\%userroles,\@rolecodes);
4918: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4919: }
4920: }
4921: $$tstatus = 'is';
4922: }
4923: }
4924: if ($$tend) {
4925: if ($$tend<$update) {
4926: $$tstatus='expired';
4927: } elsif ($$tend<$now) {
4928: $$tstatus='will_not';
4929: }
4930: }
4931: }
4932: }
4933: }
4934:
4935: sub get_groups_roles {
4936: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
4937: return unless((ref($cdom_courseroles) eq 'HASH') &&
4938: (ref($rolecodes) eq 'ARRAY') &&
4939: (ref($groups_roles) eq 'HASH'));
4940: if (keys(%{$cdom_courseroles}) > 0) {
4941: my ($cnum) = ($rest =~ /^($match_courseid)/);
4942: if ($cdom ne '' && $cnum ne '') {
4943: foreach my $key (keys(%{$cdom_courseroles})) {
4944: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
4945: my $crsrole = $1;
4946: my $crssec = $2;
4947: if ($crsrole =~ /^cr/) {
4948: unless (grep(/^cr$/,@{$rolecodes})) {
4949: push(@{$rolecodes},'cr');
4950: }
4951: } else {
4952: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
4953: push(@{$rolecodes},$crsrole);
4954: }
4955: }
4956: my $rolekey = "$crsrole./$cdom/$cnum";
4957: if ($crssec ne '') {
4958: $rolekey .= "/$crssec";
4959: }
4960: $rolekey .= './';
4961: $groups_roles->{$rolekey} = $rolecodes;
4962: }
4963: }
4964: }
4965: }
4966: return;
4967: }
4968:
4969: sub delete_env_groupprivs {
4970: my ($where,$courseroles,$possroles) = @_;
4971: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
4972: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
4973: unless (ref($courseroles->{$udom}) eq 'HASH') {
4974: %{$courseroles->{$udom}} =
4975: &get_my_roles('','','userroles',['active'],
4976: $possroles,[$udom],1);
4977: }
4978: if (ref($courseroles->{$udom}) eq 'HASH') {
4979: foreach my $item (keys(%{$courseroles->{$udom}})) {
4980: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
4981: my $area = '/'.$cdom.'/'.$cnum;
4982: my $privkey = "user.priv.$crsrole.$area";
4983: if ($crssec ne '') {
4984: $privkey .= '/'.$crssec;
4985: }
4986: $privkey .= ".$area/$group";
4987: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
4988: }
4989: }
4990: return;
4991: }
4992:
4993: sub check_adhoc_privs {
4994: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
4995: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4996: if ($env{$cckey}) {
4997: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
4998: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
4999: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
5000: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
5001: }
5002: } else {
5003: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
5004: }
5005: }
5006:
5007: sub set_adhoc_privileges {
5008: # role can be cc or ca
5009: my ($dcdom,$pickedcourse,$role,$caller) = @_;
5010: my $area = '/'.$dcdom.'/'.$pickedcourse;
5011: my $spec = $role.'.'.$area;
5012: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
5013: $env{'user.name'});
5014: my %ccrole = ();
5015: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5016: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5017: &appenv(\%userroles,[$role,'cm']);
5018: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5019: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5020: &appenv( {'request.role' => $spec,
5021: 'request.role.domain' => $dcdom,
5022: 'request.course.sec' => ''
5023: }
5024: );
5025: my $tadv=0;
5026: if (&allowed('adv') eq 'F') { $tadv=1; }
5027: &appenv({'request.role.adv' => $tadv});
5028: }
5029: }
5030:
5031: # --------------------------------------------------------------- get interface
5032:
5033: sub get {
5034: my ($namespace,$storearr,$udomain,$uname)=@_;
5035: my $items='';
5036: foreach my $item (@$storearr) {
5037: $items.=&escape($item).'&';
5038: }
5039: $items=~s/\&$//;
5040: if (!$udomain) { $udomain=$env{'user.domain'}; }
5041: if (!$uname) { $uname=$env{'user.name'}; }
5042: my $uhome=&homeserver($uname,$udomain);
5043:
5044: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
5045: my @pairs=split(/\&/,$rep);
5046: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5047: return @pairs;
5048: }
5049: my %returnhash=();
5050: my $i=0;
5051: foreach my $item (@$storearr) {
5052: $returnhash{$item}=&thaw_unescape($pairs[$i]);
5053: $i++;
5054: }
5055: return %returnhash;
5056: }
5057:
5058: # --------------------------------------------------------------- del interface
5059:
5060: sub del {
5061: my ($namespace,$storearr,$udomain,$uname)=@_;
5062: my $items='';
5063: foreach my $item (@$storearr) {
5064: $items.=&escape($item).'&';
5065: }
5066:
5067: $items=~s/\&$//;
5068: if (!$udomain) { $udomain=$env{'user.domain'}; }
5069: if (!$uname) { $uname=$env{'user.name'}; }
5070: my $uhome=&homeserver($uname,$udomain);
5071: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
5072: }
5073:
5074: # -------------------------------------------------------------- dump interface
5075:
5076: sub dump {
5077: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
5078: if (!$udomain) { $udomain=$env{'user.domain'}; }
5079: if (!$uname) { $uname=$env{'user.name'}; }
5080: my $uhome=&homeserver($uname,$udomain);
5081:
5082: if ($regexp) {
5083: $regexp=&escape($regexp);
5084: } else {
5085: $regexp='.';
5086: }
5087: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
5088: my @pairs=split(/\&/,$rep);
5089: my %returnhash=();
5090: if (!($rep =~ /^error/ )) {
5091: foreach my $item (@pairs) {
5092: my ($key,$value)=split(/=/,$item,2);
5093: $key = &unescape($key);
5094: next if ($key =~ /^error: 2 /);
5095: $returnhash{$key}=&thaw_unescape($value);
5096: }
5097: }
5098: return %returnhash;
5099: }
5100:
5101:
5102: # --------------------------------------------------------- dumpstore interface
5103:
5104: sub dumpstore {
5105: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
5106: if (!$udomain) { $udomain=$env{'user.domain'}; }
5107: if (!$uname) { $uname=$env{'user.name'}; }
5108: my $uhome=&homeserver($uname,$udomain);
5109: if ($regexp) {
5110: $regexp=&escape($regexp);
5111: } else {
5112: $regexp='.';
5113: }
5114: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
5115: my @pairs=split(/\&/,$rep);
5116: my %returnhash=();
5117: foreach my $item (@pairs) {
5118: my ($key,$value)=split(/=/,$item,2);
5119: next if ($key =~ /^error: 2 /);
5120: $returnhash{$key}=&thaw_unescape($value);
5121: }
5122: return %returnhash;
5123: }
5124:
5125: # -------------------------------------------------------------- keys interface
5126:
5127: sub getkeys {
5128: my ($namespace,$udomain,$uname)=@_;
5129: if (!$udomain) { $udomain=$env{'user.domain'}; }
5130: if (!$uname) { $uname=$env{'user.name'}; }
5131: my $uhome=&homeserver($uname,$udomain);
5132: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5133: my @keyarray=();
5134: foreach my $key (split(/\&/,$rep)) {
5135: next if ($key =~ /^error: 2 /);
5136: push(@keyarray,&unescape($key));
5137: }
5138: return @keyarray;
5139: }
5140:
5141: # --------------------------------------------------------------- currentdump
5142: sub currentdump {
5143: my ($courseid,$sdom,$sname)=@_;
5144: $courseid = $env{'request.course.id'} if (! defined($courseid));
5145: $sdom = $env{'user.domain'} if (! defined($sdom));
5146: $sname = $env{'user.name'} if (! defined($sname));
5147: my $uhome = &homeserver($sname,$sdom);
5148: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5149: return if ($rep =~ /^(error:|no_such_host)/);
5150: #
5151: my %returnhash=();
5152: #
5153: if ($rep eq "unknown_cmd") {
5154: # an old lond will not know currentdump
5155: # Do a dump and make it look like a currentdump
5156: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
5157: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5158: my %hash = @tmp;
5159: @tmp=();
5160: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
5161: } else {
5162: my @pairs=split(/\&/,$rep);
5163: foreach my $pair (@pairs) {
5164: my ($key,$value)=split(/=/,$pair,2);
5165: my ($symb,$param) = split(/:/,$key);
5166: $returnhash{&unescape($symb)}->{&unescape($param)} =
5167: &thaw_unescape($value);
5168: }
5169: }
5170: return %returnhash;
5171: }
5172:
5173: sub convert_dump_to_currentdump{
5174: my %hash = %{shift()};
5175: my %returnhash;
5176: # Code ripped from lond, essentially. The only difference
5177: # here is the unescaping done by lonnet::dump(). Conceivably
5178: # we might run in to problems with parameter names =~ /^v\./
5179: while (my ($key,$value) = each(%hash)) {
5180: my ($v,$symb,$param) = split(/:/,$key);
5181: $symb = &unescape($symb);
5182: $param = &unescape($param);
5183: next if ($v eq 'version' || $symb eq 'keys');
5184: next if (exists($returnhash{$symb}) &&
5185: exists($returnhash{$symb}->{$param}) &&
5186: $returnhash{$symb}->{'v.'.$param} > $v);
5187: $returnhash{$symb}->{$param}=$value;
5188: $returnhash{$symb}->{'v.'.$param}=$v;
5189: }
5190: #
5191: # Remove all of the keys in the hashes which keep track of
5192: # the version of the parameter.
5193: while (my ($symb,$param_hash) = each(%returnhash)) {
5194: # use a foreach because we are going to delete from the hash.
5195: foreach my $key (keys(%$param_hash)) {
5196: delete($param_hash->{$key}) if ($key =~ /^v\./);
5197: }
5198: }
5199: return \%returnhash;
5200: }
5201:
5202: # ------------------------------------------------------ critical inc interface
5203:
5204: sub cinc {
5205: return &inc(@_,'critical');
5206: }
5207:
5208: # --------------------------------------------------------------- inc interface
5209:
5210: sub inc {
5211: my ($namespace,$store,$udomain,$uname,$critical) = @_;
5212: if (!$udomain) { $udomain=$env{'user.domain'}; }
5213: if (!$uname) { $uname=$env{'user.name'}; }
5214: my $uhome=&homeserver($uname,$udomain);
5215: my $items='';
5216: if (! ref($store)) {
5217: # got a single value, so use that instead
5218: $items = &escape($store).'=&';
5219: } elsif (ref($store) eq 'SCALAR') {
5220: $items = &escape($$store).'=&';
5221: } elsif (ref($store) eq 'ARRAY') {
5222: $items = join('=&',map {&escape($_);} @{$store});
5223: } elsif (ref($store) eq 'HASH') {
5224: while (my($key,$value) = each(%{$store})) {
5225: $items.= &escape($key).'='.&escape($value).'&';
5226: }
5227: }
5228: $items=~s/\&$//;
5229: if ($critical) {
5230: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5231: } else {
5232: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5233: }
5234: }
5235:
5236: # --------------------------------------------------------------- put interface
5237:
5238: sub put {
5239: my ($namespace,$storehash,$udomain,$uname)=@_;
5240: if (!$udomain) { $udomain=$env{'user.domain'}; }
5241: if (!$uname) { $uname=$env{'user.name'}; }
5242: my $uhome=&homeserver($uname,$udomain);
5243: my $items='';
5244: foreach my $item (keys(%$storehash)) {
5245: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5246: }
5247: $items=~s/\&$//;
5248: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
5249: }
5250:
5251: # ------------------------------------------------------------ newput interface
5252:
5253: sub newput {
5254: my ($namespace,$storehash,$udomain,$uname)=@_;
5255: if (!$udomain) { $udomain=$env{'user.domain'}; }
5256: if (!$uname) { $uname=$env{'user.name'}; }
5257: my $uhome=&homeserver($uname,$udomain);
5258: my $items='';
5259: foreach my $key (keys(%$storehash)) {
5260: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5261: }
5262: $items=~s/\&$//;
5263: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5264: }
5265:
5266: # --------------------------------------------------------- putstore interface
5267:
5268: sub putstore {
5269: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5270: if (!$udomain) { $udomain=$env{'user.domain'}; }
5271: if (!$uname) { $uname=$env{'user.name'}; }
5272: my $uhome=&homeserver($uname,$udomain);
5273: my $items='';
5274: foreach my $key (keys(%$storehash)) {
5275: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
5276: }
5277: $items=~s/\&$//;
5278: my $esc_symb=&escape($symb);
5279: my $esc_v=&escape($version);
5280: my $reply =
5281: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
5282: $uhome);
5283: if ($reply eq 'unknown_cmd') {
5284: # gfall back to way things use to be done
5285: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5286: $uname);
5287: }
5288: return $reply;
5289: }
5290:
5291: sub old_putstore {
5292: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5293: if (!$udomain) { $udomain=$env{'user.domain'}; }
5294: if (!$uname) { $uname=$env{'user.name'}; }
5295: my $uhome=&homeserver($uname,$udomain);
5296: my %newstorehash;
5297: foreach my $item (keys(%$storehash)) {
5298: my $key = $version.':'.&escape($symb).':'.$item;
5299: $newstorehash{$key} = $storehash->{$item};
5300: }
5301: my $items='';
5302: my %allitems = ();
5303: foreach my $item (keys(%newstorehash)) {
5304: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
5305: my $key = $1.':keys:'.$2;
5306: $allitems{$key} .= $3.':';
5307: }
5308: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
5309: }
5310: foreach my $item (keys(%allitems)) {
5311: $allitems{$item} =~ s/\:$//;
5312: $items.= $item.'='.$allitems{$item}.'&';
5313: }
5314: $items=~s/\&$//;
5315: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
5316: }
5317:
5318: # ------------------------------------------------------ critical put interface
5319:
5320: sub cput {
5321: my ($namespace,$storehash,$udomain,$uname)=@_;
5322: if (!$udomain) { $udomain=$env{'user.domain'}; }
5323: if (!$uname) { $uname=$env{'user.name'}; }
5324: my $uhome=&homeserver($uname,$udomain);
5325: my $items='';
5326: foreach my $item (keys(%$storehash)) {
5327: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5328: }
5329: $items=~s/\&$//;
5330: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
5331: }
5332:
5333: # -------------------------------------------------------------- eget interface
5334:
5335: sub eget {
5336: my ($namespace,$storearr,$udomain,$uname)=@_;
5337: my $items='';
5338: foreach my $item (@$storearr) {
5339: $items.=&escape($item).'&';
5340: }
5341: $items=~s/\&$//;
5342: if (!$udomain) { $udomain=$env{'user.domain'}; }
5343: if (!$uname) { $uname=$env{'user.name'}; }
5344: my $uhome=&homeserver($uname,$udomain);
5345: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
5346: my @pairs=split(/\&/,$rep);
5347: my %returnhash=();
5348: my $i=0;
5349: foreach my $item (@$storearr) {
5350: $returnhash{$item}=&thaw_unescape($pairs[$i]);
5351: $i++;
5352: }
5353: return %returnhash;
5354: }
5355:
5356: # ------------------------------------------------------------ tmpput interface
5357: sub tmpput {
5358: my ($storehash,$server,$context)=@_;
5359: my $items='';
5360: foreach my $item (keys(%$storehash)) {
5361: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5362: }
5363: $items=~s/\&$//;
5364: if (defined($context)) {
5365: $items .= ':'.&escape($context);
5366: }
5367: return &reply("tmpput:$items",$server);
5368: }
5369:
5370: # ------------------------------------------------------------ tmpget interface
5371: sub tmpget {
5372: my ($token,$server)=@_;
5373: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5374: my $rep=&reply("tmpget:$token",$server);
5375: my %returnhash;
5376: foreach my $item (split(/\&/,$rep)) {
5377: my ($key,$value)=split(/=/,$item);
5378: next if ($key =~ /^error: 2 /);
5379: $returnhash{&unescape($key)}=&thaw_unescape($value);
5380: }
5381: return %returnhash;
5382: }
5383:
5384: # ------------------------------------------------------------ tmpdel interface
5385: sub tmpdel {
5386: my ($token,$server)=@_;
5387: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5388: return &reply("tmpdel:$token",$server);
5389: }
5390:
5391: # -------------------------------------------------- portfolio access checking
5392:
5393: sub portfolio_access {
5394: my ($requrl) = @_;
5395: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5396: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
5397: if ($result) {
5398: my %setters;
5399: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5400: my ($startblock,$endblock) =
5401: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5402: if ($startblock && $endblock) {
5403: return 'B';
5404: }
5405: } else {
5406: my ($startblock,$endblock) =
5407: &Apache::loncommon::blockcheck(\%setters,'port');
5408: if ($startblock && $endblock) {
5409: return 'B';
5410: }
5411: }
5412: }
5413: if ($result eq 'ok') {
5414: return 'F';
5415: } elsif ($result =~ /^[^:]+:guest_/) {
5416: return 'A';
5417: }
5418: return '';
5419: }
5420:
5421: sub get_portfolio_access {
5422: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5423:
5424: if (!ref($access_hash)) {
5425: my $current_perms = &get_portfile_permissions($udom,$unum);
5426: my %access_controls = &get_access_controls($current_perms,$group,
5427: $file_name);
5428: $access_hash = $access_controls{$file_name};
5429: }
5430:
5431: my ($public,$guest,@domains,@users,@courses,@groups);
5432: my $now = time;
5433: if (ref($access_hash) eq 'HASH') {
5434: foreach my $key (keys(%{$access_hash})) {
5435: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5436: if ($start > $now) {
5437: next;
5438: }
5439: if ($end && $end<$now) {
5440: next;
5441: }
5442: if ($scope eq 'public') {
5443: $public = $key;
5444: last;
5445: } elsif ($scope eq 'guest') {
5446: $guest = $key;
5447: } elsif ($scope eq 'domains') {
5448: push(@domains,$key);
5449: } elsif ($scope eq 'users') {
5450: push(@users,$key);
5451: } elsif ($scope eq 'course') {
5452: push(@courses,$key);
5453: } elsif ($scope eq 'group') {
5454: push(@groups,$key);
5455: }
5456: }
5457: if ($public) {
5458: return 'ok';
5459: }
5460: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5461: if ($guest) {
5462: return $guest;
5463: }
5464: } else {
5465: if (@domains > 0) {
5466: foreach my $domkey (@domains) {
5467: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
5468: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
5469: return 'ok';
5470: }
5471: }
5472: }
5473: }
5474: if (@users > 0) {
5475: foreach my $userkey (@users) {
5476: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
5477: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
5478: if (ref($item) eq 'HASH') {
5479: if (($item->{'uname'} eq $env{'user.name'}) &&
5480: ($item->{'udom'} eq $env{'user.domain'})) {
5481: return 'ok';
5482: }
5483: }
5484: }
5485: }
5486: }
5487: }
5488: my %roleshash;
5489: my @courses_and_groups = @courses;
5490: push(@courses_and_groups,@groups);
5491: if (@courses_and_groups > 0) {
5492: my (%allgroups,%allroles);
5493: my ($start,$end,$role,$sec,$group);
5494: foreach my $envkey (%env) {
5495: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
5496: my $cid = $2.'_'.$3;
5497: if ($1 eq 'gr') {
5498: $group = $4;
5499: $allgroups{$cid}{$group} = $env{$envkey};
5500: } else {
5501: if ($4 eq '') {
5502: $sec = 'none';
5503: } else {
5504: $sec = $4;
5505: }
5506: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5507: }
5508: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
5509: my $cid = $2.'_'.$3;
5510: if ($4 eq '') {
5511: $sec = 'none';
5512: } else {
5513: $sec = $4;
5514: }
5515: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5516: }
5517: }
5518: if (keys(%allroles) == 0) {
5519: return;
5520: }
5521: foreach my $key (@courses_and_groups) {
5522: my %content = %{$$access_hash{$key}};
5523: my $cnum = $content{'number'};
5524: my $cdom = $content{'domain'};
5525: my $cid = $cdom.'_'.$cnum;
5526: if (!exists($allroles{$cid})) {
5527: next;
5528: }
5529: foreach my $role_id (keys(%{$content{'roles'}})) {
5530: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5531: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5532: my @status = @{$content{'roles'}{$role_id}{'access'}};
5533: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5534: foreach my $role (keys(%{$allroles{$cid}})) {
5535: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5536: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5537: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5538: if (grep/^all$/,@sections) {
5539: return 'ok';
5540: } else {
5541: if (grep/^$sec$/,@sections) {
5542: return 'ok';
5543: }
5544: }
5545: }
5546: }
5547: if (keys(%{$allgroups{$cid}}) == 0) {
5548: if (grep/^none$/,@groups) {
5549: return 'ok';
5550: }
5551: } else {
5552: if (grep/^all$/,@groups) {
5553: return 'ok';
5554: }
5555: foreach my $group (keys(%{$allgroups{$cid}})) {
5556: if (grep/^$group$/,@groups) {
5557: return 'ok';
5558: }
5559: }
5560: }
5561: }
5562: }
5563: }
5564: }
5565: }
5566: if ($guest) {
5567: return $guest;
5568: }
5569: }
5570: }
5571: return;
5572: }
5573:
5574: sub course_group_datechecker {
5575: my ($dates,$now,$status) = @_;
5576: my ($start,$end) = split(/\./,$dates);
5577: if (!$start && !$end) {
5578: return 'ok';
5579: }
5580: if (grep/^active$/,@{$status}) {
5581: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5582: return 'ok';
5583: }
5584: }
5585: if (grep/^previous$/,@{$status}) {
5586: if ($end > $now ) {
5587: return 'ok';
5588: }
5589: }
5590: if (grep/^future$/,@{$status}) {
5591: if ($start > $now) {
5592: return 'ok';
5593: }
5594: }
5595: return;
5596: }
5597:
5598: sub parse_portfolio_url {
5599: my ($url) = @_;
5600:
5601: my ($type,$udom,$unum,$group,$file_name);
5602:
5603: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
5604: $type = 1;
5605: $udom = $1;
5606: $unum = $2;
5607: $file_name = $3;
5608: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
5609: $type = 2;
5610: $udom = $1;
5611: $unum = $2;
5612: $group = $3;
5613: $file_name = $3.'/'.$4;
5614: }
5615: if (wantarray) {
5616: return ($type,$udom,$unum,$file_name,$group);
5617: }
5618: return $type;
5619: }
5620:
5621: sub is_portfolio_url {
5622: my ($url) = @_;
5623: return scalar(&parse_portfolio_url($url));
5624: }
5625:
5626: sub is_portfolio_file {
5627: my ($file) = @_;
5628: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
5629: return 1;
5630: }
5631: return;
5632: }
5633:
5634: sub usertools_access {
5635: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
5636: my ($access,%tools);
5637: if ($context eq '') {
5638: $context = 'tools';
5639: }
5640: if ($context eq 'requestcourses') {
5641: %tools = (
5642: official => 1,
5643: unofficial => 1,
5644: community => 1,
5645: );
5646: } else {
5647: %tools = (
5648: aboutme => 1,
5649: blog => 1,
5650: portfolio => 1,
5651: );
5652: }
5653: return if (!defined($tools{$tool}));
5654:
5655: if ((!defined($udom)) || (!defined($uname))) {
5656: $udom = $env{'user.domain'};
5657: $uname = $env{'user.name'};
5658: }
5659:
5660: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5661: if ($action ne 'reload') {
5662: if ($context eq 'requestcourses') {
5663: return $env{'environment.canrequest.'.$tool};
5664: } else {
5665: return $env{'environment.availabletools.'.$tool};
5666: }
5667: }
5668: }
5669:
5670: my ($toolstatus,$inststatus);
5671:
5672: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5673: ($action ne 'reload')) {
5674: $toolstatus = $env{'environment.'.$context.'.'.$tool};
5675: $inststatus = $env{'environment.inststatus'};
5676: } else {
5677: if (ref($userenvref) eq 'HASH') {
5678: $toolstatus = $userenvref->{$context.'.'.$tool};
5679: $inststatus = $userenvref->{'inststatus'};
5680: } else {
5681: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5682: $toolstatus = $userenv{$context.'.'.$tool};
5683: $inststatus = $userenv{'inststatus'};
5684: }
5685: }
5686:
5687: if ($toolstatus ne '') {
5688: if ($toolstatus) {
5689: $access = 1;
5690: } else {
5691: $access = 0;
5692: }
5693: return $access;
5694: }
5695:
5696: my ($is_adv,%domdef);
5697: if (ref($is_advref) eq 'HASH') {
5698: $is_adv = $is_advref->{'is_adv'};
5699: } else {
5700: $is_adv = &is_advanced_user($udom,$uname);
5701: }
5702: if (ref($domdefref) eq 'HASH') {
5703: %domdef = %{$domdefref};
5704: } else {
5705: %domdef = &get_domain_defaults($udom);
5706: }
5707: if (ref($domdef{$tool}) eq 'HASH') {
5708: if ($is_adv) {
5709: if ($domdef{$tool}{'_LC_adv'} ne '') {
5710: if ($domdef{$tool}{'_LC_adv'}) {
5711: $access = 1;
5712: } else {
5713: $access = 0;
5714: }
5715: return $access;
5716: }
5717: }
5718: if ($inststatus ne '') {
5719: my ($hasaccess,$hasnoaccess);
5720: foreach my $affiliation (split(/:/,$inststatus)) {
5721: if ($domdef{$tool}{$affiliation} ne '') {
5722: if ($domdef{$tool}{$affiliation}) {
5723: $hasaccess = 1;
5724: } else {
5725: $hasnoaccess = 1;
5726: }
5727: }
5728: }
5729: if ($hasaccess || $hasnoaccess) {
5730: if ($hasaccess) {
5731: $access = 1;
5732: } elsif ($hasnoaccess) {
5733: $access = 0;
5734: }
5735: return $access;
5736: }
5737: } else {
5738: if ($domdef{$tool}{'default'} ne '') {
5739: if ($domdef{$tool}{'default'}) {
5740: $access = 1;
5741: } elsif ($domdef{$tool}{'default'} == 0) {
5742: $access = 0;
5743: }
5744: return $access;
5745: }
5746: }
5747: } else {
5748: if ($context eq 'tools') {
5749: $access = 1;
5750: } else {
5751: $access = 0;
5752: }
5753: return $access;
5754: }
5755: }
5756:
5757: sub is_course_owner {
5758: my ($cdom,$cnum,$udom,$uname) = @_;
5759: if (($udom eq '') || ($uname eq '')) {
5760: $udom = $env{'user.domain'};
5761: $uname = $env{'user.name'};
5762: }
5763: unless (($udom eq '') || ($uname eq '')) {
5764: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5765: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5766: return 1;
5767: } else {
5768: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5769: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5770: return 1;
5771: }
5772: }
5773: }
5774: }
5775: return;
5776: }
5777:
5778: sub is_advanced_user {
5779: my ($udom,$uname) = @_;
5780: if ($udom ne '' && $uname ne '') {
5781: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5782: if (wantarray) {
5783: return ($env{'user.adv'},$env{'user.author'});
5784: } else {
5785: return $env{'user.adv'};
5786: }
5787: }
5788: }
5789: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5790: my %allroles;
5791: my ($is_adv,$is_author);
5792: foreach my $role (keys(%roleshash)) {
5793: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5794: my $area = '/'.$tdomain.'/'.$trest;
5795: if ($sec ne '') {
5796: $area .= '/'.$sec;
5797: }
5798: if (($area ne '') && ($trole ne '')) {
5799: my $spec=$trole.'.'.$area;
5800: if ($trole =~ /^cr\//) {
5801: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5802: } elsif ($trole ne 'gr') {
5803: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5804: }
5805: if ($trole eq 'au') {
5806: $is_author = 1;
5807: }
5808: }
5809: }
5810: foreach my $role (keys(%allroles)) {
5811: last if ($is_adv);
5812: foreach my $item (split(/:/,$allroles{$role})) {
5813: if ($item ne '') {
5814: my ($privilege,$restrictions)=split(/&/,$item);
5815: if ($privilege eq 'adv') {
5816: $is_adv = 1;
5817: last;
5818: }
5819: }
5820: }
5821: }
5822: if (wantarray) {
5823: return ($is_adv,$is_author);
5824: }
5825: return $is_adv;
5826: }
5827:
5828: sub check_can_request {
5829: my ($dom,$can_request,$request_domains) = @_;
5830: my $canreq = 0;
5831: my ($types,$typename) = &Apache::loncommon::course_types();
5832: my @options = ('approval','validate','autolimit');
5833: my $optregex = join('|',@options);
5834: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5835: foreach my $type (@{$types}) {
5836: if (&usertools_access($env{'user.name'},
5837: $env{'user.domain'},
5838: $type,undef,'requestcourses')) {
5839: $canreq ++;
5840: if (ref($request_domains) eq 'HASH') {
5841: push(@{$request_domains->{$type}},$env{'user.domain'});
5842: }
5843: if ($dom eq $env{'user.domain'}) {
5844: $can_request->{$type} = 1;
5845: }
5846: }
5847: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5848: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5849: if (@curr > 0) {
5850: foreach my $item (@curr) {
5851: if (ref($request_domains) eq 'HASH') {
5852: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5853: if ($otherdom ne '') {
5854: if (ref($request_domains->{$type}) eq 'ARRAY') {
5855: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5856: push(@{$request_domains->{$type}},$otherdom);
5857: }
5858: } else {
5859: push(@{$request_domains->{$type}},$otherdom);
5860: }
5861: }
5862: }
5863: }
5864: unless($dom eq $env{'user.domain'}) {
5865: $canreq ++;
5866: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5867: $can_request->{$type} = 1;
5868: }
5869: }
5870: }
5871: }
5872: }
5873: }
5874: return $canreq;
5875: }
5876:
5877: # ---------------------------------------------- Custom access rule evaluation
5878:
5879: sub customaccess {
5880: my ($priv,$uri)=@_;
5881: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
5882: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
5883: $udom = &LONCAPA::clean_domain($udom);
5884: $ucrs = &LONCAPA::clean_username($ucrs);
5885: my $access=0;
5886: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
5887: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5888: if ($type eq 'user') {
5889: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5890: my ($tdom,$tuname)=split(m{/},$scope);
5891: if ($tdom) {
5892: if ($tdom ne $env{'user.domain'}) { next; }
5893: }
5894: if ($tuname) {
5895: if ($tuname ne $env{'user.name'}) { next; }
5896: }
5897: $access=($effect eq 'allow');
5898: last;
5899: }
5900: } else {
5901: if ($role) {
5902: if ($role ne $urole) { next; }
5903: }
5904: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5905: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5906: if ($tdom) {
5907: if ($tdom ne $udom) { next; }
5908: }
5909: if ($tcrs) {
5910: if ($tcrs ne $ucrs) { next; }
5911: }
5912: if ($tsec) {
5913: if ($tsec ne $usec) { next; }
5914: }
5915: $access=($effect eq 'allow');
5916: last;
5917: }
5918: if ($realm eq '' && $role eq '') {
5919: $access=($effect eq 'allow');
5920: }
5921: }
5922: }
5923: return $access;
5924: }
5925:
5926: # ------------------------------------------------- Check for a user privilege
5927:
5928: sub allowed {
5929: my ($priv,$uri,$symb,$role)=@_;
5930: my $ver_orguri=$uri;
5931: $uri=&deversion($uri);
5932: my $orguri=$uri;
5933: $uri=&declutter($uri);
5934:
5935: if ($priv eq 'evb') {
5936: # Evade communication block restrictions for specified role in a course
5937: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5938: return $1;
5939: } else {
5940: return;
5941: }
5942: }
5943:
5944: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
5945: # Free bre access to adm and meta resources
5946: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
5947: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5948: && ($priv eq 'bre')) {
5949: return 'F';
5950: }
5951:
5952: # Free bre access to user's own portfolio contents
5953: my ($space,$domain,$name,@dir)=split('/',$uri);
5954: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
5955: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
5956: my %setters;
5957: my ($startblock,$endblock) =
5958: &Apache::loncommon::blockcheck(\%setters,'port');
5959: if ($startblock && $endblock) {
5960: return 'B';
5961: } else {
5962: return 'F';
5963: }
5964: }
5965:
5966: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
5967: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5968: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5969: if (exists($env{'request.course.id'})) {
5970: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5971: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5972: if (($domain eq $cdom) && ($name eq $cnum)) {
5973: my $courseprivid=$env{'request.course.id'};
5974: $courseprivid=~s/\_/\//;
5975: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5976: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5977: return $1;
5978: } else {
5979: if ($env{'request.course.sec'}) {
5980: $courseprivid.='/'.$env{'request.course.sec'};
5981: }
5982: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5983: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5984: return $2;
5985: }
5986: }
5987: }
5988: }
5989: }
5990:
5991: # Free bre to public access
5992:
5993: if ($priv eq 'bre') {
5994: my $copyright=&metadata($uri,'copyright');
5995: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
5996: return 'F';
5997: }
5998: if ($copyright eq 'priv') {
5999: $uri=~/([^\/]+)\/([^\/]+)\//;
6000: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
6001: return '';
6002: }
6003: }
6004: if ($copyright eq 'domain') {
6005: $uri=~/([^\/]+)\/([^\/]+)\//;
6006: unless (($env{'user.domain'} eq $1) ||
6007: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
6008: return '';
6009: }
6010: }
6011: if ($env{'request.role'}=~ /li\.\//) {
6012: # Library role, so allow browsing of resources in this domain.
6013: return 'F';
6014: }
6015: if ($copyright eq 'custom') {
6016: unless (&customaccess($priv,$uri)) { return ''; }
6017: }
6018: }
6019: # Domain coordinator is trying to create a course
6020: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
6021: # uri is the requested domain in this case.
6022: # comparison to 'request.role.domain' shows if the user has selected
6023: # a role of dc for the domain in question.
6024: return 'F' if ($uri eq $env{'request.role.domain'});
6025: }
6026:
6027: my $thisallowed='';
6028: my $statecond=0;
6029: my $courseprivid='';
6030:
6031: my $ownaccess;
6032: # Community Coordinator or Assistant Co-author browsing resource space.
6033: if (($priv eq 'bro') && ($env{'user.author'})) {
6034: if ($uri eq '') {
6035: $ownaccess = 1;
6036: } else {
6037: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6038: my $udom = $env{'user.domain'};
6039: my $uname = $env{'user.name'};
6040: if ($uri =~ m{^\Q$udom\E/?$}) {
6041: $ownaccess = 1;
6042: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
6043: unless ($uri =~ m{\.\./}) {
6044: $ownaccess = 1;
6045: }
6046: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6047: my $now = time;
6048: if ($uri =~ m{^([^/]+)/?$}) {
6049: my $adom = $1;
6050: foreach my $key (keys(%env)) {
6051: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
6052: my ($start,$end) = split('.',$env{$key});
6053: if (($now >= $start) && (!$end || $end < $now)) {
6054: $ownaccess = 1;
6055: last;
6056: }
6057: }
6058: }
6059: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6060: my $adom = $1;
6061: my $aname = $2;
6062: foreach my $role ('ca','aa') {
6063: if ($env{"user.role.$role./$adom/$aname"}) {
6064: my ($start,$end) =
6065: split('.',$env{"user.role.$role./$adom/$aname"});
6066: if (($now >= $start) && (!$end || $end < $now)) {
6067: $ownaccess = 1;
6068: last;
6069: }
6070: }
6071: }
6072: }
6073: }
6074: }
6075: }
6076: }
6077:
6078: # Course
6079:
6080: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
6081: unless (($priv eq 'bro') && (!$ownaccess)) {
6082: $thisallowed.=$1;
6083: }
6084: }
6085:
6086: # Domain
6087:
6088: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
6089: =~/\Q$priv\E\&([^\:]*)/) {
6090: unless (($priv eq 'bro') && (!$ownaccess)) {
6091: $thisallowed.=$1;
6092: }
6093: }
6094:
6095: # User who is not author or co-author might still be able to edit
6096: # resource of an author in the domain (e.g., if Domain Coordinator).
6097: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6098: (&allowed('mdc',$env{'request.course.id'}))) {
6099: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6100: $thisallowed.=$1;
6101: }
6102: }
6103:
6104: # Course: uri itself is a course
6105: my $courseuri=$uri;
6106: $courseuri=~s/\_(\d)/\/$1/;
6107: $courseuri=~s/^([^\/])/\/$1/;
6108:
6109: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
6110: =~/\Q$priv\E\&([^\:]*)/) {
6111: unless (($priv eq 'bro') && (!$ownaccess)) {
6112: $thisallowed.=$1;
6113: }
6114: }
6115:
6116: # URI is an uploaded document for this course, default permissions don't matter
6117: # not allowing 'edit' access (editupload) to uploaded course docs
6118: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
6119: $thisallowed='';
6120: my ($match)=&is_on_map($uri);
6121: if ($match) {
6122: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6123: =~/\Q$priv\E\&([^\:]*)/) {
6124: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6125: if (@blockers > 0) {
6126: $thisallowed = 'B';
6127: } else {
6128: $thisallowed.=$1;
6129: }
6130: }
6131: } else {
6132: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
6133: if ($refuri) {
6134: if ($refuri =~ m|^/adm/|) {
6135: $thisallowed='F';
6136: } else {
6137: $refuri=&declutter($refuri);
6138: my ($match) = &is_on_map($refuri);
6139: if ($match) {
6140: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6141: if (@blockers > 0) {
6142: $thisallowed = 'B';
6143: } else {
6144: $thisallowed='F';
6145: }
6146: }
6147: }
6148: }
6149: }
6150: }
6151:
6152: if ($priv eq 'bre'
6153: && $thisallowed ne 'F'
6154: && $thisallowed ne '2'
6155: && &is_portfolio_url($uri)) {
6156: $thisallowed = &portfolio_access($uri);
6157: }
6158:
6159: # Full access at system, domain or course-wide level? Exit.
6160: if ($thisallowed=~/F/) {
6161: return 'F';
6162: }
6163:
6164: # If this is generating or modifying users, exit with special codes
6165:
6166: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6167: if (($priv eq 'cca') || ($priv eq 'caa')) {
6168: my ($audom,$auname)=split('/',$uri);
6169: # no author name given, so this just checks on the general right to make a co-author in this domain
6170: unless ($auname) { return $thisallowed; }
6171: # an author name is given, so we are about to actually make a co-author for a certain account
6172: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6173: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6174: ($audom ne $env{'request.role.domain'}))) { return ''; }
6175: }
6176: return $thisallowed;
6177: }
6178: #
6179: # Gathered so far: system, domain and course wide privileges
6180: #
6181: # Course: See if uri or referer is an individual resource that is part of
6182: # the course
6183:
6184: if ($env{'request.course.id'}) {
6185:
6186: $courseprivid=$env{'request.course.id'};
6187: if ($env{'request.course.sec'}) {
6188: $courseprivid.='/'.$env{'request.course.sec'};
6189: }
6190: $courseprivid=~s/\_/\//;
6191: my $checkreferer=1;
6192: my ($match,$cond)=&is_on_map($uri);
6193: if ($match) {
6194: $statecond=$cond;
6195: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
6196: =~/\Q$priv\E\&([^\:]*)/) {
6197: my $value = $1;
6198: if ($priv eq 'bre') {
6199: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6200: if (@blockers > 0) {
6201: $thisallowed = 'B';
6202: } else {
6203: $thisallowed.=$value;
6204: }
6205: } else {
6206: $thisallowed.=$value;
6207: }
6208: $checkreferer=0;
6209: }
6210: }
6211:
6212: if ($checkreferer) {
6213: my $refuri=$env{'httpref.'.$orguri};
6214: unless ($refuri) {
6215: foreach my $key (keys(%env)) {
6216: if ($key=~/^httpref\..*\*/) {
6217: my $pattern=$key;
6218: $pattern=~s/^httpref\.\/res\///;
6219: $pattern=~s/\*/\[\^\/\]\+/g;
6220: $pattern=~s/\//\\\//g;
6221: if ($orguri=~/$pattern/) {
6222: $refuri=$env{$key};
6223: }
6224: }
6225: }
6226: }
6227:
6228: if ($refuri) {
6229: $refuri=&declutter($refuri);
6230: my ($match,$cond)=&is_on_map($refuri);
6231: if ($match) {
6232: my $refstatecond=$cond;
6233: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
6234: =~/\Q$priv\E\&([^\:]*)/) {
6235: my $value = $1;
6236: if ($priv eq 'bre') {
6237: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6238: if (@blockers > 0) {
6239: $thisallowed = 'B';
6240: } else {
6241: $thisallowed.=$value;
6242: }
6243: } else {
6244: $thisallowed.=$value;
6245: }
6246: $uri=$refuri;
6247: $statecond=$refstatecond;
6248: }
6249: }
6250: }
6251: }
6252: }
6253:
6254: #
6255: # Gathered now: all privileges that could apply, and condition number
6256: #
6257: #
6258: # Full or no access?
6259: #
6260:
6261: if ($thisallowed=~/F/) {
6262: return 'F';
6263: }
6264:
6265: unless ($thisallowed) {
6266: return '';
6267: }
6268:
6269: # Restrictions exist, deal with them
6270: #
6271: # C:according to course preferences
6272: # R:according to resource settings
6273: # L:unless locked
6274: # X:according to user session state
6275: #
6276:
6277: # Possibly locked functionality, check all courses
6278: # Locks might take effect only after 10 minutes cache expiration for other
6279: # courses, and 2 minutes for current course
6280:
6281: my $envkey;
6282: if ($thisallowed=~/L/) {
6283: foreach $envkey (keys(%env)) {
6284: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6285: my $courseid=$2;
6286: my $roleid=$1.'.'.$2;
6287: $courseid=~s/^\///;
6288: my $expiretime=600;
6289: if ($env{'request.role'} eq $roleid) {
6290: $expiretime=120;
6291: }
6292: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6293: my $prefix='course.'.$cdom.'_'.$cnum.'.';
6294: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
6295: &coursedescription($courseid,{'freshen_cache' => 1});
6296: }
6297: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6298: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6299: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6300: &log($env{'user.domain'},$env{'user.name'},
6301: $env{'user.home'},
6302: 'Locked by res: '.$priv.' for '.$uri.' due to '.
6303: $cdom.'/'.$cnum.'/'.$csec.' expire '.
6304: $env{$prefix.'priv.'.$priv.'.lock.expire'});
6305: return '';
6306: }
6307: }
6308: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6309: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6310: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6311: &log($env{'user.domain'},$env{'user.name'},
6312: $env{'user.home'},
6313: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
6314: $cdom.'/'.$cnum.'/'.$csec.' expire '.
6315: $env{$prefix.'priv.'.$priv.'.lock.expire'});
6316: return '';
6317: }
6318: }
6319: }
6320: }
6321: }
6322:
6323: #
6324: # Rest of the restrictions depend on selected course
6325: #
6326:
6327: unless ($env{'request.course.id'}) {
6328: if ($thisallowed eq 'A') {
6329: return 'A';
6330: } elsif ($thisallowed eq 'B') {
6331: return 'B';
6332: } else {
6333: return '1';
6334: }
6335: }
6336:
6337: #
6338: # Now user is definitely in a course
6339: #
6340:
6341:
6342: # Course preferences
6343:
6344: if ($thisallowed=~/C/) {
6345: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6346: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6347: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
6348: =~/\Q$rolecode\E/) {
6349: if (($priv ne 'pch') && ($priv ne 'plc')) {
6350: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6351: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6352: $env{'request.course.id'});
6353: }
6354: return '';
6355: }
6356:
6357: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
6358: =~/\Q$unamedom\E/) {
6359: if (($priv ne 'pch') && ($priv ne 'plc')) {
6360: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6361: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6362: $env{'request.course.id'});
6363: }
6364: return '';
6365: }
6366: }
6367:
6368: # Resource preferences
6369:
6370: if ($thisallowed=~/R/) {
6371: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6372: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
6373: if (($priv ne 'pch') && ($priv ne 'plc')) {
6374: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6375: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6376: }
6377: return '';
6378: }
6379: }
6380:
6381: # Restricted by state or randomout?
6382:
6383: if ($thisallowed=~/X/) {
6384: if ($env{'acc.randomout'}) {
6385: if (!$symb) { $symb=&symbread($uri,1); }
6386: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
6387: return '';
6388: }
6389: }
6390: if (&condval($statecond)) {
6391: return '2';
6392: } else {
6393: return '';
6394: }
6395: }
6396:
6397: if ($thisallowed eq 'A') {
6398: return 'A';
6399: } elsif ($thisallowed eq 'B') {
6400: return 'B';
6401: }
6402: return 'F';
6403: }
6404:
6405: sub get_comm_blocks {
6406: my ($cdom,$cnum) = @_;
6407: if ($cdom eq '' || $cnum eq '') {
6408: return unless ($env{'request.course.id'});
6409: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6410: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6411: }
6412: my %commblocks;
6413: my $hashid=$cdom.'_'.$cnum;
6414: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
6415: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
6416: %commblocks = %{$blocksref};
6417: } else {
6418: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
6419: my $cachetime = 600;
6420: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
6421: }
6422: return %commblocks;
6423: }
6424:
6425: sub has_comm_blocking {
6426: my ($priv,$symb,$uri,$blocks) = @_;
6427: return unless ($env{'request.course.id'});
6428: return unless ($priv eq 'bre');
6429: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
6430: my %commblocks;
6431: if (ref($blocks) eq 'HASH') {
6432: %commblocks = %{$blocks};
6433: } else {
6434: %commblocks = &get_comm_blocks();
6435: }
6436: return unless (keys(%commblocks) > 0);
6437: if (!$symb) { $symb=&symbread($uri,1); }
6438: my ($map,$resid,undef)=&decode_symb($symb);
6439: my %tocheck = (
6440: maps => $map,
6441: resources => $symb,
6442: );
6443: my @blockers;
6444: my $now = time;
6445: my $navmap = Apache::lonnavmaps::navmap->new();
6446: foreach my $block (keys(%commblocks)) {
6447: if ($block =~ /^(\d+)____(\d+)$/) {
6448: my ($start,$end) = ($1,$2);
6449: if ($start <= $now && $end >= $now) {
6450: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
6451: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
6452: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
6453: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
6454: unless (grep(/^\Q$block\E$/,@blockers)) {
6455: push(@blockers,$block);
6456: }
6457: }
6458: }
6459: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
6460: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
6461: unless (grep(/^\Q$block\E$/,@blockers)) {
6462: push(@blockers,$block);
6463: }
6464: }
6465: }
6466: }
6467: }
6468: }
6469: } elsif ($block =~ /^firstaccess____(.+)$/) {
6470: my $item = $1;
6471: my @to_test;
6472: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
6473: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
6474: my $check_interval;
6475: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
6476: my @interval;
6477: my $type = 'map';
6478: if ($item eq 'course') {
6479: $type = 'course';
6480: @interval=&EXT("resource.0.interval");
6481: } else {
6482: if ($item =~ /___\d+___/) {
6483: $type = 'resource';
6484: @interval=&EXT("resource.0.interval",$item);
6485: if (ref($navmap)) {
6486: my $res = $navmap->getBySymb($item);
6487: push(@to_test,$res);
6488: }
6489: } else {
6490: my $mapsymb = &symbread($item,1);
6491: if ($mapsymb) {
6492: if (ref($navmap)) {
6493: my $mapres = $navmap->getBySymb($mapsymb);
6494: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
6495: foreach my $res (@to_test) {
6496: my $symb = $res->symb();
6497: next if ($symb eq $mapsymb);
6498: if ($symb ne '') {
6499: @interval=&EXT("resource.0.interval",$symb);
6500: last;
6501: }
6502: }
6503: }
6504: }
6505: }
6506: }
6507: if ($interval[0] =~ /\d+/) {
6508: my $first_access;
6509: if ($type eq 'resource') {
6510: $first_access=&get_first_access($interval[1],$item);
6511: } elsif ($type eq 'map') {
6512: $first_access=&get_first_access($interval[1],undef,$item);
6513: } else {
6514: $first_access=&get_first_access($interval[1]);
6515: }
6516: if ($first_access) {
6517: my $timesup = $first_access+$interval[0];
6518: if ($timesup > $now) {
6519: foreach my $res (@to_test) {
6520: if ($res->is_problem()) {
6521: if ($res->completable()) {
6522: unless (grep(/^\Q$block\E$/,@blockers)) {
6523: push(@blockers,$block);
6524: }
6525: last;
6526: }
6527: }
6528: }
6529: }
6530: }
6531: }
6532: }
6533: }
6534: }
6535: }
6536: }
6537: return @blockers;
6538: }
6539:
6540: sub check_docs_block {
6541: my ($docsblock,$tocheck) =@_;
6542: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
6543: return;
6544: }
6545: if (ref($docsblock->{'maps'}) eq 'HASH') {
6546: if ($tocheck->{'maps'}) {
6547: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
6548: return 1;
6549: }
6550: }
6551: }
6552: if (ref($docsblock->{'resources'}) eq 'HASH') {
6553: if ($tocheck->{'resources'}) {
6554: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
6555: return 1;
6556: }
6557: }
6558: }
6559: return;
6560: }
6561:
6562: #
6563: # Removes the versino from a URI and
6564: # splits it in to its filename and path to the filename.
6565: # Seems like File::Basename could have done this more clearly.
6566: # Parameters:
6567: # $uri - input URI
6568: # Returns:
6569: # Two element list consisting of
6570: # $pathname - the URI up to and excluding the trailing /
6571: # $filename - The part of the URI following the last /
6572: # NOTE:
6573: # Another realization of this is simply:
6574: # use File::Basename;
6575: # ...
6576: # $uri = shift;
6577: # $filename = basename($uri);
6578: # $path = dirname($uri);
6579: # return ($filename, $path);
6580: #
6581: # The implementation below is probably faster however.
6582: #
6583: sub split_uri_for_cond {
6584: my $uri=&deversion(&declutter(shift));
6585: my @uriparts=split(/\//,$uri);
6586: my $filename=pop(@uriparts);
6587: my $pathname=join('/',@uriparts);
6588: return ($pathname,$filename);
6589: }
6590: # --------------------------------------------------- Is a resource on the map?
6591:
6592: sub is_on_map {
6593: my ($pathname,$filename) = &split_uri_for_cond(shift);
6594: #Trying to find the conditional for the file
6595: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
6596: /\&\Q$filename\E\:([\d\|]+)\&/);
6597: if ($match) {
6598: return (1,$1);
6599: } else {
6600: return (0,0);
6601: }
6602: }
6603:
6604: # --------------------------------------------------------- Get symb from alias
6605:
6606: sub get_symb_from_alias {
6607: my $symb=shift;
6608: my ($map,$resid,$url)=&decode_symb($symb);
6609: # Already is a symb
6610: if ($url) { return $symb; }
6611: # Must be an alias
6612: my $aliassymb='';
6613: my %bighash;
6614: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6615: &GDBM_READER(),0640)) {
6616: my $rid=$bighash{'mapalias_'.$symb};
6617: if ($rid) {
6618: my ($mapid,$resid)=split(/\./,$rid);
6619: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
6620: $resid,$bighash{'src_'.$rid});
6621: }
6622: untie %bighash;
6623: }
6624: return $aliassymb;
6625: }
6626:
6627: # ----------------------------------------------------------------- Define Role
6628:
6629: sub definerole {
6630: if (allowed('mcr','/')) {
6631: my ($rolename,$sysrole,$domrole,$courole)=@_;
6632: foreach my $role (split(':',$sysrole)) {
6633: my ($crole,$cqual)=split(/\&/,$role);
6634: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
6635: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
6636: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
6637: return "refused:s:$crole&$cqual";
6638: }
6639: }
6640: }
6641: foreach my $role (split(':',$domrole)) {
6642: my ($crole,$cqual)=split(/\&/,$role);
6643: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
6644: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
6645: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
6646: return "refused:d:$crole&$cqual";
6647: }
6648: }
6649: }
6650: foreach my $role (split(':',$courole)) {
6651: my ($crole,$cqual)=split(/\&/,$role);
6652: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
6653: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
6654: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
6655: return "refused:c:$crole&$cqual";
6656: }
6657: }
6658: }
6659: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
6660: "$env{'user.domain'}:$env{'user.name'}:".
6661: "rolesdef_$rolename=".
6662: escape($sysrole.'_'.$domrole.'_'.$courole);
6663: return reply($command,$env{'user.home'});
6664: } else {
6665: return 'refused';
6666: }
6667: }
6668:
6669: # ---------------- Make a metadata query against the network of library servers
6670:
6671: sub metadata_query {
6672: my ($query,$custom,$customshow,$server_array)=@_;
6673: my %rhash;
6674: my %libserv = &all_library();
6675: my @server_list = (defined($server_array) ? @$server_array
6676: : keys(%libserv) );
6677: for my $server (@server_list) {
6678: unless ($custom or $customshow) {
6679: my $reply=&reply("querysend:".&escape($query),$server);
6680: $rhash{$server}=$reply;
6681: }
6682: else {
6683: my $reply=&reply("querysend:".&escape($query).':'.
6684: &escape($custom).':'.&escape($customshow),
6685: $server);
6686: $rhash{$server}=$reply;
6687: }
6688: }
6689: return \%rhash;
6690: }
6691:
6692: # ----------------------------------------- Send log queries and wait for reply
6693:
6694: sub log_query {
6695: my ($uname,$udom,$query,%filters)=@_;
6696: my $uhome=&homeserver($uname,$udom);
6697: if ($uhome eq 'no_host') { return 'error: no_host'; }
6698: my $uhost=&hostname($uhome);
6699: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
6700: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
6701: $uhome);
6702: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
6703: return get_query_reply($queryid);
6704: }
6705:
6706: # -------------------------- Update MySQL table for portfolio file
6707:
6708: sub update_portfolio_table {
6709: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
6710: if ($group ne '') {
6711: $file_name =~s /^\Q$group\E//;
6712: }
6713: my $homeserver = &homeserver($uname,$udom);
6714: my $queryid=
6715: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
6716: ':'.&escape($file_name).':'.$action,$homeserver);
6717: my $reply = &get_query_reply($queryid);
6718: return $reply;
6719: }
6720:
6721: # -------------------------- Update MySQL allusers table
6722:
6723: sub update_allusers_table {
6724: my ($uname,$udom,$names) = @_;
6725: my $homeserver = &homeserver($uname,$udom);
6726: my $queryid=
6727: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
6728: 'lastname='.&escape($names->{'lastname'}).'%%'.
6729: 'firstname='.&escape($names->{'firstname'}).'%%'.
6730: 'middlename='.&escape($names->{'middlename'}).'%%'.
6731: 'generation='.&escape($names->{'generation'}).'%%'.
6732: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
6733: 'id='.&escape($names->{'id'}),$homeserver);
6734: return;
6735: }
6736:
6737: # ------- Request retrieval of institutional classlists for course(s)
6738:
6739: sub fetch_enrollment_query {
6740: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
6741: my $homeserver;
6742: my $maxtries = 1;
6743: if ($context eq 'automated') {
6744: $homeserver = $perlvar{'lonHostID'};
6745: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
6746: } else {
6747: $homeserver = &homeserver($cnum,$dom);
6748: }
6749: my $host=&hostname($homeserver);
6750: my $cmd = '';
6751: foreach my $affiliate (keys(%{$affiliatesref})) {
6752: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
6753: }
6754: $cmd =~ s/%%$//;
6755: $cmd = &escape($cmd);
6756: my $query = 'fetchenrollment';
6757: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
6758: unless ($queryid=~/^\Q$host\E\_/) {
6759: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
6760: return 'error: '.$queryid;
6761: }
6762: my $reply = &get_query_reply($queryid);
6763: my $tries = 1;
6764: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6765: $reply = &get_query_reply($queryid);
6766: $tries ++;
6767: }
6768: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6769: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6770: } else {
6771: my @responses = split(/:/,$reply);
6772: if ($homeserver eq $perlvar{'lonHostID'}) {
6773: foreach my $line (@responses) {
6774: my ($key,$value) = split(/=/,$line,2);
6775: $$replyref{$key} = $value;
6776: }
6777: } else {
6778: my $pathname = LONCAPA::tempdir();
6779: foreach my $line (@responses) {
6780: my ($key,$value) = split(/=/,$line);
6781: $$replyref{$key} = $value;
6782: if ($value > 0) {
6783: foreach my $item (@{$$affiliatesref{$key}}) {
6784: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
6785: my $destname = $pathname.'/'.$filename;
6786: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
6787: if ($xml_classlist =~ /^error/) {
6788: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6789: } else {
6790: if ( open(FILE,">$destname") ) {
6791: print FILE &unescape($xml_classlist);
6792: close(FILE);
6793: } else {
6794: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
6795: }
6796: }
6797: }
6798: }
6799: }
6800: }
6801: return 'ok';
6802: }
6803: return 'error';
6804: }
6805:
6806: sub get_query_reply {
6807: my $queryid=shift;
6808: my $replyfile=LONCAPA::tempdir().$queryid;
6809: my $reply='';
6810: for (1..100) {
6811: sleep 2;
6812: if (-e $replyfile.'.end') {
6813: if (open(my $fh,$replyfile)) {
6814: $reply = join('',<$fh>);
6815: close($fh);
6816: } else { return 'error: reply_file_error'; }
6817: return &unescape($reply);
6818: }
6819: }
6820: return 'timeout:'.$queryid;
6821: }
6822:
6823: sub courselog_query {
6824: #
6825: # possible filters:
6826: # url: url or symb
6827: # username
6828: # domain
6829: # action: view, submit, grade
6830: # start: timestamp
6831: # end: timestamp
6832: #
6833: my (%filters)=@_;
6834: unless ($env{'request.course.id'}) { return 'no_course'; }
6835: if ($filters{'url'}) {
6836: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6837: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6838: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6839: }
6840: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6841: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6842: return &log_query($cname,$cdom,'courselog',%filters);
6843: }
6844:
6845: sub userlog_query {
6846: #
6847: # possible filters:
6848: # action: log check role
6849: # start: timestamp
6850: # end: timestamp
6851: #
6852: my ($uname,$udom,%filters)=@_;
6853: return &log_query($uname,$udom,'userlog',%filters);
6854: }
6855:
6856: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6857:
6858: sub auto_run {
6859: my ($cnum,$cdom) = @_;
6860: my $response = 0;
6861: my $settings;
6862: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6863: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6864: $settings = $domconfig{'autoenroll'};
6865: if ($settings->{'run'} eq '1') {
6866: $response = 1;
6867: }
6868: } else {
6869: my $homeserver;
6870: if (&is_course($cdom,$cnum)) {
6871: $homeserver = &homeserver($cnum,$cdom);
6872: } else {
6873: $homeserver = &domain($cdom,'primary');
6874: }
6875: if ($homeserver ne 'no_host') {
6876: $response = &reply('autorun:'.$cdom,$homeserver);
6877: }
6878: }
6879: return $response;
6880: }
6881:
6882: sub auto_get_sections {
6883: my ($cnum,$cdom,$inst_coursecode) = @_;
6884: my $homeserver;
6885: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6886: $homeserver = &homeserver($cnum,$cdom);
6887: }
6888: if (!defined($homeserver)) {
6889: if ($cdom =~ /^$match_domain$/) {
6890: $homeserver = &domain($cdom,'primary');
6891: }
6892: }
6893: my @secs;
6894: if (defined($homeserver)) {
6895: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6896: unless ($response eq 'refused') {
6897: @secs = split(/:/,$response);
6898: }
6899: }
6900: return @secs;
6901: }
6902:
6903: sub auto_new_course {
6904: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
6905: my $homeserver = &homeserver($cnum,$cdom);
6906: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
6907: return $response;
6908: }
6909:
6910: sub auto_validate_courseID {
6911: my ($cnum,$cdom,$inst_course_id) = @_;
6912: my $homeserver = &homeserver($cnum,$cdom);
6913: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
6914: return $response;
6915: }
6916:
6917: sub auto_validate_instcode {
6918: my ($cnum,$cdom,$instcode,$owner) = @_;
6919: my ($homeserver,$response);
6920: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6921: $homeserver = &homeserver($cnum,$cdom);
6922: }
6923: if (!defined($homeserver)) {
6924: if ($cdom =~ /^$match_domain$/) {
6925: $homeserver = &domain($cdom,'primary');
6926: }
6927: }
6928: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6929: &escape($instcode).':'.&escape($owner),$homeserver));
6930: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6931: return ($outcome,$description);
6932: }
6933:
6934: sub auto_create_password {
6935: my ($cnum,$cdom,$authparam,$udom) = @_;
6936: my ($homeserver,$response);
6937: my $create_passwd = 0;
6938: my $authchk = '';
6939: if ($udom =~ /^$match_domain$/) {
6940: $homeserver = &domain($udom,'primary');
6941: }
6942: if ($homeserver eq '') {
6943: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6944: $homeserver = &homeserver($cnum,$cdom);
6945: }
6946: }
6947: if ($homeserver eq '') {
6948: $authchk = 'nodomain';
6949: } else {
6950: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6951: if ($response eq 'refused') {
6952: $authchk = 'refused';
6953: } else {
6954: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
6955: }
6956: }
6957: return ($authparam,$create_passwd,$authchk);
6958: }
6959:
6960: sub auto_photo_permission {
6961: my ($cnum,$cdom,$students) = @_;
6962: my $homeserver = &homeserver($cnum,$cdom);
6963: my ($outcome,$perm_reqd,$conditions) =
6964: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
6965: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6966: return (undef,undef);
6967: }
6968: return ($outcome,$perm_reqd,$conditions);
6969: }
6970:
6971: sub auto_checkphotos {
6972: my ($uname,$udom,$pid) = @_;
6973: my $homeserver = &homeserver($uname,$udom);
6974: my ($result,$resulttype);
6975: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
6976: &escape($uname).':'.&escape($pid),
6977: $homeserver));
6978: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6979: return (undef,undef);
6980: }
6981: if ($outcome) {
6982: ($result,$resulttype) = split(/:/,$outcome);
6983: }
6984: return ($result,$resulttype);
6985: }
6986:
6987: sub auto_photochoice {
6988: my ($cnum,$cdom) = @_;
6989: my $homeserver = &homeserver($cnum,$cdom);
6990: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
6991: &escape($cdom),
6992: $homeserver)));
6993: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6994: return (undef,undef);
6995: }
6996: return ($update,$comment);
6997: }
6998:
6999: sub auto_photoupdate {
7000: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7001: my $homeserver = &homeserver($cnum,$dom);
7002: my $host=&hostname($homeserver);
7003: my $cmd = '';
7004: my $maxtries = 1;
7005: foreach my $affiliate (keys(%{$affiliatesref})) {
7006: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
7007: }
7008: $cmd =~ s/%%$//;
7009: $cmd = &escape($cmd);
7010: my $query = 'institutionalphotos';
7011: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7012: unless ($queryid=~/^\Q$host\E\_/) {
7013: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7014: return 'error: '.$queryid;
7015: }
7016: my $reply = &get_query_reply($queryid);
7017: my $tries = 1;
7018: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7019: $reply = &get_query_reply($queryid);
7020: $tries ++;
7021: }
7022: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7023: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7024: } else {
7025: my @responses = split(/:/,$reply);
7026: my $outcome = shift(@responses);
7027: foreach my $item (@responses) {
7028: my ($key,$value) = split(/=/,$item);
7029: $$photo{$key} = $value;
7030: }
7031: return $outcome;
7032: }
7033: return 'error';
7034: }
7035:
7036: sub auto_instcode_format {
7037: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7038: $cat_order) = @_;
7039: my $courses = '';
7040: my @homeservers;
7041: if ($caller eq 'global') {
7042: my %servers = &get_servers($codedom,'library');
7043: foreach my $tryserver (keys(%servers)) {
7044: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7045: push(@homeservers,$tryserver);
7046: }
7047: }
7048: } elsif ($caller eq 'requests') {
7049: if ($codedom =~ /^$match_domain$/) {
7050: my $chome = &domain($codedom,'primary');
7051: unless ($chome eq 'no_host') {
7052: push(@homeservers,$chome);
7053: }
7054: }
7055: } else {
7056: push(@homeservers,&homeserver($caller,$codedom));
7057: }
7058: foreach my $code (keys(%{$instcodes})) {
7059: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
7060: }
7061: chop($courses);
7062: my $ok_response = 0;
7063: my $response;
7064: while (@homeservers > 0 && $ok_response == 0) {
7065: my $server = shift(@homeservers);
7066: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7067: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7068: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
7069: split(/:/,$response);
7070: %{$codes} = (%{$codes},&str2hash($codes_str));
7071: push(@{$codetitles},&str2array($codetitles_str));
7072: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7073: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7074: $ok_response = 1;
7075: }
7076: }
7077: if ($ok_response) {
7078: return 'ok';
7079: } else {
7080: return $response;
7081: }
7082: }
7083:
7084: sub auto_instcode_defaults {
7085: my ($domain,$returnhash,$code_order) = @_;
7086: my @homeservers;
7087:
7088: my %servers = &get_servers($domain,'library');
7089: foreach my $tryserver (keys(%servers)) {
7090: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7091: push(@homeservers,$tryserver);
7092: }
7093: }
7094:
7095: my $response;
7096: foreach my $server (@homeservers) {
7097: $response=&reply('autoinstcodedefaults:'.$domain,$server);
7098: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7099:
7100: foreach my $pair (split(/\&/,$response)) {
7101: my ($name,$value)=split(/\=/,$pair);
7102: if ($name eq 'code_order') {
7103: @{$code_order} = split(/\&/,&unescape($value));
7104: } else {
7105: $returnhash->{&unescape($name)}=&unescape($value);
7106: }
7107: }
7108: return 'ok';
7109: }
7110:
7111: return $response;
7112: }
7113:
7114: sub auto_possible_instcodes {
7115: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7116: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7117: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7118: return;
7119: }
7120: my (@homeservers,$uhome);
7121: if (defined(&domain($domain,'primary'))) {
7122: $uhome=&domain($domain,'primary');
7123: push(@homeservers,&domain($domain,'primary'));
7124: } else {
7125: my %servers = &get_servers($domain,'library');
7126: foreach my $tryserver (keys(%servers)) {
7127: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7128: push(@homeservers,$tryserver);
7129: }
7130: }
7131: }
7132: my $response;
7133: foreach my $server (@homeservers) {
7134: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7135: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7136: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7137: split(':',$response);
7138: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7139: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
7140: foreach my $item (split('&',$cat_title)) {
7141: my ($name,$value)=split('=',$item);
7142: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
7143: }
7144: foreach my $item (split('&',$cat_order)) {
7145: my ($name,$value)=split('=',$item);
7146: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
7147: }
7148: return 'ok';
7149: }
7150: return $response;
7151: }
7152:
7153: sub auto_courserequest_checks {
7154: my ($dom) = @_;
7155: my ($homeserver,%validations);
7156: if ($dom =~ /^$match_domain$/) {
7157: $homeserver = &domain($dom,'primary');
7158: }
7159: unless ($homeserver eq 'no_host') {
7160: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7161: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7162: my @items = split(/&/,$response);
7163: foreach my $item (@items) {
7164: my ($key,$value) = split('=',$item);
7165: $validations{&unescape($key)} = &thaw_unescape($value);
7166: }
7167: }
7168: }
7169: return %validations;
7170: }
7171:
7172: sub auto_courserequest_validation {
7173: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
7174: my ($homeserver,$response);
7175: if ($dom =~ /^$match_domain$/) {
7176: $homeserver = &domain($dom,'primary');
7177: }
7178: unless ($homeserver eq 'no_host') {
7179:
7180: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
7181: ':'.&escape($crstype).':'.&escape($inststatuslist).
7182: ':'.&escape($instcode).':'.&escape($instseclist),
7183: $homeserver));
7184: }
7185: return $response;
7186: }
7187:
7188: sub auto_validate_class_sec {
7189: my ($cdom,$cnum,$owners,$inst_class) = @_;
7190: my $homeserver = &homeserver($cnum,$cdom);
7191: my $ownerlist;
7192: if (ref($owners) eq 'ARRAY') {
7193: $ownerlist = join(',',@{$owners});
7194: } else {
7195: $ownerlist = $owners;
7196: }
7197: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
7198: &escape($ownerlist).':'.$cdom,$homeserver);
7199: return $response;
7200: }
7201:
7202: # ------------------------------------------------------- Course Group routines
7203:
7204: sub get_coursegroups {
7205: my ($cdom,$cnum,$group,$namespace) = @_;
7206: return(&dump($namespace,$cdom,$cnum,$group));
7207: }
7208:
7209: sub modify_coursegroup {
7210: my ($cdom,$cnum,$groupsettings) = @_;
7211: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7212: }
7213:
7214: sub toggle_coursegroup_status {
7215: my ($cdom,$cnum,$group,$action) = @_;
7216: my ($from_namespace,$to_namespace);
7217: if ($action eq 'delete') {
7218: $from_namespace = 'coursegroups';
7219: $to_namespace = 'deleted_groups';
7220: } else {
7221: $from_namespace = 'deleted_groups';
7222: $to_namespace = 'coursegroups';
7223: }
7224: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
7225: if (my $tmp = &error(%curr_group)) {
7226: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7227: return ('read error',$tmp);
7228: } else {
7229: my %savedsettings = %curr_group;
7230: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
7231: my $deloutcome;
7232: if ($result eq 'ok') {
7233: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
7234: } else {
7235: return ('write error',$result);
7236: }
7237: if ($deloutcome eq 'ok') {
7238: return 'ok';
7239: } else {
7240: return ('delete error',$deloutcome);
7241: }
7242: }
7243: }
7244:
7245: sub modify_group_roles {
7246: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
7247: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7248: my $role = 'gr/'.&escape($userprivs);
7249: my ($uname,$udom) = split(/:/,$user);
7250: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
7251: if ($result eq 'ok') {
7252: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7253: }
7254: return $result;
7255: }
7256:
7257: sub modify_coursegroup_membership {
7258: my ($cdom,$cnum,$membership) = @_;
7259: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7260: return $result;
7261: }
7262:
7263: sub get_active_groups {
7264: my ($udom,$uname,$cdom,$cnum) = @_;
7265: my $now = time;
7266: my %groups = ();
7267: foreach my $key (keys(%env)) {
7268: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
7269: my ($start,$end) = split(/\./,$env{$key});
7270: if (($end!=0) && ($end<$now)) { next; }
7271: if (($start!=0) && ($start>$now)) { next; }
7272: if ($1 eq $cdom && $2 eq $cnum) {
7273: $groups{$3} = $env{$key} ;
7274: }
7275: }
7276: }
7277: return %groups;
7278: }
7279:
7280: sub get_group_membership {
7281: my ($cdom,$cnum,$group) = @_;
7282: return(&dump('groupmembership',$cdom,$cnum,$group));
7283: }
7284:
7285: sub get_users_groups {
7286: my ($udom,$uname,$courseid) = @_;
7287: my @usersgroups;
7288: my $cachetime=1800;
7289:
7290: my $hashid="$udom:$uname:$courseid";
7291: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
7292: if (defined($cached)) {
7293: @usersgroups = split(/:/,$grouplist);
7294: } else {
7295: $grouplist = '';
7296: my $courseurl = &courseid_to_courseurl($courseid);
7297: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
7298: my $access_end = $env{'course.'.$courseid.
7299: '.default_enrollment_end_date'};
7300: my $now = time;
7301: foreach my $key (keys(%roleshash)) {
7302: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
7303: my $group = $1;
7304: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
7305: my $start = $2;
7306: my $end = $1;
7307: if ($start == -1) { next; } # deleted from group
7308: if (($start!=0) && ($start>$now)) { next; }
7309: if (($end!=0) && ($end<$now)) {
7310: if ($access_end && $access_end < $now) {
7311: if ($access_end - $end < 86400) {
7312: push(@usersgroups,$group);
7313: }
7314: }
7315: next;
7316: }
7317: push(@usersgroups,$group);
7318: }
7319: }
7320: }
7321: @usersgroups = &sort_course_groups($courseid,@usersgroups);
7322: $grouplist = join(':',@usersgroups);
7323: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
7324: }
7325: return @usersgroups;
7326: }
7327:
7328: sub devalidate_getgroups_cache {
7329: my ($udom,$uname,$cdom,$cnum)=@_;
7330: my $courseid = $cdom.'_'.$cnum;
7331:
7332: my $hashid="$udom:$uname:$courseid";
7333: &devalidate_cache_new('getgroups',$hashid);
7334: }
7335:
7336: # ------------------------------------------------------------------ Plain Text
7337:
7338: sub plaintext {
7339: my ($short,$type,$cid,$forcedefault) = @_;
7340: if ($short =~ m{^cr/}) {
7341: return (split('/',$short))[-1];
7342: }
7343: if (!defined($cid)) {
7344: $cid = $env{'request.course.id'};
7345: }
7346: my %rolenames = (
7347: Course => 'std',
7348: Community => 'alt1',
7349: );
7350: if ($cid ne '') {
7351: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
7352: unless ($forcedefault) {
7353: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
7354: &Apache::lonlocal::mt_escape(\$roletext);
7355: return &Apache::lonlocal::mt($roletext);
7356: }
7357: }
7358: }
7359: if ((defined($type)) && (defined($rolenames{$type})) &&
7360: (defined($rolenames{$type})) &&
7361: (defined($prp{$short}{$rolenames{$type}}))) {
7362: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
7363: } elsif ($cid ne '') {
7364: my $crstype = $env{'course.'.$cid.'.type'};
7365: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
7366: (defined($prp{$short}{$rolenames{$crstype}}))) {
7367: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
7368: }
7369: }
7370: return &Apache::lonlocal::mt($prp{$short}{'std'});
7371: }
7372:
7373: # ----------------------------------------------------------------- Assign Role
7374:
7375: sub assignrole {
7376: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
7377: $context)=@_;
7378: my $mrole;
7379: if ($role =~ /^cr\//) {
7380: my $cwosec=$url;
7381: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
7382: unless (&allowed('ccr',$cwosec)) {
7383: my $refused = 1;
7384: if ($context eq 'requestcourses') {
7385: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7386: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
7387: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
7388: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7389: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7390: if ($crsenv{'internal.courseowner'} eq
7391: $env{'user.name'}.':'.$env{'user.domain'}) {
7392: $refused = '';
7393: }
7394: }
7395: }
7396: }
7397: }
7398: if ($refused) {
7399: &logthis('Refused custom assignrole: '.
7400: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
7401: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
7402: return 'refused';
7403: }
7404: }
7405: $mrole='cr';
7406: } elsif ($role =~ /^gr\//) {
7407: my $cwogrp=$url;
7408: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
7409: unless (&allowed('mdg',$cwogrp)) {
7410: &logthis('Refused group assignrole: '.
7411: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
7412: $env{'user.name'}.' at '.$env{'user.domain'});
7413: return 'refused';
7414: }
7415: $mrole='gr';
7416: } else {
7417: my $cwosec=$url;
7418: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
7419: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
7420: my $refused;
7421: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
7422: if (!(&allowed('c'.$role,$url))) {
7423: $refused = 1;
7424: }
7425: } else {
7426: $refused = 1;
7427: }
7428: if ($refused) {
7429: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7430: if (!$selfenroll && $context eq 'course') {
7431: my %crsenv;
7432: if ($role eq 'cc' || $role eq 'co') {
7433: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7434: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
7435: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
7436: if ($crsenv{'internal.courseowner'} eq
7437: $env{'user.name'}.':'.$env{'user.domain'}) {
7438: $refused = '';
7439: }
7440: }
7441: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
7442: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
7443: if ($crsenv{'internal.courseowner'} eq
7444: $env{'user.name'}.':'.$env{'user.domain'}) {
7445: $refused = '';
7446: }
7447: }
7448: }
7449: }
7450: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7451: $refused = '';
7452: } elsif ($context eq 'requestcourses') {
7453: my @possroles = ('st','ta','ep','in','cc','co');
7454: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
7455: my $wrongcc;
7456: if ($cnum =~ /^$match_community$/) {
7457: $wrongcc = 1 if ($role eq 'cc');
7458: } else {
7459: $wrongcc = 1 if ($role eq 'co');
7460: }
7461: unless ($wrongcc) {
7462: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7463: if ($crsenv{'internal.courseowner'} eq
7464: $env{'user.name'}.':'.$env{'user.domain'}) {
7465: $refused = '';
7466: }
7467: }
7468: }
7469: }
7470: if ($refused) {
7471: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
7472: ' '.$role.' '.$end.' '.$start.' by '.
7473: $env{'user.name'}.' at '.$env{'user.domain'});
7474: return 'refused';
7475: }
7476: }
7477: } elsif ($role eq 'au') {
7478: if ($url ne '/'.$udom.'/') {
7479: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
7480: ' to assign author role for '.$uname.':'.$udom.
7481: ' in domain: '.$url.' refused (wrong domain).');
7482: return 'refused';
7483: }
7484: }
7485: $mrole=$role;
7486: }
7487: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7488: "$udom:$uname:$url".'_'."$mrole=$role";
7489: if ($end) { $command.='_'.$end; }
7490: if ($start) {
7491: if ($end) {
7492: $command.='_'.$start;
7493: } else {
7494: $command.='_0_'.$start;
7495: }
7496: }
7497: my $origstart = $start;
7498: my $origend = $end;
7499: my $delflag;
7500: # actually delete
7501: if ($deleteflag) {
7502: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
7503: # modify command to delete the role
7504: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
7505: "$udom:$uname:$url".'_'."$mrole";
7506: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
7507: # set start and finish to negative values for userrolelog
7508: $start=-1;
7509: $end=-1;
7510: $delflag = 1;
7511: }
7512: }
7513: # send command
7514: my $answer=&reply($command,&homeserver($uname,$udom));
7515: # log new user role if status is ok
7516: if ($answer eq 'ok') {
7517: &userrolelog($role,$uname,$udom,$url,$start,$end);
7518: # for course roles, perform group memberships changes triggered by role change.
7519: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
7520: unless ($role =~ /^gr/) {
7521: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
7522: $origstart,$selfenroll,$context);
7523: }
7524: if ($role eq 'cc') {
7525: &autoupdate_coowners($url,$end,$start,$uname,$udom);
7526: }
7527: }
7528: return $answer;
7529: }
7530:
7531: sub autoupdate_coowners {
7532: my ($url,$end,$start,$uname,$udom) = @_;
7533: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
7534: if (($cdom ne '') && ($cnum ne '')) {
7535: my $now = time;
7536: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
7537: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
7538: my %coursehash = &coursedescription($cdom.'_'.$cnum);
7539: my $instcode = $coursehash{'internal.coursecode'};
7540: if ($instcode ne '') {
7541: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
7542: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
7543: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
7544: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
7545: if ($result eq 'valid') {
7546: if ($coursehash{'internal.co-owners'}) {
7547: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7548: push(@newcoowners,$coowner);
7549: }
7550: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
7551: push(@newcoowners,$uname.':'.$udom);
7552: }
7553: @newcoowners = sort(@newcoowners);
7554: } else {
7555: push(@newcoowners,$uname.':'.$udom);
7556: }
7557: } else {
7558: if ($coursehash{'internal.co-owners'}) {
7559: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7560: unless ($coowner eq $uname.':'.$udom) {
7561: push(@newcoowners,$coowner);
7562: }
7563: }
7564: unless (@newcoowners > 0) {
7565: $delcoowners = 1;
7566: $coowners = '';
7567: }
7568: }
7569: }
7570: if (@newcoowners || $delcoowners) {
7571: &store_coowners($cdom,$cnum,$coursehash{'home'},
7572: $delcoowners,@newcoowners);
7573: }
7574: }
7575: }
7576: }
7577: }
7578: }
7579: }
7580:
7581: sub store_coowners {
7582: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
7583: my $cid = $cdom.'_'.$cnum;
7584: my ($coowners,$delresult,$putresult);
7585: if (@newcoowners) {
7586: $coowners = join(',',@newcoowners);
7587: my %coownershash = (
7588: 'internal.co-owners' => $coowners,
7589: );
7590: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
7591: if ($putresult eq 'ok') {
7592: if ($env{'course.'.$cid.'.num'} eq $cnum) {
7593: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
7594: }
7595: }
7596: }
7597: if ($delcoowners) {
7598: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
7599: if ($delresult eq 'ok') {
7600: if ($env{'course.'.$cid.'.internal.co-owners'}) {
7601: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
7602: }
7603: }
7604: }
7605: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
7606: my %crsinfo =
7607: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
7608: if (ref($crsinfo{$cid}) eq 'HASH') {
7609: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
7610: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
7611: }
7612: }
7613: }
7614:
7615: # -------------------------------------------------- Modify user authentication
7616: # Overrides without validation
7617:
7618: sub modifyuserauth {
7619: my ($udom,$uname,$umode,$upass)=@_;
7620: my $uhome=&homeserver($uname,$udom);
7621: unless (&allowed('mau',$udom)) { return 'refused'; }
7622: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
7623: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7624: ' in domain '.$env{'request.role.domain'});
7625: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
7626: &escape($upass),$uhome);
7627: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
7628: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
7629: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7630: &log($udom,,$uname,$uhome,
7631: 'Authentication changed by '.$env{'user.domain'}.', '.
7632: $env{'user.name'}.', '.$umode.
7633: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7634: unless ($reply eq 'ok') {
7635: &logthis('Authentication mode error: '.$reply);
7636: return 'error: '.$reply;
7637: }
7638: return 'ok';
7639: }
7640:
7641: # --------------------------------------------------------------- Modify a user
7642:
7643: sub modifyuser {
7644: my ($udom, $uname, $uid,
7645: $umode, $upass, $first,
7646: $middle, $last, $gene,
7647: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
7648: $udom= &LONCAPA::clean_domain($udom);
7649: $uname=&LONCAPA::clean_username($uname);
7650: my $showcandelete = 'none';
7651: if (ref($candelete) eq 'ARRAY') {
7652: if (@{$candelete} > 0) {
7653: $showcandelete = join(', ',@{$candelete});
7654: }
7655: }
7656: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
7657: $umode.', '.$first.', '.$middle.', '.
7658: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
7659: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
7660: ' desiredhome not specified').
7661: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7662: ' in domain '.$env{'request.role.domain'});
7663: my $uhome=&homeserver($uname,$udom,'true');
7664: my $newuser;
7665: if ($uhome eq 'no_host') {
7666: $newuser = 1;
7667: }
7668: # ----------------------------------------------------------------- Create User
7669: if (($uhome eq 'no_host') &&
7670: (($umode && $upass) || ($umode eq 'localauth'))) {
7671: my $unhome='';
7672: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
7673: $unhome = $desiredhome;
7674: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
7675: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
7676: } else { # load balancing routine for determining $unhome
7677: my $loadm=10000000;
7678: my %servers = &get_servers($udom,'library');
7679: foreach my $tryserver (keys(%servers)) {
7680: my $answer=reply('load',$tryserver);
7681: if (($answer=~/\d+/) && ($answer<$loadm)) {
7682: $loadm=$answer;
7683: $unhome=$tryserver;
7684: }
7685: }
7686: }
7687: if (($unhome eq '') || ($unhome eq 'no_host')) {
7688: return 'error: unable to find a home server for '.$uname.
7689: ' in domain '.$udom;
7690: }
7691: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
7692: &escape($upass),$unhome);
7693: unless ($reply eq 'ok') {
7694: return 'error: '.$reply;
7695: }
7696: $uhome=&homeserver($uname,$udom,'true');
7697: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
7698: return 'error: unable verify users home machine.';
7699: }
7700: } # End of creation of new user
7701: # ---------------------------------------------------------------------- Add ID
7702: if ($uid) {
7703: $uid=~tr/A-Z/a-z/;
7704: my %uidhash=&idrget($udom,$uname);
7705: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
7706: && (!$forceid)) {
7707: unless ($uid eq $uidhash{$uname}) {
7708: return 'error: user id "'.$uid.'" does not match '.
7709: 'current user id "'.$uidhash{$uname}.'".';
7710: }
7711: } else {
7712: &idput($udom,($uname => $uid));
7713: }
7714: }
7715: # -------------------------------------------------------------- Add names, etc
7716: my @tmp=&get('environment',
7717: ['firstname','middlename','lastname','generation','id',
7718: 'permanentemail','inststatus'],
7719: $udom,$uname);
7720: my (%names,%oldnames);
7721: if ($tmp[0] =~ m/^error:.*/) {
7722: %names=();
7723: } else {
7724: %names = @tmp;
7725: %oldnames = %names;
7726: }
7727: #
7728: # If name, email and/or uid are blank (e.g., because an uploaded file
7729: # of users did not contain them), do not overwrite existing values
7730: # unless field is in $candelete array ref.
7731: #
7732:
7733: my @fields = ('firstname','middlename','lastname','generation',
7734: 'permanentemail','id');
7735: my %newvalues;
7736: if (ref($candelete) eq 'ARRAY') {
7737: foreach my $field (@fields) {
7738: if (grep(/^\Q$field\E$/,@{$candelete})) {
7739: if ($field eq 'firstname') {
7740: $names{$field} = $first;
7741: } elsif ($field eq 'middlename') {
7742: $names{$field} = $middle;
7743: } elsif ($field eq 'lastname') {
7744: $names{$field} = $last;
7745: } elsif ($field eq 'generation') {
7746: $names{$field} = $gene;
7747: } elsif ($field eq 'permanentemail') {
7748: $names{$field} = $email;
7749: } elsif ($field eq 'id') {
7750: $names{$field} = $uid;
7751: }
7752: }
7753: }
7754: }
7755: if ($first) { $names{'firstname'} = $first; }
7756: if (defined($middle)) { $names{'middlename'} = $middle; }
7757: if ($last) { $names{'lastname'} = $last; }
7758: if (defined($gene)) { $names{'generation'} = $gene; }
7759: if ($email) {
7760: $email=~s/[^\w\@\.\-\,]//gs;
7761: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
7762: }
7763: if ($uid) { $names{'id'} = $uid; }
7764: if (defined($inststatus)) {
7765: $names{'inststatus'} = '';
7766: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
7767: if (ref($usertypes) eq 'HASH') {
7768: my @okstatuses;
7769: foreach my $item (split(/:/,$inststatus)) {
7770: if (defined($usertypes->{$item})) {
7771: push(@okstatuses,$item);
7772: }
7773: }
7774: if (@okstatuses) {
7775: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
7776: }
7777: }
7778: }
7779: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
7780: $umode.', '.$first.', '.$middle.', '.
7781: $last.', '.$gene.', '.$email.', '.$inststatus;
7782: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
7783: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
7784: } else {
7785: $logmsg .= ' during self creation';
7786: }
7787: my $changed;
7788: if ($newuser) {
7789: $changed = 1;
7790: } else {
7791: foreach my $field (@fields) {
7792: if ($names{$field} ne $oldnames{$field}) {
7793: $changed = 1;
7794: last;
7795: }
7796: }
7797: }
7798: unless ($changed) {
7799: $logmsg = 'No changes in user information needed for: '.$logmsg;
7800: &logthis($logmsg);
7801: return 'ok';
7802: }
7803: my $reply = &put('environment', \%names, $udom,$uname);
7804: if ($reply ne 'ok') {
7805: return 'error: '.$reply;
7806: }
7807: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7808: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7809: }
7810: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7811: &devalidate_cache_new('namescache',$uname.':'.$udom);
7812: $logmsg = 'Success modifying user '.$logmsg;
7813: &logthis($logmsg);
7814: return 'ok';
7815: }
7816:
7817: # -------------------------------------------------------------- Modify student
7818:
7819: sub modifystudent {
7820: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
7821: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
7822: $selfenroll,$context,$inststatus)=@_;
7823: if (!$cid) {
7824: unless ($cid=$env{'request.course.id'}) {
7825: return 'not_in_class';
7826: }
7827: }
7828: # --------------------------------------------------------------- Make the user
7829: my $reply=&modifyuser
7830: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
7831: $desiredhome,$email,$inststatus);
7832: unless ($reply eq 'ok') { return $reply; }
7833: # This will cause &modify_student_enrollment to get the uid from the
7834: # students environment
7835: $uid = undef if (!$forceid);
7836: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
7837: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
7838: return $reply;
7839: }
7840:
7841: sub modify_student_enrollment {
7842: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
7843: my ($cdom,$cnum,$chome);
7844: if (!$cid) {
7845: unless ($cid=$env{'request.course.id'}) {
7846: return 'not_in_class';
7847: }
7848: $cdom=$env{'course.'.$cid.'.domain'};
7849: $cnum=$env{'course.'.$cid.'.num'};
7850: } else {
7851: ($cdom,$cnum)=split(/_/,$cid);
7852: }
7853: $chome=$env{'course.'.$cid.'.home'};
7854: if (!$chome) {
7855: $chome=&homeserver($cnum,$cdom);
7856: }
7857: if (!$chome) { return 'unknown_course'; }
7858: # Make sure the user exists
7859: my $uhome=&homeserver($uname,$udom);
7860: if (($uhome eq '') || ($uhome eq 'no_host')) {
7861: return 'error: no such user';
7862: }
7863: # Get student data if we were not given enough information
7864: if (!defined($first) || $first eq '' ||
7865: !defined($last) || $last eq '' ||
7866: !defined($uid) || $uid eq '' ||
7867: !defined($middle) || $middle eq '' ||
7868: !defined($gene) || $gene eq '') {
7869: # They did not supply us with enough data to enroll the student, so
7870: # we need to pick up more information.
7871: my %tmp = &get('environment',
7872: ['firstname','middlename','lastname', 'generation','id']
7873: ,$udom,$uname);
7874:
7875: #foreach my $key (keys(%tmp)) {
7876: # &logthis("key $key = ".$tmp{$key});
7877: #}
7878: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7879: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7880: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
7881: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
7882: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7883: }
7884: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
7885: my $user = "$uname:$udom";
7886: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
7887: my $reply=cput('classlist',
7888: {$user =>
7889: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
7890: $cdom,$cnum);
7891: if (($reply eq 'ok') || ($reply eq 'delayed')) {
7892: &devalidate_getsection_cache($udom,$uname,$cid);
7893: } else {
7894: return 'error: '.$reply;
7895: }
7896: # Add student role to user
7897: my $uurl='/'.$cid;
7898: $uurl=~s/\_/\//g;
7899: if ($usec) {
7900: $uurl.='/'.$usec;
7901: }
7902: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
7903: $selfenroll,$context);
7904: if ($result ne 'ok') {
7905: if ($old_entry{$user} ne '') {
7906: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
7907: } else {
7908: $reply = &del('classlist',[$user],$cdom,$cnum);
7909: }
7910: }
7911: return $result;
7912: }
7913:
7914: sub format_name {
7915: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7916: my $name;
7917: if ($first ne 'lastname') {
7918: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7919: } else {
7920: if ($lastname=~/\S/) {
7921: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7922: $name=~s/\s+,/,/;
7923: } else {
7924: $name.= $firstname.' '.$middlename.' '.$generation;
7925: }
7926: }
7927: $name=~s/^\s+//;
7928: $name=~s/\s+$//;
7929: $name=~s/\s+/ /g;
7930: return $name;
7931: }
7932:
7933: # ------------------------------------------------- Write to course preferences
7934:
7935: sub writecoursepref {
7936: my ($courseid,%prefs)=@_;
7937: $courseid=~s/^\///;
7938: $courseid=~s/\_/\//g;
7939: my ($cdomain,$cnum)=split(/\//,$courseid);
7940: my $chome=homeserver($cnum,$cdomain);
7941: if (($chome eq '') || ($chome eq 'no_host')) {
7942: return 'error: no such course';
7943: }
7944: my $cstring='';
7945: foreach my $pref (keys(%prefs)) {
7946: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
7947: }
7948: $cstring=~s/\&$//;
7949: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7950: }
7951:
7952: # ---------------------------------------------------------- Make/modify course
7953:
7954: sub createcourse {
7955: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
7956: $course_owner,$crstype,$cnum,$context,$category)=@_;
7957: $url=&declutter($url);
7958: my $cid='';
7959: if ($context eq 'requestcourses') {
7960: my $can_create = 0;
7961: my ($ownername,$ownerdom) = split(':',$course_owner);
7962: if ($udom eq $ownerdom) {
7963: if (&usertools_access($ownername,$ownerdom,$category,undef,
7964: $context)) {
7965: $can_create = 1;
7966: }
7967: } else {
7968: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7969: $category);
7970: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7971: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7972: if (@curr > 0) {
7973: my @options = qw(approval validate autolimit);
7974: my $optregex = join('|',@options);
7975: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7976: $can_create = 1;
7977: }
7978: }
7979: }
7980: }
7981: if ($can_create) {
7982: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7983: unless (&allowed('ccc',$udom)) {
7984: return 'refused';
7985: }
7986: }
7987: } else {
7988: return 'refused';
7989: }
7990: } elsif (!&allowed('ccc',$udom)) {
7991: return 'refused';
7992: }
7993: # --------------------------------------------------------------- Get Unique ID
7994: my $uname;
7995: if ($cnum =~ /^$match_courseid$/) {
7996: my $chome=&homeserver($cnum,$udom,'true');
7997: if (($chome eq '') || ($chome eq 'no_host')) {
7998: $uname = $cnum;
7999: } else {
8000: $uname = &generate_coursenum($udom,$crstype);
8001: }
8002: } else {
8003: $uname = &generate_coursenum($udom,$crstype);
8004: }
8005: return $uname if ($uname =~ /^error/);
8006: # -------------------------------------------------- Check supplied server name
8007: if (!defined($course_server)) {
8008: if (defined(&domain($udom,'primary'))) {
8009: $course_server = &domain($udom,'primary');
8010: } else {
8011: $course_server = $env{'user.home'};
8012: }
8013: }
8014: my %host_servers =
8015: &Apache::lonnet::get_servers($udom,'library');
8016: unless ($host_servers{$course_server}) {
8017: return 'error: invalid home server for course: '.$course_server;
8018: }
8019: # ------------------------------------------------------------- Make the course
8020: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
8021: $course_server);
8022: unless ($reply eq 'ok') { return 'error: '.$reply; }
8023: my $uhome=&homeserver($uname,$udom,'true');
8024: if (($uhome eq '') || ($uhome eq 'no_host')) {
8025: return 'error: no such course';
8026: }
8027: # ----------------------------------------------------------------- Course made
8028: # log existence
8029: my $now = time;
8030: my $newcourse = {
8031: $udom.'_'.$uname => {
8032: description => $description,
8033: inst_code => $inst_code,
8034: owner => $course_owner,
8035: type => $crstype,
8036: creator => $env{'user.name'}.':'.
8037: $env{'user.domain'},
8038: created => $now,
8039: context => $context,
8040: },
8041: };
8042: &courseidput($udom,$newcourse,$uhome,'notime');
8043: # set toplevel url
8044: my $topurl=$url;
8045: unless ($nonstandard) {
8046: # ------------------------------------------ For standard courses, make top url
8047: my $mapurl=&clutter($url);
8048: if ($mapurl eq '/res/') { $mapurl=''; }
8049: $env{'form.initmap'}=(<<ENDINITMAP);
8050: <map>
8051: <resource id="1" type="start"></resource>
8052: <resource id="2" src="$mapurl"></resource>
8053: <resource id="3" type="finish"></resource>
8054: <link index="1" from="1" to="2"></link>
8055: <link index="2" from="2" to="3"></link>
8056: </map>
8057: ENDINITMAP
8058: $topurl=&declutter(
8059: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
8060: );
8061: }
8062: # ----------------------------------------------------------- Write preferences
8063: &writecoursepref($udom.'_'.$uname,
8064: ('description' => $description,
8065: 'url' => $topurl,
8066: 'internal.creator' => $env{'user.name'}.':'.
8067: $env{'user.domain'},
8068: 'internal.created' => $now,
8069: 'internal.creationcontext' => $context)
8070: );
8071: return '/'.$udom.'/'.$uname;
8072: }
8073:
8074: # ------------------------------------------------------------------- Create ID
8075: sub generate_coursenum {
8076: my ($udom,$crstype) = @_;
8077: my $domdesc = &domain($udom);
8078: return 'error: invalid domain' if ($domdesc eq '');
8079: my $first;
8080: if ($crstype eq 'Community') {
8081: $first = '0';
8082: } else {
8083: $first = int(1+rand(9));
8084: }
8085: my $uname=$first.
8086: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8087: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8088: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8089: # ----------------------------------------------- Make sure that does not exist
8090: my $uhome=&homeserver($uname,$udom,'true');
8091: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8092: if ($crstype eq 'Community') {
8093: $first = '0';
8094: } else {
8095: $first = int(1+rand(9));
8096: }
8097: $uname=$first.
8098: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8099: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8100: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8101: $uhome=&homeserver($uname,$udom,'true');
8102: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8103: return 'error: unable to generate unique course-ID';
8104: }
8105: }
8106: return $uname;
8107: }
8108:
8109: sub is_course {
8110: my ($cdom, $cnum) = scalar(@_) == 1 ?
8111: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8112:
8113: return unless $cdom and $cnum;
8114:
8115: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8116: '.');
8117:
8118: return unless exists($courses{$cdom.'_'.$cnum});
8119: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
8120: }
8121:
8122: sub store_userdata {
8123: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
8124: my $result;
8125: if ($datakey ne '') {
8126: if (ref($storehash) eq 'HASH') {
8127: if ($udom eq '' || $uname eq '') {
8128: $udom = $env{'user.domain'};
8129: $uname = $env{'user.name'};
8130: }
8131: my $uhome=&homeserver($uname,$udom);
8132: if (($uhome eq '') || ($uhome eq 'no_host')) {
8133: $result = 'error: no_host';
8134: } else {
8135: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8136: $storehash->{'host'} = $perlvar{'lonHostID'};
8137:
8138: my $namevalue='';
8139: foreach my $key (keys(%{$storehash})) {
8140: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8141: }
8142: $namevalue=~s/\&$//;
8143: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8144: $namevalue,$uhome);
8145: }
8146: } else {
8147: $result = 'error: data to store was not a hash reference';
8148: }
8149: } else {
8150: $result= 'error: invalid requestkey';
8151: }
8152: return $result;
8153: }
8154:
8155: # ---------------------------------------------------------- Assign Custom Role
8156:
8157: sub assigncustomrole {
8158: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
8159: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
8160: $end,$start,$deleteflag,$selfenroll,$context);
8161: }
8162:
8163: # ----------------------------------------------------------------- Revoke Role
8164:
8165: sub revokerole {
8166: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
8167: my $now=time;
8168: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
8169: }
8170:
8171: # ---------------------------------------------------------- Revoke Custom Role
8172:
8173: sub revokecustomrole {
8174: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
8175: my $now=time;
8176: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
8177: $deleteflag,$selfenroll,$context);
8178: }
8179:
8180: # ------------------------------------------------------------ Disk usage
8181: sub diskusage {
8182: my ($udom,$uname,$directorypath,$getpropath)=@_;
8183: $directorypath =~ s/\/$//;
8184: my $listing=&reply('du2:'.&escape($directorypath).':'
8185: .&escape($getpropath).':'.&escape($uname).':'
8186: .&escape($udom),homeserver($uname,$udom));
8187: if ($listing eq 'unknown_cmd') {
8188: if ($getpropath) {
8189: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8190: }
8191: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8192: }
8193: return $listing;
8194: }
8195:
8196: sub is_locked {
8197: my ($file_name, $domain, $user, $which) = @_;
8198: my @check;
8199: my $is_locked;
8200: push (@check,$file_name);
8201: my %locked = &get('file_permissions',\@check,
8202: $env{'user.domain'},$env{'user.name'});
8203: my ($tmp)=keys(%locked);
8204: if ($tmp=~/^error:/) { undef(%locked); }
8205:
8206: if (ref($locked{$file_name}) eq 'ARRAY') {
8207: $is_locked = 'false';
8208: foreach my $entry (@{$locked{$file_name}}) {
8209: if (ref($entry) eq 'ARRAY') {
8210: $is_locked = 'true';
8211: if (ref($which) eq 'ARRAY') {
8212: push(@{$which},$entry);
8213: } else {
8214: last;
8215: }
8216: }
8217: }
8218: } else {
8219: $is_locked = 'false';
8220: }
8221: return $is_locked;
8222: }
8223:
8224: sub declutter_portfile {
8225: my ($file) = @_;
8226: $file =~ s{^(/portfolio/|portfolio/)}{/};
8227: return $file;
8228: }
8229:
8230: # ------------------------------------------------------------- Mark as Read Only
8231:
8232: sub mark_as_readonly {
8233: my ($domain,$user,$files,$what) = @_;
8234: my %current_permissions = &dump('file_permissions',$domain,$user);
8235: my ($tmp)=keys(%current_permissions);
8236: if ($tmp=~/^error:/) { undef(%current_permissions); }
8237: foreach my $file (@{$files}) {
8238: $file = &declutter_portfile($file);
8239: push(@{$current_permissions{$file}},$what);
8240: }
8241: &put('file_permissions',\%current_permissions,$domain,$user);
8242: return;
8243: }
8244:
8245: # ------------------------------------------------------------Save Selected Files
8246:
8247: sub save_selected_files {
8248: my ($user, $path, @files) = @_;
8249: my $filename = $user."savedfiles";
8250: my @other_files = &files_not_in_path($user, $path);
8251: open (OUT, '>'.$tmpdir.$filename);
8252: foreach my $file (@files) {
8253: print (OUT $env{'form.currentpath'}.$file."\n");
8254: }
8255: foreach my $file (@other_files) {
8256: print (OUT $file."\n");
8257: }
8258: close (OUT);
8259: return 'ok';
8260: }
8261:
8262: sub clear_selected_files {
8263: my ($user) = @_;
8264: my $filename = $user."savedfiles";
8265: open (OUT, '>'.LONCAPA::tempdir().$filename);
8266: print (OUT undef);
8267: close (OUT);
8268: return ("ok");
8269: }
8270:
8271: sub files_in_path {
8272: my ($user, $path) = @_;
8273: my $filename = $user."savedfiles";
8274: my %return_files;
8275: open (IN, '<'.LONCAPA::tempdir().$filename);
8276: while (my $line_in = <IN>) {
8277: chomp ($line_in);
8278: my @paths_and_file = split (m!/!, $line_in);
8279: my $file_part = pop (@paths_and_file);
8280: my $path_part = join ('/', @paths_and_file);
8281: $path_part.='/';
8282: my $path_and_file = $path_part.$file_part;
8283: if ($path_part eq $path) {
8284: $return_files{$file_part}= 'selected';
8285: }
8286: }
8287: close (IN);
8288: return (\%return_files);
8289: }
8290:
8291: # called in portfolio select mode, to show files selected NOT in current directory
8292: sub files_not_in_path {
8293: my ($user, $path) = @_;
8294: my $filename = $user."savedfiles";
8295: my @return_files;
8296: my $path_part;
8297: open(IN, '<'.LONCAPA::.$filename);
8298: while (my $line = <IN>) {
8299: #ok, I know it's clunky, but I want it to work
8300: my @paths_and_file = split(m|/|, $line);
8301: my $file_part = pop(@paths_and_file);
8302: chomp($file_part);
8303: my $path_part = join('/', @paths_and_file);
8304: $path_part .= '/';
8305: my $path_and_file = $path_part.$file_part;
8306: if ($path_part ne $path) {
8307: push(@return_files, ($path_and_file));
8308: }
8309: }
8310: close(OUT);
8311: return (@return_files);
8312: }
8313:
8314: #----------------------------------------------Get portfolio file permissions
8315:
8316: sub get_portfile_permissions {
8317: my ($domain,$user) = @_;
8318: my %current_permissions = &dump('file_permissions',$domain,$user);
8319: my ($tmp)=keys(%current_permissions);
8320: if ($tmp=~/^error:/) { undef(%current_permissions); }
8321: return \%current_permissions;
8322: }
8323:
8324: #---------------------------------------------Get portfolio file access controls
8325:
8326: sub get_access_controls {
8327: my ($current_permissions,$group,$file) = @_;
8328: my %access;
8329: my $real_file = $file;
8330: $file =~ s/\.meta$//;
8331: if (defined($file)) {
8332: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
8333: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
8334: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
8335: }
8336: }
8337: } else {
8338: foreach my $key (keys(%{$current_permissions})) {
8339: if ($key =~ /\0accesscontrol$/) {
8340: if (defined($group)) {
8341: if ($key !~ m-^\Q$group\E/-) {
8342: next;
8343: }
8344: }
8345: my ($fullpath) = split(/\0/,$key);
8346: if (ref($$current_permissions{$key}) eq 'HASH') {
8347: foreach my $control (keys(%{$$current_permissions{$key}})) {
8348: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
8349: }
8350: }
8351: }
8352: }
8353: }
8354: return %access;
8355: }
8356:
8357: sub modify_access_controls {
8358: my ($file_name,$changes,$domain,$user)=@_;
8359: my ($outcome,$deloutcome);
8360: my %store_permissions;
8361: my %new_values;
8362: my %new_control;
8363: my %translation;
8364: my @deletions = ();
8365: my $now = time;
8366: if (exists($$changes{'activate'})) {
8367: if (ref($$changes{'activate'}) eq 'HASH') {
8368: my @newitems = sort(keys(%{$$changes{'activate'}}));
8369: my $numnew = scalar(@newitems);
8370: for (my $i=0; $i<$numnew; $i++) {
8371: my $newkey = $newitems[$i];
8372: my $newid = &Apache::loncommon::get_cgi_id();
8373: if ($newkey =~ /^\d+:/) {
8374: $newkey =~ s/^(\d+)/$newid/;
8375: $translation{$1} = $newid;
8376: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
8377: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
8378: $translation{$1} = $newid;
8379: }
8380: $new_values{$file_name."\0".$newkey} =
8381: $$changes{'activate'}{$newitems[$i]};
8382: $new_control{$newkey} = $now;
8383: }
8384: }
8385: }
8386: my %todelete;
8387: my %changed_items;
8388: foreach my $action ('delete','update') {
8389: if (exists($$changes{$action})) {
8390: if (ref($$changes{$action}) eq 'HASH') {
8391: foreach my $key (keys(%{$$changes{$action}})) {
8392: my ($itemnum) = ($key =~ /^([^:]+):/);
8393: if ($action eq 'delete') {
8394: $todelete{$itemnum} = 1;
8395: } else {
8396: $changed_items{$itemnum} = $key;
8397: }
8398: }
8399: }
8400: }
8401: }
8402: # get lock on access controls for file.
8403: my $lockhash = {
8404: $file_name."\0".'locked_access_records' => $env{'user.name'}.
8405: ':'.$env{'user.domain'},
8406: };
8407: my $tries = 0;
8408: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8409:
8410: while (($gotlock ne 'ok') && $tries <3) {
8411: $tries ++;
8412: sleep 1;
8413: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8414: }
8415: if ($gotlock eq 'ok') {
8416: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
8417: my ($tmp)=keys(%curr_permissions);
8418: if ($tmp=~/^error:/) { undef(%curr_permissions); }
8419: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
8420: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
8421: if (ref($curr_controls) eq 'HASH') {
8422: foreach my $control_item (keys(%{$curr_controls})) {
8423: my ($itemnum) = ($control_item =~ /^([^:]+):/);
8424: if (defined($todelete{$itemnum})) {
8425: push(@deletions,$file_name."\0".$control_item);
8426: } else {
8427: if (defined($changed_items{$itemnum})) {
8428: $new_control{$changed_items{$itemnum}} = $now;
8429: push(@deletions,$file_name."\0".$control_item);
8430: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
8431: } else {
8432: $new_control{$control_item} = $$curr_controls{$control_item};
8433: }
8434: }
8435: }
8436: }
8437: }
8438: my ($group);
8439: if (&is_course($domain,$user)) {
8440: ($group,my $file) = split(/\//,$file_name,2);
8441: }
8442: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
8443: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
8444: $outcome = &put('file_permissions',\%new_values,$domain,$user);
8445: # remove lock
8446: my @del_lock = ($file_name."\0".'locked_access_records');
8447: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
8448: my $sqlresult =
8449: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
8450: $group);
8451: } else {
8452: $outcome = "error: could not obtain lockfile\n";
8453: }
8454: return ($outcome,$deloutcome,\%new_values,\%translation);
8455: }
8456:
8457: sub make_public_indefinitely {
8458: my ($requrl) = @_;
8459: my $now = time;
8460: my $action = 'activate';
8461: my $aclnum = 0;
8462: if (&is_portfolio_url($requrl)) {
8463: my (undef,$udom,$unum,$file_name,$group) =
8464: &parse_portfolio_url($requrl);
8465: my $current_perms = &get_portfile_permissions($udom,$unum);
8466: my %access_controls = &get_access_controls($current_perms,
8467: $group,$file_name);
8468: foreach my $key (keys(%{$access_controls{$file_name}})) {
8469: my ($num,$scope,$end,$start) =
8470: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
8471: if ($scope eq 'public') {
8472: if ($start <= $now && $end == 0) {
8473: $action = 'none';
8474: } else {
8475: $action = 'update';
8476: $aclnum = $num;
8477: }
8478: last;
8479: }
8480: }
8481: if ($action eq 'none') {
8482: return 'ok';
8483: } else {
8484: my %changes;
8485: my $newend = 0;
8486: my $newstart = $now;
8487: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
8488: $changes{$action}{$newkey} = {
8489: type => 'public',
8490: time => {
8491: start => $newstart,
8492: end => $newend,
8493: },
8494: };
8495: my ($outcome,$deloutcome,$new_values,$translation) =
8496: &modify_access_controls($file_name,\%changes,$udom,$unum);
8497: return $outcome;
8498: }
8499: } else {
8500: return 'invalid';
8501: }
8502: }
8503:
8504: #------------------------------------------------------Get Marked as Read Only
8505:
8506: sub get_marked_as_readonly {
8507: my ($domain,$user,$what,$group) = @_;
8508: my $current_permissions = &get_portfile_permissions($domain,$user);
8509: my @readonly_files;
8510: my $cmp1=$what;
8511: if (ref($what)) { $cmp1=join('',@{$what}) };
8512: while (my ($file_name,$value) = each(%{$current_permissions})) {
8513: if (defined($group)) {
8514: if ($file_name !~ m-^\Q$group\E/-) {
8515: next;
8516: }
8517: }
8518: if (ref($value) eq "ARRAY"){
8519: foreach my $stored_what (@{$value}) {
8520: my $cmp2=$stored_what;
8521: if (ref($stored_what) eq 'ARRAY') {
8522: $cmp2=join('',@{$stored_what});
8523: }
8524: if ($cmp1 eq $cmp2) {
8525: push(@readonly_files, $file_name);
8526: last;
8527: } elsif (!defined($what)) {
8528: push(@readonly_files, $file_name);
8529: last;
8530: }
8531: }
8532: }
8533: }
8534: return @readonly_files;
8535: }
8536: #-----------------------------------------------------------Get Marked as Read Only Hash
8537:
8538: sub get_marked_as_readonly_hash {
8539: my ($current_permissions,$group,$what) = @_;
8540: my %readonly_files;
8541: while (my ($file_name,$value) = each(%{$current_permissions})) {
8542: if (defined($group)) {
8543: if ($file_name !~ m-^\Q$group\E/-) {
8544: next;
8545: }
8546: }
8547: if (ref($value) eq "ARRAY"){
8548: foreach my $stored_what (@{$value}) {
8549: if (ref($stored_what) eq 'ARRAY') {
8550: foreach my $lock_descriptor(@{$stored_what}) {
8551: if ($lock_descriptor eq 'graded') {
8552: $readonly_files{$file_name} = 'graded';
8553: } elsif ($lock_descriptor eq 'handback') {
8554: $readonly_files{$file_name} = 'handback';
8555: } else {
8556: if (!exists($readonly_files{$file_name})) {
8557: $readonly_files{$file_name} = 'locked';
8558: }
8559: }
8560: }
8561: }
8562: }
8563: }
8564: }
8565: return %readonly_files;
8566: }
8567: # ------------------------------------------------------------ Unmark as Read Only
8568:
8569: sub unmark_as_readonly {
8570: # unmarks $file_name (if $file_name is defined), or all files locked by $what
8571: # for portfolio submissions, $what contains [$symb,$crsid]
8572: my ($domain,$user,$what,$file_name,$group) = @_;
8573: $file_name = &declutter_portfile($file_name);
8574: my $symb_crs = $what;
8575: if (ref($what)) { $symb_crs=join('',@$what); }
8576: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
8577: my ($tmp)=keys(%current_permissions);
8578: if ($tmp=~/^error:/) { undef(%current_permissions); }
8579: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
8580: foreach my $file (@readonly_files) {
8581: my $clean_file = &declutter_portfile($file);
8582: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
8583: my $current_locks = $current_permissions{$file};
8584: my @new_locks;
8585: my @del_keys;
8586: if (ref($current_locks) eq "ARRAY"){
8587: foreach my $locker (@{$current_locks}) {
8588: my $compare=$locker;
8589: if (ref($locker) eq 'ARRAY') {
8590: $compare=join('',@{$locker});
8591: if ($compare ne $symb_crs) {
8592: push(@new_locks, $locker);
8593: }
8594: }
8595: }
8596: if (scalar(@new_locks) > 0) {
8597: $current_permissions{$file} = \@new_locks;
8598: } else {
8599: push(@del_keys, $file);
8600: &del('file_permissions',\@del_keys, $domain, $user);
8601: delete($current_permissions{$file});
8602: }
8603: }
8604: }
8605: &put('file_permissions',\%current_permissions,$domain,$user);
8606: return;
8607: }
8608:
8609: # ------------------------------------------------------------ Directory lister
8610:
8611: sub dirlist {
8612: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
8613: $uri=~s/^\///;
8614: $uri=~s/\/$//;
8615: my ($udom, $uname);
8616: if ($getuserdir) {
8617: $udom = $userdomain;
8618: $uname = $username;
8619: } else {
8620: (undef,$udom,$uname)=split(/\//,$uri);
8621: if(defined($userdomain)) {
8622: $udom = $userdomain;
8623: }
8624: if(defined($username)) {
8625: $uname = $username;
8626: }
8627: }
8628: my ($dirRoot,$listing,@listing_results);
8629:
8630: $dirRoot = $perlvar{'lonDocRoot'};
8631: if (defined($getpropath)) {
8632: $dirRoot = &propath($udom,$uname);
8633: $dirRoot =~ s/\/$//;
8634: } elsif (defined($getuserdir)) {
8635: my $subdir=$uname.'__';
8636: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
8637: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
8638: ."/$udom/$subdir/$uname";
8639: } elsif (defined($alternateRoot)) {
8640: $dirRoot = $alternateRoot;
8641: }
8642:
8643: if($udom) {
8644: if($uname) {
8645: my $uhome = &homeserver($uname,$udom);
8646: if ($uhome eq 'no_host') {
8647: return ([],'no_host');
8648: }
8649: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
8650: .$getuserdir.':'.&escape($dirRoot)
8651: .':'.&escape($uname).':'.&escape($udom),$uhome);
8652: if ($listing eq 'unknown_cmd') {
8653: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
8654: } else {
8655: @listing_results = map { &unescape($_); } split(/:/,$listing);
8656: }
8657: if ($listing eq 'unknown_cmd') {
8658: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
8659: @listing_results = split(/:/,$listing);
8660: } else {
8661: @listing_results = map { &unescape($_); } split(/:/,$listing);
8662: }
8663: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
8664: ($listing eq 'rejected') || ($listing eq 'refused') ||
8665: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8666: return ([],$listing);
8667: } else {
8668: return (\@listing_results);
8669: }
8670: } elsif(!$alternateRoot) {
8671: my (%allusers,%listerror);
8672: my %servers = &get_servers($udom,'library');
8673: foreach my $tryserver (keys(%servers)) {
8674: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
8675: &escape($udom),$tryserver);
8676: if ($listing eq 'unknown_cmd') {
8677: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
8678: $udom, $tryserver);
8679: } else {
8680: @listing_results = map { &unescape($_); } split(/:/,$listing);
8681: }
8682: if ($listing eq 'unknown_cmd') {
8683: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
8684: $udom, $tryserver);
8685: @listing_results = split(/:/,$listing);
8686: } else {
8687: @listing_results =
8688: map { &unescape($_); } split(/:/,$listing);
8689: }
8690: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
8691: ($listing eq 'rejected') || ($listing eq 'refused') ||
8692: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8693: $listerror{$tryserver} = $listing;
8694: } else {
8695: foreach my $line (@listing_results) {
8696: my ($entry) = split(/&/,$line,2);
8697: $allusers{$entry} = 1;
8698: }
8699: }
8700: }
8701: my @alluserslist=();
8702: foreach my $user (sort(keys(%allusers))) {
8703: push(@alluserslist,$user.'&user');
8704: }
8705: return (\@alluserslist);
8706: } else {
8707: return ([],'missing username');
8708: }
8709: } elsif(!defined($getpropath)) {
8710: my $path = $perlvar{'lonDocRoot'}.'/res/';
8711: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
8712: return (\@all_domains);
8713: } else {
8714: return ([],'missing domain');
8715: }
8716: }
8717:
8718: # --------------------------------------------- GetFileTimestamp
8719: # This function utilizes dirlist and returns the date stamp for
8720: # when it was last modified. It will also return an error of -1
8721: # if an error occurs
8722:
8723: sub GetFileTimestamp {
8724: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
8725: $studentDomain = &LONCAPA::clean_domain($studentDomain);
8726: $studentName = &LONCAPA::clean_username($studentName);
8727: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
8728: undef,$getuserdir);
8729: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8730: return -1;
8731: }
8732: if (ref($fileref) eq 'ARRAY') {
8733: my @stats = split('&',$fileref->[0]);
8734: # @stats contains first the filename, then the stat output
8735: return $stats[10]; # so this is 10 instead of 9.
8736: } else {
8737: return -1;
8738: }
8739: }
8740:
8741: sub stat_file {
8742: my ($uri) = @_;
8743: $uri = &clutter_with_no_wrapper($uri);
8744:
8745: my ($udom,$uname,$file);
8746: if ($uri =~ m-^/(uploaded|editupload)/-) {
8747: ($udom,$uname,$file) =
8748: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
8749: $file = 'userfiles/'.$file;
8750: }
8751: if ($uri =~ m-^/res/-) {
8752: ($udom,$uname) =
8753: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
8754: $file = $uri;
8755: }
8756:
8757: if (!$udom || !$uname || !$file) {
8758: # unable to handle the uri
8759: return ();
8760: }
8761: my $getpropath;
8762: if ($file =~ /^userfiles\//) {
8763: $getpropath = 1;
8764: }
8765: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
8766: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8767: return ();
8768: } else {
8769: if (ref($listref) eq 'ARRAY') {
8770: my @stats = split('&',$listref->[0]);
8771: shift(@stats); #filename is first
8772: return @stats;
8773: }
8774: }
8775: return ();
8776: }
8777:
8778: # -------------------------------------------------------- Value of a Condition
8779:
8780: # gets the value of a specific preevaluated condition
8781: # stored in the string $env{user.state.<cid>}
8782: # or looks up a condition reference in the bighash and if if hasn't
8783: # already been evaluated recurses into docondval to get the value of
8784: # the condition, then memoizing it to
8785: # $env{user.state.<cid>.<condition>}
8786: sub directcondval {
8787: my $number=shift;
8788: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
8789: &Apache::lonuserstate::evalstate();
8790: }
8791: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
8792: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
8793: } elsif ($number =~ /^_/) {
8794: my $sub_condition;
8795: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8796: &GDBM_READER(),0640)) {
8797: $sub_condition=$bighash{'conditions'.$number};
8798: untie(%bighash);
8799: }
8800: my $value = &docondval($sub_condition);
8801: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
8802: return $value;
8803: }
8804: if ($env{'user.state.'.$env{'request.course.id'}}) {
8805: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
8806: } else {
8807: return 2;
8808: }
8809: }
8810:
8811: # get the collection of conditions for this resource
8812: sub condval {
8813: my $condidx=shift;
8814: my $allpathcond='';
8815: foreach my $cond (split(/\|/,$condidx)) {
8816: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8817: $allpathcond.=
8818: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8819: }
8820: }
8821: $allpathcond=~s/\|$//;
8822: return &docondval($allpathcond);
8823: }
8824:
8825: #evaluates an expression of conditions
8826: sub docondval {
8827: my ($allpathcond) = @_;
8828: my $result=0;
8829: if ($env{'request.course.id'}
8830: && defined($allpathcond)) {
8831: my $operand='|';
8832: my @stack;
8833: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8834: if ($chunk eq '(') {
8835: push @stack,($operand,$result);
8836: } elsif ($chunk eq ')') {
8837: my $before=pop @stack;
8838: if (pop @stack eq '&') {
8839: $result=$result>$before?$before:$result;
8840: } else {
8841: $result=$result>$before?$result:$before;
8842: }
8843: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8844: $operand=$chunk;
8845: } else {
8846: my $new=directcondval($chunk);
8847: if ($operand eq '&') {
8848: $result=$result>$new?$new:$result;
8849: } else {
8850: $result=$result>$new?$result:$new;
8851: }
8852: }
8853: }
8854: }
8855: return $result;
8856: }
8857:
8858: # ---------------------------------------------------- Devalidate courseresdata
8859:
8860: sub devalidatecourseresdata {
8861: my ($coursenum,$coursedomain)=@_;
8862: my $hashid=$coursenum.':'.$coursedomain;
8863: &devalidate_cache_new('courseres',$hashid);
8864: }
8865:
8866:
8867: # --------------------------------------------------- Course Resourcedata Query
8868: #
8869: # Parameters:
8870: # $coursenum - Number of the course.
8871: # $coursedomain - Domain at which the course was created.
8872: # Returns:
8873: # A hash of the course parameters along (I think) with timestamps
8874: # and version info.
8875:
8876: sub get_courseresdata {
8877: my ($coursenum,$coursedomain)=@_;
8878: my $coursehom=&homeserver($coursenum,$coursedomain);
8879: my $hashid=$coursenum.':'.$coursedomain;
8880: my ($result,$cached)=&is_cached_new('courseres',$hashid);
8881: my %dumpreply;
8882: unless (defined($cached)) {
8883: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
8884: $result=\%dumpreply;
8885: my ($tmp) = keys(%dumpreply);
8886: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
8887: &do_cache_new('courseres',$hashid,$result,600);
8888: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8889: return $tmp;
8890: } elsif ($tmp =~ /^(error)/) {
8891: $result=undef;
8892: &do_cache_new('courseres',$hashid,$result,600);
8893: }
8894: }
8895: return $result;
8896: }
8897:
8898: sub devalidateuserresdata {
8899: my ($uname,$udom)=@_;
8900: my $hashid="$udom:$uname";
8901: &devalidate_cache_new('userres',$hashid);
8902: }
8903:
8904: sub get_userresdata {
8905: my ($uname,$udom)=@_;
8906: #most student don\'t have any data set, check if there is some data
8907: if (&EXT_cache_status($udom,$uname)) { return undef; }
8908:
8909: my $hashid="$udom:$uname";
8910: my ($result,$cached)=&is_cached_new('userres',$hashid);
8911: if (!defined($cached)) {
8912: my %resourcedata=&dump('resourcedata',$udom,$uname);
8913: $result=\%resourcedata;
8914: &do_cache_new('userres',$hashid,$result,600);
8915: }
8916: my ($tmp)=keys(%$result);
8917: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8918: return $result;
8919: }
8920: #error 2 occurs when the .db doesn't exist
8921: if ($tmp!~/error: 2 /) {
8922: &logthis("<font color=\"blue\">WARNING:".
8923: " Trying to get resource data for ".
8924: $uname." at ".$udom.": ".
8925: $tmp."</font>");
8926: } elsif ($tmp=~/error: 2 /) {
8927: #&EXT_cache_set($udom,$uname);
8928: &do_cache_new('userres',$hashid,undef,600);
8929: undef($tmp); # not really an error so don't send it back
8930: }
8931: return $tmp;
8932: }
8933: #----------------------------------------------- resdata - return resource data
8934: # Purpose:
8935: # Return resource data for either users or for a course.
8936: # Parameters:
8937: # $name - Course/user name.
8938: # $domain - Name of the domain the user/course is registered on.
8939: # $type - Type of thing $name is (must be 'course' or 'user'
8940: # @which - Array of names of resources desired.
8941: # Returns:
8942: # The value of the first reasource in @which that is found in the
8943: # resource hash.
8944: # Exceptional Conditions:
8945: # If the $type passed in is not valid (not the string 'course' or
8946: # 'user', an undefined reference is returned.
8947: # If none of the resources are found, an undef is returned
8948: sub resdata {
8949: my ($name,$domain,$type,@which)=@_;
8950: my $result;
8951: if ($type eq 'course') {
8952: $result=&get_courseresdata($name,$domain);
8953: } elsif ($type eq 'user') {
8954: $result=&get_userresdata($name,$domain);
8955: }
8956: if (!ref($result)) { return $result; }
8957: foreach my $item (@which) {
8958: if (defined($result->{$item->[0]})) {
8959: return [$result->{$item->[0]},$item->[1]];
8960: }
8961: }
8962: return undef;
8963: }
8964:
8965: #
8966: # EXT resource caching routines
8967: #
8968:
8969: sub clear_EXT_cache_status {
8970: &delenv('cache.EXT.');
8971: }
8972:
8973: sub EXT_cache_status {
8974: my ($target_domain,$target_user) = @_;
8975: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
8976: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
8977: # We know already the user has no data
8978: return 1;
8979: } else {
8980: return 0;
8981: }
8982: }
8983:
8984: sub EXT_cache_set {
8985: my ($target_domain,$target_user) = @_;
8986: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
8987: #&appenv({$cachename => time});
8988: }
8989:
8990: # --------------------------------------------------------- Value of a Variable
8991: sub EXT {
8992:
8993: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
8994: unless ($varname) { return ''; }
8995: #get real user name/domain, courseid and symb
8996: my $courseid;
8997: my $publicuser;
8998: if ($symbparm) {
8999: $symbparm=&get_symb_from_alias($symbparm);
9000: }
9001: if (!($uname && $udom)) {
9002: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
9003: if (!$symbparm) { $symbparm=$cursymb; }
9004: } else {
9005: $courseid=$env{'request.course.id'};
9006: }
9007: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9008: my $rest;
9009: if (defined($therest[0])) {
9010: $rest=join('.',@therest);
9011: } else {
9012: $rest='';
9013: }
9014:
9015: my $qualifierrest=$qualifier;
9016: if ($rest) { $qualifierrest.='.'.$rest; }
9017: my $spacequalifierrest=$space;
9018: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
9019: if ($realm eq 'user') {
9020: # --------------------------------------------------------------- user.resource
9021: if ($space eq 'resource') {
9022: if ( (defined($Apache::lonhomework::parsing_a_problem)
9023: || defined($Apache::lonhomework::parsing_a_task))
9024: &&
9025: ($symbparm eq &symbread()) ) {
9026: # if we are in the middle of processing the resource the
9027: # get the value we are planning on committing
9028: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9029: return $Apache::lonhomework::results{$qualifierrest};
9030: } else {
9031: return $Apache::lonhomework::history{$qualifierrest};
9032: }
9033: } else {
9034: my %restored;
9035: if ($publicuser || $env{'request.state'} eq 'construct') {
9036: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9037: } else {
9038: %restored=&restore($symbparm,$courseid,$udom,$uname);
9039: }
9040: return $restored{$qualifierrest};
9041: }
9042: # ----------------------------------------------------------------- user.access
9043: } elsif ($space eq 'access') {
9044: # FIXME - not supporting calls for a specific user
9045: return &allowed($qualifier,$rest);
9046: # ------------------------------------------ user.preferences, user.environment
9047: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
9048: if (($uname eq $env{'user.name'}) &&
9049: ($udom eq $env{'user.domain'})) {
9050: return $env{join('.',('environment',$qualifierrest))};
9051: } else {
9052: my %returnhash;
9053: if (!$publicuser) {
9054: %returnhash=&userenvironment($udom,$uname,
9055: $qualifierrest);
9056: }
9057: return $returnhash{$qualifierrest};
9058: }
9059: # ----------------------------------------------------------------- user.course
9060: } elsif ($space eq 'course') {
9061: # FIXME - not supporting calls for a specific user
9062: return $env{join('.',('request.course',$qualifier))};
9063: # ------------------------------------------------------------------- user.role
9064: } elsif ($space eq 'role') {
9065: # FIXME - not supporting calls for a specific user
9066: my ($role,$where)=split(/\./,$env{'request.role'});
9067: if ($qualifier eq 'value') {
9068: return $role;
9069: } elsif ($qualifier eq 'extent') {
9070: return $where;
9071: }
9072: # ----------------------------------------------------------------- user.domain
9073: } elsif ($space eq 'domain') {
9074: return $udom;
9075: # ------------------------------------------------------------------- user.name
9076: } elsif ($space eq 'name') {
9077: return $uname;
9078: # ---------------------------------------------------- Any other user namespace
9079: } else {
9080: my %reply;
9081: if (!$publicuser) {
9082: %reply=&get($space,[$qualifierrest],$udom,$uname);
9083: }
9084: return $reply{$qualifierrest};
9085: }
9086: } elsif ($realm eq 'query') {
9087: # ---------------------------------------------- pull stuff out of query string
9088: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9089: [$spacequalifierrest]);
9090: return $env{'form.'.$spacequalifierrest};
9091: } elsif ($realm eq 'request') {
9092: # ------------------------------------------------------------- request.browser
9093: if ($space eq 'browser') {
9094: return $env{'browser.'.$qualifier};
9095: # ------------------------------------------------------------ request.filename
9096: } else {
9097: return $env{'request.'.$spacequalifierrest};
9098: }
9099: } elsif ($realm eq 'course') {
9100: # ---------------------------------------------------------- course.description
9101: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
9102: } elsif ($realm eq 'resource') {
9103:
9104: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
9105: if (!$symbparm) { $symbparm=&symbread(); }
9106: }
9107:
9108: if ($space eq 'title') {
9109: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9110: return &gettitle($symbparm);
9111: }
9112:
9113: if ($space eq 'map') {
9114: my ($map) = &decode_symb($symbparm);
9115: return &symbread($map);
9116: }
9117: if ($space eq 'filename') {
9118: if ($symbparm) {
9119: return &clutter((&decode_symb($symbparm))[2]);
9120: }
9121: return &hreflocation('',$env{'request.filename'});
9122: }
9123:
9124: my ($section, $group, @groups);
9125: my ($courselevelm,$courselevel);
9126: if ($symbparm && defined($courseid) &&
9127: $courseid eq $env{'request.course.id'}) {
9128:
9129: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
9130:
9131: # ----------------------------------------------------- Cascading lookup scheme
9132: my $symbp=$symbparm;
9133: my $mapp=&deversion((&decode_symb($symbp))[0]);
9134:
9135: my $symbparm=$symbp.'.'.$spacequalifierrest;
9136: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9137:
9138: if (($env{'user.name'} eq $uname) &&
9139: ($env{'user.domain'} eq $udom)) {
9140: $section=$env{'request.course.sec'};
9141: @groups = split(/:/,$env{'request.course.groups'});
9142: @groups=&sort_course_groups($courseid,@groups);
9143: } else {
9144: if (! defined($usection)) {
9145: $section=&getsection($udom,$uname,$courseid);
9146: } else {
9147: $section = $usection;
9148: }
9149: @groups = &get_users_groups($udom,$uname,$courseid);
9150: }
9151:
9152: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9153: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9154: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9155:
9156: $courselevel=$courseid.'.'.$spacequalifierrest;
9157: my $courselevelr=$courseid.'.'.$symbparm;
9158: $courselevelm=$courseid.'.'.$mapparm;
9159:
9160: # ----------------------------------------------------------- first, check user
9161:
9162: my $userreply=&resdata($uname,$udom,'user',
9163: ([$courselevelr,'resource'],
9164: [$courselevelm,'map' ],
9165: [$courselevel, 'course' ]));
9166: if (defined($userreply)) { return &get_reply($userreply); }
9167:
9168: # ------------------------------------------------ second, check some of course
9169: my $coursereply;
9170: if (@groups > 0) {
9171: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9172: $mapparm,$spacequalifierrest);
9173: if (defined($coursereply)) { return &get_reply($coursereply); }
9174: }
9175:
9176: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9177: $env{'course.'.$courseid.'.domain'},
9178: 'course',
9179: ([$seclevelr, 'resource'],
9180: [$seclevelm, 'map' ],
9181: [$seclevel, 'course' ],
9182: [$courselevelr,'resource']));
9183: if (defined($coursereply)) { return &get_reply($coursereply); }
9184:
9185: # ------------------------------------------------------ third, check map parms
9186: my %parmhash=();
9187: my $thisparm='';
9188: if (tie(%parmhash,'GDBM_File',
9189: $env{'request.course.fn'}.'_parms.db',
9190: &GDBM_READER(),0640)) {
9191: $thisparm=$parmhash{$symbparm};
9192: untie(%parmhash);
9193: }
9194: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
9195: }
9196: # ------------------------------------------ fourth, look in resource metadata
9197:
9198: $spacequalifierrest=~s/\./\_/;
9199: my $filename;
9200: if (!$symbparm) { $symbparm=&symbread(); }
9201: if ($symbparm) {
9202: $filename=(&decode_symb($symbparm))[2];
9203: } else {
9204: $filename=$env{'request.filename'};
9205: }
9206: my $metadata=&metadata($filename,$spacequalifierrest);
9207: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
9208: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
9209: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
9210:
9211: # ---------------------------------------------- fourth, look in rest of course
9212: if ($symbparm && defined($courseid) &&
9213: $courseid eq $env{'request.course.id'}) {
9214: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9215: $env{'course.'.$courseid.'.domain'},
9216: 'course',
9217: ([$courselevelm,'map' ],
9218: [$courselevel, 'course']));
9219: if (defined($coursereply)) { return &get_reply($coursereply); }
9220: }
9221: # ------------------------------------------------------------------ Cascade up
9222: unless ($space eq '0') {
9223: my @parts=split(/_/,$space);
9224: my $id=pop(@parts);
9225: my $part=join('_',@parts);
9226: if ($part eq '') { $part='0'; }
9227: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
9228: $symbparm,$udom,$uname,$section,1);
9229: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
9230: }
9231: if ($recurse) { return undef; }
9232: my $pack_def=&packages_tab_default($filename,$varname);
9233: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
9234: # ---------------------------------------------------- Any other user namespace
9235: } elsif ($realm eq 'environment') {
9236: # ----------------------------------------------------------------- environment
9237: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
9238: return $env{'environment.'.$spacequalifierrest};
9239: } else {
9240: if ($uname eq 'anonymous' && $udom eq '') {
9241: return '';
9242: }
9243: my %returnhash=&userenvironment($udom,$uname,
9244: $spacequalifierrest);
9245: return $returnhash{$spacequalifierrest};
9246: }
9247: } elsif ($realm eq 'system') {
9248: # ----------------------------------------------------------------- system.time
9249: if ($space eq 'time') {
9250: return time;
9251: }
9252: } elsif ($realm eq 'server') {
9253: # ----------------------------------------------------------------- system.time
9254: if ($space eq 'name') {
9255: return $ENV{'SERVER_NAME'};
9256: }
9257: }
9258: return '';
9259: }
9260:
9261: sub get_reply {
9262: my ($reply_value) = @_;
9263: if (ref($reply_value) eq 'ARRAY') {
9264: if (wantarray) {
9265: return @$reply_value;
9266: }
9267: return $reply_value->[0];
9268: } else {
9269: return $reply_value;
9270: }
9271: }
9272:
9273: sub check_group_parms {
9274: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
9275: my @groupitems = ();
9276: my $resultitem;
9277: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
9278: foreach my $group (@{$groups}) {
9279: foreach my $level (@levels) {
9280: my $item = $courseid.'.['.$group.'].'.$level->[0];
9281: push(@groupitems,[$item,$level->[1]]);
9282: }
9283: }
9284: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
9285: $env{'course.'.$courseid.'.domain'},
9286: 'course',@groupitems);
9287: return $coursereply;
9288: }
9289:
9290: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
9291: my ($courseid,@groups) = @_;
9292: @groups = sort(@groups);
9293: return @groups;
9294: }
9295:
9296: sub packages_tab_default {
9297: my ($uri,$varname)=@_;
9298: my (undef,$part,$name)=split(/\./,$varname);
9299:
9300: my (@extension,@specifics,$do_default);
9301: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
9302: my ($pack_type,$pack_part)=split(/_/,$package,2);
9303: if ($pack_type eq 'default') {
9304: $do_default=1;
9305: } elsif ($pack_type eq 'extension') {
9306: push(@extension,[$package,$pack_type,$pack_part]);
9307: } elsif ($pack_part eq $part || $pack_type eq 'part') {
9308: # only look at packages defaults for packages that this id is
9309: push(@specifics,[$package,$pack_type,$pack_part]);
9310: }
9311: }
9312: # first look for a package that matches the requested part id
9313: foreach my $package (@specifics) {
9314: my (undef,$pack_type,$pack_part)=@{$package};
9315: next if ($pack_part ne $part);
9316: if (defined($packagetab{"$pack_type&$name&default"})) {
9317: return $packagetab{"$pack_type&$name&default"};
9318: }
9319: }
9320: # look for any possible matching non extension_ package
9321: foreach my $package (@specifics) {
9322: my (undef,$pack_type,$pack_part)=@{$package};
9323: if (defined($packagetab{"$pack_type&$name&default"})) {
9324: return $packagetab{"$pack_type&$name&default"};
9325: }
9326: if ($pack_type eq 'part') { $pack_part='0'; }
9327: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
9328: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
9329: }
9330: }
9331: # look for any posible extension_ match
9332: foreach my $package (@extension) {
9333: my ($package,$pack_type)=@{$package};
9334: if (defined($packagetab{"$pack_type&$name&default"})) {
9335: return $packagetab{"$pack_type&$name&default"};
9336: }
9337: if (defined($packagetab{$package."&$name&default"})) {
9338: return $packagetab{$package."&$name&default"};
9339: }
9340: }
9341: # look for a global default setting
9342: if ($do_default && defined($packagetab{"default&$name&default"})) {
9343: return $packagetab{"default&$name&default"};
9344: }
9345: return undef;
9346: }
9347:
9348: sub add_prefix_and_part {
9349: my ($prefix,$part)=@_;
9350: my $keyroot;
9351: if (defined($prefix) && $prefix !~ /^__/) {
9352: # prefix that has a part already
9353: $keyroot=$prefix;
9354: } elsif (defined($prefix)) {
9355: # prefix that is missing a part
9356: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
9357: } else {
9358: # no prefix at all
9359: if (defined($part)) { $keyroot='_'.$part; }
9360: }
9361: return $keyroot;
9362: }
9363:
9364: # ---------------------------------------------------------------- Get metadata
9365:
9366: my %metaentry;
9367: my %importedpartids;
9368: sub metadata {
9369: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
9370: $uri=&declutter($uri);
9371: # if it is a non metadata possible uri return quickly
9372: if (($uri eq '') ||
9373: (($uri =~ m|^/*adm/|) &&
9374: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
9375: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
9376: return undef;
9377: }
9378: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
9379: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
9380: return undef;
9381: }
9382: my $filename=$uri;
9383: $uri=~s/\.meta$//;
9384: #
9385: # Is the metadata already cached?
9386: # Look at timestamp of caching
9387: # Everything is cached by the main uri, libraries are never directly cached
9388: #
9389: if (!defined($liburi)) {
9390: my ($result,$cached)=&is_cached_new('meta',$uri);
9391: if (defined($cached)) { return $result->{':'.$what}; }
9392: }
9393: {
9394: # Imported parts would go here
9395: my %importedids=();
9396: my @origfileimportpartids=();
9397: my $importedparts=0;
9398: #
9399: # Is this a recursive call for a library?
9400: #
9401: # if (! exists($metacache{$uri})) {
9402: # $metacache{$uri}={};
9403: # }
9404: my $cachetime = 60*60;
9405: if ($liburi) {
9406: $liburi=&declutter($liburi);
9407: $filename=$liburi;
9408: } else {
9409: &devalidate_cache_new('meta',$uri);
9410: undef(%metaentry);
9411: }
9412: my %metathesekeys=();
9413: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
9414: my $metastring;
9415: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
9416: my $which = &hreflocation('','/'.($liburi || $uri));
9417: $metastring =
9418: &Apache::lonnet::ssi_body($which,
9419: ('grade_target' => 'meta'));
9420: $cachetime = 1; # only want this cached in the child not long term
9421: } elsif (($uri !~ m -^(editupload)/-) &&
9422: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
9423: my $file=&filelocation('',&clutter($filename));
9424: #push(@{$metaentry{$uri.'.file'}},$file);
9425: $metastring=&getfile($file);
9426: }
9427: my $parser=HTML::LCParser->new(\$metastring);
9428: my $token;
9429: undef %metathesekeys;
9430: while ($token=$parser->get_token) {
9431: if ($token->[0] eq 'S') {
9432: if (defined($token->[2]->{'package'})) {
9433: #
9434: # This is a package - get package info
9435: #
9436: my $package=$token->[2]->{'package'};
9437: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9438: if (defined($token->[2]->{'id'})) {
9439: $keyroot.='_'.$token->[2]->{'id'};
9440: }
9441: if ($metaentry{':packages'}) {
9442: $metaentry{':packages'}.=','.$package.$keyroot;
9443: } else {
9444: $metaentry{':packages'}=$package.$keyroot;
9445: }
9446: foreach my $pack_entry (keys(%packagetab)) {
9447: my $part=$keyroot;
9448: $part=~s/^\_//;
9449: if ($pack_entry=~/^\Q$package\E\&/ ||
9450: $pack_entry=~/^\Q$package\E_0\&/) {
9451: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
9452: # ignore package.tab specified default values
9453: # here &package_tab_default() will fetch those
9454: if ($subp eq 'default') { next; }
9455: my $value=$packagetab{$pack_entry};
9456: my $unikey;
9457: if ($pack =~ /_0$/) {
9458: $unikey='parameter_0_'.$name;
9459: $part=0;
9460: } else {
9461: $unikey='parameter'.$keyroot.'_'.$name;
9462: }
9463: if ($subp eq 'display') {
9464: $value.=' [Part: '.$part.']';
9465: }
9466: $metaentry{':'.$unikey.'.part'}=$part;
9467: $metathesekeys{$unikey}=1;
9468: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9469: $metaentry{':'.$unikey.'.'.$subp}=$value;
9470: }
9471: if (defined($metaentry{':'.$unikey.'.default'})) {
9472: $metaentry{':'.$unikey}=
9473: $metaentry{':'.$unikey.'.default'};
9474: }
9475: }
9476: }
9477: } else {
9478: #
9479: # This is not a package - some other kind of start tag
9480: #
9481: my $entry=$token->[1];
9482: my $unikey='';
9483:
9484: if ($entry eq 'import') {
9485: #
9486: # Importing a library here
9487: #
9488: my $location=$parser->get_text('/import');
9489: my $dir=$filename;
9490: $dir=~s|[^/]*$||;
9491: $location=&filelocation($dir,$location);
9492:
9493: my $importmode=$token->[2]->{'importmode'};
9494: if ($importmode eq 'problem') {
9495: # Import as problem/response
9496: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9497: } elsif ($importmode eq 'part') {
9498: # Import as part(s)
9499: $importedparts=1;
9500: # We need to get the original file and the imported file to get the part order correct
9501: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
9502: # Load and inspect original file
9503: if ($#origfileimportpartids<0) {
9504: undef(%importedpartids);
9505: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
9506: my $origfile=&getfile($origfilelocation);
9507: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9508: }
9509:
9510: # Load and inspect imported file
9511: my $impfile=&getfile($location);
9512: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9513: if ($#impfilepartids>=0) {
9514: # This problem had parts
9515: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
9516: } else {
9517: # Importing by turning a single problem into a problem part
9518: # It gets the import-tags ID as part-ID
9519: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
9520: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
9521: }
9522: } else {
9523: # Normal import
9524: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9525: if (defined($token->[2]->{'id'})) {
9526: $unikey.='_'.$token->[2]->{'id'};
9527: }
9528: }
9529:
9530: if ($depthcount<20) {
9531: my $metadata =
9532: &metadata($uri,'keys', $location,$unikey,
9533: $depthcount+1);
9534: foreach my $meta (split(',',$metadata)) {
9535: $metaentry{':'.$meta}=$metaentry{':'.$meta};
9536: $metathesekeys{$meta}=1;
9537: }
9538:
9539: }
9540: } else {
9541: #
9542: # Not importing, some other kind of non-package, non-library start tag
9543: #
9544: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
9545: if (defined($token->[2]->{'id'})) {
9546: $unikey.='_'.$token->[2]->{'id'};
9547: }
9548: if (defined($token->[2]->{'name'})) {
9549: $unikey.='_'.$token->[2]->{'name'};
9550: }
9551: $metathesekeys{$unikey}=1;
9552: foreach my $param (@{$token->[3]}) {
9553: $metaentry{':'.$unikey.'.'.$param} =
9554: $token->[2]->{$param};
9555: }
9556: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
9557: my $default=$metaentry{':'.$unikey.'.default'};
9558: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
9559: # only ws inside the tag, and not in default, so use default
9560: # as value
9561: $metaentry{':'.$unikey}=$default;
9562: } elsif ( $internaltext =~ /\S/ ) {
9563: # something interesting inside the tag
9564: $metaentry{':'.$unikey}=$internaltext;
9565: } else {
9566: # no interesting values, don't set a default
9567: }
9568: # end of not-a-package not-a-library import
9569: }
9570: # end of not-a-package start tag
9571: }
9572: # the next is the end of "start tag"
9573: }
9574: }
9575: my ($extension) = ($uri =~ /\.(\w+)$/);
9576: $extension = lc($extension);
9577: if ($extension eq 'htm') { $extension='html'; }
9578:
9579: foreach my $key (keys(%packagetab)) {
9580: #no specific packages #how's our extension
9581: if ($key!~/^extension_\Q$extension\E&/) { next; }
9582: &metadata_create_package_def($uri,$key,'extension_'.$extension,
9583: \%metathesekeys);
9584: }
9585:
9586: if (!exists($metaentry{':packages'})
9587: || $packagetab{"import_defaults&extension_$extension"}) {
9588: foreach my $key (keys(%packagetab)) {
9589: #no specific packages well let's get default then
9590: if ($key!~/^default&/) { next; }
9591: &metadata_create_package_def($uri,$key,'default',
9592: \%metathesekeys);
9593: }
9594: }
9595: # are there custom rights to evaluate
9596: if ($metaentry{':copyright'} eq 'custom') {
9597:
9598: #
9599: # Importing a rights file here
9600: #
9601: unless ($depthcount) {
9602: my $location=$metaentry{':customdistributionfile'};
9603: my $dir=$filename;
9604: $dir=~s|[^/]*$||;
9605: $location=&filelocation($dir,$location);
9606: my $rights_metadata =
9607: &metadata($uri,'keys',$location,'_rights',
9608: $depthcount+1);
9609: foreach my $rights (split(',',$rights_metadata)) {
9610: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
9611: $metathesekeys{$rights}=1;
9612: }
9613: }
9614: }
9615: # uniqifiy package listing
9616: my %seen;
9617: my @uniq_packages =
9618: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
9619: $metaentry{':packages'} = join(',',@uniq_packages);
9620:
9621: if ($importedparts) {
9622: # We had imported parts and need to rebuild partorder
9623: $metaentry{':partorder'}='';
9624: $metathesekeys{'partorder'}=1;
9625: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
9626: if ($origfileimportpartids[$index] eq 'part') {
9627: # original part, part of the problem
9628: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
9629: } else {
9630: # we have imported parts at this position
9631: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
9632: }
9633: }
9634: $metaentry{':partorder'}=~s/^\,//;
9635: }
9636:
9637: $metaentry{':keys'} = join(',',keys(%metathesekeys));
9638: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
9639: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
9640: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
9641: # this is the end of "was not already recently cached
9642: }
9643: return $metaentry{':'.$what};
9644: }
9645:
9646: sub metadata_create_package_def {
9647: my ($uri,$key,$package,$metathesekeys)=@_;
9648: my ($pack,$name,$subp)=split(/\&/,$key);
9649: if ($subp eq 'default') { next; }
9650:
9651: if (defined($metaentry{':packages'})) {
9652: $metaentry{':packages'}.=','.$package;
9653: } else {
9654: $metaentry{':packages'}=$package;
9655: }
9656: my $value=$packagetab{$key};
9657: my $unikey;
9658: $unikey='parameter_0_'.$name;
9659: $metaentry{':'.$unikey.'.part'}=0;
9660: $$metathesekeys{$unikey}=1;
9661: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9662: $metaentry{':'.$unikey.'.'.$subp}=$value;
9663: }
9664: if (defined($metaentry{':'.$unikey.'.default'})) {
9665: $metaentry{':'.$unikey}=
9666: $metaentry{':'.$unikey.'.default'};
9667: }
9668: }
9669:
9670: sub metadata_generate_part0 {
9671: my ($metadata,$metacache,$uri) = @_;
9672: my %allnames;
9673: foreach my $metakey (keys(%$metadata)) {
9674: if ($metakey=~/^parameter\_(.*)/) {
9675: my $part=$$metacache{':'.$metakey.'.part'};
9676: my $name=$$metacache{':'.$metakey.'.name'};
9677: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
9678: $allnames{$name}=$part;
9679: }
9680: }
9681: }
9682: foreach my $name (keys(%allnames)) {
9683: $$metadata{"parameter_0_$name"}=1;
9684: my $key=":parameter_0_$name";
9685: $$metacache{"$key.part"}='0';
9686: $$metacache{"$key.name"}=$name;
9687: $$metacache{"$key.type"}=$$metacache{':parameter_'.
9688: $allnames{$name}.'_'.$name.
9689: '.type'};
9690: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
9691: '.display'};
9692: my $expr='[Part: '.$allnames{$name}.']';
9693: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
9694: $$metacache{"$key.display"}=$olddis;
9695: }
9696: }
9697:
9698: # ------------------------------------------------------ Devalidate title cache
9699:
9700: sub devalidate_title_cache {
9701: my ($url)=@_;
9702: if (!$env{'request.course.id'}) { return; }
9703: my $symb=&symbread($url);
9704: if (!$symb) { return; }
9705: my $key=$env{'request.course.id'}."\0".$symb;
9706: &devalidate_cache_new('title',$key);
9707: }
9708:
9709: # ------------------------------------------------- Get the title of a course
9710:
9711: sub current_course_title {
9712: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
9713: }
9714: # ------------------------------------------------- Get the title of a resource
9715:
9716: sub gettitle {
9717: my $urlsymb=shift;
9718: my $symb=&symbread($urlsymb);
9719: if ($symb) {
9720: my $key=$env{'request.course.id'}."\0".$symb;
9721: my ($result,$cached)=&is_cached_new('title',$key);
9722: if (defined($cached)) {
9723: return $result;
9724: }
9725: my ($map,$resid,$url)=&decode_symb($symb);
9726: my $title='';
9727: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
9728: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
9729: } else {
9730: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9731: &GDBM_READER(),0640)) {
9732: my $mapid=$bighash{'map_pc_'.&clutter($map)};
9733: $title=$bighash{'title_'.$mapid.'.'.$resid};
9734: untie(%bighash);
9735: }
9736: }
9737: $title=~s/\&colon\;/\:/gs;
9738: if ($title) {
9739: # Remember both $symb and $title for dynamic metadata
9740: $accesshash{$symb.'___crstitle'}=$title;
9741: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
9742: # Cache this title and then return it
9743: return &do_cache_new('title',$key,$title,600);
9744: }
9745: $urlsymb=$url;
9746: }
9747: my $title=&metadata($urlsymb,'title');
9748: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
9749: return $title;
9750: }
9751:
9752: sub get_slot {
9753: my ($which,$cnum,$cdom)=@_;
9754: if (!$cnum || !$cdom) {
9755: (undef,my $courseid)=&whichuser();
9756: $cdom=$env{'course.'.$courseid.'.domain'};
9757: $cnum=$env{'course.'.$courseid.'.num'};
9758: }
9759: my $key=join("\0",'slots',$cdom,$cnum,$which);
9760: my %slotinfo;
9761: if (exists($remembered{$key})) {
9762: $slotinfo{$which} = $remembered{$key};
9763: } else {
9764: %slotinfo=&get('slots',[$which],$cdom,$cnum);
9765: &Apache::lonhomework::showhash(%slotinfo);
9766: my ($tmp)=keys(%slotinfo);
9767: if ($tmp=~/^error:/) { return (); }
9768: $remembered{$key} = $slotinfo{$which};
9769: }
9770: if (ref($slotinfo{$which}) eq 'HASH') {
9771: return %{$slotinfo{$which}};
9772: }
9773: return $slotinfo{$which};
9774: }
9775:
9776: sub get_reservable_slots {
9777: my ($cnum,$cdom,$uname,$udom) = @_;
9778: my $now = time;
9779: my $reservable_info;
9780: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
9781: if (exists($remembered{$key})) {
9782: $reservable_info = $remembered{$key};
9783: } else {
9784: my %resv;
9785: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
9786: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
9787: $reservable_info = \%resv;
9788: $remembered{$key} = $reservable_info;
9789: }
9790: return $reservable_info;
9791: }
9792:
9793: sub get_course_slots {
9794: my ($cnum,$cdom) = @_;
9795: my $hashid=$cnum.':'.$cdom;
9796: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
9797: if (defined($cached)) {
9798: if (ref($result) eq 'HASH') {
9799: return %{$result};
9800: }
9801: } else {
9802: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
9803: my ($tmp) = keys(%slots);
9804: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9805: &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
9806: return %slots;
9807: }
9808: }
9809: return;
9810: }
9811:
9812: sub devalidate_slots_cache {
9813: my ($cnum,$cdom)=@_;
9814: my $hashid=$cnum.':'.$cdom;
9815: &devalidate_cache_new('allslots',$hashid);
9816: }
9817:
9818: # ------------------------------------------------- Update symbolic store links
9819:
9820: sub symblist {
9821: my ($mapname,%newhash)=@_;
9822: $mapname=&deversion(&declutter($mapname));
9823: my %hash;
9824: if (($env{'request.course.fn'}) && (%newhash)) {
9825: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
9826: &GDBM_WRCREAT(),0640)) {
9827: foreach my $url (keys(%newhash)) {
9828: next if ($url eq 'last_known'
9829: && $env{'form.no_update_last_known'});
9830: $hash{declutter($url)}=&encode_symb($mapname,
9831: $newhash{$url}->[1],
9832: $newhash{$url}->[0]);
9833: }
9834: if (untie(%hash)) {
9835: return 'ok';
9836: }
9837: }
9838: }
9839: return 'error';
9840: }
9841:
9842: # --------------------------------------------------------------- Verify a symb
9843:
9844: sub symbverify {
9845: my ($symb,$thisurl)=@_;
9846: my $thisfn=$thisurl;
9847: $thisfn=&declutter($thisfn);
9848: # direct jump to resource in page or to a sequence - will construct own symbs
9849: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
9850: # check URL part
9851: my ($map,$resid,$url)=&decode_symb($symb);
9852:
9853: unless ($url eq $thisfn) { return 0; }
9854:
9855: $symb=&symbclean($symb);
9856: $thisurl=&deversion($thisurl);
9857: $thisfn=&deversion($thisfn);
9858:
9859: my %bighash;
9860: my $okay=0;
9861:
9862: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9863: &GDBM_READER(),0640)) {
9864: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
9865: $thisurl =~ s/\?.+$//;
9866: }
9867: my $ids=$bighash{'ids_'.&clutter($thisurl)};
9868: unless ($ids) {
9869: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
9870: $ids=$bighash{$idkey};
9871: }
9872: if ($ids) {
9873: # ------------------------------------------------------------------- Has ID(s)
9874: foreach my $id (split(/\,/,$ids)) {
9875: my ($mapid,$resid)=split(/\./,$id);
9876: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
9877: $symb =~ s/\?.+$//;
9878: }
9879: if (
9880: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
9881: eq $symb) {
9882: if (($env{'request.role.adv'}) ||
9883: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
9884: ($thisurl eq '/adm/navmaps')) {
9885: $okay=1;
9886: }
9887: }
9888: }
9889: }
9890: untie(%bighash);
9891: }
9892: return $okay;
9893: }
9894:
9895: # --------------------------------------------------------------- Clean-up symb
9896:
9897: sub symbclean {
9898: my $symb=shift;
9899: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9900: # remove version from map
9901: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
9902:
9903: # remove version from URL
9904: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
9905:
9906: # remove wrapper
9907:
9908: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
9909: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
9910: return $symb;
9911: }
9912:
9913: # ---------------------------------------------- Split symb to find map and url
9914:
9915: sub encode_symb {
9916: my ($map,$resid,$url)=@_;
9917: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
9918: }
9919:
9920: sub decode_symb {
9921: my $symb=shift;
9922: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9923: my ($map,$resid,$url)=split(/___/,$symb);
9924: return (&fixversion($map),$resid,&fixversion($url));
9925: }
9926:
9927: sub fixversion {
9928: my $fn=shift;
9929: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
9930: my %bighash;
9931: my $uri=&clutter($fn);
9932: my $key=$env{'request.course.id'}.'_'.$uri;
9933: # is this cached?
9934: my ($result,$cached)=&is_cached_new('courseresversion',$key);
9935: if (defined($cached)) { return $result; }
9936: # unfortunately not cached, or expired
9937: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9938: &GDBM_READER(),0640)) {
9939: if ($bighash{'version_'.$uri}) {
9940: my $version=$bighash{'version_'.$uri};
9941: unless (($version eq 'mostrecent') ||
9942: ($version==&getversion($uri))) {
9943: $uri=~s/\.(\w+)$/\.$version\.$1/;
9944: }
9945: }
9946: untie %bighash;
9947: }
9948: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
9949: }
9950:
9951: sub deversion {
9952: my $url=shift;
9953: $url=~s/\.\d+\.(\w+)$/\.$1/;
9954: return $url;
9955: }
9956:
9957: # ------------------------------------------------------ Return symb list entry
9958:
9959: sub symbread {
9960: my ($thisfn,$donotrecurse)=@_;
9961: my $cache_str='request.symbread.cached.'.$thisfn;
9962: if (defined($env{$cache_str})) { return $env{$cache_str}; }
9963: # no filename provided? try from environment
9964: unless ($thisfn) {
9965: if ($env{'request.symb'}) {
9966: return $env{$cache_str}=&symbclean($env{'request.symb'});
9967: }
9968: $thisfn=$env{'request.filename'};
9969: }
9970: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
9971: # is that filename actually a symb? Verify, clean, and return
9972: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
9973: if (&symbverify($thisfn,$1)) {
9974: return $env{$cache_str}=&symbclean($thisfn);
9975: }
9976: }
9977: $thisfn=declutter($thisfn);
9978: my %hash;
9979: my %bighash;
9980: my $syval='';
9981: if (($env{'request.course.fn'}) && ($thisfn)) {
9982: my $targetfn = $thisfn;
9983: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
9984: $targetfn = 'adm/wrapper/'.$thisfn;
9985: }
9986: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9987: $targetfn=$1;
9988: }
9989: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
9990: &GDBM_READER(),0640)) {
9991: $syval=$hash{$targetfn};
9992: untie(%hash);
9993: }
9994: # ---------------------------------------------------------- There was an entry
9995: if ($syval) {
9996: #unless ($syval=~/\_\d+$/) {
9997: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
9998: #&appenv({'request.ambiguous' => $thisfn});
9999: #return $env{$cache_str}='';
10000: #}
10001: #$syval.=$1;
10002: #}
10003: } else {
10004: # ------------------------------------------------------- Was not in symb table
10005: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10006: &GDBM_READER(),0640)) {
10007: # ---------------------------------------------- Get ID(s) for current resource
10008: my $ids=$bighash{'ids_'.&clutter($thisfn)};
10009: unless ($ids) {
10010: $ids=$bighash{'ids_/'.$thisfn};
10011: }
10012: unless ($ids) {
10013: # alias?
10014: $ids=$bighash{'mapalias_'.$thisfn};
10015: }
10016: if ($ids) {
10017: # ------------------------------------------------------------------- Has ID(s)
10018: my @possibilities=split(/\,/,$ids);
10019: if ($#possibilities==0) {
10020: # ----------------------------------------------- There is only one possibility
10021: my ($mapid,$resid)=split(/\./,$ids);
10022: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10023: $resid,$thisfn);
10024: } elsif (!$donotrecurse) {
10025: # ------------------------------------------ There is more than one possibility
10026: my $realpossible=0;
10027: foreach my $id (@possibilities) {
10028: my $file=$bighash{'src_'.$id};
10029: if (&allowed('bre',$file)) {
10030: my ($mapid,$resid)=split(/\./,$id);
10031: if ($bighash{'map_type_'.$mapid} ne 'page') {
10032: $realpossible++;
10033: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10034: $resid,$thisfn);
10035: }
10036: }
10037: }
10038: if ($realpossible!=1) { $syval=''; }
10039: } else {
10040: $syval='';
10041: }
10042: }
10043: untie(%bighash)
10044: }
10045: }
10046: if ($syval) {
10047: return $env{$cache_str}=$syval;
10048: }
10049: }
10050: &appenv({'request.ambiguous' => $thisfn});
10051: return $env{$cache_str}='';
10052: }
10053:
10054: # ---------------------------------------------------------- Return random seed
10055:
10056: sub numval {
10057: my $txt=shift;
10058: $txt=~tr/A-J/0-9/;
10059: $txt=~tr/a-j/0-9/;
10060: $txt=~tr/K-T/0-9/;
10061: $txt=~tr/k-t/0-9/;
10062: $txt=~tr/U-Z/0-5/;
10063: $txt=~tr/u-z/0-5/;
10064: $txt=~s/\D//g;
10065: if ($_64bit) { if ($txt > 2**32) { return -1; } }
10066: return int($txt);
10067: }
10068:
10069: sub numval2 {
10070: my $txt=shift;
10071: $txt=~tr/A-J/0-9/;
10072: $txt=~tr/a-j/0-9/;
10073: $txt=~tr/K-T/0-9/;
10074: $txt=~tr/k-t/0-9/;
10075: $txt=~tr/U-Z/0-5/;
10076: $txt=~tr/u-z/0-5/;
10077: $txt=~s/\D//g;
10078: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10079: my $total;
10080: foreach my $val (@txts) { $total+=$val; }
10081: if ($_64bit) { if ($total > 2**32) { return -1; } }
10082: return int($total);
10083: }
10084:
10085: sub numval3 {
10086: use integer;
10087: my $txt=shift;
10088: $txt=~tr/A-J/0-9/;
10089: $txt=~tr/a-j/0-9/;
10090: $txt=~tr/K-T/0-9/;
10091: $txt=~tr/k-t/0-9/;
10092: $txt=~tr/U-Z/0-5/;
10093: $txt=~tr/u-z/0-5/;
10094: $txt=~s/\D//g;
10095: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10096: my $total;
10097: foreach my $val (@txts) { $total+=$val; }
10098: if ($_64bit) { $total=(($total<<32)>>32); }
10099: return $total;
10100: }
10101:
10102: sub digest {
10103: my ($data)=@_;
10104: my $digest=&Digest::MD5::md5($data);
10105: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10106: my ($e,$f);
10107: {
10108: use integer;
10109: $e=($a+$b);
10110: $f=($c+$d);
10111: if ($_64bit) {
10112: $e=(($e<<32)>>32);
10113: $f=(($f<<32)>>32);
10114: }
10115: }
10116: if (wantarray) {
10117: return ($e,$f);
10118: } else {
10119: my $g;
10120: {
10121: use integer;
10122: $g=($e+$f);
10123: if ($_64bit) {
10124: $g=(($g<<32)>>32);
10125: }
10126: }
10127: return $g;
10128: }
10129: }
10130:
10131: sub latest_rnd_algorithm_id {
10132: return '64bit5';
10133: }
10134:
10135: sub get_rand_alg {
10136: my ($courseid)=@_;
10137: if (!$courseid) { $courseid=(&whichuser())[1]; }
10138: if ($courseid) {
10139: return $env{"course.$courseid.rndseed"};
10140: }
10141: return &latest_rnd_algorithm_id();
10142: }
10143:
10144: sub validCODE {
10145: my ($CODE)=@_;
10146: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10147: return 0;
10148: }
10149:
10150: sub getCODE {
10151: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10152: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10153: defined($Apache::lonhomework::parsing_a_task) ) &&
10154: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10155: return $Apache::lonhomework::history{'resource.CODE'};
10156: }
10157: return undef;
10158: }
10159: #
10160: # Determines the random seed for a specific context:
10161: #
10162: # parameters:
10163: # symb - in course context the symb for the seed.
10164: # course_id - The course id of the form domain_coursenum.
10165: # domain - Domain for the user.
10166: # course - Course for the user.
10167: # cenv - environment of the course.
10168: #
10169: # NOTE:
10170: # All parameters are picked out of the environment if missing
10171: # or not defined.
10172: # If a symb cannot be determined the current time is used instead.
10173: #
10174: # For a given well defined symb, courside, domain, username,
10175: # and course environment, the seed is reproducible.
10176: #
10177: sub rndseed {
10178: my ($symb,$courseid,$domain,$username, $cenv)=@_;
10179: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10180: if (!defined($symb)) {
10181: unless ($symb=$wsymb) { return time; }
10182: }
10183: if (!defined $courseid) {
10184: $courseid=$wcourseid;
10185: }
10186: if (!defined $domain) { $domain=$wdomain; }
10187: if (!defined $username) { $username=$wusername }
10188:
10189: my $which;
10190: if (defined($cenv->{'rndseed'})) {
10191: $which = $cenv->{'rndseed'};
10192: } else {
10193: $which =&get_rand_alg($courseid);
10194: }
10195: if (defined(&getCODE())) {
10196:
10197: if ($which eq '64bit5') {
10198: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10199: } elsif ($which eq '64bit4') {
10200: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10201: } else {
10202: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10203: }
10204: } elsif ($which eq '64bit5') {
10205: return &rndseed_64bit5($symb,$courseid,$domain,$username);
10206: } elsif ($which eq '64bit4') {
10207: return &rndseed_64bit4($symb,$courseid,$domain,$username);
10208: } elsif ($which eq '64bit3') {
10209: return &rndseed_64bit3($symb,$courseid,$domain,$username);
10210: } elsif ($which eq '64bit2') {
10211: return &rndseed_64bit2($symb,$courseid,$domain,$username);
10212: } elsif ($which eq '64bit') {
10213: return &rndseed_64bit($symb,$courseid,$domain,$username);
10214: }
10215: return &rndseed_32bit($symb,$courseid,$domain,$username);
10216: }
10217:
10218: sub rndseed_32bit {
10219: my ($symb,$courseid,$domain,$username)=@_;
10220: {
10221: use integer;
10222: my $symbchck=unpack("%32C*",$symb) << 27;
10223: my $symbseed=numval($symb) << 22;
10224: my $namechck=unpack("%32C*",$username) << 17;
10225: my $nameseed=numval($username) << 12;
10226: my $domainseed=unpack("%32C*",$domain) << 7;
10227: my $courseseed=unpack("%32C*",$courseid);
10228: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
10229: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10230: #&logthis("rndseed :$num:$symb");
10231: if ($_64bit) { $num=(($num<<32)>>32); }
10232: return $num;
10233: }
10234: }
10235:
10236: sub rndseed_64bit {
10237: my ($symb,$courseid,$domain,$username)=@_;
10238: {
10239: use integer;
10240: my $symbchck=unpack("%32S*",$symb) << 21;
10241: my $symbseed=numval($symb) << 10;
10242: my $namechck=unpack("%32S*",$username);
10243:
10244: my $nameseed=numval($username) << 21;
10245: my $domainseed=unpack("%32S*",$domain) << 10;
10246: my $courseseed=unpack("%32S*",$courseid);
10247:
10248: my $num1=$symbchck+$symbseed+$namechck;
10249: my $num2=$nameseed+$domainseed+$courseseed;
10250: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10251: #&logthis("rndseed :$num:$symb");
10252: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10253: return "$num1,$num2";
10254: }
10255: }
10256:
10257: sub rndseed_64bit2 {
10258: my ($symb,$courseid,$domain,$username)=@_;
10259: {
10260: use integer;
10261: # strings need to be an even # of cahracters long, it it is odd the
10262: # last characters gets thrown away
10263: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10264: my $symbseed=numval($symb) << 10;
10265: my $namechck=unpack("%32S*",$username.' ');
10266:
10267: my $nameseed=numval($username) << 21;
10268: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10269: my $courseseed=unpack("%32S*",$courseid.' ');
10270:
10271: my $num1=$symbchck+$symbseed+$namechck;
10272: my $num2=$nameseed+$domainseed+$courseseed;
10273: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10274: #&logthis("rndseed :$num:$symb");
10275: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10276: return "$num1,$num2";
10277: }
10278: }
10279:
10280: sub rndseed_64bit3 {
10281: my ($symb,$courseid,$domain,$username)=@_;
10282: {
10283: use integer;
10284: # strings need to be an even # of cahracters long, it it is odd the
10285: # last characters gets thrown away
10286: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10287: my $symbseed=numval2($symb) << 10;
10288: my $namechck=unpack("%32S*",$username.' ');
10289:
10290: my $nameseed=numval2($username) << 21;
10291: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10292: my $courseseed=unpack("%32S*",$courseid.' ');
10293:
10294: my $num1=$symbchck+$symbseed+$namechck;
10295: my $num2=$nameseed+$domainseed+$courseseed;
10296: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10297: #&logthis("rndseed :$num1:$num2:$_64bit");
10298: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10299:
10300: return "$num1:$num2";
10301: }
10302: }
10303:
10304: sub rndseed_64bit4 {
10305: my ($symb,$courseid,$domain,$username)=@_;
10306: {
10307: use integer;
10308: # strings need to be an even # of cahracters long, it it is odd the
10309: # last characters gets thrown away
10310: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10311: my $symbseed=numval3($symb) << 10;
10312: my $namechck=unpack("%32S*",$username.' ');
10313:
10314: my $nameseed=numval3($username) << 21;
10315: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10316: my $courseseed=unpack("%32S*",$courseid.' ');
10317:
10318: my $num1=$symbchck+$symbseed+$namechck;
10319: my $num2=$nameseed+$domainseed+$courseseed;
10320: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10321: #&logthis("rndseed :$num1:$num2:$_64bit");
10322: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10323:
10324: return "$num1:$num2";
10325: }
10326: }
10327:
10328: sub rndseed_64bit5 {
10329: my ($symb,$courseid,$domain,$username)=@_;
10330: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
10331: return "$num1:$num2";
10332: }
10333:
10334: sub rndseed_CODE_64bit {
10335: my ($symb,$courseid,$domain,$username)=@_;
10336: {
10337: use integer;
10338: my $symbchck=unpack("%32S*",$symb.' ') << 16;
10339: my $symbseed=numval2($symb);
10340: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10341: my $CODEseed=numval(&getCODE());
10342: my $courseseed=unpack("%32S*",$courseid.' ');
10343: my $num1=$symbseed+$CODEchck;
10344: my $num2=$CODEseed+$courseseed+$symbchck;
10345: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10346: #&logthis("rndseed :$num1:$num2:$symb");
10347: if ($_64bit) { $num1=(($num1<<32)>>32); }
10348: if ($_64bit) { $num2=(($num2<<32)>>32); }
10349: return "$num1:$num2";
10350: }
10351: }
10352:
10353: sub rndseed_CODE_64bit4 {
10354: my ($symb,$courseid,$domain,$username)=@_;
10355: {
10356: use integer;
10357: my $symbchck=unpack("%32S*",$symb.' ') << 16;
10358: my $symbseed=numval3($symb);
10359: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10360: my $CODEseed=numval3(&getCODE());
10361: my $courseseed=unpack("%32S*",$courseid.' ');
10362: my $num1=$symbseed+$CODEchck;
10363: my $num2=$CODEseed+$courseseed+$symbchck;
10364: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10365: #&logthis("rndseed :$num1:$num2:$symb");
10366: if ($_64bit) { $num1=(($num1<<32)>>32); }
10367: if ($_64bit) { $num2=(($num2<<32)>>32); }
10368: return "$num1:$num2";
10369: }
10370: }
10371:
10372: sub rndseed_CODE_64bit5 {
10373: my ($symb,$courseid,$domain,$username)=@_;
10374: my $code = &getCODE();
10375: my ($num1,$num2)=&digest("$symb,$courseid,$code");
10376: return "$num1:$num2";
10377: }
10378:
10379: sub setup_random_from_rndseed {
10380: my ($rndseed)=@_;
10381: if ($rndseed =~/([,:])/) {
10382: my ($num1,$num2)=split(/[,:]/,$rndseed);
10383: &Math::Random::random_set_seed(abs($num1),abs($num2));
10384: } else {
10385: &Math::Random::random_set_seed_from_phrase($rndseed);
10386: }
10387: }
10388:
10389: sub latest_receipt_algorithm_id {
10390: return 'receipt3';
10391: }
10392:
10393: sub recunique {
10394: my $fucourseid=shift;
10395: my $unique;
10396: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10397: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10398: $unique=$env{"course.$fucourseid.internal.encseed"};
10399: } else {
10400: $unique=$perlvar{'lonReceipt'};
10401: }
10402: return unpack("%32C*",$unique);
10403: }
10404:
10405: sub recprefix {
10406: my $fucourseid=shift;
10407: my $prefix;
10408: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10409: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10410: $prefix=$env{"course.$fucourseid.internal.encpref"};
10411: } else {
10412: $prefix=$perlvar{'lonHostID'};
10413: }
10414: return unpack("%32C*",$prefix);
10415: }
10416:
10417: sub ireceipt {
10418: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
10419:
10420: my $return =&recprefix($fucourseid).'-';
10421:
10422: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10423: $env{'request.state'} eq 'construct') {
10424: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10425: return $return;
10426: }
10427:
10428: my $cuname=unpack("%32C*",$funame);
10429: my $cudom=unpack("%32C*",$fudom);
10430: my $cucourseid=unpack("%32C*",$fucourseid);
10431: my $cusymb=unpack("%32C*",$fusymb);
10432: my $cunique=&recunique($fucourseid);
10433: my $cpart=unpack("%32S*",$part);
10434: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10435:
10436: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
10437:
10438: $return.= ($cunique%$cuname+
10439: $cunique%$cudom+
10440: $cusymb%$cuname+
10441: $cusymb%$cudom+
10442: $cucourseid%$cuname+
10443: $cucourseid%$cudom+
10444: $cpart%$cuname+
10445: $cpart%$cudom);
10446: } else {
10447: $return.= ($cunique%$cuname+
10448: $cunique%$cudom+
10449: $cusymb%$cuname+
10450: $cusymb%$cudom+
10451: $cucourseid%$cuname+
10452: $cucourseid%$cudom);
10453: }
10454: return $return;
10455: }
10456:
10457: sub receipt {
10458: my ($part)=@_;
10459: my ($symb,$courseid,$domain,$name) = &whichuser();
10460: return &ireceipt($name,$domain,$courseid,$symb,$part);
10461: }
10462:
10463: sub whichuser {
10464: my ($passedsymb)=@_;
10465: my ($symb,$courseid,$domain,$name,$publicuser);
10466: if (defined($env{'form.grade_symb'})) {
10467: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10468: my $allowed=&allowed('vgr',$tmp_courseid);
10469: if (!$allowed &&
10470: exists($env{'request.course.sec'}) &&
10471: $env{'request.course.sec'} !~ /^\s*$/) {
10472: $allowed=&allowed('vgr',$tmp_courseid.
10473: '/'.$env{'request.course.sec'});
10474: }
10475: if ($allowed) {
10476: ($symb)=&get_env_multiple('form.grade_symb');
10477: $courseid=$tmp_courseid;
10478: ($domain)=&get_env_multiple('form.grade_domain');
10479: ($name)=&get_env_multiple('form.grade_username');
10480: return ($symb,$courseid,$domain,$name,$publicuser);
10481: }
10482: }
10483: if (!$passedsymb) {
10484: $symb=&symbread();
10485: } else {
10486: $symb=$passedsymb;
10487: }
10488: $courseid=$env{'request.course.id'};
10489: $domain=$env{'user.domain'};
10490: $name=$env{'user.name'};
10491: if ($name eq 'public' && $domain eq 'public') {
10492: if (!defined($env{'form.username'})) {
10493: $env{'form.username'}.=time.rand(10000000);
10494: }
10495: $name.=$env{'form.username'};
10496: }
10497: return ($symb,$courseid,$domain,$name,$publicuser);
10498:
10499: }
10500:
10501: # ------------------------------------------------------------ Serves up a file
10502: # returns either the contents of the file or
10503: # -1 if the file doesn't exist
10504: #
10505: # if the target is a file that was uploaded via DOCS,
10506: # a check will be made to see if a current copy exists on the local server,
10507: # if it does this will be served, otherwise a copy will be retrieved from
10508: # the home server for the course and stored in /home/httpd/html/userfiles on
10509: # the local server.
10510:
10511: sub getfile {
10512: my ($file) = @_;
10513: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
10514: &repcopy($file);
10515: return &readfile($file);
10516: }
10517:
10518: sub repcopy_userfile {
10519: my ($file)=@_;
10520: my $londocroot = $perlvar{'lonDocRoot'};
10521: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
10522: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
10523: my ($cdom,$cnum,$filename) =
10524: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
10525: my $uri="/uploaded/$cdom/$cnum/$filename";
10526: if (-e "$file") {
10527: # we already have a local copy, check it out
10528: my @fileinfo = stat($file);
10529: my $rtncode;
10530: my $info;
10531: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
10532: if ($lwpresp ne 'ok') {
10533: # there is no such file anymore, even though we had a local copy
10534: if ($rtncode eq '404') {
10535: unlink($file);
10536: }
10537: return -1;
10538: }
10539: if ($info < $fileinfo[9]) {
10540: # nice, the file we have is up-to-date, just say okay
10541: return 'ok';
10542: } else {
10543: # the file is outdated, get rid of it
10544: unlink($file);
10545: }
10546: }
10547: # one way or the other, at this point, we don't have the file
10548: # construct the correct path for the file
10549: my @parts = ($cdom,$cnum);
10550: if ($filename =~ m|^(.+)/[^/]+$|) {
10551: push @parts, split(/\//,$1);
10552: }
10553: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10554: foreach my $part (@parts) {
10555: $path .= '/'.$part;
10556: if (!-e $path) {
10557: mkdir($path,0770);
10558: }
10559: }
10560: # now the path exists for sure
10561: # get a user agent
10562: my $ua=new LWP::UserAgent;
10563: my $transferfile=$file.'.in.transfer';
10564: # FIXME: this should flock
10565: if (-e $transferfile) { return 'ok'; }
10566: my $request;
10567: $uri=~s/^\///;
10568: my $homeserver = &homeserver($cnum,$cdom);
10569: my $protocol = $protocol{$homeserver};
10570: $protocol = 'http' if ($protocol ne 'https');
10571: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
10572: my $response=$ua->request($request,$transferfile);
10573: # did it work?
10574: if ($response->is_error()) {
10575: unlink($transferfile);
10576: &logthis("Userfile repcopy failed for $uri");
10577: return -1;
10578: }
10579: # worked, rename the transfer file
10580: rename($transferfile,$file);
10581: return 'ok';
10582: }
10583:
10584: sub tokenwrapper {
10585: my $uri=shift;
10586: $uri=~s|^https?\://([^/]+)||;
10587: $uri=~s|^/||;
10588: $env{'user.environment'}=~/\/([^\/]+)\.id/;
10589: my $token=$1;
10590: my (undef,$udom,$uname,$file)=split('/',$uri,4);
10591: if ($udom && $uname && $file) {
10592: $file=~s|(\?\.*)*$||;
10593: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
10594: my $homeserver = &homeserver($uname,$udom);
10595: my $protocol = $protocol{$homeserver};
10596: $protocol = 'http' if ($protocol ne 'https');
10597: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
10598: (($uri=~/\?/)?'&':'?').'token='.$token.
10599: '&tokenissued='.$perlvar{'lonHostID'};
10600: } else {
10601: return '/adm/notfound.html';
10602: }
10603: }
10604:
10605: # call with reqtype HEAD: get last modification time
10606: # call with reqtype GET: get the file contents
10607: # Do not call this with reqtype GET for large files! It loads everything into memory
10608: #
10609: sub getuploaded {
10610: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10611: $uri=~s/^\///;
10612: my $homeserver = &homeserver($cnum,$cdom);
10613: my $protocol = $protocol{$homeserver};
10614: $protocol = 'http' if ($protocol ne 'https');
10615: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
10616: my $ua=new LWP::UserAgent;
10617: my $request=new HTTP::Request($reqtype,$uri);
10618: my $response=$ua->request($request);
10619: $$rtncode = $response->code;
10620: if (! $response->is_success()) {
10621: return 'failed';
10622: }
10623: if ($reqtype eq 'HEAD') {
10624: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
10625: } elsif ($reqtype eq 'GET') {
10626: $$info = $response->content;
10627: }
10628: return 'ok';
10629: }
10630:
10631: sub readfile {
10632: my $file = shift;
10633: if ( (! -e $file ) || ($file eq '') ) { return -1; };
10634: my $fh;
10635: open($fh,"<$file");
10636: my $a='';
10637: while (my $line = <$fh>) { $a .= $line; }
10638: return $a;
10639: }
10640:
10641: sub filelocation {
10642: my ($dir,$file) = @_;
10643: my $location;
10644: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
10645:
10646: if ($file =~ m-^/adm/-) {
10647: $file=~s-^/adm/wrapper/-/-;
10648: $file=~s-^/adm/coursedocs/showdoc/-/-;
10649: }
10650:
10651: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
10652: $location = $file;
10653: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
10654: my ($udom,$uname,$filename)=
10655: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
10656: my $home=&homeserver($uname,$udom);
10657: my $is_me=0;
10658: my @ids=¤t_machine_ids();
10659: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10660: if ($is_me) {
10661: $location=propath($udom,$uname).'/userfiles/'.$filename;
10662: } else {
10663: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10664: $udom.'/'.$uname.'/'.$filename;
10665: }
10666: } elsif ($file =~ m-^/adm/-) {
10667: $location = $perlvar{'lonDocRoot'}.'/'.$file;
10668: } else {
10669: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10670: $file=~s:^/(res|priv)/:/:;
10671: my $space=$1;
10672: if ( !( $file =~ m:^/:) ) {
10673: $location = $dir. '/'.$file;
10674: } else {
10675: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
10676: }
10677: }
10678: $location=~s://+:/:g; # remove duplicate /
10679: while ($location=~m{/\.\./}) {
10680: if ($location =~ m{/[^/]+/\.\./}) {
10681: $location=~ s{/[^/]+/\.\./}{/}g;
10682: } else {
10683: $location=~ s{/\.\./}{/}g;
10684: }
10685: } #remove dir/..
10686: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10687: return $location;
10688: }
10689:
10690: sub hreflocation {
10691: my ($dir,$file)=@_;
10692: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
10693: $file=filelocation($dir,$file);
10694: } elsif ($file=~m-^/adm/-) {
10695: $file=~s-^/adm/wrapper/-/-;
10696: $file=~s-^/adm/coursedocs/showdoc/-/-;
10697: }
10698: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10699: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10700: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
10701: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10702: {/uploaded/$1/$2/}x;
10703: }
10704: if ($file=~ m{^/userfiles/}) {
10705: $file =~ s{^/userfiles/}{/uploaded/};
10706: }
10707: return $file;
10708: }
10709:
10710:
10711:
10712:
10713:
10714: sub current_machine_domains {
10715: return &machine_domains(&hostname($perlvar{'lonHostID'}));
10716: }
10717:
10718: sub machine_domains {
10719: my ($hostname) = @_;
10720: my @domains;
10721: my %hostname = &all_hostnames();
10722: while( my($id, $name) = each(%hostname)) {
10723: # &logthis("-$id-$name-$hostname-");
10724: if ($hostname eq $name) {
10725: push(@domains,&host_domain($id));
10726: }
10727: }
10728: return @domains;
10729: }
10730:
10731: sub current_machine_ids {
10732: return &machine_ids(&hostname($perlvar{'lonHostID'}));
10733: }
10734:
10735: sub machine_ids {
10736: my ($hostname) = @_;
10737: $hostname ||= &hostname($perlvar{'lonHostID'});
10738: my @ids;
10739: my %name_to_host = &all_names();
10740: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10741: return @{ $name_to_host{$hostname} };
10742: }
10743: return;
10744: }
10745:
10746: sub additional_machine_domains {
10747: my @domains;
10748: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10749: while( my $line = <$fh>) {
10750: $line =~ s/\s//g;
10751: push(@domains,$line);
10752: }
10753: return @domains;
10754: }
10755:
10756: sub default_login_domain {
10757: my $domain = $perlvar{'lonDefDomain'};
10758: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10759: foreach my $posdom (¤t_machine_domains(),
10760: &additional_machine_domains()) {
10761: if (lc($posdom) eq lc($testdomain)) {
10762: $domain=$posdom;
10763: last;
10764: }
10765: }
10766: return $domain;
10767: }
10768:
10769: # ------------------------------------------------------------- Declutters URLs
10770:
10771: sub declutter {
10772: my $thisfn=shift;
10773: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10774: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10775: $thisfn=~s/^\///;
10776: $thisfn=~s|^adm/wrapper/||;
10777: $thisfn=~s|^adm/coursedocs/showdoc/||;
10778: $thisfn=~s/^res\///;
10779: $thisfn=~s/^priv\///;
10780: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10781: $thisfn=~s/\?.+$//;
10782: }
10783: return $thisfn;
10784: }
10785:
10786: # ------------------------------------------------------------- Clutter up URLs
10787:
10788: sub clutter {
10789: my $thisfn='/'.&declutter(shift);
10790: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
10791: || $thisfn =~ m{^/adm/(includes|pages)} ) {
10792: $thisfn='/res'.$thisfn;
10793: }
10794: if ($thisfn !~m|^/adm|) {
10795: if ($thisfn =~ m|^/ext/|) {
10796: $thisfn='/adm/wrapper'.$thisfn;
10797: } else {
10798: my ($ext) = ($thisfn =~ /\.(\w+)$/);
10799: my $embstyle=&Apache::loncommon::fileembstyle($ext);
10800: if ($embstyle eq 'ssi'
10801: || ($embstyle eq 'hdn')
10802: || ($embstyle eq 'rat')
10803: || ($embstyle eq 'prv')
10804: || ($embstyle eq 'ign')) {
10805: #do nothing with these
10806: } elsif (($embstyle eq 'img')
10807: || ($embstyle eq 'emb')
10808: || ($embstyle eq 'wrp')) {
10809: $thisfn='/adm/wrapper'.$thisfn;
10810: } elsif ($embstyle eq 'unk'
10811: && $thisfn!~/\.(sequence|page)$/) {
10812: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
10813: } else {
10814: # &logthis("Got a blank emb style");
10815: }
10816: }
10817: }
10818: return $thisfn;
10819: }
10820:
10821: sub clutter_with_no_wrapper {
10822: my $uri = &clutter(shift);
10823: if ($uri =~ m-^/adm/-) {
10824: $uri =~ s-^/adm/wrapper/-/-;
10825: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
10826: }
10827: return $uri;
10828: }
10829:
10830: sub freeze_escape {
10831: my ($value)=@_;
10832: if (ref($value)) {
10833: $value=&nfreeze($value);
10834: return '__FROZEN__'.&escape($value);
10835: }
10836: return &escape($value);
10837: }
10838:
10839:
10840: sub thaw_unescape {
10841: my ($value)=@_;
10842: if ($value =~ /^__FROZEN__/) {
10843: substr($value,0,10,undef);
10844: $value=&unescape($value);
10845: return &thaw($value);
10846: }
10847: return &unescape($value);
10848: }
10849:
10850: sub correct_line_ends {
10851: my ($result)=@_;
10852: $$result =~s/\r\n/\n/mg;
10853: $$result =~s/\r/\n/mg;
10854: }
10855: # ================================================================ Main Program
10856:
10857: sub goodbye {
10858: &logthis("Starting Shut down");
10859: #not converted to using infrastruture and probably shouldn't be
10860: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
10861: #converted
10862: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
10863: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10864: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10865: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
10866: #1.1 only
10867: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10868: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10869: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10870: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10871: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
10872: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10873: &logthis(sprintf("%-20s is %s",'hits',$hits));
10874: &flushcourselogs();
10875: &logthis("Shutting down");
10876: }
10877:
10878: sub get_dns {
10879: my ($url,$func,$ignore_cache) = @_;
10880: if (!$ignore_cache) {
10881: my ($content,$cached)=
10882: &Apache::lonnet::is_cached_new('dns',$url);
10883: if ($cached) {
10884: &$func($content);
10885: return;
10886: }
10887: }
10888:
10889: my %alldns;
10890: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10891: foreach my $dns (<$config>) {
10892: next if ($dns !~ /^\^(\S*)/x);
10893: my $line = $1;
10894: my ($host,$protocol) = split(/:/,$line);
10895: if ($protocol ne 'https') {
10896: $protocol = 'http';
10897: }
10898: $alldns{$host} = $protocol;
10899: }
10900: while (%alldns) {
10901: my ($dns) = keys(%alldns);
10902: my $ua=new LWP::UserAgent;
10903: $ua->timeout(30);
10904: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
10905: my $response=$ua->request($request);
10906: delete($alldns{$dns});
10907: next if ($response->is_error());
10908: my @content = split("\n",$response->content);
10909: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
10910: &$func(\@content);
10911: return;
10912: }
10913: close($config);
10914: my $which = (split('/',$url))[3];
10915: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10916: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
10917: my @content = <$config>;
10918: &$func(\@content);
10919: return;
10920: }
10921: # ------------------------------------------------------------ Read domain file
10922: {
10923: my $loaded;
10924: my %domain;
10925:
10926: sub parse_domain_tab {
10927: my ($lines) = @_;
10928: foreach my $line (@$lines) {
10929: next if ($line =~ /^(\#|\s*$ )/x);
10930:
10931: chomp($line);
10932: my ($name,@elements) = split(/:/,$line,9);
10933: my %this_domain;
10934: foreach my $field ('description', 'auth_def', 'auth_arg_def',
10935: 'lang_def', 'city', 'longi', 'lati',
10936: 'primary') {
10937: $this_domain{$field} = shift(@elements);
10938: }
10939: $domain{$name} = \%this_domain;
10940: }
10941: }
10942:
10943: sub reset_domain_info {
10944: undef($loaded);
10945: undef(%domain);
10946: }
10947:
10948: sub load_domain_tab {
10949: my ($ignore_cache) = @_;
10950: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
10951: my $fh;
10952: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10953: my @lines = <$fh>;
10954: &parse_domain_tab(\@lines);
10955: }
10956: close($fh);
10957: $loaded = 1;
10958: }
10959:
10960: sub domain {
10961: &load_domain_tab() if (!$loaded);
10962:
10963: my ($name,$what) = @_;
10964: return if ( !exists($domain{$name}) );
10965:
10966: if (!$what) {
10967: return $domain{$name}{'description'};
10968: }
10969: return $domain{$name}{$what};
10970: }
10971:
10972: sub domain_info {
10973: &load_domain_tab() if (!$loaded);
10974: return %domain;
10975: }
10976:
10977: }
10978:
10979:
10980: # ------------------------------------------------------------- Read hosts file
10981: {
10982: my %hostname;
10983: my %hostdom;
10984: my %libserv;
10985: my $loaded;
10986: my %name_to_host;
10987: my %internetdom;
10988: my %LC_dns_serv;
10989:
10990: sub parse_hosts_tab {
10991: my ($file) = @_;
10992: foreach my $configline (@$file) {
10993: next if ($configline =~ /^(\#|\s*$ )/x);
10994: chomp($configline);
10995: if ($configline =~ /^\^/) {
10996: if ($configline =~ /^\^([\w.\-]+)/) {
10997: $LC_dns_serv{$1} = 1;
10998: }
10999: next;
11000: }
11001: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11002: $name=~s/\s//g;
11003: if ($id && $domain && $role && $name) {
11004: $hostname{$id}=$name;
11005: push(@{$name_to_host{$name}}, $id);
11006: $hostdom{$id}=$domain;
11007: if ($role eq 'library') { $libserv{$id}=$name; }
11008: if (defined($protocol)) {
11009: if ($protocol eq 'https') {
11010: $protocol{$id} = $protocol;
11011: } else {
11012: $protocol{$id} = 'http';
11013: }
11014: } else {
11015: $protocol{$id} = 'http';
11016: }
11017: if (defined($intdom)) {
11018: $internetdom{$id} = $intdom;
11019: }
11020: }
11021: }
11022: }
11023:
11024: sub reset_hosts_info {
11025: &purge_remembered();
11026: &reset_domain_info();
11027: &reset_hosts_ip_info();
11028: undef(%name_to_host);
11029: undef(%hostname);
11030: undef(%hostdom);
11031: undef(%libserv);
11032: undef($loaded);
11033: }
11034:
11035: sub load_hosts_tab {
11036: my ($ignore_cache) = @_;
11037: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11038: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11039: my @config = <$config>;
11040: &parse_hosts_tab(\@config);
11041: close($config);
11042: $loaded=1;
11043: }
11044:
11045: sub hostname {
11046: &load_hosts_tab() if (!$loaded);
11047:
11048: my ($lonid) = @_;
11049: return $hostname{$lonid};
11050: }
11051:
11052: sub all_hostnames {
11053: &load_hosts_tab() if (!$loaded);
11054:
11055: return %hostname;
11056: }
11057:
11058: sub all_names {
11059: &load_hosts_tab() if (!$loaded);
11060:
11061: return %name_to_host;
11062: }
11063:
11064: sub all_host_domain {
11065: &load_hosts_tab() if (!$loaded);
11066: return %hostdom;
11067: }
11068:
11069: sub is_library {
11070: &load_hosts_tab() if (!$loaded);
11071:
11072: return exists($libserv{$_[0]});
11073: }
11074:
11075: sub all_library {
11076: &load_hosts_tab() if (!$loaded);
11077:
11078: return %libserv;
11079: }
11080:
11081: sub unique_library {
11082: #2x reverse removes all hostnames that appear more than once
11083: my %unique = reverse &all_library();
11084: return reverse %unique;
11085: }
11086:
11087: sub get_servers {
11088: &load_hosts_tab() if (!$loaded);
11089:
11090: my ($domain,$type) = @_;
11091: my %possible_hosts = ($type eq 'library') ? %libserv
11092: : %hostname;
11093: my %result;
11094: if (ref($domain) eq 'ARRAY') {
11095: while ( my ($host,$hostname) = each(%possible_hosts)) {
11096: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11097: $result{$host} = $hostname;
11098: }
11099: }
11100: } else {
11101: while ( my ($host,$hostname) = each(%possible_hosts)) {
11102: if ($hostdom{$host} eq $domain) {
11103: $result{$host} = $hostname;
11104: }
11105: }
11106: }
11107: return %result;
11108: }
11109:
11110: sub get_unique_servers {
11111: my %unique = reverse &get_servers(@_);
11112: return reverse %unique;
11113: }
11114:
11115: sub host_domain {
11116: &load_hosts_tab() if (!$loaded);
11117:
11118: my ($lonid) = @_;
11119: return $hostdom{$lonid};
11120: }
11121:
11122: sub all_domains {
11123: &load_hosts_tab() if (!$loaded);
11124:
11125: my %seen;
11126: my @uniq = grep(!$seen{$_}++, values(%hostdom));
11127: return @uniq;
11128: }
11129:
11130: sub internet_dom {
11131: &load_hosts_tab() if (!$loaded);
11132:
11133: my ($lonid) = @_;
11134: return $internetdom{$lonid};
11135: }
11136:
11137: sub is_LC_dns {
11138: &load_hosts_tab() if (!$loaded);
11139:
11140: my ($hostname) = @_;
11141: return exists($LC_dns_serv{$hostname});
11142: }
11143:
11144: }
11145:
11146: {
11147: my %iphost;
11148: my %name_to_ip;
11149: my %lonid_to_ip;
11150:
11151: sub get_hosts_from_ip {
11152: my ($ip) = @_;
11153: my %iphosts = &get_iphost();
11154: if (ref($iphosts{$ip})) {
11155: return @{$iphosts{$ip}};
11156: }
11157: return;
11158: }
11159:
11160: sub reset_hosts_ip_info {
11161: undef(%iphost);
11162: undef(%name_to_ip);
11163: undef(%lonid_to_ip);
11164: }
11165:
11166: sub get_host_ip {
11167: my ($lonid) = @_;
11168: if (exists($lonid_to_ip{$lonid})) {
11169: return $lonid_to_ip{$lonid};
11170: }
11171: my $name=&hostname($lonid);
11172: my $ip = gethostbyname($name);
11173: return if (!$ip || length($ip) ne 4);
11174: $ip=inet_ntoa($ip);
11175: $name_to_ip{$name} = $ip;
11176: $lonid_to_ip{$lonid} = $ip;
11177: return $ip;
11178: }
11179:
11180: sub get_iphost {
11181: my ($ignore_cache) = @_;
11182:
11183: if (!$ignore_cache) {
11184: if (%iphost) {
11185: return %iphost;
11186: }
11187: my ($ip_info,$cached)=
11188: &Apache::lonnet::is_cached_new('iphost','iphost');
11189: if ($cached) {
11190: %iphost = %{$ip_info->[0]};
11191: %name_to_ip = %{$ip_info->[1]};
11192: %lonid_to_ip = %{$ip_info->[2]};
11193: return %iphost;
11194: }
11195: }
11196:
11197: # get yesterday's info for fallback
11198: my %old_name_to_ip;
11199: my ($ip_info,$cached)=
11200: &Apache::lonnet::is_cached_new('iphost','iphost');
11201: if ($cached) {
11202: %old_name_to_ip = %{$ip_info->[1]};
11203: }
11204:
11205: my %name_to_host = &all_names();
11206: foreach my $name (keys(%name_to_host)) {
11207: my $ip;
11208: if (!exists($name_to_ip{$name})) {
11209: $ip = gethostbyname($name);
11210: if (!$ip || length($ip) ne 4) {
11211: if (defined($old_name_to_ip{$name})) {
11212: $ip = $old_name_to_ip{$name};
11213: &logthis("Can't find $name defaulting to old $ip");
11214: } else {
11215: &logthis("Name $name no IP found");
11216: next;
11217: }
11218: } else {
11219: $ip=inet_ntoa($ip);
11220: }
11221: $name_to_ip{$name} = $ip;
11222: } else {
11223: $ip = $name_to_ip{$name};
11224: }
11225: foreach my $id (@{ $name_to_host{$name} }) {
11226: $lonid_to_ip{$id} = $ip;
11227: }
11228: push(@{$iphost{$ip}},@{$name_to_host{$name}});
11229: }
11230: &Apache::lonnet::do_cache_new('iphost','iphost',
11231: [\%iphost,\%name_to_ip,\%lonid_to_ip],
11232: 48*60*60);
11233:
11234: return %iphost;
11235: }
11236:
11237: #
11238: # Given a DNS returns the loncapa host name for that DNS
11239: #
11240: sub host_from_dns {
11241: my ($dns) = @_;
11242: my @hosts;
11243: my $ip;
11244:
11245: if (exists($name_to_ip{$dns})) {
11246: $ip = $name_to_ip{$dns};
11247: }
11248: if (!$ip) {
11249: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11250: if (length($ip) == 4) {
11251: $ip = &IO::Socket::inet_ntoa($ip);
11252: }
11253: }
11254: if ($ip) {
11255: @hosts = get_hosts_from_ip($ip);
11256: return $hosts[0];
11257: }
11258: return undef;
11259: }
11260:
11261: sub get_internet_names {
11262: my ($lonid) = @_;
11263: return if ($lonid eq '');
11264: my ($idnref,$cached)=
11265: &Apache::lonnet::is_cached_new('internetnames',$lonid);
11266: if ($cached) {
11267: return $idnref;
11268: }
11269: my $ip = &get_host_ip($lonid);
11270: my @hosts = &get_hosts_from_ip($ip);
11271: my %iphost = &get_iphost();
11272: my (@idns,%seen);
11273: foreach my $id (@hosts) {
11274: my $dom = &host_domain($id);
11275: my $prim_id = &domain($dom,'primary');
11276: my $prim_ip = &get_host_ip($prim_id);
11277: next if ($seen{$prim_ip});
11278: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
11279: foreach my $id (@{$iphost{$prim_ip}}) {
11280: my $intdom = &internet_dom($id);
11281: unless (grep(/^\Q$intdom\E$/,@idns)) {
11282: push(@idns,$intdom);
11283: }
11284: }
11285: }
11286: $seen{$prim_ip} = 1;
11287: }
11288: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
11289: }
11290:
11291: }
11292:
11293: sub all_loncaparevs {
11294: 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);
11295: }
11296:
11297: BEGIN {
11298:
11299: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
11300: unless ($readit) {
11301: {
11302: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
11303: %perlvar = (%perlvar,%{$configvars});
11304: }
11305:
11306:
11307: # ------------------------------------------------------ Read spare server file
11308: {
11309: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
11310:
11311: while (my $configline=<$config>) {
11312: chomp($configline);
11313: if ($configline) {
11314: my ($host,$type) = split(':',$configline,2);
11315: if (!defined($type) || $type eq '') { $type = 'default' };
11316: push(@{ $spareid{$type} }, $host);
11317: }
11318: }
11319: close($config);
11320: }
11321: # ------------------------------------------------------------ Read permissions
11322: {
11323: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
11324:
11325: while (my $configline=<$config>) {
11326: chomp($configline);
11327: if ($configline) {
11328: my ($role,$perm)=split(/ /,$configline);
11329: if ($perm ne '') { $pr{$role}=$perm; }
11330: }
11331: }
11332: close($config);
11333: }
11334:
11335: # -------------------------------------------- Read plain texts for permissions
11336: {
11337: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
11338:
11339: while (my $configline=<$config>) {
11340: chomp($configline);
11341: if ($configline) {
11342: my ($short,@plain)=split(/:/,$configline);
11343: %{$prp{$short}} = ();
11344: if (@plain > 0) {
11345: $prp{$short}{'std'} = $plain[0];
11346: for (my $i=1; $i<@plain; $i++) {
11347: $prp{$short}{'alt'.$i} = $plain[$i];
11348: }
11349: }
11350: }
11351: }
11352: close($config);
11353: }
11354:
11355: # ---------------------------------------------------------- Read package table
11356: {
11357: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
11358:
11359: while (my $configline=<$config>) {
11360: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
11361: chomp($configline);
11362: my ($short,$plain)=split(/:/,$configline);
11363: my ($pack,$name)=split(/\&/,$short);
11364: if ($plain ne '') {
11365: $packagetab{$pack.'&'.$name.'&name'}=$name;
11366: $packagetab{$short}=$plain;
11367: }
11368: }
11369: close($config);
11370: }
11371:
11372: # ---------------------------------------------------------- Read loncaparev table
11373: {
11374: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11375: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11376: while (my $configline=<$config>) {
11377: chomp($configline);
11378: my ($hostid,$loncaparev)=split(/:/,$configline);
11379: $loncaparevs{$hostid}=$loncaparev;
11380: }
11381: close($config);
11382: }
11383: }
11384: }
11385:
11386: # ---------------------------------------------------------- Read serverhostID table
11387: {
11388: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11389: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11390: while (my $configline=<$config>) {
11391: chomp($configline);
11392: my ($name,$id)=split(/:/,$configline);
11393: $serverhomeIDs{$name}=$id;
11394: }
11395: close($config);
11396: }
11397: }
11398: }
11399:
11400: {
11401: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11402: if (-e $file) {
11403: my $parser = HTML::LCParser->new($file);
11404: while (my $token = $parser->get_token()) {
11405: if ($token->[0] eq 'S') {
11406: my $item = $token->[1];
11407: my $name = $token->[2]{'name'};
11408: my $value = $token->[2]{'value'};
11409: if ($item ne '' && $name ne '' && $value ne '') {
11410: my $release = $parser->get_text();
11411: $release =~ s/(^\s*|\s*$ )//gx;
11412: $needsrelease{$item.':'.$name.':'.$value} = $release;
11413: }
11414: }
11415: }
11416: }
11417: }
11418:
11419: # ---------------------------------------------------------- Read managers table
11420: {
11421: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11422: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11423: while (my $configline=<$config>) {
11424: chomp($configline);
11425: next if ($configline =~ /^\#/);
11426: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11427: $managerstab{$configline} = 1;
11428: }
11429: }
11430: close($config);
11431: }
11432: }
11433: }
11434:
11435: # ------------- set up temporary directory
11436: {
11437: $tmpdir = LONCAPA::tempdir();
11438:
11439: }
11440:
11441: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
11442: 'compress_threshold'=> 20_000,
11443: });
11444:
11445: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
11446: $dumpcount=0;
11447: $locknum=0;
11448:
11449: &logtouch();
11450: &logthis('<font color="yellow">INFO: Read configuration</font>');
11451: $readit=1;
11452: {
11453: use integer;
11454: my $test=(2**32)+1;
11455: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
11456: &logthis(" Detected 64bit platform ($_64bit)");
11457: }
11458: }
11459: }
11460:
11461: 1;
11462: __END__
11463:
11464: =pod
11465:
11466: =head1 NAME
11467:
11468: Apache::lonnet - Subroutines to ask questions about things in the network.
11469:
11470: =head1 SYNOPSIS
11471:
11472: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
11473:
11474: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11475:
11476: Common parameters:
11477:
11478: =over 4
11479:
11480: =item *
11481:
11482: $uname : an internal username (if $cname expecting a course Id specifically)
11483:
11484: =item *
11485:
11486: $udom : a domain (if $cdom expecting a course's domain specifically)
11487:
11488: =item *
11489:
11490: $symb : a resource instance identifier
11491:
11492: =item *
11493:
11494: $namespace : the name of a .db file that contains the data needed or
11495: being set.
11496:
11497: =back
11498:
11499: =head1 OVERVIEW
11500:
11501: lonnet provides subroutines which interact with the
11502: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11503: about classes, users, and resources.
11504:
11505: For many of these objects you can also use this to store data about
11506: them or modify them in various ways.
11507:
11508: =head2 Symbs
11509:
11510: To identify a specific instance of a resource, LON-CAPA uses symbols
11511: or "symbs"X<symb>. These identifiers are built from the URL of the
11512: map, the resource number of the resource in the map, and the URL of
11513: the resource itself. The latter is somewhat redundant, but might help
11514: if maps change.
11515:
11516: An example is
11517:
11518: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11519:
11520: The respective map entry is
11521:
11522: <resource id="19" src="/res/msu/korte/tests/part12.problem"
11523: title="Problem 2">
11524: </resource>
11525:
11526: Symbs are used by the random number generator, as well as to store and
11527: restore data specific to a certain instance of for example a problem.
11528:
11529: =head2 Storing And Retrieving Data
11530:
11531: X<store()>X<cstore()>X<restore()>Three of the most important functions
11532: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11533: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11534: is is the non-critical message twin of cstore. These functions are for
11535: handlers to store a perl hash to a user's permanent data space in an
11536: easy manner, and to retrieve it again on another call. It is expected
11537: that a handler would use this once at the beginning to retrieve data,
11538: and then again once at the end to send only the new data back.
11539:
11540: The data is stored in the user's data directory on the user's
11541: homeserver under the ID of the course.
11542:
11543: The hash that is returned by restore will have all of the previous
11544: value for all of the elements of the hash.
11545:
11546: Example:
11547:
11548: #creating a hash
11549: my %hash;
11550: $hash{'foo'}='bar';
11551:
11552: #storing it
11553: &Apache::lonnet::cstore(\%hash);
11554:
11555: #changing a value
11556: $hash{'foo'}='notbar';
11557:
11558: #adding a new value
11559: $hash{'bar'}='foo';
11560: &Apache::lonnet::cstore(\%hash);
11561:
11562: #retrieving the hash
11563: my %history=&Apache::lonnet::restore();
11564:
11565: #print the hash
11566: foreach my $key (sort(keys(%history))) {
11567: print("\%history{$key} = $history{$key}");
11568: }
11569:
11570: Will print out:
11571:
11572: %history{1:foo} = bar
11573: %history{1:keys} = foo:timestamp
11574: %history{1:timestamp} = 990455579
11575: %history{2:bar} = foo
11576: %history{2:foo} = notbar
11577: %history{2:keys} = foo:bar:timestamp
11578: %history{2:timestamp} = 990455580
11579: %history{bar} = foo
11580: %history{foo} = notbar
11581: %history{timestamp} = 990455580
11582: %history{version} = 2
11583:
11584: Note that the special hash entries C<keys>, C<version> and
11585: C<timestamp> were added to the hash. C<version> will be equal to the
11586: total number of versions of the data that have been stored. The
11587: C<timestamp> attribute will be the UNIX time the hash was
11588: stored. C<keys> is available in every historical section to list which
11589: keys were added or changed at a specific historical revision of a
11590: hash.
11591:
11592: B<Warning>: do not store the hash that restore returns directly. This
11593: will cause a mess since it will restore the historical keys as if the
11594: were new keys. I.E. 1:foo will become 1:1:foo etc.
11595:
11596: Calling convention:
11597:
11598: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11599: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
11600:
11601: For more detailed information, see lonnet specific documentation.
11602:
11603: =head1 RETURN MESSAGES
11604:
11605: =over 4
11606:
11607: =item * B<con_lost>: unable to contact remote host
11608:
11609: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11610: when the connection is brought back up
11611:
11612: =item * B<con_failed>: unable to contact remote host and unable to save message
11613: for later delivery
11614:
11615: =item * B<error:>: an error a occurred, a description of the error follows the :
11616:
11617: =item * B<no_such_host>: unable to fund a host associated with the user/domain
11618: that was requested
11619:
11620: =back
11621:
11622: =head1 PUBLIC SUBROUTINES
11623:
11624: =head2 Session Environment Functions
11625:
11626: =over 4
11627:
11628: =item *
11629: X<appenv()>
11630: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
11631: the user envirnoment file, and will be restored for each access this
11632: user makes during this session, also modifies the %env for the current
11633: process. Optional rolesarrayref - if defined contains a reference to an array
11634: of roles which are exempt from the restriction on modifying user.role entries
11635: in the user's environment.db and in %env.
11636:
11637: =item *
11638: X<delenv()>
11639: B<delenv($delthis,$regexp)>: removes all items from the session
11640: environment file that begin with $delthis. If the
11641: optional second arg - $regexp - is true, $delthis is treated as a
11642: regular expression, otherwise \Q$delthis\E is used.
11643: The values are also deleted from the current processes %env.
11644:
11645: =item * get_env_multiple($name)
11646:
11647: gets $name from the %env hash, it seemlessly handles the cases where multiple
11648: values may be defined and end up as an array ref.
11649:
11650: returns an array of values
11651:
11652: =back
11653:
11654: =head2 User Information
11655:
11656: =over 4
11657:
11658: =item *
11659: X<queryauthenticate()>
11660: B<queryauthenticate($uname,$udom)>: try to determine user's current
11661: authentication scheme
11662:
11663: =item *
11664: X<authenticate()>
11665: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
11666: authenticate user from domain's lib servers (first use the current
11667: one). C<$upass> should be the users password.
11668: $checkdefauth is optional (value is 1 if a check should be made to
11669: authenticate user using default authentication method, and allow
11670: account creation if username does not have account in the domain).
11671: $clientcancheckhost is optional (value is 1 if checking whether the
11672: server can host will occur on the client side in lonauth.pm).
11673:
11674: =item *
11675: X<homeserver()>
11676: B<homeserver($uname,$udom)>: find the server which has
11677: the user's directory and files (there must be only one), this caches
11678: the answer, and also caches if there is a borken connection.
11679:
11680: =item *
11681: X<idget()>
11682: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11683: (IDs are a unique resource in a domain, there must be only 1 ID per
11684: username, and only 1 username per ID in a specific domain) (returns
11685: hash: id=>name,id=>name)
11686:
11687: =item *
11688: X<idrget()>
11689: B<idrget($udom,@unames)>: find the IDs behind a list of
11690: usernames (returns hash: name=>id,name=>id)
11691:
11692: =item *
11693: X<idput()>
11694: B<idput($udom,%ids)>: store away a list of names and associated IDs
11695:
11696: =item *
11697: X<rolesinit()>
11698: B<rolesinit($udom,$username)>: get user privileges.
11699: returns user role, first access and timer interval hashes
11700:
11701: =item *
11702: X<privileged()>
11703: B<privileged($username,$domain)>: returns a true if user has a
11704: privileged and active role (i.e. su or dc), false otherwise.
11705:
11706: =item *
11707: X<getsection()>
11708: B<getsection($udom,$uname,$cname)>: finds the section of student in the
11709: course $cname, return section name/number or '' for "not in course"
11710: and '-1' for "no section"
11711:
11712: =item *
11713: X<userenvironment()>
11714: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
11715: passed in @what from the requested user's environment, returns a hash
11716:
11717: =item *
11718: X<userlog_query()>
11719: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11720: activity.log file. %filters defines filters applied when parsing the
11721: log file. These can be start or end timestamps, or the type of action
11722: - log to look for Login or Logout events, check for Checkin or
11723: Checkout, role for role selection. The response is in the form
11724: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
11725: escaped strings of the action recorded in the activity.log file.
11726:
11727: =back
11728:
11729: =head2 User Roles
11730:
11731: =over 4
11732:
11733: =item *
11734:
11735: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
11736: F: full access
11737: U,I,K: authentication modes (cxx only)
11738: '': forbidden
11739: 1: user needs to choose course
11740: 2: browse allowed
11741: A: passphrase authentication needed
11742:
11743: =item *
11744:
11745: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11746: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11747: and course level
11748:
11749: =item *
11750:
11751: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
11752: (rolesplain.tab); plain text explanation of a user role term.
11753: $type is Course (default) or Community.
11754: If $forcedefault evaluates to true, text returned will be default
11755: text for $type. Otherwise, if this is a course, the text returned
11756: will be a custom name for the role (if defined in the course's
11757: environment). If no custom name is defined the default is returned.
11758:
11759: =item *
11760:
11761: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
11762: All arguments are optional. Returns a hash of a roles, either for
11763: co-author/assistant author roles for a user's Construction Space
11764: (default), or if $context is 'userroles', roles for the user himself,
11765: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11766: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11767: For each key, value is set to colon-separated start and end times for
11768: the role. If no username and domain are specified, will default to
11769: current user/domain. Types, roles, and roledoms are references to arrays
11770: of role statuses (active, future or previous), roles
11771: (e.g., cc,in, st etc.) and domains of the roles which can be used
11772: to restrict the list of roles reported. If no array ref is
11773: provided for types, will default to return only active roles.
11774:
11775: =back
11776:
11777: =head2 User Modification
11778:
11779: =over 4
11780:
11781: =item *
11782:
11783: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
11784: user for the level given by URL. Optional start and end dates (leave empty
11785: string or zero for "no date")
11786:
11787: =item *
11788:
11789: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11790: change a users, password, possible return values are: ok,
11791: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11792: refused
11793:
11794: =item *
11795:
11796: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
11797:
11798: =item *
11799:
11800: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11801: $forceid,$desiredhome,$email,$inststatus,$candelete) :
11802:
11803: will update user information (firstname,middlename,lastname,generation,
11804: permanentemail), and if forceid is true, student/employee ID also.
11805: A user's institutional affiliation(s) can also be updated.
11806: User information fields will not be overwritten with empty entries
11807: unless the field is included in the $candelete array reference.
11808: This array is included when a single user is modified via "Manage Users",
11809: or when Autoupdate.pl is run by cron in a domain.
11810:
11811: =item *
11812:
11813: modifystudent
11814:
11815: modify a student's enrollment and identification information.
11816: The course id is resolved based on the current users environment.
11817: This means the envoking user must be a course coordinator or otherwise
11818: associated with a course.
11819:
11820: This call is essentially a wrapper for lonnet::modifyuser and
11821: lonnet::modify_student_enrollment
11822:
11823: Inputs:
11824:
11825: =over 4
11826:
11827: =item B<$udom> Student's loncapa domain
11828:
11829: =item B<$uname> Student's loncapa login name
11830:
11831: =item B<$uid> Student/Employee ID
11832:
11833: =item B<$umode> Student's authentication mode
11834:
11835: =item B<$upass> Student's password
11836:
11837: =item B<$first> Student's first name
11838:
11839: =item B<$middle> Student's middle name
11840:
11841: =item B<$last> Student's last name
11842:
11843: =item B<$gene> Student's generation
11844:
11845: =item B<$usec> Student's section in course
11846:
11847: =item B<$end> Unix time of the roles expiration
11848:
11849: =item B<$start> Unix time of the roles start date
11850:
11851: =item B<$forceid> If defined, allow $uid to be changed
11852:
11853: =item B<$desiredhome> server to use as home server for student
11854:
11855: =item B<$email> Student's permanent e-mail address
11856:
11857: =item B<$type> Type of enrollment (auto or manual)
11858:
11859: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
11860:
11861: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
11862:
11863: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
11864:
11865: =item B<$context> role change context (shown in User Management Logs display in a course)
11866:
11867: =item B<$inststatus> institutional status of user - : separated string of escaped status types
11868:
11869: =back
11870:
11871: =item *
11872:
11873: modify_student_enrollment
11874:
11875: Change a students enrollment status in a class. The environment variable
11876: 'role.request.course' must be defined for this function to proceed.
11877:
11878: Inputs:
11879:
11880: =over 4
11881:
11882: =item $udom, students domain
11883:
11884: =item $uname, students name
11885:
11886: =item $uid, students user id
11887:
11888: =item $first, students first name
11889:
11890: =item $middle
11891:
11892: =item $last
11893:
11894: =item $gene
11895:
11896: =item $usec
11897:
11898: =item $end
11899:
11900: =item $start
11901:
11902: =item $type
11903:
11904: =item $locktype
11905:
11906: =item $cid
11907:
11908: =item $selfenroll
11909:
11910: =item $context
11911:
11912: =back
11913:
11914:
11915: =item *
11916:
11917: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11918: custom role; give a custom role to a user for the level given by URL. Specify
11919: name and domain of role author, and role name
11920:
11921: =item *
11922:
11923: revokerole($udom,$uname,$url,$role) : revoke a role for url
11924:
11925: =item *
11926:
11927: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11928:
11929: =back
11930:
11931: =head2 Course Infomation
11932:
11933: =over 4
11934:
11935: =item *
11936:
11937: coursedescription($courseid,$options) : returns a hash of information about the
11938: specified course id, including all environment settings for the
11939: course, the description of the course will be in the hash under the
11940: key 'description'
11941:
11942: $options is an optional parameter that if supplied is a hash reference that controls
11943: what how this function works. It has the following key/values:
11944:
11945: =over 4
11946:
11947: =item freshen_cache
11948:
11949: If defined, and the environment cache for the course is valid, it is
11950: returned in the returned hash.
11951:
11952: =item one_time
11953:
11954: If defined, the last cache time is set to _now_
11955:
11956: =item user
11957:
11958: If defined, the supplied username is used instead of the current user.
11959:
11960:
11961: =back
11962:
11963: =item *
11964:
11965: resdata($name,$domain,$type,@which) : request for current parameter
11966: setting for a specific $type, where $type is either 'course' or 'user',
11967: @what should be a list of parameters to ask about. This routine caches
11968: answers for 5 minutes.
11969:
11970: =item *
11971:
11972: get_courseresdata($courseid, $domain) : dump the entire course resource
11973: data base, returning a hash that is keyed by the resource name and has
11974: values that are the resource value. I believe that the timestamps and
11975: versions are also returned.
11976:
11977:
11978: =back
11979:
11980: =head2 Course Modification
11981:
11982: =over 4
11983:
11984: =item *
11985:
11986: writecoursepref($courseid,%prefs) : write preferences (environment
11987: database) for a course
11988:
11989: =item *
11990:
11991: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11992:
11993: =item *
11994:
11995: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
11996:
11997: =item *
11998:
11999: is_course($courseid), is_course($cdom, $cnum)
12000:
12001: Accepts either a combined $courseid (in the form of domain_courseid) or the
12002: two component version $cdom, $cnum. It checks if the specified course exists.
12003:
12004: Returns:
12005: undef if the course doesn't exist, otherwise
12006: in scalar context the combined courseid.
12007: in list context the two components of the course identifier, domain and
12008: courseid.
12009:
12010: =back
12011:
12012: =head2 Resource Subroutines
12013:
12014: =over 4
12015:
12016: =item *
12017:
12018: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12019:
12020: =item *
12021:
12022: repcopy($filename) : subscribes to the requested file, and attempts to
12023: replicate from the owning library server, Might return
12024: 'unavailable', 'not_found', 'forbidden', 'ok', or
12025: 'bad_request', also attempts to grab the metadata for the
12026: resource. Expects the local filesystem pathname
12027: (/home/httpd/html/res/....)
12028:
12029: =back
12030:
12031: =head2 Resource Information
12032:
12033: =over 4
12034:
12035: =item *
12036:
12037: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12038: a vairety of different possible values, $varname should be a request
12039: string, and the other parameters can be used to specify who and what
12040: one is asking about.
12041:
12042: Possible values for $varname are environment.lastname (or other item
12043: from the envirnment hash), user.name (or someother aspect about the
12044: user), resource.0.maxtries (or some other part and parameter of a
12045: resource)
12046:
12047: =item *
12048:
12049: directcondval($number) : get current value of a condition; reads from a state
12050: string
12051:
12052: =item *
12053:
12054: condval($condidx) : value of condition index based on state
12055:
12056: =item *
12057:
12058: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12059: resource's metadata, $what should be either a specific key, or either
12060: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12061: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12062:
12063: this function automatically caches all requests
12064:
12065: =item *
12066:
12067: metadata_query($query,$custom,$customshow) : make a metadata query against the
12068: network of library servers; returns file handle of where SQL and regex results
12069: will be stored for query
12070:
12071: =item *
12072:
12073: symbread($filename) : return symbolic list entry (filename argument optional);
12074: returns the data handle
12075:
12076: =item *
12077:
12078: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
12079: a possible symb for the URL in $thisfn, and if is an encryypted
12080: resource that the user accessed using /enc/ returns a 1 on success, 0
12081: on failure, user must be in a course, as it assumes the existance of
12082: the course initial hash, and uses $env('request.course.id'}
12083:
12084:
12085: =item *
12086:
12087: symbclean($symb) : removes versions numbers from a symb, returns the
12088: cleaned symb
12089:
12090: =item *
12091:
12092: is_on_map($uri) : checks if the $uri is somewhere on the current
12093: course map, user must be in a course for it to work.
12094:
12095: =item *
12096:
12097: numval($salt) : return random seed value (addend for rndseed)
12098:
12099: =item *
12100:
12101: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12102: a random seed, all arguments are optional, if they aren't sent it uses the
12103: environment to derive them. Note: if symb isn't sent and it can't get one
12104: from &symbread it will use the current time as its return value
12105:
12106: =item *
12107:
12108: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12109: unfakeable, receipt
12110:
12111: =item *
12112:
12113: receipt() : API to ireceipt working off of env values; given out to users
12114:
12115: =item *
12116:
12117: countacc($url) : count the number of accesses to a given URL
12118:
12119: =item *
12120:
12121: 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
12122:
12123: =item *
12124:
12125: 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)
12126:
12127: =item *
12128:
12129: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
12130:
12131: =item *
12132:
12133: devalidate($symb) : devalidate temporary spreadsheet calculations,
12134: forcing spreadsheet to reevaluate the resource scores next time.
12135:
12136: =back
12137:
12138: =head2 Storing/Retreiving Data
12139:
12140: =over 4
12141:
12142: =item *
12143:
12144: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12145: for this url; hashref needs to be given and should be a \%hashname; the
12146: remaining args aren't required and if they aren't passed or are '' they will
12147: be derived from the env
12148:
12149: =item *
12150:
12151: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12152: uses critical subroutine
12153:
12154: =item *
12155:
12156: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12157: all args are optional
12158:
12159: =item *
12160:
12161: dumpstore($namespace,$udom,$uname,$regexp,$range) :
12162: dumps the complete (or key matching regexp) namespace into a hash
12163: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12164: normally &store()ed into
12165:
12166: $range should be either an integer '100' (give me the first 100
12167: matching records)
12168: or be two integers sperated by a - with no spaces
12169: '30-50' (give me the 30th through the 50th matching
12170: records)
12171:
12172:
12173: =item *
12174:
12175: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12176: replaces a &store() version of data with a replacement set of data
12177: for a particular resource in a namespace passed in the $storehash hash
12178: reference
12179:
12180: =item *
12181:
12182: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12183: works very similar to store/cstore, but all data is stored in a
12184: temporary location and can be reset using tmpreset, $storehash should
12185: be a hash reference, returns nothing on success
12186:
12187: =item *
12188:
12189: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12190: similar to restore, but all data is stored in a temporary location and
12191: can be reset using tmpreset. Returns a hash of values on success,
12192: error string otherwise.
12193:
12194: =item *
12195:
12196: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
12197: deltes all keys for $symb form the temporary storage hash.
12198:
12199: =item *
12200:
12201: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12202: reference filled in from namesp ($udom and $uname are optional)
12203:
12204: =item *
12205:
12206: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
12207: namesp ($udom and $uname are optional)
12208:
12209: =item *
12210:
12211: dump($namespace,$udom,$uname,$regexp,$range) :
12212: dumps the complete (or key matching regexp) namespace into a hash
12213: ($udom, $uname, $regexp, $range are optional)
12214:
12215: $range should be either an integer '100' (give me the first 100
12216: matching records)
12217: or be two integers sperated by a - with no spaces
12218: '30-50' (give me the 30th through the 50th matching
12219: records)
12220: =item *
12221:
12222: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
12223: $store can be a scalar, an array reference, or if the amount to be
12224: incremented is > 1, a hash reference.
12225:
12226: ($udom and $uname are optional)
12227:
12228: =item *
12229:
12230: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
12231: ($udom and $uname are optional)
12232:
12233: =item *
12234:
12235: cput($namespace,$storehash,$udom,$uname) : critical put
12236: ($udom and $uname are optional)
12237:
12238: =item *
12239:
12240: newput($namespace,$storehash,$udom,$uname) :
12241:
12242: Attempts to store the items in the $storehash, but only if they don't
12243: currently exist, if this succeeds you can be certain that you have
12244: successfully created a new key value pair in the $namespace db.
12245:
12246:
12247: Args:
12248: $namespace: name of database to store values to
12249: $storehash: hashref to store to the db
12250: $udom: (optional) domain of user containing the db
12251: $uname: (optional) name of user caontaining the db
12252:
12253: Returns:
12254: 'ok' -> succeeded in storing all keys of $storehash
12255: 'key_exists: <key>' -> failed to anything out of $storehash, as at
12256: least <key> already existed in the db (other
12257: requested keys may also already exist)
12258: 'error: <msg>' -> unable to tie the DB or other error occurred
12259: 'con_lost' -> unable to contact request server
12260: 'refused' -> action was not allowed by remote machine
12261:
12262:
12263: =item *
12264:
12265: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12266: reference filled in from namesp (encrypts the return communication)
12267: ($udom and $uname are optional)
12268:
12269: =item *
12270:
12271: log($udom,$name,$home,$message) : write to permanent log for user; use
12272: critical subroutine
12273:
12274: =item *
12275:
12276: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
12277: array reference filled in from namespace found in domain level on either
12278: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
12279:
12280: =item *
12281:
12282: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
12283: domain level either on specified domain server ($uhome) or primary domain
12284: server ($udom and $uhome are optional)
12285:
12286: =item *
12287:
12288: get_domain_defaults($target_domain) : returns hash with defaults for
12289: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
12290: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
12291: or localauth), initial password or a kerberos realm, language (e.g., en-us).
12292: Values are retrieved from cache (if current), or from domain's configuration.db
12293: (if available), or lastly from values in lonTabs/dns_domain,tab,
12294: or lonTabs/domain.tab.
12295:
12296: %domdefaults = &get_auth_defaults($target_domain);
12297:
12298: =back
12299:
12300: =head2 Network Status Functions
12301:
12302: =over 4
12303:
12304: =item *
12305:
12306: dirlist() : return directory list based on URI (first arg).
12307:
12308: Inputs: 1 required, 5 optional.
12309:
12310: =over
12311:
12312: =item
12313: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
12314:
12315: =item
12316: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
12317:
12318: =item
12319: $username - username of user/course to be listed. Extracted from $uri if absent.
12320:
12321: =item
12322: $getpropath - boolean: 1 if prepend path using &propath().
12323:
12324: =item
12325: $getuserdir - boolean: 1 if prepend path for "userfiles".
12326:
12327: =item
12328: $alternateRoot - path to prepend in place of path from $uri.
12329:
12330: =back
12331:
12332: Returns: Array of up to two items.
12333:
12334: =over
12335:
12336: a reference to an array of files/subdirectories
12337:
12338: =over
12339:
12340: Each element in the array of files/subdirectories is a & separated list of
12341: item name and the result of running stat on the item. If dirlist was requested
12342: for a file instead of a directory, the item name will be ''. For a directory
12343: listing, if the item is a metadata file, the element will end &N&M
12344: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
12345: default copyright set (1).
12346:
12347: =back
12348:
12349: a scalar containing error condition (if encountered).
12350:
12351: =over
12352:
12353: =item
12354: no_host (no homeserver identified for $username:$domain).
12355:
12356: =item
12357: no_such_host (server contacted for listing not identified as valid host).
12358:
12359: =item
12360: con_lost (connection to remote server failed).
12361:
12362: =item
12363: refused (invalid $username:$domain received on lond side).
12364:
12365: =item
12366: no_such_dir (directory at specified path on lond side does not exist).
12367:
12368: =item
12369: empty (directory at specified path on lond side is empty).
12370:
12371: =over
12372:
12373: This is currently not encountered because the &ls3, &ls2,
12374: &ls (_handler) routines on the lond side do not filter out
12375: . and .. from a directory listing.
12376:
12377: =back
12378:
12379: =back
12380:
12381: =back
12382:
12383: =item *
12384:
12385: spareserver() : find server with least workload from spare.tab
12386:
12387:
12388: =item *
12389:
12390: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
12391: if there is no corresponding loncapa host.
12392:
12393: =back
12394:
12395:
12396: =head2 Apache Request
12397:
12398: =over 4
12399:
12400: =item *
12401:
12402: ssi($url,%hash) : server side include, does a complete request cycle on url to
12403: localhost, posts hash
12404:
12405: =back
12406:
12407: =head2 Data to String to Data
12408:
12409: =over 4
12410:
12411: =item *
12412:
12413: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12414: and '&' separators, supports elements that are arrayrefs and hashrefs
12415:
12416: =item *
12417:
12418: hashref2str($hashref) : convert a hashref into a string complete with
12419: escaping and '=' and '&' separators, supports elements that are
12420: arrayrefs and hashrefs
12421:
12422: =item *
12423:
12424: arrayref2str($arrayref) : convert an arrayref into a string complete
12425: with escaping and '&' separators, supports elements that are arrayrefs
12426: and hashrefs
12427:
12428: =item *
12429:
12430: str2hash($string) : convert string to hash using unescaping and
12431: splitting on '=' and '&', supports elements that are arrayrefs and
12432: hashrefs
12433:
12434: =item *
12435:
12436: str2array($string) : convert string to hash using unescaping and
12437: splitting on '&', supports elements that are arrayrefs and hashrefs
12438:
12439: =back
12440:
12441: =head2 Logging Routines
12442:
12443:
12444: These routines allow one to make log messages in the lonnet.log and
12445: lonnet.perm logfiles.
12446:
12447: =over 4
12448:
12449: =item *
12450:
12451: logtouch() : make sure the logfile, lonnet.log, exists
12452:
12453: =item *
12454:
12455: logthis() : append message to the normal lonnet.log file, it gets
12456: preiodically rolled over and deleted.
12457:
12458: =item *
12459:
12460: logperm() : append a permanent message to lonnet.perm.log, this log
12461: file never gets deleted by any automated portion of the system, only
12462: messages of critical importance should go in here.
12463:
12464:
12465: =back
12466:
12467: =head2 General File Helper Routines
12468:
12469: =over 4
12470:
12471: =item *
12472:
12473: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12474: (a) files in /uploaded
12475: (i) If a local copy of the file exists -
12476: compares modification date of local copy with last-modified date for
12477: definitive version stored on home server for course. If local copy is
12478: stale, requests a new version from the home server and stores it.
12479: If the original has been removed from the home server, then local copy
12480: is unlinked.
12481: (ii) If local copy does not exist -
12482: requests the file from the home server and stores it.
12483:
12484: If $caller is 'uploadrep':
12485: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12486: for request for files originally uploaded via DOCS.
12487: - returns 'ok' if fresh local copy now available, -1 otherwise.
12488:
12489: Otherwise:
12490: This indicates a call from the content generation phase of the request.
12491: - returns the entire contents of the file or -1.
12492:
12493: (b) files in /res
12494: - returns the entire contents of a file or -1;
12495: it properly subscribes to and replicates the file if neccessary.
12496:
12497:
12498: =item *
12499:
12500: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12501: reference
12502:
12503: returns either a stat() list of data about the file or an empty list
12504: if the file doesn't exist or couldn't find out about it (connection
12505: problems or user unknown)
12506:
12507: =item *
12508:
12509: filelocation($dir,$file) : returns file system location of a file
12510: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12511: directory that relative $file lookups are to looked in ($dir of /a/dir
12512: and a file of ../bob will become /a/bob)
12513:
12514: =item *
12515:
12516: hreflocation($dir,$file) : returns file system location or a URL; same as
12517: filelocation except for hrefs
12518:
12519: =item *
12520:
12521: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12522:
12523: =back
12524:
12525: =head2 Usererfile file routines (/uploaded*)
12526:
12527: =over 4
12528:
12529: =item *
12530:
12531: userfileupload(): main rotine for putting a file in a user or course's
12532: filespace, arguments are,
12533:
12534: formname - required - this is the name of the element in $env where the
12535: filename, and the contents of the file to create/modifed exist
12536: the filename is in $env{'form.'.$formname.'.filename'} and the
12537: contents of the file is located in $env{'form.'.$formname}
12538: context - if coursedoc, store the file in the course of the active role
12539: of the current user;
12540: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12541: if 'canceloverwrite': delete file in tmp/overwrites directory
12542: subdir - required - subdirectory to put the file in under ../userfiles/
12543: if undefined, it will be placed in "unknown"
12544:
12545: (This routine calls clean_filename() to remove any dangerous
12546: characters from the filename, and then calls finuserfileupload() to
12547: complete the transaction)
12548:
12549: returns either the url of the uploaded file (/uploaded/....) if successful
12550: and /adm/notfound.html if unsuccessful
12551:
12552: =item *
12553:
12554: clean_filename(): routine for cleaing a filename up for storage in
12555: userfile space, argument is:
12556:
12557: filename - proposed filename
12558:
12559: returns: the new clean filename
12560:
12561: =item *
12562:
12563: finishuserfileupload(): routine that creates and sends the file to
12564: userspace, probably shouldn't be called directly
12565:
12566: docuname: username or courseid of destination for the file
12567: docudom: domain of user/course of destination for the file
12568: formname: same as for userfileupload()
12569: fname: filename (including subdirectories) for the file
12570: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12571: allfiles: reference to hash used to store objects found by parser
12572: codebase: reference to hash used for codebases of java objects found by parser
12573: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12574: thumbheight: height (pixels) of thumbnail to be created for uploaded image
12575: resizewidth: width to be used to resize image using resizeImage from ImageMagick
12576: resizeheight: height to be used to resize image using resizeImage from ImageMagick
12577: context: if 'overwrite', will move the uploaded file from its temporary location to
12578: userfiles to facilitate overwriting a previously uploaded file with same name.
12579: mimetype: reference to scalar to accommodate mime type determined
12580: from File::MMagic if $parser = parse.
12581:
12582: returns either the url of the uploaded file (/uploaded/....) if successful
12583: and /adm/notfound.html if unsuccessful (or an error message if context
12584: was 'overwrite').
12585:
12586:
12587: =item *
12588:
12589: renameuserfile(): renames an existing userfile to a new name
12590:
12591: Args:
12592: docuname: username or courseid of destination for the file
12593: docudom: domain of user/course of destination for the file
12594: old: current file name (including any subdirs under userfiles)
12595: new: desired file name (including any subdirs under userfiles)
12596:
12597: =item *
12598:
12599: mkdiruserfile(): creates a directory is a userfiles dir
12600:
12601: Args:
12602: docuname: username or courseid of destination for the file
12603: docudom: domain of user/course of destination for the file
12604: dir: dir to create (including any subdirs under userfiles)
12605:
12606: =item *
12607:
12608: removeuserfile(): removes a file that exists in userfiles
12609:
12610: Args:
12611: docuname: username or courseid of destination for the file
12612: docudom: domain of user/course of destination for the file
12613: fname: filname to delete (including any subdirs under userfiles)
12614:
12615: =item *
12616:
12617: removeuploadedurl(): convience function for removeuserfile()
12618:
12619: Args:
12620: url: a full /uploaded/... url to delete
12621:
12622: =item *
12623:
12624: get_portfile_permissions():
12625: Args:
12626: domain: domain of user or course contain the portfolio files
12627: user: name of user or num of course contain the portfolio files
12628: Returns:
12629: hashref of a dump of the proper file_permissions.db
12630:
12631:
12632: =item *
12633:
12634: get_access_controls():
12635:
12636: Args:
12637: current_permissions: the hash ref returned from get_portfile_permissions()
12638: group: (optional) the group you want the files associated with
12639: file: (optional) the file you want access info on
12640:
12641: Returns:
12642: a hash (keys are file names) of hashes containing
12643: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12644: values are XML containing access control settings (see below)
12645:
12646: Internal notes:
12647:
12648: access controls are stored in file_permissions.db as key=value pairs.
12649: key -> path to file/file_name\0uniqueID:scope_end_start
12650: where scope -> public,guest,course,group,domains or users.
12651: end -> UNIX time for end of access (0 -> no end date)
12652: start -> UNIX time for start of access
12653:
12654: value -> XML description of access control
12655: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12656: <start></start>
12657: <end></end>
12658:
12659: <password></password> for scope type = guest
12660:
12661: <domain></domain> for scope type = course or group
12662: <number></number>
12663: <roles id="">
12664: <role></role>
12665: <access></access>
12666: <section></section>
12667: <group></group>
12668: </roles>
12669:
12670: <dom></dom> for scope type = domains
12671:
12672: <users> for scope type = users
12673: <user>
12674: <uname></uname>
12675: <udom></udom>
12676: </user>
12677: </users>
12678: </scope>
12679:
12680: Access data is also aggregated for each file in an additional key=value pair:
12681: key -> path to file/file_name\0accesscontrol
12682: value -> reference to hash
12683: hash contains key = value pairs
12684: where key = uniqueID:scope_end_start
12685: value = UNIX time record was last updated
12686:
12687: Used to improve speed of look-ups of access controls for each file.
12688:
12689: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12690:
12691: modify_access_controls():
12692:
12693: Modifies access controls for a portfolio file
12694: Args
12695: 1. file name
12696: 2. reference to hash of required changes,
12697: 3. domain
12698: 4. username
12699: where domain,username are the domain of the portfolio owner
12700: (either a user or a course)
12701:
12702: Returns:
12703: 1. result of additions or updates ('ok' or 'error', with error message).
12704: 2. result of deletions ('ok' or 'error', with error message).
12705: 3. reference to hash of any new or updated access controls.
12706: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12707: key = integer (inbound ID)
12708: value = uniqueID
12709:
12710: =back
12711:
12712: =head2 HTTP Helper Routines
12713:
12714: =over 4
12715:
12716: =item *
12717:
12718: escape() : unpack non-word characters into CGI-compatible hex codes
12719:
12720: =item *
12721:
12722: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12723:
12724: =back
12725:
12726: =head1 PRIVATE SUBROUTINES
12727:
12728: =head2 Underlying communication routines (Shouldn't call)
12729:
12730: =over 4
12731:
12732: =item *
12733:
12734: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12735:
12736: =item *
12737:
12738: reply() : uses subreply to send a message to remote machine, logs all failures
12739:
12740: =item *
12741:
12742: critical() : passes a critical message to another server; if cannot
12743: get through then place message in connection buffer directory and
12744: returns con_delayed, if incapable of saving message, returns
12745: con_failed
12746:
12747: =item *
12748:
12749: reconlonc() : tries to reconnect lonc client processes.
12750:
12751: =back
12752:
12753: =head2 Resource Access Logging
12754:
12755: =over 4
12756:
12757: =item *
12758:
12759: flushcourselogs() : flush (save) buffer logs and access logs
12760:
12761: =item *
12762:
12763: courselog($what) : save message for course in hash
12764:
12765: =item *
12766:
12767: courseacclog($what) : save message for course using &courselog(). Perform
12768: special processing for specific resource types (problems, exams, quizzes, etc).
12769:
12770: =item *
12771:
12772: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12773: as a PerlChildExitHandler
12774:
12775: =back
12776:
12777: =head2 Other
12778:
12779: =over 4
12780:
12781: =item *
12782:
12783: symblist($mapname,%newhash) : update symbolic storage links
12784:
12785: =back
12786:
12787: =cut
12788:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>