File:
[LON-CAPA] /
loncom /
lonnet /
perl /
lonnet.pm
Revision
1.1254:
download - view:
text,
annotated -
select for diffs
Mon Mar 31 01:09:20 2014 UTC (10 years, 4 months ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD
- Move &selfenroll_validation_types(), &selfenroll_default_descs(),
&get_selfenroll_titles() from domainprefs.pm to lonuserutils.pm
to facilitate re-use.
- Add self-enrollment related defaults to cached domain defaults:
(a) Self-enrollment settings controlled by DC, by default:
- <type>selfenrolladmdc (where <type> is: course type (official,
unofficial, community or textbook).
(b) Self-enrollment default values:
- <type>selfenroll<setting> where type is course type, and <setting>
is default self-enrollment setting: types, registered, approval,
limit, or cap.
- New routine in lonuserutils.pm -- &selfenrollment_administration()
provides array refs for self-enrollment items (a) managed by course
personnel; (b) managed by DC.
1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.1254 2014/03/31 01:09:20 raeburn Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28: ###
29:
30: =pod
31:
32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
71: package Apache::lonnet;
72:
73: use strict;
74: use LWP::UserAgent();
75: use HTTP::Date;
76: use Image::Magick;
77:
78:
79: use Encode;
80:
81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
82: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
83: %managerstab);
84:
85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
86: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
87: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
88: %courseownerbuf, %coursetypebuf,$locknum);
89:
90: use IO::Socket;
91: use GDBM_File;
92: use HTML::LCParser;
93: use Fcntl qw(:flock);
94: use Storable qw(thaw nfreeze);
95: use Time::HiRes qw( gettimeofday tv_interval );
96: use Cache::Memcached;
97: use Digest::MD5;
98: use Math::Random;
99: use File::MMagic;
100: use LONCAPA qw(:DEFAULT :match);
101: use LONCAPA::Configuration;
102: use LONCAPA::lonmetadata;
103: use LONCAPA::Lond;
104:
105: use File::Copy;
106:
107: my $readit;
108: my $max_connection_retries = 10; # Or some such value.
109:
110: require Exporter;
111:
112: our @ISA = qw (Exporter);
113: our @EXPORT = qw(%env);
114:
115:
116: # ------------------------------------ Logging (parameters, docs, slots, roles)
117: {
118: my $logid;
119: sub write_log {
120: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
121: if ($context eq 'course') {
122: if (($cnum eq '') || ($cdom eq '')) {
123: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
124: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
125: }
126: }
127: $logid ++;
128: my $now = time();
129: my $id=$now.'00000'.$$.'00000'.$logid;
130: my $logentry = {
131: $id => {
132: 'exe_uname' => $env{'user.name'},
133: 'exe_udom' => $env{'user.domain'},
134: 'exe_time' => $now,
135: 'exe_ip' => $ENV{'REMOTE_ADDR'},
136: 'delflag' => $delflag,
137: 'logentry' => $storehash,
138: 'uname' => $uname,
139: 'udom' => $udom,
140: }
141: };
142: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
143: }
144: }
145:
146: sub logtouch {
147: my $execdir=$perlvar{'lonDaemons'};
148: unless (-e "$execdir/logs/lonnet.log") {
149: open(my $fh,">>$execdir/logs/lonnet.log");
150: close $fh;
151: }
152: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
153: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
154: }
155:
156: sub logthis {
157: my $message=shift;
158: my $execdir=$perlvar{'lonDaemons'};
159: my $now=time;
160: my $local=localtime($now);
161: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
162: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
163: print $fh $logstring;
164: close($fh);
165: }
166: return 1;
167: }
168:
169: sub logperm {
170: my $message=shift;
171: my $execdir=$perlvar{'lonDaemons'};
172: my $now=time;
173: my $local=localtime($now);
174: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
175: print $fh "$now:$message:$local\n";
176: close($fh);
177: }
178: return 1;
179: }
180:
181: sub create_connection {
182: my ($hostname,$lonid) = @_;
183: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
184: Type => SOCK_STREAM,
185: Timeout => 10);
186: return 0 if (!$client);
187: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
188: my $result = <$client>;
189: chomp($result);
190: return 1 if ($result eq 'done');
191: return 0;
192: }
193:
194: sub get_server_timezone {
195: my ($cnum,$cdom) = @_;
196: my $home=&homeserver($cnum,$cdom);
197: if ($home ne 'no_host') {
198: my $cachetime = 24*3600;
199: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
200: if (defined($cached)) {
201: return $timezone;
202: } else {
203: my $timezone = &reply('servertimezone',$home);
204: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
205: }
206: }
207: }
208:
209: sub get_server_distarch {
210: my ($lonhost,$ignore_cache) = @_;
211: if (defined($lonhost)) {
212: if (!defined(&hostname($lonhost))) {
213: return;
214: }
215: my $cachetime = 12*3600;
216: if (!$ignore_cache) {
217: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
218: if (defined($cached)) {
219: return $distarch;
220: }
221: }
222: my $rep = &reply('serverdistarch',$lonhost);
223: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
224: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
225: $rep eq '') {
226: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
227: }
228: }
229: return;
230: }
231:
232: sub get_server_loncaparev {
233: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
234: if (defined($lonhost)) {
235: if (!defined(&hostname($lonhost))) {
236: undef($lonhost);
237: }
238: }
239: if (!defined($lonhost)) {
240: if (defined(&domain($dom,'primary'))) {
241: $lonhost=&domain($dom,'primary');
242: if ($lonhost eq 'no_host') {
243: undef($lonhost);
244: }
245: }
246: }
247: if (defined($lonhost)) {
248: my $cachetime = 12*3600;
249: if (!$ignore_cache) {
250: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
251: if (defined($cached)) {
252: return $loncaparev;
253: }
254: }
255: my ($answer,$loncaparev);
256: my @ids=¤t_machine_ids();
257: if (grep(/^\Q$lonhost\E$/,@ids)) {
258: $answer = $perlvar{'lonVersion'};
259: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
260: $loncaparev = $1;
261: }
262: } else {
263: $answer = &reply('serverloncaparev',$lonhost);
264: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
265: if ($caller eq 'loncron') {
266: my $ua=new LWP::UserAgent;
267: $ua->timeout(4);
268: my $protocol = $protocol{$lonhost};
269: $protocol = 'http' if ($protocol ne 'https');
270: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
271: my $request=new HTTP::Request('GET',$url);
272: my $response=$ua->request($request);
273: unless ($response->is_error()) {
274: my $content = $response->content;
275: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
276: $loncaparev = $1;
277: }
278: }
279: } else {
280: $loncaparev = $loncaparevs{$lonhost};
281: }
282: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
283: $loncaparev = $1;
284: }
285: }
286: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
287: }
288: }
289:
290: sub get_server_homeID {
291: my ($hostname,$ignore_cache,$caller) = @_;
292: unless ($ignore_cache) {
293: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
294: if (defined($cached)) {
295: return $serverhomeID;
296: }
297: }
298: my $cachetime = 12*3600;
299: my $serverhomeID;
300: if ($caller eq 'loncron') {
301: my @machine_ids = &machine_ids($hostname);
302: foreach my $id (@machine_ids) {
303: my $response = &reply('serverhomeID',$id);
304: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
305: $serverhomeID = $response;
306: last;
307: }
308: }
309: if ($serverhomeID eq '') {
310: $serverhomeID = $machine_ids[-1];
311: }
312: } else {
313: $serverhomeID = $serverhomeIDs{$hostname};
314: }
315: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
316: }
317:
318: sub get_remote_globals {
319: my ($lonhost,$whathash,$ignore_cache) = @_;
320: my ($result,%returnhash,%whatneeded);
321: if (ref($whathash) eq 'HASH') {
322: foreach my $what (sort(keys(%{$whathash}))) {
323: my $hashid = $lonhost.'-'.$what;
324: my ($response,$cached);
325: unless ($ignore_cache) {
326: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
327: }
328: if (defined($cached)) {
329: $returnhash{$what} = $response;
330: } else {
331: $whatneeded{$what} = 1;
332: }
333: }
334: if (keys(%whatneeded) == 0) {
335: $result = 'ok';
336: } else {
337: my $requested = &freeze_escape(\%whatneeded);
338: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
339: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
340: ($rep eq 'unknown_cmd')) {
341: $result = $rep;
342: } else {
343: $result = 'ok';
344: my @pairs=split(/\&/,$rep);
345: foreach my $item (@pairs) {
346: my ($key,$value)=split(/=/,$item,2);
347: my $what = &unescape($key);
348: my $hashid = $lonhost.'-'.$what;
349: $returnhash{$what}=&thaw_unescape($value);
350: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
351: }
352: }
353: }
354: }
355: return ($result,\%returnhash);
356: }
357:
358: sub remote_devalidate_cache {
359: my ($lonhost,$cachekeys) = @_;
360: my $items;
361: return unless (ref($cachekeys) eq 'ARRAY');
362: my $cachestr = join('&',@{$cachekeys});
363: my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
364: return $response;
365: }
366:
367: # -------------------------------------------------- Non-critical communication
368: sub subreply {
369: my ($cmd,$server)=@_;
370: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
371: #
372: # With loncnew process trimming, there's a timing hole between lonc server
373: # process exit and the master server picking up the listen on the AF_UNIX
374: # socket. In that time interval, a lock file will exist:
375:
376: my $lockfile=$peerfile.".lock";
377: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
378: sleep(1);
379: }
380: # At this point, either a loncnew parent is listening or an old lonc
381: # or loncnew child is listening so we can connect or everything's dead.
382: #
383: # We'll give the connection a few tries before abandoning it. If
384: # connection is not possible, we'll con_lost back to the client.
385: #
386: my $client;
387: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
388: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
389: Type => SOCK_STREAM,
390: Timeout => 10);
391: if ($client) {
392: last; # Connected!
393: } else {
394: &create_connection(&hostname($server),$server);
395: }
396: sleep(1); # Try again later if failed connection.
397: }
398: my $answer;
399: if ($client) {
400: print $client "sethost:$server:$cmd\n";
401: $answer=<$client>;
402: if (!$answer) { $answer="con_lost"; }
403: chomp($answer);
404: } else {
405: $answer = 'con_lost'; # Failed connection.
406: }
407: return $answer;
408: }
409:
410: sub reply {
411: my ($cmd,$server)=@_;
412: unless (defined(&hostname($server))) { return 'no_such_host'; }
413: my $answer=subreply($cmd,$server);
414: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
415: &logthis("<font color=\"blue\">WARNING:".
416: " $cmd to $server returned $answer</font>");
417: }
418: return $answer;
419: }
420:
421: # ----------------------------------------------------------- Send USR1 to lonc
422:
423: sub reconlonc {
424: my ($lonid) = @_;
425: my $hostname = &hostname($lonid);
426: if ($lonid) {
427: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
428: if ($hostname && -e $peerfile) {
429: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
430: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
431: Type => SOCK_STREAM,
432: Timeout => 10);
433: if ($client) {
434: print $client ("reset_retries\n");
435: my $answer=<$client>;
436: #reset just this one.
437: }
438: }
439: return;
440: }
441:
442: &logthis("Trying to reconnect lonc");
443: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
444: if (open(my $fh,"<$loncfile")) {
445: my $loncpid=<$fh>;
446: chomp($loncpid);
447: if (kill 0 => $loncpid) {
448: &logthis("lonc at pid $loncpid responding, sending USR1");
449: kill USR1 => $loncpid;
450: sleep 1;
451: } else {
452: &logthis(
453: "<font color=\"blue\">WARNING:".
454: " lonc at pid $loncpid not responding, giving up</font>");
455: }
456: } else {
457: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
458: }
459: }
460:
461: # ------------------------------------------------------ Critical communication
462:
463: sub critical {
464: my ($cmd,$server)=@_;
465: unless (&hostname($server)) {
466: &logthis("<font color=\"blue\">WARNING:".
467: " Critical message to unknown server ($server)</font>");
468: return 'no_such_host';
469: }
470: my $answer=reply($cmd,$server);
471: if ($answer eq 'con_lost') {
472: &reconlonc("$perlvar{'lonSockDir'}/$server");
473: my $answer=reply($cmd,$server);
474: if ($answer eq 'con_lost') {
475: my $now=time;
476: my $middlename=$cmd;
477: $middlename=substr($middlename,0,16);
478: $middlename=~s/\W//g;
479: my $dfilename=
480: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
481: $dumpcount++;
482: {
483: my $dfh;
484: if (open($dfh,">$dfilename")) {
485: print $dfh "$cmd\n";
486: close($dfh);
487: }
488: }
489: sleep 2;
490: my $wcmd='';
491: {
492: my $dfh;
493: if (open($dfh,"<$dfilename")) {
494: $wcmd=<$dfh>;
495: close($dfh);
496: }
497: }
498: chomp($wcmd);
499: if ($wcmd eq $cmd) {
500: &logthis("<font color=\"blue\">WARNING: ".
501: "Connection buffer $dfilename: $cmd</font>");
502: &logperm("D:$server:$cmd");
503: return 'con_delayed';
504: } else {
505: &logthis("<font color=\"red\">CRITICAL:"
506: ." Critical connection failed: $server $cmd</font>");
507: &logperm("F:$server:$cmd");
508: return 'con_failed';
509: }
510: }
511: }
512: return $answer;
513: }
514:
515: # ------------------------------------------- check if return value is an error
516:
517: sub error {
518: my ($result) = @_;
519: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
520: if ($2 == 2) { return undef; }
521: return $1;
522: }
523: return undef;
524: }
525:
526: sub convert_and_load_session_env {
527: my ($lonidsdir,$handle)=@_;
528: my @profile;
529: {
530: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
531: if (!$opened) {
532: return 0;
533: }
534: flock($idf,LOCK_SH);
535: @profile=<$idf>;
536: close($idf);
537: }
538: my %temp_env;
539: foreach my $line (@profile) {
540: if ($line !~ m/=/) {
541: return 0;
542: }
543: chomp($line);
544: my ($envname,$envvalue)=split(/=/,$line,2);
545: $temp_env{&unescape($envname)} = &unescape($envvalue);
546: }
547: unlink("$lonidsdir/$handle.id");
548: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
549: 0640)) {
550: %disk_env = %temp_env;
551: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
552: untie(%disk_env);
553: }
554: return 1;
555: }
556:
557: # ------------------------------------------- Transfer profile into environment
558: my $env_loaded;
559: sub transfer_profile_to_env {
560: my ($lonidsdir,$handle,$force_transfer) = @_;
561: if (!$force_transfer && $env_loaded) { return; }
562:
563: if (!defined($lonidsdir)) {
564: $lonidsdir = $perlvar{'lonIDsDir'};
565: }
566: if (!defined($handle)) {
567: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
568: }
569:
570: my $convert;
571: {
572: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
573: if (!$opened) {
574: return;
575: }
576: flock($idf,LOCK_SH);
577: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
578: &GDBM_READER(),0640)) {
579: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
580: untie(%disk_env);
581: } else {
582: $convert = 1;
583: }
584: }
585: if ($convert) {
586: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
587: &logthis("Failed to load session, or convert session.");
588: }
589: }
590:
591: my %remove;
592: while ( my $envname = each(%env) ) {
593: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
594: if ($time < time-300) {
595: $remove{$key}++;
596: }
597: }
598: }
599:
600: $env{'user.environment'} = "$lonidsdir/$handle.id";
601: $env_loaded=1;
602: foreach my $expired_key (keys(%remove)) {
603: &delenv($expired_key);
604: }
605: }
606:
607: # ---------------------------------------------------- Check for valid session
608: sub check_for_valid_session {
609: my ($r,$name,$userhashref) = @_;
610: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
611: if ($name eq '') {
612: $name = 'lonID';
613: }
614: my $lonid=$cookies{$name};
615: return undef if (!$lonid);
616:
617: my $handle=&LONCAPA::clean_handle($lonid->value);
618: my $lonidsdir;
619: if ($name eq 'lonDAV') {
620: $lonidsdir=$r->dir_config('lonDAVsessDir');
621: } else {
622: $lonidsdir=$r->dir_config('lonIDsDir');
623: }
624: return undef if (!-e "$lonidsdir/$handle.id");
625:
626: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
627: return undef if (!$opened);
628:
629: flock($idf,LOCK_SH);
630: my %disk_env;
631: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
632: &GDBM_READER(),0640)) {
633: return undef;
634: }
635:
636: if (!defined($disk_env{'user.name'})
637: || !defined($disk_env{'user.domain'})) {
638: return undef;
639: }
640:
641: if (ref($userhashref) eq 'HASH') {
642: $userhashref->{'name'} = $disk_env{'user.name'};
643: $userhashref->{'domain'} = $disk_env{'user.domain'};
644: }
645:
646: return $handle;
647: }
648:
649: sub timed_flock {
650: my ($file,$lock_type) = @_;
651: my $failed=0;
652: eval {
653: local $SIG{__DIE__}='DEFAULT';
654: local $SIG{ALRM}=sub {
655: $failed=1;
656: die("failed lock");
657: };
658: alarm(13);
659: flock($file,$lock_type);
660: alarm(0);
661: };
662: if ($failed) {
663: return undef;
664: } else {
665: return 1;
666: }
667: }
668:
669: # ---------------------------------------------------------- Append Environment
670:
671: sub appenv {
672: my ($newenv,$roles) = @_;
673: if (ref($newenv) eq 'HASH') {
674: foreach my $key (keys(%{$newenv})) {
675: my $refused = 0;
676: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
677: $refused = 1;
678: if (ref($roles) eq 'ARRAY') {
679: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
680: if (grep(/^\Q$role\E$/,@{$roles})) {
681: $refused = 0;
682: }
683: }
684: }
685: if ($refused) {
686: &logthis("<font color=\"blue\">WARNING: ".
687: "Attempt to modify environment ".$key." to ".$newenv->{$key}
688: .'</font>');
689: delete($newenv->{$key});
690: } else {
691: $env{$key}=$newenv->{$key};
692: }
693: }
694: my $opened = open(my $env_file,'+<',$env{'user.environment'});
695: if ($opened
696: && &timed_flock($env_file,LOCK_EX)
697: &&
698: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
699: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
700: while (my ($key,$value) = each(%{$newenv})) {
701: $disk_env{$key} = $value;
702: }
703: untie(%disk_env);
704: }
705: }
706: return 'ok';
707: }
708: # ----------------------------------------------------- Delete from Environment
709:
710: sub delenv {
711: my ($delthis,$regexp,$roles) = @_;
712: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
713: my $refused = 1;
714: if (ref($roles) eq 'ARRAY') {
715: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
716: if (grep(/^\Q$role\E$/,@{$roles})) {
717: $refused = 0;
718: }
719: }
720: if ($refused) {
721: &logthis("<font color=\"blue\">WARNING: ".
722: "Attempt to delete from environment ".$delthis);
723: return 'error';
724: }
725: }
726: my $opened = open(my $env_file,'+<',$env{'user.environment'});
727: if ($opened
728: && &timed_flock($env_file,LOCK_EX)
729: &&
730: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
731: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
732: foreach my $key (keys(%disk_env)) {
733: if ($regexp) {
734: if ($key=~/^$delthis/) {
735: delete($env{$key});
736: delete($disk_env{$key});
737: }
738: } else {
739: if ($key=~/^\Q$delthis\E/) {
740: delete($env{$key});
741: delete($disk_env{$key});
742: }
743: }
744: }
745: untie(%disk_env);
746: }
747: return 'ok';
748: }
749:
750: sub get_env_multiple {
751: my ($name) = @_;
752: my @values;
753: if (defined($env{$name})) {
754: # exists is it an array
755: if (ref($env{$name})) {
756: @values=@{ $env{$name} };
757: } else {
758: $values[0]=$env{$name};
759: }
760: }
761: return(@values);
762: }
763:
764: # ------------------------------------------------------------------- Locking
765:
766: sub set_lock {
767: my ($text)=@_;
768: $locknum++;
769: my $id=$$.'-'.$locknum;
770: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
771: 'session.lock.'.$id => $text});
772: return $id;
773: }
774:
775: sub get_locks {
776: my $num=0;
777: my %texts=();
778: foreach my $lock (split(/\,/,$env{'session.locks'})) {
779: if ($lock=~/\w/) {
780: $num++;
781: $texts{$lock}=$env{'session.lock.'.$lock};
782: }
783: }
784: return ($num,%texts);
785: }
786:
787: sub remove_lock {
788: my ($id)=@_;
789: my $newlocks='';
790: foreach my $lock (split(/\,/,$env{'session.locks'})) {
791: if (($lock=~/\w/) && ($lock ne $id)) {
792: $newlocks.=','.$lock;
793: }
794: }
795: &appenv({'session.locks' => $newlocks});
796: &delenv('session.lock.'.$id);
797: }
798:
799: sub remove_all_locks {
800: my $activelocks=$env{'session.locks'};
801: foreach my $lock (split(/\,/,$env{'session.locks'})) {
802: if ($lock=~/\w/) {
803: &remove_lock($lock);
804: }
805: }
806: }
807:
808:
809: # ------------------------------------------ Find out current server userload
810: sub userload {
811: my $numusers=0;
812: {
813: opendir(LONIDS,$perlvar{'lonIDsDir'});
814: my $filename;
815: my $curtime=time;
816: while ($filename=readdir(LONIDS)) {
817: next if ($filename eq '.' || $filename eq '..');
818: next if ($filename =~ /publicuser_\d+\.id/);
819: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
820: if ($curtime-$mtime < 1800) { $numusers++; }
821: }
822: closedir(LONIDS);
823: }
824: my $userloadpercent=0;
825: my $maxuserload=$perlvar{'lonUserLoadLim'};
826: if ($maxuserload) {
827: $userloadpercent=100*$numusers/$maxuserload;
828: }
829: $userloadpercent=sprintf("%.2f",$userloadpercent);
830: return $userloadpercent;
831: }
832:
833: # ------------------------------ Find server with least workload from spare.tab
834:
835: sub spareserver {
836: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
837: my $spare_server;
838: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
839: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
840: : $userloadpercent;
841: my ($uint_dom,$remotesessions);
842: if (($udom ne '') && (&domain($udom) ne '')) {
843: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
844: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
845: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
846: $remotesessions = $udomdefaults{'remotesessions'};
847: }
848: my $spareshash = &this_host_spares($udom);
849: if (ref($spareshash) eq 'HASH') {
850: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
851: foreach my $try_server (@{ $spareshash->{'primary'} }) {
852: if ($uint_dom) {
853: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
854: $try_server));
855: }
856: ($spare_server, $lowest_load) =
857: &compare_server_load($try_server, $spare_server, $lowest_load);
858: }
859: }
860:
861: my $found_server = ($spare_server ne '' && $lowest_load < 100);
862:
863: if (!$found_server) {
864: if (ref($spareshash->{'default'}) eq 'ARRAY') {
865: foreach my $try_server (@{ $spareshash->{'default'} }) {
866: if ($uint_dom) {
867: next unless (&spare_can_host($udom,$uint_dom,
868: $remotesessions,$try_server));
869: }
870: ($spare_server, $lowest_load) =
871: &compare_server_load($try_server, $spare_server, $lowest_load);
872: }
873: }
874: }
875: }
876:
877: if (!$want_server_name) {
878: my $protocol = 'http';
879: if ($protocol{$spare_server} eq 'https') {
880: $protocol = $protocol{$spare_server};
881: }
882: if (defined($spare_server)) {
883: my $hostname = &hostname($spare_server);
884: if (defined($hostname)) {
885: $spare_server = $protocol.'://'.$hostname;
886: }
887: }
888: }
889: return $spare_server;
890: }
891:
892: sub compare_server_load {
893: my ($try_server, $spare_server, $lowest_load, $required) = @_;
894:
895: if ($required) {
896: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
897: my $remoterev = &get_server_loncaparev(undef,$try_server);
898: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
899: if (($major eq '' && $minor eq '') ||
900: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
901: return ($spare_server,$lowest_load);
902: }
903: }
904:
905: my $loadans = &reply('load', $try_server);
906: my $userloadans = &reply('userload',$try_server);
907:
908: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
909: return ($spare_server, $lowest_load); #didn't get a number from the server
910: }
911:
912: my $load;
913: if ($loadans =~ /\d/) {
914: if ($userloadans =~ /\d/) {
915: #both are numbers, pick the bigger one
916: $load = ($loadans > $userloadans) ? $loadans
917: : $userloadans;
918: } else {
919: $load = $loadans;
920: }
921: } else {
922: $load = $userloadans;
923: }
924:
925: if (($load =~ /\d/) && ($load < $lowest_load)) {
926: $spare_server = $try_server;
927: $lowest_load = $load;
928: }
929: return ($spare_server,$lowest_load);
930: }
931:
932: # --------------------------- ask offload servers if user already has a session
933: sub find_existing_session {
934: my ($udom,$uname) = @_;
935: my $spareshash = &this_host_spares($udom);
936: if (ref($spareshash) eq 'HASH') {
937: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
938: foreach my $try_server (@{ $spareshash->{'primary'} }) {
939: return $try_server if (&has_user_session($try_server, $udom, $uname));
940: }
941: }
942: if (ref($spareshash->{'default'}) eq 'ARRAY') {
943: foreach my $try_server (@{ $spareshash->{'default'} }) {
944: return $try_server if (&has_user_session($try_server, $udom, $uname));
945: }
946: }
947: }
948: return;
949: }
950:
951: # -------------------------------- ask if server already has a session for user
952: sub has_user_session {
953: my ($lonid,$udom,$uname) = @_;
954: my $result = &reply(join(':','userhassession',
955: map {&escape($_)} ($udom,$uname)),$lonid);
956: return 1 if ($result eq 'ok');
957:
958: return 0;
959: }
960:
961: # --------- determine least loaded server in a user's domain which allows login
962:
963: sub choose_server {
964: my ($udom,$checkloginvia,$required) = @_;
965: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
966: my %servers = &get_servers($udom);
967: my $lowest_load = 30000;
968: my ($login_host,$hostname,$portal_path,$isredirect);
969: foreach my $lonhost (keys(%servers)) {
970: my $loginvia;
971: if ($checkloginvia) {
972: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
973: if ($loginvia) {
974: my ($server,$path) = split(/:/,$loginvia);
975: ($login_host, $lowest_load) =
976: &compare_server_load($server, $login_host, $lowest_load, $required);
977: if ($login_host eq $server) {
978: $portal_path = $path;
979: $isredirect = 1;
980: }
981: } else {
982: ($login_host, $lowest_load) =
983: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
984: if ($login_host eq $lonhost) {
985: $portal_path = '';
986: $isredirect = '';
987: }
988: }
989: } else {
990: ($login_host, $lowest_load) =
991: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
992: }
993: }
994: if ($login_host ne '') {
995: $hostname = &hostname($login_host);
996: }
997: return ($login_host,$hostname,$portal_path,$isredirect);
998: }
999:
1000: # --------------------------------------------- Try to change a user's password
1001:
1002: sub changepass {
1003: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1004: $currentpass = &escape($currentpass);
1005: $newpass = &escape($newpass);
1006: my $lonhost = $perlvar{'lonHostID'};
1007: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1008: $server);
1009: if (! $answer) {
1010: &logthis("No reply on password change request to $server ".
1011: "by $uname in domain $udom.");
1012: } elsif ($answer =~ "^ok") {
1013: &logthis("$uname in $udom successfully changed their password ".
1014: "on $server.");
1015: } elsif ($answer =~ "^pwchange_failure") {
1016: &logthis("$uname in $udom was unable to change their password ".
1017: "on $server. The action was blocked by either lcpasswd ".
1018: "or pwchange");
1019: } elsif ($answer =~ "^non_authorized") {
1020: &logthis("$uname in $udom did not get their password correct when ".
1021: "attempting to change it on $server.");
1022: } elsif ($answer =~ "^auth_mode_error") {
1023: &logthis("$uname in $udom attempted to change their password despite ".
1024: "not being locally or internally authenticated on $server.");
1025: } elsif ($answer =~ "^unknown_user") {
1026: &logthis("$uname in $udom attempted to change their password ".
1027: "on $server but were unable to because $server is not ".
1028: "their home server.");
1029: } elsif ($answer =~ "^refused") {
1030: &logthis("$server refused to change $uname in $udom password because ".
1031: "it was sent an unencrypted request to change the password.");
1032: } elsif ($answer =~ "invalid_client") {
1033: &logthis("$server refused to change $uname in $udom password because ".
1034: "it was a reset by e-mail originating from an invalid server.");
1035: }
1036: return $answer;
1037: }
1038:
1039: # ----------------------- Try to determine user's current authentication scheme
1040:
1041: sub queryauthenticate {
1042: my ($uname,$udom)=@_;
1043: my $uhome=&homeserver($uname,$udom);
1044: if (!$uhome) {
1045: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1046: return 'no_host';
1047: }
1048: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1049: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1050: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1051: }
1052: return $answer;
1053: }
1054:
1055: # --------- Try to authenticate user from domain's lib servers (first this one)
1056:
1057: sub authenticate {
1058: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1059: $upass=&escape($upass);
1060: $uname= &LONCAPA::clean_username($uname);
1061: my $uhome=&homeserver($uname,$udom,1);
1062: my $newhome;
1063: if ((!$uhome) || ($uhome eq 'no_host')) {
1064: # Maybe the machine was offline and only re-appeared again recently?
1065: &reconlonc();
1066: # One more
1067: $uhome=&homeserver($uname,$udom,1);
1068: if (($uhome eq 'no_host') && $checkdefauth) {
1069: if (defined(&domain($udom,'primary'))) {
1070: $newhome=&domain($udom,'primary');
1071: }
1072: if ($newhome ne '') {
1073: $uhome = $newhome;
1074: }
1075: }
1076: if ((!$uhome) || ($uhome eq 'no_host')) {
1077: &logthis("User $uname at $udom is unknown in authenticate");
1078: return 'no_host';
1079: }
1080: }
1081: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1082: if ($answer eq 'authorized') {
1083: if ($newhome) {
1084: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1085: return 'no_account_on_host';
1086: } else {
1087: &logthis("User $uname at $udom authorized by $uhome");
1088: return $uhome;
1089: }
1090: }
1091: if ($answer eq 'non_authorized') {
1092: &logthis("User $uname at $udom rejected by $uhome");
1093: return 'no_host';
1094: }
1095: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1096: return 'no_host';
1097: }
1098:
1099: sub can_host_session {
1100: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1101: my $canhost = 1;
1102: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1103: if (ref($remotesessions) eq 'HASH') {
1104: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1105: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1106: $canhost = 0;
1107: } else {
1108: $canhost = 1;
1109: }
1110: }
1111: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1112: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1113: $canhost = 1;
1114: } else {
1115: $canhost = 0;
1116: }
1117: }
1118: if ($canhost) {
1119: if ($remotesessions->{'version'} ne '') {
1120: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1121: if ($reqmajor ne '' && $reqminor ne '') {
1122: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1123: my $major = $1;
1124: my $minor = $2;
1125: if (($major < $reqmajor ) ||
1126: (($major == $reqmajor) && ($minor < $reqminor))) {
1127: $canhost = 0;
1128: }
1129: } else {
1130: $canhost = 0;
1131: }
1132: }
1133: }
1134: }
1135: }
1136: if ($canhost) {
1137: if (ref($hostedsessions) eq 'HASH') {
1138: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1139: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1140: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1141: if (($uint_dom ne '') &&
1142: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1143: $canhost = 0;
1144: } else {
1145: $canhost = 1;
1146: }
1147: }
1148: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1149: if (($uint_dom ne '') &&
1150: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1151: $canhost = 1;
1152: } else {
1153: $canhost = 0;
1154: }
1155: }
1156: }
1157: }
1158: return $canhost;
1159: }
1160:
1161: sub spare_can_host {
1162: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1163: my $canhost=1;
1164: my @intdoms;
1165: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1166: if (ref($internet_names) eq 'ARRAY') {
1167: @intdoms = @{$internet_names};
1168: }
1169: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1170: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1171: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1172: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1173: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1174: $canhost = &can_host_session($udom,$try_server,$remoterev,
1175: $remotesessions,
1176: $defdomdefaults{'hostedsessions'});
1177: }
1178: return $canhost;
1179: }
1180:
1181: sub this_host_spares {
1182: my ($dom) = @_;
1183: my ($dom_in_use,$lonhost_in_use,$result);
1184: my @hosts = ¤t_machine_ids();
1185: foreach my $lonhost (@hosts) {
1186: if (&host_domain($lonhost) eq $dom) {
1187: $dom_in_use = $dom;
1188: $lonhost_in_use = $lonhost;
1189: last;
1190: }
1191: }
1192: if ($dom_in_use ne '') {
1193: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1194: }
1195: if (ref($result) ne 'HASH') {
1196: $lonhost_in_use = $perlvar{'lonHostID'};
1197: $dom_in_use = &host_domain($lonhost_in_use);
1198: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1199: if (ref($result) ne 'HASH') {
1200: $result = \%spareid;
1201: }
1202: }
1203: return $result;
1204: }
1205:
1206: sub spares_for_offload {
1207: my ($dom_in_use,$lonhost_in_use) = @_;
1208: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1209: if (defined($cached)) {
1210: return $result;
1211: } else {
1212: my $cachetime = 60*60*24;
1213: my %domconfig =
1214: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1215: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1216: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1217: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1218: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1219: }
1220: }
1221: }
1222: }
1223: return;
1224: }
1225:
1226: sub get_lonbalancer_config {
1227: my ($servers) = @_;
1228: my ($currbalancer,$currtargets);
1229: if (ref($servers) eq 'HASH') {
1230: foreach my $server (keys(%{$servers})) {
1231: my %what = (
1232: spareid => 1,
1233: perlvar => 1,
1234: );
1235: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1236: if ($result eq 'ok') {
1237: if (ref($returnhash) eq 'HASH') {
1238: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1239: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1240: $currbalancer = $server;
1241: $currtargets = {};
1242: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1243: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1244: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1245: }
1246: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1247: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1248: }
1249: }
1250: last;
1251: }
1252: }
1253: }
1254: }
1255: }
1256: }
1257: return ($currbalancer,$currtargets);
1258: }
1259:
1260: sub check_loadbalancing {
1261: my ($uname,$udom) = @_;
1262: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1263: $rule_in_effect,$offloadto,$otherserver);
1264: my $lonhost = $perlvar{'lonHostID'};
1265: my @hosts = ¤t_machine_ids();
1266: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1267: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1268: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1269: my $serverhomedom = &host_domain($lonhost);
1270:
1271: my $cachetime = 60*60*24;
1272:
1273: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1274: $dom_in_use = $udom;
1275: $homeintdom = 1;
1276: } else {
1277: $dom_in_use = $serverhomedom;
1278: }
1279: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1280: unless (defined($cached)) {
1281: my %domconfig =
1282: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1283: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1284: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1285: }
1286: }
1287: if (ref($result) eq 'HASH') {
1288: ($is_balancer,$currtargets,$currrules) =
1289: &check_balancer_result($result,@hosts);
1290: if ($is_balancer) {
1291: if (ref($currrules) eq 'HASH') {
1292: if ($homeintdom) {
1293: if ($uname ne '') {
1294: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1295: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1296: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1297: $rule_in_effect = $currrules->{'_LC_author'};
1298: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1299: $rule_in_effect = $currrules->{'_LC_adv'}
1300: }
1301: }
1302: if ($rule_in_effect eq '') {
1303: my %userenv = &userenvironment($udom,$uname,'inststatus');
1304: if ($userenv{'inststatus'} ne '') {
1305: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1306: my ($othertitle,$usertypes,$types) =
1307: &Apache::loncommon::sorted_inst_types($udom);
1308: if (ref($types) eq 'ARRAY') {
1309: foreach my $type (@{$types}) {
1310: if (grep(/^\Q$type\E$/,@statuses)) {
1311: if (exists($currrules->{$type})) {
1312: $rule_in_effect = $currrules->{$type};
1313: }
1314: }
1315: }
1316: }
1317: } else {
1318: if (exists($currrules->{'default'})) {
1319: $rule_in_effect = $currrules->{'default'};
1320: }
1321: }
1322: }
1323: } else {
1324: if (exists($currrules->{'default'})) {
1325: $rule_in_effect = $currrules->{'default'};
1326: }
1327: }
1328: } else {
1329: if ($currrules->{'_LC_external'} ne '') {
1330: $rule_in_effect = $currrules->{'_LC_external'};
1331: }
1332: }
1333: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1334: $uname,$udom);
1335: }
1336: }
1337: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1338: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1339: unless (defined($cached)) {
1340: my %domconfig =
1341: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1342: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1343: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1344: }
1345: }
1346: if (ref($result) eq 'HASH') {
1347: ($is_balancer,$currtargets,$currrules) =
1348: &check_balancer_result($result,@hosts);
1349: if ($is_balancer) {
1350: if (ref($currrules) eq 'HASH') {
1351: if ($currrules->{'_LC_internetdom'} ne '') {
1352: $rule_in_effect = $currrules->{'_LC_internetdom'};
1353: }
1354: }
1355: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1356: $uname,$udom);
1357: }
1358: } else {
1359: if ($perlvar{'lonBalancer'} eq 'yes') {
1360: $is_balancer = 1;
1361: $offloadto = &this_host_spares($dom_in_use);
1362: }
1363: }
1364: } else {
1365: if ($perlvar{'lonBalancer'} eq 'yes') {
1366: $is_balancer = 1;
1367: $offloadto = &this_host_spares($dom_in_use);
1368: }
1369: }
1370: if ($is_balancer) {
1371: my $lowest_load = 30000;
1372: if (ref($offloadto) eq 'HASH') {
1373: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1374: foreach my $try_server (@{$offloadto->{'primary'}}) {
1375: ($otherserver,$lowest_load) =
1376: &compare_server_load($try_server,$otherserver,$lowest_load);
1377: }
1378: }
1379: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1380:
1381: if (!$found_server) {
1382: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1383: foreach my $try_server (@{$offloadto->{'default'}}) {
1384: ($otherserver,$lowest_load) =
1385: &compare_server_load($try_server,$otherserver,$lowest_load);
1386: }
1387: }
1388: }
1389: } elsif (ref($offloadto) eq 'ARRAY') {
1390: if (@{$offloadto} == 1) {
1391: $otherserver = $offloadto->[0];
1392: } elsif (@{$offloadto} > 1) {
1393: foreach my $try_server (@{$offloadto}) {
1394: ($otherserver,$lowest_load) =
1395: &compare_server_load($try_server,$otherserver,$lowest_load);
1396: }
1397: }
1398: }
1399: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1400: $is_balancer = 0;
1401: if ($uname ne '' && $udom ne '') {
1402: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1403:
1404: &appenv({'user.loadbalexempt' => $lonhost,
1405: 'user.loadbalcheck.time' => time});
1406: }
1407: }
1408: }
1409: }
1410: return ($is_balancer,$otherserver);
1411: }
1412:
1413: sub check_balancer_result {
1414: my ($result,@hosts) = @_;
1415: my ($is_balancer,$currtargets,$currrules);
1416: if (ref($result) eq 'HASH') {
1417: if ($result->{'lonhost'} ne '') {
1418: my $currbalancer = $result->{'lonhost'};
1419: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1420: $is_balancer = 1;
1421: $currtargets = $result->{'targets'};
1422: $currrules = $result->{'rules'};
1423: }
1424: } else {
1425: foreach my $key (keys(%{$result})) {
1426: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1427: (ref($result->{$key}) eq 'HASH')) {
1428: $is_balancer = 1;
1429: $currrules = $result->{$key}{'rules'};
1430: $currtargets = $result->{$key}{'targets'};
1431: last;
1432: }
1433: }
1434: }
1435: }
1436: return ($is_balancer,$currtargets,$currrules);
1437: }
1438:
1439: sub get_loadbalancer_targets {
1440: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1441: my $offloadto;
1442: if ($rule_in_effect eq 'none') {
1443: return [$perlvar{'lonHostID'}];
1444: } elsif ($rule_in_effect eq '') {
1445: $offloadto = $currtargets;
1446: } else {
1447: if ($rule_in_effect eq 'homeserver') {
1448: my $homeserver = &homeserver($uname,$udom);
1449: if ($homeserver ne 'no_host') {
1450: $offloadto = [$homeserver];
1451: }
1452: } elsif ($rule_in_effect eq 'externalbalancer') {
1453: my %domconfig =
1454: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1455: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1456: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1457: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1458: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1459: }
1460: }
1461: } else {
1462: my %servers = &internet_dom_servers($udom);
1463: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1464: if (&hostname($remotebalancer) ne '') {
1465: $offloadto = [$remotebalancer];
1466: }
1467: }
1468: } elsif (&hostname($rule_in_effect) ne '') {
1469: $offloadto = [$rule_in_effect];
1470: }
1471: }
1472: return $offloadto;
1473: }
1474:
1475: sub internet_dom_servers {
1476: my ($dom) = @_;
1477: my (%uniqservers,%servers);
1478: my $primaryserver = &hostname(&domain($dom,'primary'));
1479: my @machinedoms = &machine_domains($primaryserver);
1480: foreach my $mdom (@machinedoms) {
1481: my %currservers = %servers;
1482: my %server = &get_servers($mdom);
1483: %servers = (%currservers,%server);
1484: }
1485: my %by_hostname;
1486: foreach my $id (keys(%servers)) {
1487: push(@{$by_hostname{$servers{$id}}},$id);
1488: }
1489: foreach my $hostname (sort(keys(%by_hostname))) {
1490: if (@{$by_hostname{$hostname}} > 1) {
1491: my $match = 0;
1492: foreach my $id (@{$by_hostname{$hostname}}) {
1493: if (&host_domain($id) eq $dom) {
1494: $uniqservers{$id} = $hostname;
1495: $match = 1;
1496: }
1497: }
1498: unless ($match) {
1499: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1500: }
1501: } else {
1502: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1503: }
1504: }
1505: return %uniqservers;
1506: }
1507:
1508: # ---------------------- Find the homebase for a user from domain's lib servers
1509:
1510: my %homecache;
1511: sub homeserver {
1512: my ($uname,$udom,$ignoreBadCache)=@_;
1513: my $index="$uname:$udom";
1514:
1515: if (exists($homecache{$index})) { return $homecache{$index}; }
1516:
1517: my %servers = &get_servers($udom,'library');
1518: foreach my $tryserver (keys(%servers)) {
1519: next if ($ignoreBadCache ne 'true' &&
1520: exists($badServerCache{$tryserver}));
1521:
1522: my $answer=reply("home:$udom:$uname",$tryserver);
1523: if ($answer eq 'found') {
1524: delete($badServerCache{$tryserver});
1525: return $homecache{$index}=$tryserver;
1526: } elsif ($answer eq 'no_host') {
1527: $badServerCache{$tryserver}=1;
1528: }
1529: }
1530: return 'no_host';
1531: }
1532:
1533: # ------------------------------------- Find the usernames behind a list of IDs
1534:
1535: sub idget {
1536: my ($udom,@ids)=@_;
1537: my %returnhash=();
1538:
1539: my %servers = &get_servers($udom,'library');
1540: foreach my $tryserver (keys(%servers)) {
1541: my $idlist=join('&',@ids);
1542: $idlist=~tr/A-Z/a-z/;
1543: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1544: my @answer=();
1545: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1546: @answer=split(/\&/,$reply);
1547: } ;
1548: my $i;
1549: for ($i=0;$i<=$#ids;$i++) {
1550: if ($answer[$i]) {
1551: $returnhash{$ids[$i]}=$answer[$i];
1552: }
1553: }
1554: }
1555: return %returnhash;
1556: }
1557:
1558: # ------------------------------------- Find the IDs behind a list of usernames
1559:
1560: sub idrget {
1561: my ($udom,@unames)=@_;
1562: my %returnhash=();
1563: foreach my $uname (@unames) {
1564: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1565: }
1566: return %returnhash;
1567: }
1568:
1569: # ------------------------------- Store away a list of names and associated IDs
1570:
1571: sub idput {
1572: my ($udom,%ids)=@_;
1573: my %servers=();
1574: foreach my $uname (keys(%ids)) {
1575: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1576: my $uhom=&homeserver($uname,$udom);
1577: if ($uhom ne 'no_host') {
1578: my $id=&escape($ids{$uname});
1579: $id=~tr/A-Z/a-z/;
1580: my $esc_unam=&escape($uname);
1581: if ($servers{$uhom}) {
1582: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1583: } else {
1584: $servers{$uhom}=$id.'='.$esc_unam;
1585: }
1586: }
1587: }
1588: foreach my $server (keys(%servers)) {
1589: &critical('idput:'.$udom.':'.$servers{$server},$server);
1590: }
1591: }
1592:
1593: # ---------------------------------------- Delete unwanted IDs from ids.db file
1594:
1595: sub iddel {
1596: my ($udom,$idshashref,$uhome)=@_;
1597: my %result=();
1598: unless (ref($idshashref) eq 'HASH') {
1599: return %result;
1600: }
1601: my %servers=();
1602: while (my ($id,$uname) = each(%{$idshashref})) {
1603: my $uhom;
1604: if ($uhome) {
1605: $uhom = $uhome;
1606: } else {
1607: $uhom=&homeserver($uname,$udom);
1608: }
1609: if ($uhom ne 'no_host') {
1610: if ($servers{$uhom}) {
1611: $servers{$uhom}.='&'.&escape($id);
1612: } else {
1613: $servers{$uhom}=&escape($id);
1614: }
1615: }
1616: }
1617: foreach my $server (keys(%servers)) {
1618: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1619: }
1620: return %result;
1621: }
1622:
1623: # ------------------------------dump from db file owned by domainconfig user
1624: sub dump_dom {
1625: my ($namespace, $udom, $regexp) = @_;
1626:
1627: $udom ||= $env{'user.domain'};
1628:
1629: return () unless $udom;
1630:
1631: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1632: }
1633:
1634: # ------------------------------------------ get items from domain db files
1635:
1636: sub get_dom {
1637: my ($namespace,$storearr,$udom,$uhome)=@_;
1638: my $items='';
1639: foreach my $item (@$storearr) {
1640: $items.=&escape($item).'&';
1641: }
1642: $items=~s/\&$//;
1643: if (!$udom) {
1644: $udom=$env{'user.domain'};
1645: if (defined(&domain($udom,'primary'))) {
1646: $uhome=&domain($udom,'primary');
1647: } else {
1648: undef($uhome);
1649: }
1650: } else {
1651: if (!$uhome) {
1652: if (defined(&domain($udom,'primary'))) {
1653: $uhome=&domain($udom,'primary');
1654: }
1655: }
1656: }
1657: if ($udom && $uhome && ($uhome ne 'no_host')) {
1658: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1659: my %returnhash;
1660: if ($rep eq '' || $rep =~ /^error: 2 /) {
1661: return %returnhash;
1662: }
1663: my @pairs=split(/\&/,$rep);
1664: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1665: return @pairs;
1666: }
1667: my $i=0;
1668: foreach my $item (@$storearr) {
1669: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1670: $i++;
1671: }
1672: return %returnhash;
1673: } else {
1674: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1675: }
1676: }
1677:
1678: # -------------------------------------------- put items in domain db files
1679:
1680: sub put_dom {
1681: my ($namespace,$storehash,$udom,$uhome)=@_;
1682: if (!$udom) {
1683: $udom=$env{'user.domain'};
1684: if (defined(&domain($udom,'primary'))) {
1685: $uhome=&domain($udom,'primary');
1686: } else {
1687: undef($uhome);
1688: }
1689: } else {
1690: if (!$uhome) {
1691: if (defined(&domain($udom,'primary'))) {
1692: $uhome=&domain($udom,'primary');
1693: }
1694: }
1695: }
1696: if ($udom && $uhome && ($uhome ne 'no_host')) {
1697: my $items='';
1698: foreach my $item (keys(%$storehash)) {
1699: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1700: }
1701: $items=~s/\&$//;
1702: return &reply("putdom:$udom:$namespace:$items",$uhome);
1703: } else {
1704: &logthis("put_dom failed - no homeserver and/or domain");
1705: }
1706: }
1707:
1708: # --------------------- newput for items in db file owned by domainconfig user
1709: sub newput_dom {
1710: my ($namespace,$storehash,$udom) = @_;
1711: my $result;
1712: if (!$udom) {
1713: $udom=$env{'user.domain'};
1714: }
1715: if ($udom) {
1716: my $uname = &get_domainconfiguser($udom);
1717: $result = &newput($namespace,$storehash,$udom,$uname);
1718: }
1719: return $result;
1720: }
1721:
1722: # --------------------- delete for items in db file owned by domainconfig user
1723: sub del_dom {
1724: my ($namespace,$storearr,$udom)=@_;
1725: if (ref($storearr) eq 'ARRAY') {
1726: if (!$udom) {
1727: $udom=$env{'user.domain'};
1728: }
1729: if ($udom) {
1730: my $uname = &get_domainconfiguser($udom);
1731: return &del($namespace,$storearr,$udom,$uname);
1732: }
1733: }
1734: }
1735:
1736: # ----------------------------------construct domainconfig user for a domain
1737: sub get_domainconfiguser {
1738: my ($udom) = @_;
1739: return $udom.'-domainconfig';
1740: }
1741:
1742: sub retrieve_inst_usertypes {
1743: my ($udom) = @_;
1744: my (%returnhash,@order);
1745: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1746: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1747: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1748: %returnhash = %{$domdefs{'inststatustypes'}};
1749: @order = @{$domdefs{'inststatusorder'}};
1750: } else {
1751: if (defined(&domain($udom,'primary'))) {
1752: my $uhome=&domain($udom,'primary');
1753: my $rep=&reply("inst_usertypes:$udom",$uhome);
1754: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1755: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1756: return (\%returnhash,\@order);
1757: }
1758: my ($hashitems,$orderitems) = split(/:/,$rep);
1759: my @pairs=split(/\&/,$hashitems);
1760: foreach my $item (@pairs) {
1761: my ($key,$value)=split(/=/,$item,2);
1762: $key = &unescape($key);
1763: next if ($key =~ /^error: 2 /);
1764: $returnhash{$key}=&thaw_unescape($value);
1765: }
1766: my @esc_order = split(/\&/,$orderitems);
1767: foreach my $item (@esc_order) {
1768: push(@order,&unescape($item));
1769: }
1770: } else {
1771: &logthis("get_dom failed - no primary domain server for $udom");
1772: }
1773: }
1774: return (\%returnhash,\@order);
1775: }
1776:
1777: sub is_domainimage {
1778: my ($url) = @_;
1779: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1780: if (&domain($1) ne '') {
1781: return '1';
1782: }
1783: }
1784: return;
1785: }
1786:
1787: sub inst_directory_query {
1788: my ($srch) = @_;
1789: my $udom = $srch->{'srchdomain'};
1790: my %results;
1791: my $homeserver = &domain($udom,'primary');
1792: my $outcome;
1793: if ($homeserver ne '') {
1794: my $queryid=&reply("querysend:instdirsearch:".
1795: &escape($srch->{'srchby'}).':'.
1796: &escape($srch->{'srchterm'}).':'.
1797: &escape($srch->{'srchtype'}),$homeserver);
1798: my $host=&hostname($homeserver);
1799: if ($queryid !~/^\Q$host\E\_/) {
1800: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1801: return;
1802: }
1803: my $response = &get_query_reply($queryid);
1804: my $maxtries = 5;
1805: my $tries = 1;
1806: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1807: $response = &get_query_reply($queryid);
1808: $tries ++;
1809: }
1810:
1811: if (!&error($response) && $response ne 'refused') {
1812: if ($response eq 'unavailable') {
1813: $outcome = $response;
1814: } else {
1815: $outcome = 'ok';
1816: my @matches = split(/\n/,$response);
1817: foreach my $match (@matches) {
1818: my ($key,$value) = split(/=/,$match);
1819: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1820: }
1821: }
1822: }
1823: }
1824: return ($outcome,%results);
1825: }
1826:
1827: sub usersearch {
1828: my ($srch) = @_;
1829: my $dom = $srch->{'srchdomain'};
1830: my %results;
1831: my %libserv = &all_library();
1832: my $query = 'usersearch';
1833: foreach my $tryserver (keys(%libserv)) {
1834: if (&host_domain($tryserver) eq $dom) {
1835: my $host=&hostname($tryserver);
1836: my $queryid=
1837: &reply("querysend:".&escape($query).':'.
1838: &escape($srch->{'srchby'}).':'.
1839: &escape($srch->{'srchtype'}).':'.
1840: &escape($srch->{'srchterm'}),$tryserver);
1841: if ($queryid !~/^\Q$host\E\_/) {
1842: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1843: next;
1844: }
1845: my $reply = &get_query_reply($queryid);
1846: my $maxtries = 1;
1847: my $tries = 1;
1848: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1849: $reply = &get_query_reply($queryid);
1850: $tries ++;
1851: }
1852: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1853: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1854: } else {
1855: my @matches;
1856: if ($reply =~ /\n/) {
1857: @matches = split(/\n/,$reply);
1858: } else {
1859: @matches = split(/\&/,$reply);
1860: }
1861: foreach my $match (@matches) {
1862: my ($uname,$udom,%userhash);
1863: foreach my $entry (split(/:/,$match)) {
1864: my ($key,$value) =
1865: map {&unescape($_);} split(/=/,$entry);
1866: $userhash{$key} = $value;
1867: if ($key eq 'username') {
1868: $uname = $value;
1869: } elsif ($key eq 'domain') {
1870: $udom = $value;
1871: }
1872: }
1873: $results{$uname.':'.$udom} = \%userhash;
1874: }
1875: }
1876: }
1877: }
1878: return %results;
1879: }
1880:
1881: sub get_instuser {
1882: my ($udom,$uname,$id) = @_;
1883: my $homeserver = &domain($udom,'primary');
1884: my ($outcome,%results);
1885: if ($homeserver ne '') {
1886: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1887: &escape($id).':'.&escape($udom),$homeserver);
1888: my $host=&hostname($homeserver);
1889: if ($queryid !~/^\Q$host\E\_/) {
1890: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1891: return;
1892: }
1893: my $response = &get_query_reply($queryid);
1894: my $maxtries = 5;
1895: my $tries = 1;
1896: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1897: $response = &get_query_reply($queryid);
1898: $tries ++;
1899: }
1900: if (!&error($response) && $response ne 'refused') {
1901: if ($response eq 'unavailable') {
1902: $outcome = $response;
1903: } else {
1904: $outcome = 'ok';
1905: my @matches = split(/\n/,$response);
1906: foreach my $match (@matches) {
1907: my ($key,$value) = split(/=/,$match);
1908: $results{&unescape($key)} = &thaw_unescape($value);
1909: }
1910: }
1911: }
1912: }
1913: my %userinfo;
1914: if (ref($results{$uname}) eq 'HASH') {
1915: %userinfo = %{$results{$uname}};
1916: }
1917: return ($outcome,%userinfo);
1918: }
1919:
1920: sub inst_rulecheck {
1921: my ($udom,$uname,$id,$item,$rules) = @_;
1922: my %returnhash;
1923: if ($udom ne '') {
1924: if (ref($rules) eq 'ARRAY') {
1925: @{$rules} = map {&escape($_);} (@{$rules});
1926: my $rulestr = join(':',@{$rules});
1927: my $homeserver=&domain($udom,'primary');
1928: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1929: my $response;
1930: if ($item eq 'username') {
1931: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1932: ':'.&escape($uname).':'.$rulestr,
1933: $homeserver));
1934: } elsif ($item eq 'id') {
1935: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1936: ':'.&escape($id).':'.$rulestr,
1937: $homeserver));
1938: } elsif ($item eq 'selfcreate') {
1939: $response=&unescape(&reply('instselfcreatecheck:'.
1940: &escape($udom).':'.&escape($uname).
1941: ':'.$rulestr,$homeserver));
1942: }
1943: if ($response ne 'refused') {
1944: my @pairs=split(/\&/,$response);
1945: foreach my $item (@pairs) {
1946: my ($key,$value)=split(/=/,$item,2);
1947: $key = &unescape($key);
1948: next if ($key =~ /^error: 2 /);
1949: $returnhash{$key}=&thaw_unescape($value);
1950: }
1951: }
1952: }
1953: }
1954: }
1955: return %returnhash;
1956: }
1957:
1958: sub inst_userrules {
1959: my ($udom,$check) = @_;
1960: my (%ruleshash,@ruleorder);
1961: if ($udom ne '') {
1962: my $homeserver=&domain($udom,'primary');
1963: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1964: my $response;
1965: if ($check eq 'id') {
1966: $response=&reply('instidrules:'.&escape($udom),
1967: $homeserver);
1968: } elsif ($check eq 'email') {
1969: $response=&reply('instemailrules:'.&escape($udom),
1970: $homeserver);
1971: } else {
1972: $response=&reply('instuserrules:'.&escape($udom),
1973: $homeserver);
1974: }
1975: if (($response ne 'refused') && ($response ne 'error') &&
1976: ($response ne 'unknown_cmd') &&
1977: ($response ne 'no_such_host')) {
1978: my ($hashitems,$orderitems) = split(/:/,$response);
1979: my @pairs=split(/\&/,$hashitems);
1980: foreach my $item (@pairs) {
1981: my ($key,$value)=split(/=/,$item,2);
1982: $key = &unescape($key);
1983: next if ($key =~ /^error: 2 /);
1984: $ruleshash{$key}=&thaw_unescape($value);
1985: }
1986: my @esc_order = split(/\&/,$orderitems);
1987: foreach my $item (@esc_order) {
1988: push(@ruleorder,&unescape($item));
1989: }
1990: }
1991: }
1992: }
1993: return (\%ruleshash,\@ruleorder);
1994: }
1995:
1996: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1997:
1998: sub get_domain_defaults {
1999: my ($domain,$ignore_cache) = @_;
2000: return if (($domain eq '') || ($domain eq 'public'));
2001: my $cachetime = 60*60*24;
2002: unless ($ignore_cache) {
2003: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2004: if (defined($cached)) {
2005: if (ref($result) eq 'HASH') {
2006: return %{$result};
2007: }
2008: }
2009: }
2010: my %domdefaults;
2011: my %domconfig =
2012: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
2013: 'requestcourses','inststatus',
2014: 'coursedefaults','usersessions',
2015: 'requestauthor','selfenrollment'],$domain);
2016: my @coursetypes = ('official','unofficial','community','textbook');
2017: if (ref($domconfig{'defaults'}) eq 'HASH') {
2018: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2019: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2020: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
2021: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
2022: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
2023: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
2024: } else {
2025: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2026: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2027: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2028: }
2029: if (ref($domconfig{'quotas'}) eq 'HASH') {
2030: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2031: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2032: } else {
2033: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
2034: }
2035: my @usertools = ('aboutme','blog','webdav','portfolio');
2036: foreach my $item (@usertools) {
2037: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2038: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2039: }
2040: }
2041: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2042: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2043: }
2044: }
2045: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
2046: foreach my $item ('official','unofficial','community','textbook') {
2047: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2048: }
2049: }
2050: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2051: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2052: }
2053: if (ref($domconfig{'inststatus'}) eq 'HASH') {
2054: foreach my $item ('inststatustypes','inststatusorder') {
2055: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2056: }
2057: }
2058: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
2059: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
2060: foreach my $type (@coursetypes) {
2061: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2062: unless ($type eq 'community') {
2063: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2064: }
2065: }
2066: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2067: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2068: }
2069: }
2070: }
2071: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2072: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2073: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2074: }
2075: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2076: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2077: }
2078: }
2079: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2080: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2081: my @settings = ('types','registered','enroll_dates','access_dates','section',
2082: 'approval','limit');
2083: foreach my $type (@coursetypes) {
2084: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2085: my @mgrdc = ();
2086: foreach my $item (@settings) {
2087: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2088: push(@mgrdc,$item);
2089: }
2090: }
2091: if (@mgrdc) {
2092: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2093: }
2094: }
2095: }
2096: }
2097: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2098: foreach my $type (@coursetypes) {
2099: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2100: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2101: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2102: }
2103: }
2104: }
2105: }
2106: }
2107: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
2108: return %domdefaults;
2109: }
2110:
2111: # --------------------------------------------------- Assign a key to a student
2112:
2113: sub assign_access_key {
2114: #
2115: # a valid key looks like uname:udom#comments
2116: # comments are being appended
2117: #
2118: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2119: $kdom=
2120: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
2121: $knum=
2122: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
2123: $cdom=
2124: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2125: $cnum=
2126: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2127: $udom=$env{'user.name'} unless (defined($udom));
2128: $uname=$env{'user.domain'} unless (defined($uname));
2129: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
2130: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
2131: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
2132: # assigned to this person
2133: # - this should not happen,
2134: # unless something went wrong
2135: # the first time around
2136: # ready to assign
2137: $logentry=$1.'; '.$logentry;
2138: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
2139: $kdom,$knum) eq 'ok') {
2140: # key now belongs to user
2141: my $envkey='key.'.$cdom.'_'.$cnum;
2142: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
2143: &appenv({'environment.'.$envkey => $ckey});
2144: return 'ok';
2145: } else {
2146: return
2147: 'error: Count not permanently assign key, will need to be re-entered later.';
2148: }
2149: } else {
2150: return 'error: Could not assign key, try again later.';
2151: }
2152: } elsif (!$existing{$ckey}) {
2153: # the key does not exist
2154: return 'error: The key does not exist';
2155: } else {
2156: # the key is somebody else's
2157: return 'error: The key is already in use';
2158: }
2159: }
2160:
2161: # ------------------------------------------ put an additional comment on a key
2162:
2163: sub comment_access_key {
2164: #
2165: # a valid key looks like uname:udom#comments
2166: # comments are being appended
2167: #
2168: my ($ckey,$cdom,$cnum,$logentry)=@_;
2169: $cdom=
2170: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2171: $cnum=
2172: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2173: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2174: if ($existing{$ckey}) {
2175: $existing{$ckey}.='; '.$logentry;
2176: # ready to assign
2177: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
2178: $cdom,$cnum) eq 'ok') {
2179: return 'ok';
2180: } else {
2181: return 'error: Count not store comment.';
2182: }
2183: } else {
2184: # the key does not exist
2185: return 'error: The key does not exist';
2186: }
2187: }
2188:
2189: # ------------------------------------------------------ Generate a set of keys
2190:
2191: sub generate_access_keys {
2192: my ($number,$cdom,$cnum,$logentry)=@_;
2193: $cdom=
2194: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2195: $cnum=
2196: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2197: unless (&allowed('mky',$cdom)) { return 0; }
2198: unless (($cdom) && ($cnum)) { return 0; }
2199: if ($number>10000) { return 0; }
2200: sleep(2); # make sure don't get same seed twice
2201: srand(time()^($$+($$<<15))); # from "Programming Perl"
2202: my $total=0;
2203: for (my $i=1;$i<=$number;$i++) {
2204: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2205: sprintf("%lx",int(100000*rand)).'-'.
2206: sprintf("%lx",int(100000*rand));
2207: $newkey=~s/1/g/g; # folks mix up 1 and l
2208: $newkey=~s/0/h/g; # and also 0 and O
2209: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2210: if ($existing{$newkey}) {
2211: $i--;
2212: } else {
2213: if (&put('accesskeys',
2214: { $newkey => '# generated '.localtime().
2215: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
2216: '; '.$logentry },
2217: $cdom,$cnum) eq 'ok') {
2218: $total++;
2219: }
2220: }
2221: }
2222: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
2223: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2224: return $total;
2225: }
2226:
2227: # ------------------------------------------------------- Validate an accesskey
2228:
2229: sub validate_access_key {
2230: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2231: $cdom=
2232: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2233: $cnum=
2234: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2235: $udom=$env{'user.domain'} unless (defined($udom));
2236: $uname=$env{'user.name'} unless (defined($uname));
2237: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2238: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
2239: }
2240:
2241: # ------------------------------------- Find the section of student in a course
2242: sub devalidate_getsection_cache {
2243: my ($udom,$unam,$courseid)=@_;
2244: my $hashid="$udom:$unam:$courseid";
2245: &devalidate_cache_new('getsection',$hashid);
2246: }
2247:
2248: sub courseid_to_courseurl {
2249: my ($courseid) = @_;
2250: #already url style courseid
2251: return $courseid if ($courseid =~ m{^/});
2252:
2253: if (exists($env{'course.'.$courseid.'.num'})) {
2254: my $cnum = $env{'course.'.$courseid.'.num'};
2255: my $cdom = $env{'course.'.$courseid.'.domain'};
2256: return "/$cdom/$cnum";
2257: }
2258:
2259: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2260: if (exists($courseinfo{'num'})) {
2261: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2262: }
2263:
2264: return undef;
2265: }
2266:
2267: sub getsection {
2268: my ($udom,$unam,$courseid)=@_;
2269: my $cachetime=1800;
2270:
2271: my $hashid="$udom:$unam:$courseid";
2272: my ($result,$cached)=&is_cached_new('getsection',$hashid);
2273: if (defined($cached)) { return $result; }
2274:
2275: my %Pending;
2276: my %Expired;
2277: #
2278: # Each role can either have not started yet (pending), be active,
2279: # or have expired.
2280: #
2281: # If there is an active role, we are done.
2282: #
2283: # If there is more than one role which has not started yet,
2284: # choose the one which will start sooner
2285: # If there is one role which has not started yet, return it.
2286: #
2287: # If there is more than one expired role, choose the one which ended last.
2288: # If there is a role which has expired, return it.
2289: #
2290: $courseid = &courseid_to_courseurl($courseid);
2291: my %roleshash = &dump('roles',$udom,$unam,$courseid);
2292: foreach my $key (keys(%roleshash)) {
2293: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
2294: my $section=$1;
2295: if ($key eq $courseid.'_st') { $section=''; }
2296: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
2297: my $now=time;
2298: if (defined($end) && $end && ($now > $end)) {
2299: $Expired{$end}=$section;
2300: next;
2301: }
2302: if (defined($start) && $start && ($now < $start)) {
2303: $Pending{$start}=$section;
2304: next;
2305: }
2306: return &do_cache_new('getsection',$hashid,$section,$cachetime);
2307: }
2308: #
2309: # Presumedly there will be few matching roles from the above
2310: # loop and the sorting time will be negligible.
2311: if (scalar(keys(%Pending))) {
2312: my ($time) = sort {$a <=> $b} keys(%Pending);
2313: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
2314: }
2315: if (scalar(keys(%Expired))) {
2316: my @sorted = sort {$a <=> $b} keys(%Expired);
2317: my $time = pop(@sorted);
2318: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
2319: }
2320: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
2321: }
2322:
2323: sub save_cache {
2324: &purge_remembered();
2325: #&Apache::loncommon::validate_page();
2326: undef(%env);
2327: undef($env_loaded);
2328: }
2329:
2330: my $to_remember=-1;
2331: my %remembered;
2332: my %accessed;
2333: my $kicks=0;
2334: my $hits=0;
2335: sub make_key {
2336: my ($name,$id) = @_;
2337: if (length($id) > 65
2338: && length(&escape($id)) > 200) {
2339: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2340: }
2341: return &escape($name.':'.$id);
2342: }
2343:
2344: sub devalidate_cache_new {
2345: my ($name,$id,$debug) = @_;
2346: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
2347: $id=&make_key($name,$id);
2348: $memcache->delete($id);
2349: delete($remembered{$id});
2350: delete($accessed{$id});
2351: }
2352:
2353: sub is_cached_new {
2354: my ($name,$id,$debug) = @_;
2355: $id=&make_key($name,$id);
2356: if (exists($remembered{$id})) {
2357: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
2358: $accessed{$id}=[&gettimeofday()];
2359: $hits++;
2360: return ($remembered{$id},1);
2361: }
2362: my $value = $memcache->get($id);
2363: if (!(defined($value))) {
2364: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
2365: return (undef,undef);
2366: }
2367: if ($value eq '__undef__') {
2368: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2369: $value=undef;
2370: }
2371: &make_room($id,$value,$debug);
2372: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2373: return ($value,1);
2374: }
2375:
2376: sub do_cache_new {
2377: my ($name,$id,$value,$time,$debug) = @_;
2378: $id=&make_key($name,$id);
2379: my $setvalue=$value;
2380: if (!defined($setvalue)) {
2381: $setvalue='__undef__';
2382: }
2383: if (!defined($time) ) {
2384: $time=600;
2385: }
2386: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
2387: my $result = $memcache->set($id,$setvalue,$time);
2388: if (! $result) {
2389: &logthis("caching of id -> $id failed");
2390: $memcache->disconnect_all();
2391: }
2392: # need to make a copy of $value
2393: &make_room($id,$value,$debug);
2394: return $value;
2395: }
2396:
2397: sub make_room {
2398: my ($id,$value,$debug)=@_;
2399:
2400: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2401: : $value;
2402: if ($to_remember<0) { return; }
2403: $accessed{$id}=[&gettimeofday()];
2404: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2405: my $to_kick;
2406: my $max_time=0;
2407: foreach my $other (keys(%accessed)) {
2408: if (&tv_interval($accessed{$other}) > $max_time) {
2409: $to_kick=$other;
2410: $max_time=&tv_interval($accessed{$other});
2411: }
2412: }
2413: delete($remembered{$to_kick});
2414: delete($accessed{$to_kick});
2415: $kicks++;
2416: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
2417: return;
2418: }
2419:
2420: sub purge_remembered {
2421: #&logthis("Tossing ".scalar(keys(%remembered)));
2422: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
2423: undef(%remembered);
2424: undef(%accessed);
2425: }
2426: # ------------------------------------- Read an entry from a user's environment
2427:
2428: sub userenvironment {
2429: my ($udom,$unam,@what)=@_;
2430: my $items;
2431: foreach my $item (@what) {
2432: $items.=&escape($item).'&';
2433: }
2434: $items=~s/\&$//;
2435: my %returnhash=();
2436: my $uhome = &homeserver($unam,$udom);
2437: unless ($uhome eq 'no_host') {
2438: my @answer=split(/\&/,
2439: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
2440: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2441: return %returnhash;
2442: }
2443: my $i;
2444: for ($i=0;$i<=$#what;$i++) {
2445: $returnhash{$what[$i]}=&unescape($answer[$i]);
2446: }
2447: }
2448: return %returnhash;
2449: }
2450:
2451: # ---------------------------------------------------------- Get a studentphoto
2452: sub studentphoto {
2453: my ($udom,$unam,$ext) = @_;
2454: my $home=&Apache::lonnet::homeserver($unam,$udom);
2455: if (defined($env{'request.course.id'})) {
2456: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
2457: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2458: return(&retrievestudentphoto($udom,$unam,$ext));
2459: } else {
2460: my ($result,$perm_reqd)=
2461: &Apache::lonnet::auto_photo_permission($unam,$udom);
2462: if ($result eq 'ok') {
2463: if (!($perm_reqd eq 'yes')) {
2464: return(&retrievestudentphoto($udom,$unam,$ext));
2465: }
2466: }
2467: }
2468: }
2469: } else {
2470: my ($result,$perm_reqd) =
2471: &Apache::lonnet::auto_photo_permission($unam,$udom);
2472: if ($result eq 'ok') {
2473: if (!($perm_reqd eq 'yes')) {
2474: return(&retrievestudentphoto($udom,$unam,$ext));
2475: }
2476: }
2477: }
2478: return '/adm/lonKaputt/lonlogo_broken.gif';
2479: }
2480:
2481: sub retrievestudentphoto {
2482: my ($udom,$unam,$ext,$type) = @_;
2483: my $home=&Apache::lonnet::homeserver($unam,$udom);
2484: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2485: if ($ret eq 'ok') {
2486: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2487: if ($type eq 'thumbnail') {
2488: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2489: }
2490: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2491: return $tokenurl;
2492: } else {
2493: if ($type eq 'thumbnail') {
2494: return '/adm/lonKaputt/genericstudent_tn.gif';
2495: } else {
2496: return '/adm/lonKaputt/lonlogo_broken.gif';
2497: }
2498: }
2499: }
2500:
2501: # -------------------------------------------------------------------- New chat
2502:
2503: sub chatsend {
2504: my ($newentry,$anon,$group)=@_;
2505: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2506: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2507: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
2508: &reply('chatsend:'.$cdom.':'.$cnum.':'.
2509: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
2510: &escape($newentry)).':'.$group,$chome);
2511: }
2512:
2513: # ------------------------------------------ Find current version of a resource
2514:
2515: sub getversion {
2516: my $fname=&clutter(shift);
2517: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
2518: return ¤tversion(&filelocation('',$fname));
2519: }
2520:
2521: sub currentversion {
2522: my $fname=shift;
2523: my $author=$fname;
2524: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2525: my ($udom,$uname)=split(/\//,$author);
2526: my $home=&homeserver($uname,$udom);
2527: if ($home eq 'no_host') {
2528: return -1;
2529: }
2530: my $answer=&reply("currentversion:$fname",$home);
2531: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2532: return -1;
2533: }
2534: return $answer;
2535: }
2536:
2537: #
2538: # Return special version number of resource if set by override, empty otherwise
2539: #
2540: sub usedversion {
2541: my $fname=shift;
2542: unless ($fname) { $fname=$env{'request.uri'}; }
2543: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2544: if ($urlversion) { return $urlversion; }
2545: return '';
2546: }
2547:
2548: # ----------------------------- Subscribe to a resource, return URL if possible
2549:
2550: sub subscribe {
2551: my $fname=shift;
2552: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
2553: $fname=~s/[\n\r]//g;
2554: my $author=$fname;
2555: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2556: my ($udom,$uname)=split(/\//,$author);
2557: my $home=homeserver($uname,$udom);
2558: if ($home eq 'no_host') {
2559: return 'not_found';
2560: }
2561: my $answer=reply("sub:$fname",$home);
2562: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2563: $answer.=' by '.$home;
2564: }
2565: return $answer;
2566: }
2567:
2568: # -------------------------------------------------------------- Replicate file
2569:
2570: sub repcopy {
2571: my $filename=shift;
2572: $filename=~s/\/+/\//g;
2573: my $londocroot = $perlvar{'lonDocRoot'};
2574: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
2575: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
2576: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2577: $filename=~m{^/*(uploaded|editupload)/}) {
2578: return &repcopy_userfile($filename);
2579: }
2580: $filename=~s/[\n\r]//g;
2581: my $transname="$filename.in.transfer";
2582: # FIXME: this should flock
2583: if ((-e $filename) || (-e $transname)) { return 'ok'; }
2584: my $remoteurl=subscribe($filename);
2585: if ($remoteurl =~ /^con_lost by/) {
2586: &logthis("Subscribe returned $remoteurl: $filename");
2587: return 'unavailable';
2588: } elsif ($remoteurl eq 'not_found') {
2589: #&logthis("Subscribe returned not_found: $filename");
2590: return 'not_found';
2591: } elsif ($remoteurl =~ /^rejected by/) {
2592: &logthis("Subscribe returned $remoteurl: $filename");
2593: return 'forbidden';
2594: } elsif ($remoteurl eq 'directory') {
2595: return 'ok';
2596: } else {
2597: my $author=$filename;
2598: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2599: my ($udom,$uname)=split(/\//,$author);
2600: my $home=homeserver($uname,$udom);
2601: unless ($home eq $perlvar{'lonHostID'}) {
2602: my @parts=split(/\//,$filename);
2603: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2604: if ($path ne "$londocroot/res") {
2605: &logthis("Malconfiguration for replication: $filename");
2606: return 'bad_request';
2607: }
2608: my $count;
2609: for ($count=5;$count<$#parts;$count++) {
2610: $path.="/$parts[$count]";
2611: if ((-e $path)!=1) {
2612: mkdir($path,0777);
2613: }
2614: }
2615: my $ua=new LWP::UserAgent;
2616: my $request=new HTTP::Request('GET',"$remoteurl");
2617: my $response=$ua->request($request,$transname);
2618: if ($response->is_error()) {
2619: unlink($transname);
2620: my $message=$response->status_line;
2621: &logthis("<font color=\"blue\">WARNING:"
2622: ." LWP get: $message: $filename</font>");
2623: return 'unavailable';
2624: } else {
2625: if ($remoteurl!~/\.meta$/) {
2626: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2627: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2628: if ($mresponse->is_error()) {
2629: unlink($filename.'.meta');
2630: &logthis(
2631: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
2632: }
2633: }
2634: rename($transname,$filename);
2635: return 'ok';
2636: }
2637: }
2638: }
2639: }
2640:
2641: # ------------------------------------------------ Get server side include body
2642: sub ssi_body {
2643: my ($filelink,%form)=@_;
2644: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2645: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2646: }
2647: my $output='';
2648: my $response;
2649: if ($filelink=~/^https?\:/) {
2650: ($output,$response)=&externalssi($filelink);
2651: } else {
2652: $filelink .= $filelink=~/\?/ ? '&' : '?';
2653: $filelink .= 'inhibitmenu=yes';
2654: ($output,$response)=&ssi($filelink,%form);
2655: }
2656: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
2657: $output=~s/^.*?\<body[^\>]*\>//si;
2658: $output=~s/\<\/body\s*\>.*?$//si;
2659: if (wantarray) {
2660: return ($output, $response);
2661: } else {
2662: return $output;
2663: }
2664: }
2665:
2666: # --------------------------------------------------------- Server Side Include
2667:
2668: sub absolute_url {
2669: my ($host_name) = @_;
2670: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2671: if ($host_name eq '') {
2672: $host_name = $ENV{'SERVER_NAME'};
2673: }
2674: return $protocol.$host_name;
2675: }
2676:
2677: #
2678: # Server side include.
2679: # Parameters:
2680: # fn Possibly encrypted resource name/id.
2681: # form Hash that describes how the rendering should be done
2682: # and other things.
2683: # Returns:
2684: # Scalar context: The content of the response.
2685: # Array context: 2 element list of the content and the full response object.
2686: #
2687: sub ssi {
2688:
2689: my ($fn,%form)=@_;
2690: my $ua=new LWP::UserAgent;
2691: my $request;
2692:
2693: $form{'no_update_last_known'}=1;
2694: &Apache::lonenc::check_encrypt(\$fn);
2695: if (%form) {
2696: $request=new HTTP::Request('POST',&absolute_url().$fn);
2697: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
2698: } else {
2699: $request=new HTTP::Request('GET',&absolute_url().$fn);
2700: }
2701:
2702: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2703: my $response= $ua->request($request);
2704: my $content = $response->content;
2705:
2706:
2707: if (wantarray) {
2708: return ($content, $response);
2709: } else {
2710: return $content;
2711: }
2712: }
2713:
2714: sub externalssi {
2715: my ($url)=@_;
2716: my $ua=new LWP::UserAgent;
2717: my $request=new HTTP::Request('GET',$url);
2718: my $response=$ua->request($request);
2719: if (wantarray) {
2720: return ($response->content, $response);
2721: } else {
2722: return $response->content;
2723: }
2724: }
2725:
2726: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2727:
2728: sub allowuploaded {
2729: my ($srcurl,$url)=@_;
2730: $url=&clutter(&declutter($url));
2731: my $dir=$url;
2732: $dir=~s/\/[^\/]+$//;
2733: my %httpref=();
2734: my $httpurl=&hreflocation('',$url);
2735: $httpref{'httpref.'.$httpurl}=$srcurl;
2736: &Apache::lonnet::appenv(\%httpref);
2737: }
2738:
2739: #
2740: # Determine if the current user should be able to edit a particular resource,
2741: # when viewing in course context.
2742: # (a) When viewing resource used to determine if "Edit" item is included in
2743: # Functions.
2744: # (b) When displaying folder contents in course editor, used to determine if
2745: # "Edit" link will be displayed alongside resource.
2746: #
2747: # input: six args -- filename (decluttered), course number, course domain,
2748: # url, symb (if registered) and group (if this is a group
2749: # item -- e.g., bulletin board, group page etc.).
2750: # output: array of five scalars --
2751: # $cfile -- url for file editing if editable on current server
2752: # $home -- homeserver of resource (i.e., for author if published,
2753: # or course if uploaded.).
2754: # $switchserver -- 1 if server switch will be needed.
2755: # $forceedit -- 1 if icon/link should be to go to edit mode
2756: # $forceview -- 1 if icon/link should be to go to view mode
2757: #
2758:
2759: sub can_edit_resource {
2760: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2761: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2762: #
2763: # For aboutme pages user can only edit his/her own.
2764: #
2765: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
2766: my ($sdom,$sname) = ($1,$2);
2767: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2768: $home = $env{'user.home'};
2769: $cfile = $resurl;
2770: if ($env{'form.forceedit'}) {
2771: $forceview = 1;
2772: } else {
2773: $forceedit = 1;
2774: }
2775: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2776: } else {
2777: return;
2778: }
2779: }
2780:
2781: if ($env{'request.course.id'}) {
2782: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2783: if ($group ne '') {
2784: # if this is a group homepage or group bulletin board, check group privs
2785: my $allowed = 0;
2786: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2787: if ((&allowed('mdg',$env{'request.course.id'}.
2788: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2789: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2790: $allowed = 1;
2791: }
2792: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2793: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2794: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2795: $allowed = 1;
2796: }
2797: }
2798: if ($allowed) {
2799: $home=&homeserver($cnum,$cdom);
2800: if ($env{'form.forceedit'}) {
2801: $forceview = 1;
2802: } else {
2803: $forceedit = 1;
2804: }
2805: $cfile = $resurl;
2806: } else {
2807: return;
2808: }
2809: } else {
2810: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2811: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2812: return;
2813: }
2814: } elsif (!$crsedit) {
2815: #
2816: # No edit allowed where CC has switched to student role.
2817: #
2818: return;
2819: }
2820: }
2821: }
2822:
2823: if ($file ne '') {
2824: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
2825: if (&is_course_upload($file,$cnum,$cdom)) {
2826: $uploaded = 1;
2827: $incourse = 1;
2828: if ($file =~/\.(htm|html|css|js|txt)$/) {
2829: $cfile = &hreflocation('',$file);
2830: if ($env{'form.forceedit'}) {
2831: $forceview = 1;
2832: } else {
2833: $forceedit = 1;
2834: }
2835: }
2836: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2837: $incourse = 1;
2838: if ($env{'form.forceedit'}) {
2839: $forceview = 1;
2840: } else {
2841: $forceedit = 1;
2842: }
2843: $cfile = $resurl;
2844: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2845: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2846: $incourse = 1;
2847: if ($env{'form.forceedit'}) {
2848: $forceview = 1;
2849: } else {
2850: $forceedit = 1;
2851: }
2852: $cfile = $resurl;
2853: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
2854: $incourse = 1;
2855: $cfile = $resurl.'/smpedit';
2856: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
2857: $incourse = 1;
2858: if ($env{'form.forceedit'}) {
2859: $forceview = 1;
2860: } else {
2861: $forceedit = 1;
2862: }
2863: $cfile = $resurl;
2864: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2865: $incourse = 1;
2866: if ($env{'form.forceedit'}) {
2867: $forceview = 1;
2868: } else {
2869: $forceedit = 1;
2870: }
2871: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
2872: }
2873: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2874: my $template = '/res/lib/templates/simpleproblem.problem';
2875: if (&is_on_map($template)) {
2876: $incourse = 1;
2877: $forceview = 1;
2878: $cfile = $template;
2879: }
2880: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2881: $incourse = 1;
2882: if ($env{'form.forceedit'}) {
2883: $forceview = 1;
2884: } else {
2885: $forceedit = 1;
2886: }
2887: $cfile = $resurl;
2888: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2889: $incourse = 1;
2890: $forceview = 1;
2891: if ($symb) {
2892: my ($map,$id,$res)=&decode_symb($symb);
2893: $env{'request.symb'} = $symb;
2894: $cfile = &clutter($res);
2895: } else {
2896: $cfile = $env{'form.suppurl'};
2897: $cfile =~ s{^http://}{};
2898: $cfile = '/adm/wrapper/ext/'.$cfile;
2899: }
2900: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2901: if ($env{'form.forceedit'}) {
2902: $forceview = 1;
2903: } else {
2904: $forceedit = 1;
2905: }
2906: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
2907: }
2908: }
2909: if ($uploaded || $incourse) {
2910: $home=&homeserver($cnum,$cdom);
2911: } elsif ($file !~ m{/$}) {
2912: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2913: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2914: # Check that the user has permission to edit this resource
2915: my $setpriv = 1;
2916: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2917: if (defined($cfudom)) {
2918: $home=&homeserver($cfuname,$cfudom);
2919: $cfile=$file;
2920: }
2921: }
2922: if (($cfile ne '') && (!$incourse || $uploaded) &&
2923: (($home ne '') && ($home ne 'no_host'))) {
2924: my @ids=¤t_machine_ids();
2925: unless (grep(/^\Q$home\E$/,@ids)) {
2926: $switchserver=1;
2927: }
2928: }
2929: }
2930: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2931: }
2932:
2933: sub is_course_upload {
2934: my ($file,$cnum,$cdom) = @_;
2935: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2936: $uploadpath =~ s{^\/}{};
2937: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2938: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
2939: return 1;
2940: }
2941: return;
2942: }
2943:
2944: sub in_course {
2945: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2946: if ($hideprivileged) {
2947: my $skipuser;
2948: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2949: my @possdoms = ($cdom);
2950: if ($coursehash{'checkforpriv'}) {
2951: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
2952: }
2953: if (&privileged($uname,$udom,\@possdoms)) {
2954: $skipuser = 1;
2955: if ($coursehash{'nothideprivileged'}) {
2956: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2957: my $user;
2958: if ($item =~ /:/) {
2959: $user = $item;
2960: } else {
2961: $user = join(':',split(/[\@]/,$item));
2962: }
2963: if ($user eq $uname.':'.$udom) {
2964: undef($skipuser);
2965: last;
2966: }
2967: }
2968: }
2969: if ($skipuser) {
2970: return 0;
2971: }
2972: }
2973: }
2974: $type ||= 'any';
2975: if (!defined($cdom) || !defined($cnum)) {
2976: my $cid = $env{'request.course.id'};
2977: $cdom = $env{'course.'.$cid.'.domain'};
2978: $cnum = $env{'course.'.$cid.'.num'};
2979: }
2980: my $typesref;
2981: if (($type eq 'any') || ($type eq 'all')) {
2982: $typesref = ['active','previous','future'];
2983: } elsif ($type eq 'previous' || $type eq 'future') {
2984: $typesref = [$type];
2985: }
2986: my %roles = &get_my_roles($uname,$udom,'userroles',
2987: $typesref,undef,[$cdom]);
2988: my ($tmp) = keys(%roles);
2989: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
2990: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
2991: if (@course_roles > 0) {
2992: return 1;
2993: }
2994: return 0;
2995: }
2996:
2997: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
2998: # input: action, courseID, current domain, intended
2999: # path to file, source of file, instruction to parse file for objects,
3000: # ref to hash for embedded objects,
3001: # ref to hash for codebase of java objects.
3002: # reference to scalar to accommodate mime type determined
3003: # from File::MMagic if $parser = parse.
3004: #
3005: # output: url to file (if action was uploaddoc),
3006: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
3007: #
3008: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3009: # course.
3010: #
3011: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3012: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3013: # course's home server.
3014: #
3015: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3016: # be copied from $source (current location) to
3017: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3018: # and will then be copied to
3019: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3020: # course's home server.
3021: #
3022: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3023: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
3024: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3025: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3026: # in course's home server.
3027: #
3028:
3029: sub process_coursefile {
3030: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3031: $mimetype)=@_;
3032: my $fetchresult;
3033: my $home=&homeserver($docuname,$docudom);
3034: if ($action eq 'propagate') {
3035: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3036: $home);
3037: } else {
3038: my $fpath = '';
3039: my $fname = $file;
3040: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3041: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3042: my $filepath = &build_filepath($fpath);
3043: if ($action eq 'copy') {
3044: if ($source eq '') {
3045: $fetchresult = 'no source file';
3046: return $fetchresult;
3047: } else {
3048: my $destination = $filepath.'/'.$fname;
3049: rename($source,$destination);
3050: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3051: $home);
3052: }
3053: } elsif ($action eq 'uploaddoc') {
3054: open(my $fh,'>'.$filepath.'/'.$fname);
3055: print $fh $env{'form.'.$source};
3056: close($fh);
3057: if ($parser eq 'parse') {
3058: my $mm = new File::MMagic;
3059: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3060: if ($type eq 'text/html') {
3061: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3062: unless ($parse_result eq 'ok') {
3063: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3064: }
3065: }
3066: if (ref($mimetype)) {
3067: $$mimetype = $type;
3068: }
3069: }
3070: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3071: $home);
3072: if ($fetchresult eq 'ok') {
3073: return '/uploaded/'.$fpath.'/'.$fname;
3074: } else {
3075: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3076: ' to host '.$home.': '.$fetchresult);
3077: return '/adm/notfound.html';
3078: }
3079: }
3080: }
3081: unless ( $fetchresult eq 'ok') {
3082: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3083: ' to host '.$home.': '.$fetchresult);
3084: }
3085: return $fetchresult;
3086: }
3087:
3088: sub build_filepath {
3089: my ($fpath) = @_;
3090: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3091: unless ($fpath eq '') {
3092: my @parts=split('/',$fpath);
3093: foreach my $part (@parts) {
3094: $filepath.= '/'.$part;
3095: if ((-e $filepath)!=1) {
3096: mkdir($filepath,0777);
3097: }
3098: }
3099: }
3100: return $filepath;
3101: }
3102:
3103: sub store_edited_file {
3104: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
3105: my $file = $primary_url;
3106: $file =~ s#^/uploaded/$docudom/$docuname/##;
3107: my $fpath = '';
3108: my $fname = $file;
3109: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3110: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3111: my $filepath = &build_filepath($fpath);
3112: open(my $fh,'>'.$filepath.'/'.$fname);
3113: print $fh $content;
3114: close($fh);
3115: my $home=&homeserver($docuname,$docudom);
3116: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3117: $home);
3118: if ($$fetchresult eq 'ok') {
3119: return '/uploaded/'.$fpath.'/'.$fname;
3120: } else {
3121: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3122: ' to host '.$home.': '.$$fetchresult);
3123: return '/adm/notfound.html';
3124: }
3125: }
3126:
3127: sub clean_filename {
3128: my ($fname,$args)=@_;
3129: # Replace Windows backslashes by forward slashes
3130: $fname=~s/\\/\//g;
3131: if (!$args->{'keep_path'}) {
3132: # Get rid of everything but the actual filename
3133: $fname=~s/^.*\/([^\/]+)$/$1/;
3134: }
3135: # Replace spaces by underscores
3136: $fname=~s/\s+/\_/g;
3137: # Replace all other weird characters by nothing
3138: $fname=~s{[^/\w\.\-]}{}g;
3139: # Replace all .\d. sequences with _\d. so they no longer look like version
3140: # numbers
3141: $fname=~s/\.(\d+)(?=\.)/_$1/g;
3142: return $fname;
3143: }
3144: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3145: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3146: # image with the same aspect ratio as the original, but with dimensions which do
3147: # not exceed $resizewidth and $resizeheight.
3148:
3149: sub resizeImage {
3150: my ($img_path,$resizewidth,$resizeheight) = @_;
3151: my $ima = Image::Magick->new;
3152: my $resized;
3153: if (-e $img_path) {
3154: $ima->Read($img_path);
3155: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3156: my $width = $ima->Get('width');
3157: my $height = $ima->Get('height');
3158: if ($width > $resizewidth) {
3159: my $factor = $width/$resizewidth;
3160: my $newheight = $height/$factor;
3161: $ima->Scale(width=>$resizewidth,height=>$newheight);
3162: $resized = 1;
3163: }
3164: }
3165: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3166: my $width = $ima->Get('width');
3167: my $height = $ima->Get('height');
3168: if ($height > $resizeheight) {
3169: my $factor = $height/$resizeheight;
3170: my $newwidth = $width/$factor;
3171: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3172: $resized = 1;
3173: }
3174: }
3175: if ($resized) {
3176: $ima->Write($img_path);
3177: }
3178: }
3179: return;
3180: }
3181:
3182: # --------------- Take an uploaded file and put it into the userfiles directory
3183: # input: $formname - the contents of the file are in $env{"form.$formname"}
3184: # the desired filename is in $env{"form.$formname.filename"}
3185: # $context - possible values: coursedoc, existingfile, overwrite,
3186: # canceloverwrite, or ''.
3187: # if 'coursedoc': upload to the current course
3188: # if 'existingfile': write file to tmp/overwrites directory
3189: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3190: # $context is passed as argument to &finishuserfileupload
3191: # $subdir - directory in userfile to store the file into
3192: # $parser - instruction to parse file for objects ($parser = parse)
3193: # $allfiles - reference to hash for embedded objects
3194: # $codebase - reference to hash for codebase of java objects
3195: # $desuname - username for permanent storage of uploaded file
3196: # $dsetudom - domain for permanaent storage of uploaded file
3197: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3198: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
3199: # $resizewidth - width (pixels) to which to resize uploaded image
3200: # $resizeheight - height (pixels) to which to resize uploaded image
3201: # $mimetype - reference to scalar to accommodate mime type determined
3202: # from File::MMagic.
3203: #
3204: # output: url of file in userspace, or error: <message>
3205: # or /adm/notfound.html if failure to upload occurse
3206:
3207: sub userfileupload {
3208: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
3209: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
3210: if (!defined($subdir)) { $subdir='unknown'; }
3211: my $fname=$env{'form.'.$formname.'.filename'};
3212: $fname=&clean_filename($fname);
3213: # See if there is anything left
3214: unless ($fname) { return 'error: no uploaded file'; }
3215: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3216: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3217: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3218: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3219: my $now = time;
3220: my $filepath;
3221: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
3222: $filepath = 'tmp/helprequests/'.$now;
3223: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3224: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3225: '_'.$env{'user.domain'}.'/pending';
3226: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3227: my ($docuname,$docudom);
3228: if ($destudom) {
3229: $docudom = $destudom;
3230: } else {
3231: $docudom = $env{'user.domain'};
3232: }
3233: if ($destuname) {
3234: $docuname = $destuname;
3235: } else {
3236: $docuname = $env{'user.name'};
3237: }
3238: if (exists($env{'form.group'})) {
3239: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3240: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3241: }
3242: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3243: if ($context eq 'canceloverwrite') {
3244: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3245: if (-e $tempfile) {
3246: my @info = stat($tempfile);
3247: if ($info[9] eq $env{'form.timestamp'}) {
3248: unlink($tempfile);
3249: }
3250: }
3251: return;
3252: }
3253: }
3254: # Create the directory if not present
3255: my @parts=split(/\//,$filepath);
3256: my $fullpath = $perlvar{'lonDaemons'};
3257: for (my $i=0;$i<@parts;$i++) {
3258: $fullpath .= '/'.$parts[$i];
3259: if ((-e $fullpath)!=1) {
3260: mkdir($fullpath,0777);
3261: }
3262: }
3263: open(my $fh,'>'.$fullpath.'/'.$fname);
3264: print $fh $env{'form.'.$formname};
3265: close($fh);
3266: if ($context eq 'existingfile') {
3267: my @info = stat($fullpath.'/'.$fname);
3268: return ($fullpath.'/'.$fname,$info[9]);
3269: } else {
3270: return $fullpath.'/'.$fname;
3271: }
3272: }
3273: if ($subdir eq 'scantron') {
3274: $fname = 'scantron_orig_'.$fname;
3275: } else {
3276: $fname="$subdir/$fname";
3277: }
3278: if ($context eq 'coursedoc') {
3279: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3280: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3281: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
3282: return &finishuserfileupload($docuname,$docudom,
3283: $formname,$fname,$parser,$allfiles,
3284: $codebase,$thumbwidth,$thumbheight,
3285: $resizewidth,$resizeheight,$context,$mimetype);
3286: } else {
3287: if ($env{'form.folder'}) {
3288: $fname=$env{'form.folder'}.'/'.$fname;
3289: }
3290: return &process_coursefile('uploaddoc',$docuname,$docudom,
3291: $fname,$formname,$parser,
3292: $allfiles,$codebase,$mimetype);
3293: }
3294: } elsif (defined($destuname)) {
3295: my $docuname=$destuname;
3296: my $docudom=$destudom;
3297: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3298: $parser,$allfiles,$codebase,
3299: $thumbwidth,$thumbheight,
3300: $resizewidth,$resizeheight,$context,$mimetype);
3301: } else {
3302: my $docuname=$env{'user.name'};
3303: my $docudom=$env{'user.domain'};
3304: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
3305: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3306: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3307: }
3308: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3309: $parser,$allfiles,$codebase,
3310: $thumbwidth,$thumbheight,
3311: $resizewidth,$resizeheight,$context,$mimetype);
3312: }
3313: }
3314:
3315: sub finishuserfileupload {
3316: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
3317: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
3318: my $path=$docudom.'/'.$docuname.'/';
3319: my $filepath=$perlvar{'lonDocRoot'};
3320:
3321: my ($fnamepath,$file,$fetchthumb);
3322: $file=$fname;
3323: if ($fname=~m|/|) {
3324: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3325: $path.=$fnamepath.'/';
3326: }
3327: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
3328: my $count;
3329: for ($count=4;$count<=$#parts;$count++) {
3330: $filepath.="/$parts[$count]";
3331: if ((-e $filepath)!=1) {
3332: mkdir($filepath,0777);
3333: }
3334: }
3335:
3336: # Save the file
3337: {
3338: if (!open(FH,'>'.$filepath.'/'.$file)) {
3339: &logthis('Failed to create '.$filepath.'/'.$file);
3340: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3341: return '/adm/notfound.html';
3342: }
3343: if ($context eq 'overwrite') {
3344: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
3345: my $target = $filepath.'/'.$file;
3346: if (-e $source) {
3347: my @info = stat($source);
3348: if ($info[9] eq $env{'form.timestamp'}) {
3349: unless (&File::Copy::move($source,$target)) {
3350: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3351: return "Moving from $source failed";
3352: }
3353: } else {
3354: return "Temporary file: $source had unexpected date/time for last modification";
3355: }
3356: } else {
3357: return "Temporary file: $source missing";
3358: }
3359: } elsif (!print FH ($env{'form.'.$formname})) {
3360: &logthis('Failed to write to '.$filepath.'/'.$file);
3361: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3362: return '/adm/notfound.html';
3363: }
3364: close(FH);
3365: if ($resizewidth && $resizeheight) {
3366: my $mm = new File::MMagic;
3367: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3368: if ($mime_type =~ m{^image/}) {
3369: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3370: }
3371: }
3372: }
3373: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3374: if (ref($mimetype)) {
3375: if ($$mimetype eq '') {
3376: my $mm = new File::MMagic;
3377: my $type = $mm->checktype_filename($filepath.'/'.$file);
3378: $$mimetype = $type;
3379: }
3380: }
3381: }
3382: if ($parser eq 'parse') {
3383: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
3384: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3385: $allfiles,$codebase);
3386: unless ($parse_result eq 'ok') {
3387: &logthis('Failed to parse '.$filepath.$file.
3388: ' for embedded media: '.$parse_result);
3389: }
3390: }
3391: }
3392: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3393: my $input = $filepath.'/'.$file;
3394: my $output = $filepath.'/'.'tn-'.$file;
3395: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3396: system("convert -sample $thumbsize $input $output");
3397: if (-e $filepath.'/'.'tn-'.$file) {
3398: $fetchthumb = 1;
3399: }
3400: }
3401:
3402: # Notify homeserver to grep it
3403: #
3404: my $docuhome=&homeserver($docuname,$docudom);
3405: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
3406: if ($fetchresult eq 'ok') {
3407: if ($fetchthumb) {
3408: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3409: if ($thumbresult ne 'ok') {
3410: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3411: $docuhome.': '.$thumbresult);
3412: }
3413: }
3414: #
3415: # Return the URL to it
3416: return '/uploaded/'.$path.$file;
3417: } else {
3418: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3419: ': '.$fetchresult);
3420: return '/adm/notfound.html';
3421: }
3422: }
3423:
3424: sub extract_embedded_items {
3425: my ($fullpath,$allfiles,$codebase,$content) = @_;
3426: my @state = ();
3427: my (%lastids,%related,%shockwave,%flashvars);
3428: my %javafiles = (
3429: codebase => '',
3430: code => '',
3431: archive => ''
3432: );
3433: my %mediafiles = (
3434: src => '',
3435: movie => '',
3436: );
3437: my $p;
3438: if ($content) {
3439: $p = HTML::LCParser->new($content);
3440: } else {
3441: $p = HTML::LCParser->new($fullpath);
3442: }
3443: while (my $t=$p->get_token()) {
3444: if ($t->[0] eq 'S') {
3445: my ($tagname, $attr) = ($t->[1],$t->[2]);
3446: push(@state, $tagname);
3447: if (lc($tagname) eq 'allow') {
3448: &add_filetype($allfiles,$attr->{'src'},'src');
3449: }
3450: if (lc($tagname) eq 'img') {
3451: &add_filetype($allfiles,$attr->{'src'},'src');
3452: }
3453: if (lc($tagname) eq 'a') {
3454: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3455: &add_filetype($allfiles,$attr->{'href'},'href');
3456: }
3457: }
3458: if (lc($tagname) eq 'script') {
3459: my $src;
3460: if ($attr->{'archive'} =~ /\.jar$/i) {
3461: &add_filetype($allfiles,$attr->{'archive'},'archive');
3462: } else {
3463: if ($attr->{'src'} ne '') {
3464: $src = $attr->{'src'};
3465: &add_filetype($allfiles,$src,'src');
3466: }
3467: }
3468: my $text = $p->get_trimmed_text();
3469: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3470: my @swfargs = split(/,/,$1);
3471: foreach my $item (@swfargs) {
3472: $item =~ s/["']//g;
3473: $item =~ s/^\s+//;
3474: $item =~ s/\s+$//;
3475: }
3476: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3477: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3478: push(@{$related{$swfargs[0]}},$swfargs[2]);
3479: } else {
3480: $related{$swfargs[0]} = [$swfargs[2]];
3481: }
3482: }
3483: }
3484: }
3485: if (lc($tagname) eq 'link') {
3486: if (lc($attr->{'rel'}) eq 'stylesheet') {
3487: &add_filetype($allfiles,$attr->{'href'},'href');
3488: }
3489: }
3490: if (lc($tagname) eq 'object' ||
3491: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3492: foreach my $item (keys(%javafiles)) {
3493: $javafiles{$item} = '';
3494: }
3495: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3496: $lastids{lc($tagname)} = $attr->{'id'};
3497: }
3498: }
3499: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3500: my $name = lc($attr->{'name'});
3501: foreach my $item (keys(%javafiles)) {
3502: if ($name eq $item) {
3503: $javafiles{$item} = $attr->{'value'};
3504: last;
3505: }
3506: }
3507: my $pathfrom;
3508: foreach my $item (keys(%mediafiles)) {
3509: if ($name eq $item) {
3510: $pathfrom = $attr->{'value'};
3511: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3512: &add_filetype($allfiles,$pathfrom,$name);
3513: last;
3514: }
3515: }
3516: if ($name eq 'flashvars') {
3517: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3518: }
3519: if ($pathfrom ne '') {
3520: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3521: $pathfrom);
3522: }
3523: }
3524: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3525: foreach my $item (keys(%javafiles)) {
3526: if ($attr->{$item}) {
3527: $javafiles{$item} = $attr->{$item};
3528: last;
3529: }
3530: }
3531: foreach my $item (keys(%mediafiles)) {
3532: if ($attr->{$item}) {
3533: &add_filetype($allfiles,$attr->{$item},$item);
3534: last;
3535: }
3536: }
3537: if (lc($tagname) eq 'embed') {
3538: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3539: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3540: $attr->{'src'});
3541: }
3542: }
3543: }
3544: if (lc($tagname) eq 'iframe') {
3545: my $src = $attr->{'src'} ;
3546: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3547: &add_filetype($allfiles,$src,'src');
3548: } elsif ($src =~ m{^/}) {
3549: if ($env{'request.course.id'}) {
3550: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3551: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3552: my $url = &hreflocation('',$fullpath);
3553: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3554: my $relpath = $1;
3555: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3556: &add_filetype($allfiles,$1,'src');
3557: }
3558: }
3559: }
3560: }
3561: }
3562: if ($t->[4] =~ m{/>$}) {
3563: pop(@state);
3564: }
3565: } elsif ($t->[0] eq 'E') {
3566: my ($tagname) = ($t->[1]);
3567: if ($javafiles{'codebase'} ne '') {
3568: $javafiles{'codebase'} .= '/';
3569: }
3570: if (lc($tagname) eq 'applet' ||
3571: lc($tagname) eq 'object' ||
3572: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3573: ) {
3574: foreach my $item (keys(%javafiles)) {
3575: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3576: my $file=$javafiles{'codebase'}.$javafiles{$item};
3577: &add_filetype($allfiles,$file,$item);
3578: }
3579: }
3580: }
3581: pop @state;
3582: }
3583: }
3584: foreach my $id (sort(keys(%flashvars))) {
3585: if ($shockwave{$id} ne '') {
3586: my @pairs = split(/\&/,$flashvars{$id});
3587: foreach my $pair (@pairs) {
3588: my ($key,$value) = split(/\=/,$pair);
3589: if ($key eq 'thumb') {
3590: &add_filetype($allfiles,$value,$key);
3591: } elsif ($key eq 'content') {
3592: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3593: my ($ext) = ($value =~ /\.([^.]+)$/);
3594: if ($ext ne '') {
3595: &add_filetype($allfiles,$path.$value,$ext);
3596: }
3597: }
3598: }
3599: }
3600: }
3601: return 'ok';
3602: }
3603:
3604: sub add_filetype {
3605: my ($allfiles,$file,$type)=@_;
3606: if (exists($allfiles->{$file})) {
3607: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3608: push(@{$allfiles->{$file}}, &escape($type));
3609: }
3610: } else {
3611: @{$allfiles->{$file}} = (&escape($type));
3612: }
3613: }
3614:
3615: sub embedded_dependency {
3616: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3617: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3618: if (($identifier ne '') &&
3619: (ref($related->{$identifier}) eq 'ARRAY') &&
3620: ($pathfrom ne '')) {
3621: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3622: foreach my $dep (@{$related->{$identifier}}) {
3623: &add_filetype($allfiles,$path.$dep,'object');
3624: }
3625: }
3626: }
3627: return;
3628: }
3629:
3630: sub removeuploadedurl {
3631: my ($url)=@_;
3632: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
3633: return &removeuserfile($uname,$udom,$fname);
3634: }
3635:
3636: sub removeuserfile {
3637: my ($docuname,$docudom,$fname)=@_;
3638: my $home=&homeserver($docuname,$docudom);
3639: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
3640: if ($result eq 'ok') {
3641: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3642: my $metafile = $fname.'.meta';
3643: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
3644: my $url = "/uploaded/$docudom/$docuname/$fname";
3645: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
3646: my $sqlresult =
3647: &update_portfolio_table($docuname,$docudom,$file,
3648: 'portfolio_metadata',$group,
3649: 'delete');
3650: }
3651: }
3652: return $result;
3653: }
3654:
3655: sub mkdiruserfile {
3656: my ($docuname,$docudom,$dir)=@_;
3657: my $home=&homeserver($docuname,$docudom);
3658: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3659: }
3660:
3661: sub renameuserfile {
3662: my ($docuname,$docudom,$old,$new)=@_;
3663: my $home=&homeserver($docuname,$docudom);
3664: my $result = &reply("renameuserfile:$docudom:$docuname:".
3665: &escape("$old").':'.&escape("$new"),$home);
3666: if ($result eq 'ok') {
3667: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3668: my $oldmeta = $old.'.meta';
3669: my $newmeta = $new.'.meta';
3670: my $metaresult =
3671: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
3672: my $url = "/uploaded/$docudom/$docuname/$old";
3673: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
3674: my $sqlresult =
3675: &update_portfolio_table($docuname,$docudom,$file,
3676: 'portfolio_metadata',$group,
3677: 'delete');
3678: }
3679: }
3680: return $result;
3681: }
3682:
3683: # ------------------------------------------------------------------------- Log
3684:
3685: sub log {
3686: my ($dom,$nam,$hom,$what)=@_;
3687: return critical("log:$dom:$nam:$what",$hom);
3688: }
3689:
3690: # ------------------------------------------------------------------ Course Log
3691: #
3692: # This routine flushes several buffers of non-mission-critical nature
3693: #
3694:
3695: sub flushcourselogs {
3696: &logthis('Flushing log buffers');
3697: #
3698: # course logs
3699: # This is a log of all transactions in a course, which can be used
3700: # for data mining purposes
3701: #
3702: # It also collects the courseid database, which lists last transaction
3703: # times and course titles for all courseids
3704: #
3705: my %courseidbuffer=();
3706: foreach my $crsid (keys(%courselogs)) {
3707: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
3708: &escape($courselogs{$crsid}),
3709: $coursehombuf{$crsid}) eq 'ok') {
3710: delete $courselogs{$crsid};
3711: } else {
3712: &logthis('Failed to flush log buffer for '.$crsid);
3713: if (length($courselogs{$crsid})>40000) {
3714: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
3715: " exceeded maximum size, deleting.</font>");
3716: delete $courselogs{$crsid};
3717: }
3718: }
3719: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
3720: 'description' => $coursedescrbuf{$crsid},
3721: 'inst_code' => $courseinstcodebuf{$crsid},
3722: 'type' => $coursetypebuf{$crsid},
3723: 'owner' => $courseownerbuf{$crsid},
3724: };
3725: }
3726: #
3727: # Write course id database (reverse lookup) to homeserver of courses
3728: # Is used in pickcourse
3729: #
3730: foreach my $crs_home (keys(%courseidbuffer)) {
3731: my $response = &courseidput(&host_domain($crs_home),
3732: $courseidbuffer{$crs_home},
3733: $crs_home,'timeonly');
3734: }
3735: #
3736: # File accesses
3737: # Writes to the dynamic metadata of resources to get hit counts, etc.
3738: #
3739: foreach my $entry (keys(%accesshash)) {
3740: if ($entry =~ /___count$/) {
3741: my ($dom,$name);
3742: ($dom,$name,undef)=
3743: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
3744: if (! defined($dom) || $dom eq '' ||
3745: ! defined($name) || $name eq '') {
3746: my $cid = $env{'request.course.id'};
3747: $dom = $env{'request.'.$cid.'.domain'};
3748: $name = $env{'request.'.$cid.'.num'};
3749: }
3750: my $value = $accesshash{$entry};
3751: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3752: my %temphash=($url => $value);
3753: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3754: if ($result eq 'ok') {
3755: delete $accesshash{$entry};
3756: }
3757: } else {
3758: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
3759: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
3760: my %temphash=($entry => $accesshash{$entry});
3761: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3762: delete $accesshash{$entry};
3763: }
3764: }
3765: }
3766: #
3767: # Roles
3768: # Reverse lookup of user roles for course faculty/staff and co-authorship
3769: #
3770: foreach my $entry (keys(%userrolehash)) {
3771: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
3772: split(/\:/,$entry);
3773: if (&Apache::lonnet::put('nohist_userroles',
3774: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
3775: $rudom,$runame) eq 'ok') {
3776: delete $userrolehash{$entry};
3777: }
3778: }
3779: #
3780: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3781: #
3782: my %domrolebuffer = ();
3783: foreach my $entry (keys(%domainrolehash)) {
3784: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
3785: if ($domrolebuffer{$rudom}) {
3786: $domrolebuffer{$rudom}.='&'.&escape($entry).
3787: '='.&escape($domainrolehash{$entry});
3788: } else {
3789: $domrolebuffer{$rudom}.=&escape($entry).
3790: '='.&escape($domainrolehash{$entry});
3791: }
3792: delete $domainrolehash{$entry};
3793: }
3794: foreach my $dom (keys(%domrolebuffer)) {
3795: my %servers = &get_servers($dom,'library');
3796: foreach my $tryserver (keys(%servers)) {
3797: unless (&reply('domroleput:'.$dom.':'.
3798: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3799: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3800: }
3801: }
3802: }
3803: $dumpcount++;
3804: }
3805:
3806: sub courselog {
3807: my $what=shift;
3808: $what=time.':'.$what;
3809: unless ($env{'request.course.id'}) { return ''; }
3810: $coursedombuf{$env{'request.course.id'}}=
3811: $env{'course.'.$env{'request.course.id'}.'.domain'};
3812: $coursenumbuf{$env{'request.course.id'}}=
3813: $env{'course.'.$env{'request.course.id'}.'.num'};
3814: $coursehombuf{$env{'request.course.id'}}=
3815: $env{'course.'.$env{'request.course.id'}.'.home'};
3816: $coursedescrbuf{$env{'request.course.id'}}=
3817: $env{'course.'.$env{'request.course.id'}.'.description'};
3818: $courseinstcodebuf{$env{'request.course.id'}}=
3819: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3820: $courseownerbuf{$env{'request.course.id'}}=
3821: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
3822: $coursetypebuf{$env{'request.course.id'}}=
3823: $env{'course.'.$env{'request.course.id'}.'.type'};
3824: if (defined $courselogs{$env{'request.course.id'}}) {
3825: $courselogs{$env{'request.course.id'}}.='&'.$what;
3826: } else {
3827: $courselogs{$env{'request.course.id'}}.=$what;
3828: }
3829: if (length($courselogs{$env{'request.course.id'}})>4048) {
3830: &flushcourselogs();
3831: }
3832: }
3833:
3834: sub courseacclog {
3835: my $fnsymb=shift;
3836: unless ($env{'request.course.id'}) { return ''; }
3837: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
3838: if ($fnsymb=~/$LONCAPA::assess_re/) {
3839: $what.=':POST';
3840: # FIXME: Probably ought to escape things....
3841: foreach my $key (keys(%env)) {
3842: if ($key=~/^form\.(.*)/) {
3843: my $formitem = $1;
3844: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3845: $what.=':'.$formitem.'='.$env{$key};
3846: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3847: $what.=':'.$formitem.'='.$env{$key};
3848: }
3849: }
3850: }
3851: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3852: # FIXME: We should not be depending on a form parameter that someone
3853: # editing lonsearchcat.pm might change in the future.
3854: if ($env{'form.phase'} eq 'course_search') {
3855: $what.= ':POST';
3856: # FIXME: Probably ought to escape things....
3857: foreach my $element ('courseexp','crsfulltext','crsrelated',
3858: 'crsdiscuss') {
3859: $what.=':'.$element.'='.$env{'form.'.$element};
3860: }
3861: }
3862: }
3863: &courselog($what);
3864: }
3865:
3866: sub countacc {
3867: my $url=&declutter(shift);
3868: return if (! defined($url) || $url eq '');
3869: unless ($env{'request.course.id'}) { return ''; }
3870: #
3871: # Mark that this url was used in this course
3872: #
3873: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
3874: #
3875: # Increase the access count for this resource in this child process
3876: #
3877: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
3878: $accesshash{$key}++;
3879: }
3880:
3881: sub linklog {
3882: my ($from,$to)=@_;
3883: $from=&declutter($from);
3884: $to=&declutter($to);
3885: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3886: $accesshash{$to.'___'.$from.'___goto'}=1;
3887: }
3888:
3889: sub statslog {
3890: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3891: if ($users<2) { return; }
3892: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3893: 'course' => $env{'request.course.id'},
3894: 'sections' => '"all"',
3895: 'num_students' => $users,
3896: 'part' => $part,
3897: 'symb' => $symb,
3898: 'mean_tries' => $av_attempts,
3899: 'deg_of_diff' => $degdiff});
3900: foreach my $key (keys(%dynstore)) {
3901: $accesshash{$key}=$dynstore{$key};
3902: }
3903: }
3904:
3905: sub userrolelog {
3906: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
3907: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
3908: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3909: $userrolehash
3910: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3911: =$tend.':'.$tstart;
3912: }
3913: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
3914: $userrolehash
3915: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3916: =$tend.':'.$tstart;
3917: }
3918: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
3919: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3920: $domainrolehash
3921: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3922: = $tend.':'.$tstart;
3923: }
3924: }
3925:
3926: sub courserolelog {
3927: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3928: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3929: my $cdom = $1;
3930: my $cnum = $2;
3931: my $sec = $3;
3932: my $namespace = 'rolelog';
3933: my %storehash = (
3934: role => $trole,
3935: start => $tstart,
3936: end => $tend,
3937: selfenroll => $selfenroll,
3938: context => $context,
3939: );
3940: if ($trole eq 'gr') {
3941: $namespace = 'groupslog';
3942: $storehash{'group'} = $sec;
3943: } else {
3944: $storehash{'section'} = $sec;
3945: }
3946: &write_log('course',$namespace,\%storehash,$delflag,$username,
3947: $domain,$cnum,$cdom);
3948: if (($trole ne 'st') || ($sec ne '')) {
3949: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3950: }
3951: }
3952: return;
3953: }
3954:
3955: sub domainrolelog {
3956: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3957: if ($area =~ m{^/($match_domain)/$}) {
3958: my $cdom = $1;
3959: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
3960: my $namespace = 'rolelog';
3961: my %storehash = (
3962: role => $trole,
3963: start => $tstart,
3964: end => $tend,
3965: context => $context,
3966: );
3967: &write_log('domain',$namespace,\%storehash,$delflag,$username,
3968: $domain,$domconfiguser,$cdom);
3969: }
3970: return;
3971:
3972: }
3973:
3974: sub coauthorrolelog {
3975: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3976: if ($area =~ m{^/($match_domain)/($match_username)$}) {
3977: my $audom = $1;
3978: my $auname = $2;
3979: my $namespace = 'rolelog';
3980: my %storehash = (
3981: role => $trole,
3982: start => $tstart,
3983: end => $tend,
3984: context => $context,
3985: );
3986: &write_log('author',$namespace,\%storehash,$delflag,$username,
3987: $domain,$auname,$audom);
3988: }
3989: return;
3990: }
3991:
3992: sub get_course_adv_roles {
3993: my ($cid,$codes) = @_;
3994: $cid=$env{'request.course.id'} unless (defined($cid));
3995: my %coursehash=&coursedescription($cid);
3996: my $crstype = &Apache::loncommon::course_type($cid);
3997: my %nothide=();
3998: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3999: if ($user !~ /:/) {
4000: $nothide{join(':',split(/[\@]/,$user))}=1;
4001: } else {
4002: $nothide{$user}=1;
4003: }
4004: }
4005: my @possdoms = ($coursehash{'domain'});
4006: if ($coursehash{'checkforpriv'}) {
4007: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4008: }
4009: my %returnhash=();
4010: my %dumphash=
4011: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4012: my $now=time;
4013: my %privileged;
4014: foreach my $entry (keys(%dumphash)) {
4015: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4016: if (($tstart) && ($tstart<0)) { next; }
4017: if (($tend) && ($tend<$now)) { next; }
4018: if (($tstart) && ($now<$tstart)) { next; }
4019: my ($role,$username,$domain,$section)=split(/\:/,$entry);
4020: if ($username eq '' || $domain eq '') { next; }
4021: if ((&privileged($username,$domain,\@possdoms)) &&
4022: (!$nothide{$username.':'.$domain})) { next; }
4023: if ($role eq 'cr') { next; }
4024: if ($codes) {
4025: if ($section) { $role .= ':'.$section; }
4026: if ($returnhash{$role}) {
4027: $returnhash{$role}.=','.$username.':'.$domain;
4028: } else {
4029: $returnhash{$role}=$username.':'.$domain;
4030: }
4031: } else {
4032: my $key=&plaintext($role,$crstype);
4033: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
4034: if ($returnhash{$key}) {
4035: $returnhash{$key}.=','.$username.':'.$domain;
4036: } else {
4037: $returnhash{$key}=$username.':'.$domain;
4038: }
4039: }
4040: }
4041: return %returnhash;
4042: }
4043:
4044: sub get_my_roles {
4045: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
4046: unless (defined($uname)) { $uname=$env{'user.name'}; }
4047: unless (defined($udom)) { $udom=$env{'user.domain'}; }
4048: my (%dumphash,%nothide);
4049: if ($context eq 'userroles') {
4050: %dumphash = &dump('roles',$udom,$uname);
4051: } else {
4052: %dumphash = &dump('nohist_userroles',$udom,$uname);
4053: if ($hidepriv) {
4054: my %coursehash=&coursedescription($udom.'_'.$uname);
4055: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4056: if ($user !~ /:/) {
4057: $nothide{join(':',split(/[\@]/,$user))} = 1;
4058: } else {
4059: $nothide{$user} = 1;
4060: }
4061: }
4062: }
4063: }
4064: my %returnhash=();
4065: my $now=time;
4066: my %privileged;
4067: foreach my $entry (keys(%dumphash)) {
4068: my ($role,$tend,$tstart);
4069: if ($context eq 'userroles') {
4070: next if ($entry =~ /^rolesdef/);
4071: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4072: } else {
4073: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4074: }
4075: if (($tstart) && ($tstart<0)) { next; }
4076: my $status = 'active';
4077: if (($tend) && ($tend<=$now)) {
4078: $status = 'previous';
4079: }
4080: if (($tstart) && ($now<$tstart)) {
4081: $status = 'future';
4082: }
4083: if (ref($types) eq 'ARRAY') {
4084: if (!grep(/^\Q$status\E$/,@{$types})) {
4085: next;
4086: }
4087: } else {
4088: if ($status ne 'active') {
4089: next;
4090: }
4091: }
4092: my ($rolecode,$username,$domain,$section,$area);
4093: if ($context eq 'userroles') {
4094: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
4095: (undef,$domain,$username,$section) = split(/\//,$area);
4096: } else {
4097: ($role,$username,$domain,$section) = split(/\:/,$entry);
4098: }
4099: if (ref($roledoms) eq 'ARRAY') {
4100: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4101: next;
4102: }
4103: }
4104: if (ref($roles) eq 'ARRAY') {
4105: if (!grep(/^\Q$role\E$/,@{$roles})) {
4106: if ($role =~ /^cr\//) {
4107: if (!grep(/^cr$/,@{$roles})) {
4108: next;
4109: }
4110: } elsif ($role =~ /^gr\//) {
4111: if (!grep(/^gr$/,@{$roles})) {
4112: next;
4113: }
4114: } else {
4115: next;
4116: }
4117: }
4118: }
4119: if ($hidepriv) {
4120: my @privroles = ('dc','su');
4121: if ($context eq 'userroles') {
4122: next if (grep(/^\Q$role\E$/,@privroles));
4123: } else {
4124: my $possdoms = [$domain];
4125: if (ref($roledoms) eq 'ARRAY') {
4126: push(@{$possdoms},@{$roledoms});
4127: }
4128: if (&privileged($username,$domain,$possdoms,\@privroles)) {
4129: if (!$nothide{$username.':'.$domain}) {
4130: next;
4131: }
4132: }
4133: }
4134: }
4135: if ($withsec) {
4136: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4137: $tstart.':'.$tend;
4138: } else {
4139: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4140: }
4141: }
4142: return %returnhash;
4143: }
4144:
4145: # ----------------------------------------------------- Frontpage Announcements
4146: #
4147: #
4148:
4149: sub postannounce {
4150: my ($server,$text)=@_;
4151: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
4152: unless ($text=~/\w/) { $text=''; }
4153: return &reply('setannounce:'.&escape($text),$server);
4154: }
4155:
4156: sub getannounce {
4157:
4158: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
4159: my $announcement='';
4160: while (my $line = <$fh>) { $announcement .= $line; }
4161: close($fh);
4162: if ($announcement=~/\w/) {
4163: return
4164: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
4165: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
4166: } else {
4167: return '';
4168: }
4169: } else {
4170: return '';
4171: }
4172: }
4173:
4174: # ---------------------------------------------------------- Course ID routines
4175: # Deal with domain's nohist_courseid.db files
4176: #
4177:
4178: sub courseidput {
4179: my ($domain,$storehash,$coursehome,$caller) = @_;
4180: return unless (ref($storehash) eq 'HASH');
4181: my $outcome;
4182: if ($caller eq 'timeonly') {
4183: my $cids = '';
4184: foreach my $item (keys(%$storehash)) {
4185: $cids.=&escape($item).'&';
4186: }
4187: $cids=~s/\&$//;
4188: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4189: $coursehome);
4190: } else {
4191: my $items = '';
4192: foreach my $item (keys(%$storehash)) {
4193: $items.= &escape($item).'='.
4194: &freeze_escape($$storehash{$item}).'&';
4195: }
4196: $items=~s/\&$//;
4197: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4198: $coursehome);
4199: }
4200: if ($outcome eq 'unknown_cmd') {
4201: my $what;
4202: foreach my $cid (keys(%$storehash)) {
4203: $what .= &escape($cid).'=';
4204: foreach my $item ('description','inst_code','owner','type') {
4205: $what .= &escape($storehash->{$cid}{$item}).':';
4206: }
4207: $what =~ s/\:$/&/;
4208: }
4209: $what =~ s/\&$//;
4210: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4211: } else {
4212: return $outcome;
4213: }
4214: }
4215:
4216: sub courseiddump {
4217: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
4218: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
4219: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
4220: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
4221: $hasuniquecode)=@_;
4222: my $as_hash = 1;
4223: my %returnhash;
4224: if (!$domfilter) { $domfilter=''; }
4225: my %libserv = &all_library();
4226: foreach my $tryserver (keys(%libserv)) {
4227: if ( ( $hostidflag == 1
4228: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4229: || (!defined($hostidflag)) ) {
4230:
4231: if (($domfilter eq '') ||
4232: (&host_domain($tryserver) eq $domfilter)) {
4233: my $rep;
4234: if (grep { $_ eq $tryserver } current_machine_ids()) {
4235: $rep = LONCAPA::Lond::dump_course_id_handler(
4236: join(":", (&host_domain($tryserver), $sincefilter,
4237: &escape($descfilter), &escape($instcodefilter),
4238: &escape($ownerfilter), &escape($coursefilter),
4239: &escape($typefilter), &escape($regexp_ok),
4240: $as_hash, &escape($selfenrollonly),
4241: &escape($catfilter), $showhidden, $caller,
4242: &escape($cloner), &escape($cc_clone), $cloneonly,
4243: &escape($createdbefore), &escape($createdafter),
4244: &escape($creationcontext), $domcloner, $hasuniquecode)));
4245: } else {
4246: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4247: $sincefilter.':'.&escape($descfilter).':'.
4248: &escape($instcodefilter).':'.&escape($ownerfilter).
4249: ':'.&escape($coursefilter).':'.&escape($typefilter).
4250: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4251: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4252: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4253: &escape($cc_clone).':'.$cloneonly.':'.
4254: &escape($createdbefore).':'.&escape($createdafter).':'.
4255: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
4256: $tryserver);
4257: }
4258:
4259: my @pairs=split(/\&/,$rep);
4260: foreach my $item (@pairs) {
4261: my ($key,$value)=split(/\=/,$item,2);
4262: $key = &unescape($key);
4263: next if ($key =~ /^error: 2 /);
4264: my $result = &thaw_unescape($value);
4265: if (ref($result) eq 'HASH') {
4266: $returnhash{$key}=$result;
4267: } else {
4268: my @responses = split(/:/,$value);
4269: my @items = ('description','inst_code','owner','type');
4270: for (my $i=0; $i<@responses; $i++) {
4271: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
4272: }
4273: }
4274: }
4275: }
4276: }
4277: }
4278: return %returnhash;
4279: }
4280:
4281: sub courselastaccess {
4282: my ($cdom,$cnum,$hostidref) = @_;
4283: my %returnhash;
4284: if ($cdom && $cnum) {
4285: my $chome = &homeserver($cnum,$cdom);
4286: if ($chome ne 'no_host') {
4287: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4288: &extract_lastaccess(\%returnhash,$rep);
4289: }
4290: } else {
4291: if (!$cdom) { $cdom=''; }
4292: my %libserv = &all_library();
4293: foreach my $tryserver (keys(%libserv)) {
4294: if (ref($hostidref) eq 'ARRAY') {
4295: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4296: }
4297: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4298: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4299: &extract_lastaccess(\%returnhash,$rep);
4300: }
4301: }
4302: }
4303: return %returnhash;
4304: }
4305:
4306: sub extract_lastaccess {
4307: my ($returnhash,$rep) = @_;
4308: if (ref($returnhash) eq 'HASH') {
4309: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4310: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4311: $rep eq '') {
4312: my @pairs=split(/\&/,$rep);
4313: foreach my $item (@pairs) {
4314: my ($key,$value)=split(/\=/,$item,2);
4315: $key = &unescape($key);
4316: next if ($key =~ /^error: 2 /);
4317: $returnhash->{$key} = &thaw_unescape($value);
4318: }
4319: }
4320: }
4321: return;
4322: }
4323:
4324: # ---------------------------------------------------------- DC e-mail
4325:
4326: sub dcmailput {
4327: my ($domain,$msgid,$message,$server)=@_;
4328: my $status = &Apache::lonnet::critical(
4329: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4330: &escape($message),$server);
4331: return $status;
4332: }
4333:
4334: sub dcmaildump {
4335: my ($dom,$startdate,$enddate,$senders) = @_;
4336: my %returnhash=();
4337:
4338: if (defined(&domain($dom,'primary'))) {
4339: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4340: &escape($enddate).':';
4341: my @esc_senders=map { &escape($_)} @$senders;
4342: $cmd.=&escape(join('&',@esc_senders));
4343: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
4344: my ($key,$value) = split(/\=/,$line,2);
4345: if (($key) && ($value)) {
4346: $returnhash{&unescape($key)} = &unescape($value);
4347: }
4348: }
4349: }
4350: return %returnhash;
4351: }
4352: # ---------------------------------------------------------- Domain roles
4353:
4354: sub get_domain_roles {
4355: my ($dom,$roles,$startdate,$enddate)=@_;
4356: if ((!defined($startdate)) || ($startdate eq '')) {
4357: $startdate = '.';
4358: }
4359: if ((!defined($enddate)) || ($enddate eq '')) {
4360: $enddate = '.';
4361: }
4362: my $rolelist;
4363: if (ref($roles) eq 'ARRAY') {
4364: $rolelist = join('&',@{$roles});
4365: }
4366: my %personnel = ();
4367:
4368: my %servers = &get_servers($dom,'library');
4369: foreach my $tryserver (keys(%servers)) {
4370: %{$personnel{$tryserver}}=();
4371: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4372: &escape($startdate).':'.
4373: &escape($enddate).':'.
4374: &escape($rolelist), $tryserver))) {
4375: my ($key,$value) = split(/\=/,$line,2);
4376: if (($key) && ($value)) {
4377: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4378: }
4379: }
4380: }
4381: return %personnel;
4382: }
4383:
4384: # ----------------------------------------------------------- Interval timing
4385:
4386: {
4387: # Caches needed for speedup of navmaps
4388: # We don't want to cache this for very long at all (5 seconds at most)
4389: #
4390: # The user for whom we cache
4391: my $cachedkey='';
4392: # The cached times for this user
4393: my %cachedtimes=();
4394: # When this was last done
4395: my $cachedtime=();
4396:
4397: sub load_all_first_access {
4398: my ($uname,$udom)=@_;
4399: if (($cachedkey eq $uname.':'.$udom) &&
4400: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
4401: return;
4402: }
4403: $cachedtime=time;
4404: $cachedkey=$uname.':'.$udom;
4405: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
4406: }
4407:
4408: sub get_first_access {
4409: my ($type,$argsymb,$argmap)=@_;
4410: my ($symb,$courseid,$udom,$uname)=&whichuser();
4411: if ($argsymb) { $symb=$argsymb; }
4412: my ($map,$id,$res)=&decode_symb($symb);
4413: if ($argmap) { $map = $argmap; }
4414: if ($type eq 'course') {
4415: $res='course';
4416: } elsif ($type eq 'map') {
4417: $res=&symbread($map);
4418: } else {
4419: $res=$symb;
4420: }
4421: &load_all_first_access($uname,$udom);
4422: return $cachedtimes{"$courseid\0$res"};
4423: }
4424:
4425: sub set_first_access {
4426: my ($type,$interval)=@_;
4427: my ($symb,$courseid,$udom,$uname)=&whichuser();
4428: my ($map,$id,$res)=&decode_symb($symb);
4429: if ($type eq 'course') {
4430: $res='course';
4431: } elsif ($type eq 'map') {
4432: $res=&symbread($map);
4433: } else {
4434: $res=$symb;
4435: }
4436: $cachedkey='';
4437: my $firstaccess=&get_first_access($type,$symb,$map);
4438: if (!$firstaccess) {
4439: my $start = time;
4440: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4441: $udom,$uname);
4442: if ($putres eq 'ok') {
4443: &put('timerinterval',{"$courseid\0$res"=>$interval},
4444: $udom,$uname);
4445: &appenv(
4446: {
4447: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4448: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4449: }
4450: );
4451: }
4452: return $putres;
4453: }
4454: return 'already_set';
4455: }
4456: }
4457: # --------------------------------------------- Set Expire Date for Spreadsheet
4458:
4459: sub expirespread {
4460: my ($uname,$udom,$stype,$usymb)=@_;
4461: my $cid=$env{'request.course.id'};
4462: if ($cid) {
4463: my $now=time;
4464: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
4465: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4466: $env{'course.'.$cid.'.num'}.
4467: ':nohist_expirationdates:'.
4468: &escape($key).'='.$now,
4469: $env{'course.'.$cid.'.home'})
4470: }
4471: return 'ok';
4472: }
4473:
4474: # ----------------------------------------------------- Devalidate Spreadsheets
4475:
4476: sub devalidate {
4477: my ($symb,$uname,$udom)=@_;
4478: my $cid=$env{'request.course.id'};
4479: if ($cid) {
4480: # delete the stored spreadsheets for
4481: # - the student level sheet of this user in course's homespace
4482: # - the assessment level sheet for this resource
4483: # for this user in user's homespace
4484: # - current conditional state info
4485: my $key=$uname.':'.$udom.':';
4486: my $status=
4487: &del('nohist_calculatedsheets',
4488: [$key.'studentcalc:'],
4489: $env{'course.'.$cid.'.domain'},
4490: $env{'course.'.$cid.'.num'})
4491: .' '.
4492: &del('nohist_calculatedsheets_'.$cid,
4493: [$key.'assesscalc:'.$symb],$udom,$uname);
4494: unless ($status eq 'ok ok') {
4495: &logthis('Could not devalidate spreadsheet '.
4496: $uname.' at '.$udom.' for '.
4497: $symb.': '.$status);
4498: }
4499: &delenv('user.state.'.$cid);
4500: }
4501: }
4502:
4503: sub get_scalar {
4504: my ($string,$end) = @_;
4505: my $value;
4506: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4507: $value = $1;
4508: } elsif ($$string =~ s/^([^&]*?)&//) {
4509: $value = $1;
4510: }
4511: return &unescape($value);
4512: }
4513:
4514: sub array2str {
4515: my (@array) = @_;
4516: my $result=&arrayref2str(\@array);
4517: $result=~s/^__ARRAY_REF__//;
4518: $result=~s/__END_ARRAY_REF__$//;
4519: return $result;
4520: }
4521:
4522: sub arrayref2str {
4523: my ($arrayref) = @_;
4524: my $result='__ARRAY_REF__';
4525: foreach my $elem (@$arrayref) {
4526: if(ref($elem) eq 'ARRAY') {
4527: $result.=&arrayref2str($elem).'&';
4528: } elsif(ref($elem) eq 'HASH') {
4529: $result.=&hashref2str($elem).'&';
4530: } elsif(ref($elem)) {
4531: #print("Got a ref of ".(ref($elem))." skipping.");
4532: } else {
4533: $result.=&escape($elem).'&';
4534: }
4535: }
4536: $result=~s/\&$//;
4537: $result .= '__END_ARRAY_REF__';
4538: return $result;
4539: }
4540:
4541: sub hash2str {
4542: my (%hash) = @_;
4543: my $result=&hashref2str(\%hash);
4544: $result=~s/^__HASH_REF__//;
4545: $result=~s/__END_HASH_REF__$//;
4546: return $result;
4547: }
4548:
4549: sub hashref2str {
4550: my ($hashref)=@_;
4551: my $result='__HASH_REF__';
4552: foreach my $key (sort(keys(%$hashref))) {
4553: if (ref($key) eq 'ARRAY') {
4554: $result.=&arrayref2str($key).'=';
4555: } elsif (ref($key) eq 'HASH') {
4556: $result.=&hashref2str($key).'=';
4557: } elsif (ref($key)) {
4558: $result.='=';
4559: #print("Got a ref of ".(ref($key))." skipping.");
4560: } else {
4561: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
4562: }
4563:
4564: if(ref($hashref->{$key}) eq 'ARRAY') {
4565: $result.=&arrayref2str($hashref->{$key}).'&';
4566: } elsif(ref($hashref->{$key}) eq 'HASH') {
4567: $result.=&hashref2str($hashref->{$key}).'&';
4568: } elsif(ref($hashref->{$key})) {
4569: $result.='&';
4570: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
4571: } else {
4572: $result.=&escape($hashref->{$key}).'&';
4573: }
4574: }
4575: $result=~s/\&$//;
4576: $result .= '__END_HASH_REF__';
4577: return $result;
4578: }
4579:
4580: sub str2hash {
4581: my ($string)=@_;
4582: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4583: return %$hash;
4584: }
4585:
4586: sub str2hashref {
4587: my ($string) = @_;
4588:
4589: my %hash;
4590:
4591: if($string !~ /^__HASH_REF__/) {
4592: if (! ($string eq '' || !defined($string))) {
4593: $hash{'error'}='Not hash reference';
4594: }
4595: return (\%hash, $string);
4596: }
4597:
4598: $string =~ s/^__HASH_REF__//;
4599:
4600: while($string !~ /^__END_HASH_REF__/) {
4601: #key
4602: my $key='';
4603: if($string =~ /^__HASH_REF__/) {
4604: ($key, $string)=&str2hashref($string);
4605: if(defined($key->{'error'})) {
4606: $hash{'error'}='Bad data';
4607: return (\%hash, $string);
4608: }
4609: } elsif($string =~ /^__ARRAY_REF__/) {
4610: ($key, $string)=&str2arrayref($string);
4611: if($key->[0] eq 'Array reference error') {
4612: $hash{'error'}='Bad data';
4613: return (\%hash, $string);
4614: }
4615: } else {
4616: $string =~ s/^(.*?)=//;
4617: $key=&unescape($1);
4618: }
4619: $string =~ s/^=//;
4620:
4621: #value
4622: my $value='';
4623: if($string =~ /^__HASH_REF__/) {
4624: ($value, $string)=&str2hashref($string);
4625: if(defined($value->{'error'})) {
4626: $hash{'error'}='Bad data';
4627: return (\%hash, $string);
4628: }
4629: } elsif($string =~ /^__ARRAY_REF__/) {
4630: ($value, $string)=&str2arrayref($string);
4631: if($value->[0] eq 'Array reference error') {
4632: $hash{'error'}='Bad data';
4633: return (\%hash, $string);
4634: }
4635: } else {
4636: $value=&get_scalar(\$string,'__END_HASH_REF__');
4637: }
4638: $string =~ s/^&//;
4639:
4640: $hash{$key}=$value;
4641: }
4642:
4643: $string =~ s/^__END_HASH_REF__//;
4644:
4645: return (\%hash, $string);
4646: }
4647:
4648: sub str2array {
4649: my ($string)=@_;
4650: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4651: return @$array;
4652: }
4653:
4654: sub str2arrayref {
4655: my ($string) = @_;
4656: my @array;
4657:
4658: if($string !~ /^__ARRAY_REF__/) {
4659: if (! ($string eq '' || !defined($string))) {
4660: $array[0]='Array reference error';
4661: }
4662: return (\@array, $string);
4663: }
4664:
4665: $string =~ s/^__ARRAY_REF__//;
4666:
4667: while($string !~ /^__END_ARRAY_REF__/) {
4668: my $value='';
4669: if($string =~ /^__HASH_REF__/) {
4670: ($value, $string)=&str2hashref($string);
4671: if(defined($value->{'error'})) {
4672: $array[0] ='Array reference error';
4673: return (\@array, $string);
4674: }
4675: } elsif($string =~ /^__ARRAY_REF__/) {
4676: ($value, $string)=&str2arrayref($string);
4677: if($value->[0] eq 'Array reference error') {
4678: $array[0] ='Array reference error';
4679: return (\@array, $string);
4680: }
4681: } else {
4682: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4683: }
4684: $string =~ s/^&//;
4685:
4686: push(@array, $value);
4687: }
4688:
4689: $string =~ s/^__END_ARRAY_REF__//;
4690:
4691: return (\@array, $string);
4692: }
4693:
4694: # -------------------------------------------------------------------Temp Store
4695:
4696: sub tmpreset {
4697: my ($symb,$namespace,$domain,$stuname) = @_;
4698: if (!$symb) {
4699: $symb=&symbread();
4700: if (!$symb) { $symb= $env{'request.url'}; }
4701: }
4702: $symb=escape($symb);
4703:
4704: if (!$namespace) { $namespace=$env{'request.state'}; }
4705: $namespace=~s/\//\_/g;
4706: $namespace=~s/\W//g;
4707:
4708: if (!$domain) { $domain=$env{'user.domain'}; }
4709: if (!$stuname) { $stuname=$env{'user.name'}; }
4710: if ($domain eq 'public' && $stuname eq 'public') {
4711: $stuname=$ENV{'REMOTE_ADDR'};
4712: }
4713: my $path=LONCAPA::tempdir();
4714: my %hash;
4715: if (tie(%hash,'GDBM_File',
4716: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4717: &GDBM_WRCREAT(),0640)) {
4718: foreach my $key (keys(%hash)) {
4719: if ($key=~ /:$symb/) {
4720: delete($hash{$key});
4721: }
4722: }
4723: }
4724: }
4725:
4726: sub tmpstore {
4727: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4728:
4729: if (!$symb) {
4730: $symb=&symbread();
4731: if (!$symb) { $symb= $env{'request.url'}; }
4732: }
4733: $symb=escape($symb);
4734:
4735: if (!$namespace) {
4736: # I don't think we would ever want to store this for a course.
4737: # it seems this will only be used if we don't have a course.
4738: #$namespace=$env{'request.course.id'};
4739: #if (!$namespace) {
4740: $namespace=$env{'request.state'};
4741: #}
4742: }
4743: $namespace=~s/\//\_/g;
4744: $namespace=~s/\W//g;
4745: if (!$domain) { $domain=$env{'user.domain'}; }
4746: if (!$stuname) { $stuname=$env{'user.name'}; }
4747: if ($domain eq 'public' && $stuname eq 'public') {
4748: $stuname=$ENV{'REMOTE_ADDR'};
4749: }
4750: my $now=time;
4751: my %hash;
4752: my $path=LONCAPA::tempdir();
4753: if (tie(%hash,'GDBM_File',
4754: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4755: &GDBM_WRCREAT(),0640)) {
4756: $hash{"version:$symb"}++;
4757: my $version=$hash{"version:$symb"};
4758: my $allkeys='';
4759: foreach my $key (keys(%$storehash)) {
4760: $allkeys.=$key.':';
4761: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
4762: }
4763: $hash{"$version:$symb:timestamp"}=$now;
4764: $allkeys.='timestamp';
4765: $hash{"$version:keys:$symb"}=$allkeys;
4766: if (untie(%hash)) {
4767: return 'ok';
4768: } else {
4769: return "error:$!";
4770: }
4771: } else {
4772: return "error:$!";
4773: }
4774: }
4775:
4776: # -----------------------------------------------------------------Temp Restore
4777:
4778: sub tmprestore {
4779: my ($symb,$namespace,$domain,$stuname) = @_;
4780:
4781: if (!$symb) {
4782: $symb=&symbread();
4783: if (!$symb) { $symb= $env{'request.url'}; }
4784: }
4785: $symb=escape($symb);
4786:
4787: if (!$namespace) { $namespace=$env{'request.state'}; }
4788:
4789: if (!$domain) { $domain=$env{'user.domain'}; }
4790: if (!$stuname) { $stuname=$env{'user.name'}; }
4791: if ($domain eq 'public' && $stuname eq 'public') {
4792: $stuname=$ENV{'REMOTE_ADDR'};
4793: }
4794: my %returnhash;
4795: $namespace=~s/\//\_/g;
4796: $namespace=~s/\W//g;
4797: my %hash;
4798: my $path=LONCAPA::tempdir();
4799: if (tie(%hash,'GDBM_File',
4800: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4801: &GDBM_READER(),0640)) {
4802: my $version=$hash{"version:$symb"};
4803: $returnhash{'version'}=$version;
4804: my $scope;
4805: for ($scope=1;$scope<=$version;$scope++) {
4806: my $vkeys=$hash{"$scope:keys:$symb"};
4807: my @keys=split(/:/,$vkeys);
4808: my $key;
4809: $returnhash{"$scope:keys"}=$vkeys;
4810: foreach $key (@keys) {
4811: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4812: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4813: }
4814: }
4815: if (!(untie(%hash))) {
4816: return "error:$!";
4817: }
4818: } else {
4819: return "error:$!";
4820: }
4821: return %returnhash;
4822: }
4823:
4824: # ----------------------------------------------------------------------- Store
4825:
4826: sub store {
4827: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4828: my $home='';
4829:
4830: if ($stuname) { $home=&homeserver($stuname,$domain); }
4831:
4832: $symb=&symbclean($symb);
4833: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4834:
4835: if (!$domain) { $domain=$env{'user.domain'}; }
4836: if (!$stuname) { $stuname=$env{'user.name'}; }
4837:
4838: &devalidate($symb,$stuname,$domain);
4839:
4840: $symb=escape($symb);
4841: if (!$namespace) {
4842: unless ($namespace=$env{'request.course.id'}) {
4843: return '';
4844: }
4845: }
4846: if (!$home) { $home=$env{'user.home'}; }
4847:
4848: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4849: $$storehash{'host'}=$perlvar{'lonHostID'};
4850:
4851: my $namevalue='';
4852: foreach my $key (keys(%$storehash)) {
4853: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4854: }
4855: $namevalue=~s/\&$//;
4856: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
4857: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4858: }
4859:
4860: # -------------------------------------------------------------- Critical Store
4861:
4862: sub cstore {
4863: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4864: my $home='';
4865:
4866: if ($stuname) { $home=&homeserver($stuname,$domain); }
4867:
4868: $symb=&symbclean($symb);
4869: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4870:
4871: if (!$domain) { $domain=$env{'user.domain'}; }
4872: if (!$stuname) { $stuname=$env{'user.name'}; }
4873:
4874: &devalidate($symb,$stuname,$domain);
4875:
4876: $symb=escape($symb);
4877: if (!$namespace) {
4878: unless ($namespace=$env{'request.course.id'}) {
4879: return '';
4880: }
4881: }
4882: if (!$home) { $home=$env{'user.home'}; }
4883:
4884: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4885: $$storehash{'host'}=$perlvar{'lonHostID'};
4886:
4887: my $namevalue='';
4888: foreach my $key (keys(%$storehash)) {
4889: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4890: }
4891: $namevalue=~s/\&$//;
4892: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
4893: return critical
4894: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4895: }
4896:
4897: # --------------------------------------------------------------------- Restore
4898:
4899: sub restore {
4900: my ($symb,$namespace,$domain,$stuname) = @_;
4901: my $home='';
4902:
4903: if ($stuname) { $home=&homeserver($stuname,$domain); }
4904:
4905: if (!$symb) {
4906: return if ($namespace eq 'courserequests');
4907: unless ($symb=escape(&symbread())) { return ''; }
4908: } else {
4909: unless ($namespace eq 'courserequests') {
4910: $symb=&escape(&symbclean($symb));
4911: }
4912: }
4913: if (!$namespace) {
4914: unless ($namespace=$env{'request.course.id'}) {
4915: return '';
4916: }
4917: }
4918: if (!$domain) { $domain=$env{'user.domain'}; }
4919: if (!$stuname) { $stuname=$env{'user.name'}; }
4920: if (!$home) { $home=$env{'user.home'}; }
4921: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4922:
4923: my %returnhash=();
4924: foreach my $line (split(/\&/,$answer)) {
4925: my ($name,$value)=split(/\=/,$line);
4926: $returnhash{&unescape($name)}=&thaw_unescape($value);
4927: }
4928: my $version;
4929: for ($version=1;$version<=$returnhash{'version'};$version++) {
4930: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4931: $returnhash{$item}=$returnhash{$version.':'.$item};
4932: }
4933: }
4934: return %returnhash;
4935: }
4936:
4937: # ---------------------------------------------------------- Course Description
4938: #
4939: #
4940:
4941: sub coursedescription {
4942: my ($courseid,$args)=@_;
4943: $courseid=~s/^\///;
4944: $courseid=~s/\_/\//g;
4945: my ($cdomain,$cnum)=split(/\//,$courseid);
4946: my $chome=&homeserver($cnum,$cdomain);
4947: my $normalid=$cdomain.'_'.$cnum;
4948: # need to always cache even if we get errors otherwise we keep
4949: # trying and trying and trying to get the course description.
4950: my %envhash=();
4951: my %returnhash=();
4952:
4953: my $expiretime=600;
4954: if ($env{'request.course.id'} eq $normalid) {
4955: $expiretime=120;
4956: }
4957:
4958: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4959: if (!$args->{'freshen_cache'}
4960: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4961: foreach my $key (keys(%env)) {
4962: next if ($key !~ /^\Q$prefix\E(.*)/);
4963: my ($setting) = $1;
4964: $returnhash{$setting} = $env{$key};
4965: }
4966: return %returnhash;
4967: }
4968:
4969: # get the data again
4970:
4971: if (!$args->{'one_time'}) {
4972: $envhash{'course.'.$normalid.'.last_cache'}=time;
4973: }
4974:
4975: if ($chome ne 'no_host') {
4976: %returnhash=&dump('environment',$cdomain,$cnum);
4977: if (!exists($returnhash{'con_lost'})) {
4978: my $username = $env{'user.name'}; # Defult username
4979: if(defined $args->{'user'}) {
4980: $username = $args->{'user'};
4981: }
4982: $returnhash{'home'}= $chome;
4983: $returnhash{'domain'} = $cdomain;
4984: $returnhash{'num'} = $cnum;
4985: if (!defined($returnhash{'type'})) {
4986: $returnhash{'type'} = 'Course';
4987: }
4988: while (my ($name,$value) = each %returnhash) {
4989: $envhash{'course.'.$normalid.'.'.$name}=$value;
4990: }
4991: $returnhash{'url'}=&clutter($returnhash{'url'});
4992: $returnhash{'fn'}=LONCAPA::tempdir() .
4993: $username.'_'.$cdomain.'_'.$cnum;
4994: $envhash{'course.'.$normalid.'.home'}=$chome;
4995: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4996: $envhash{'course.'.$normalid.'.num'}=$cnum;
4997: }
4998: }
4999: if (!$args->{'one_time'}) {
5000: &appenv(\%envhash);
5001: }
5002: return %returnhash;
5003: }
5004:
5005: sub update_released_required {
5006: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5007: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5008: $cid = $env{'request.course.id'};
5009: $cdom = $env{'course.'.$cid.'.domain'};
5010: $cnum = $env{'course.'.$cid.'.num'};
5011: $chome = $env{'course.'.$cid.'.home'};
5012: }
5013: if ($needsrelease) {
5014: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5015: my $needsupdate;
5016: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5017: $needsupdate = 1;
5018: } else {
5019: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5020: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5021: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5022: $needsupdate = 1;
5023: }
5024: }
5025: if ($needsupdate) {
5026: my %needshash = (
5027: 'internal.releaserequired' => $needsrelease,
5028: );
5029: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5030: if ($putresult eq 'ok') {
5031: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5032: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5033: if (ref($crsinfo{$cid}) eq 'HASH') {
5034: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5035: &courseidput($cdom,\%crsinfo,$chome,'notime');
5036: }
5037: }
5038: }
5039: }
5040: return;
5041: }
5042:
5043: # -------------------------------------------------See if a user is privileged
5044:
5045: sub privileged {
5046: my ($username,$domain,$possdomains,$possroles)=@_;
5047: my $now = time;
5048: my $roles;
5049: if (ref($possroles) eq 'ARRAY') {
5050: $roles = $possroles;
5051: } else {
5052: $roles = ['dc','su'];
5053: }
5054: if (ref($possdomains) eq 'ARRAY') {
5055: my %privileged = &privileged_by_domain($possdomains,$roles);
5056: foreach my $dom (@{$possdomains}) {
5057: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5058: (ref($privileged{$dom}) eq 'HASH')) {
5059: foreach my $role (@{$roles}) {
5060: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5061: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5062: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5063: return 1 unless (($end && $end < $now) ||
5064: ($start && $start > $now));
5065: }
5066: }
5067: }
5068: }
5069: }
5070: } else {
5071: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5072: my $now = time;
5073:
5074: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
5075: my ($trole, $tend, $tstart) = split(/_/, $role);
5076: if (grep(/^\Q$trole\E$/,@{$roles})) {
5077: return 1 unless ($tend && $tend < $now)
5078: or ($tstart && $tstart > $now);
5079: }
5080: }
5081: }
5082: return 0;
5083: }
5084:
5085: sub privileged_by_domain {
5086: my ($domains,$roles) = @_;
5087: my %privileged = ();
5088: my $cachetime = 60*60*24;
5089: my $now = time;
5090: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5091: return %privileged;
5092: }
5093: foreach my $dom (@{$domains}) {
5094: next if (ref($privileged{$dom}) eq 'HASH');
5095: my $needroles;
5096: foreach my $role (@{$roles}) {
5097: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5098: if (defined($cached)) {
5099: if (ref($result) eq 'HASH') {
5100: $privileged{$dom}{$role} = $result;
5101: }
5102: } else {
5103: $needroles = 1;
5104: }
5105: }
5106: if ($needroles) {
5107: my %dompersonnel = &get_domain_roles($dom,$roles);
5108: $privileged{$dom} = {};
5109: foreach my $server (keys(%dompersonnel)) {
5110: if (ref($dompersonnel{$server}) eq 'HASH') {
5111: foreach my $item (keys(%{$dompersonnel{$server}})) {
5112: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5113: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5114: next if ($end && $end < $now);
5115: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5116: $dompersonnel{$server}{$item};
5117: }
5118: }
5119: }
5120: if (ref($privileged{$dom}) eq 'HASH') {
5121: foreach my $role (@{$roles}) {
5122: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5123: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5124: } else {
5125: my %hash = ();
5126: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5127: }
5128: }
5129: }
5130: }
5131: }
5132: return %privileged;
5133: }
5134:
5135: # -------------------------------------------------------- Get user privileges
5136:
5137: sub rolesinit {
5138: my ($domain, $username) = @_;
5139: my %userroles = ('user.login.time' => time);
5140: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5141:
5142: # firstaccess and timerinterval are related to timed maps/resources.
5143: # also, blocking can be triggered by an activating timer
5144: # it's saved in the user's %env.
5145: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5146: my %timerinterval = &dump('timerinterval', $domain, $username);
5147: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5148: %timerintchk, %timerintenv);
5149:
5150: foreach my $key (keys(%firstaccess)) {
5151: my ($cid, $rest) = split(/\0/, $key);
5152: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5153: }
5154:
5155: foreach my $key (keys(%timerinterval)) {
5156: my ($cid,$rest) = split(/\0/,$key);
5157: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5158: }
5159:
5160: my %allroles=();
5161: my %allgroups=();
5162:
5163: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
5164: my $role = $rolesdump{$area};
5165: $area =~ s/\_\w\w$//;
5166:
5167: my ($trole, $tend, $tstart, $group_privs);
5168:
5169: if ($role =~ /^cr/) {
5170: # Custom role, defined by a user
5171: # e.g., user.role.cr/msu/smith/mynewrole
5172: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5173: $trole = $1;
5174: ($tend, $tstart) = split('_', $2);
5175: } else {
5176: $trole = $role;
5177: }
5178: } elsif ($role =~ m|^gr/|) {
5179: # Role of member in a group, defined within a course/community
5180: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5181: ($trole, $tend, $tstart) = split(/_/, $role);
5182: next if $tstart eq '-1';
5183: ($trole, $group_privs) = split(/\//, $trole);
5184: $group_privs = &unescape($group_privs);
5185: } else {
5186: # Just a normal role, defined in roles.tab
5187: ($trole, $tend, $tstart) = split(/_/,$role);
5188: }
5189:
5190: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5191: $username);
5192: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5193:
5194: # role expired or not available yet?
5195: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5196: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5197:
5198: next if $area eq '' or $trole eq '';
5199:
5200: my $spec = "$trole.$area";
5201: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5202:
5203: if ($trole =~ /^cr\//) {
5204: # Custom role, defined by a user
5205: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5206: } elsif ($trole eq 'gr') {
5207: # Role of a member in a group, defined within a course/community
5208: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5209: next;
5210: } else {
5211: # Normal role, defined in roles.tab
5212: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5213: }
5214:
5215: my $cid = $tdomain.'_'.$trest;
5216: unless ($firstaccchk{$cid}) {
5217: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5218: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5219: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5220: $coursetimerstarts{$cid}{$item};
5221: }
5222: }
5223: $firstaccchk{$cid} = 1;
5224: }
5225: unless ($timerintchk{$cid}) {
5226: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5227: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5228: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5229: $coursetimerintervals{$cid}{$item};
5230: }
5231: }
5232: $timerintchk{$cid} = 1;
5233: }
5234: }
5235:
5236: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5237: \%allroles, \%allgroups);
5238: $env{'user.adv'} = $userroles{'user.adv'};
5239:
5240: return (\%userroles,\%firstaccenv,\%timerintenv);
5241: }
5242:
5243: sub set_arearole {
5244: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5245: unless ($nolog) {
5246: # log the associated role with the area
5247: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5248: }
5249: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
5250: }
5251:
5252: sub custom_roleprivs {
5253: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5254: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
5255: my $homsvr = &homeserver($rauthor,$rdomain);
5256: if (&hostname($homsvr) ne '') {
5257: my ($rdummy,$roledef)=
5258: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5259: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5260: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5261: if (defined($syspriv)) {
5262: if ($trest =~ /^$match_community$/) {
5263: $syspriv =~ s/bre\&S//;
5264: }
5265: $$allroles{'cm./'}.=':'.$syspriv;
5266: $$allroles{$spec.'./'}.=':'.$syspriv;
5267: }
5268: if ($tdomain ne '') {
5269: if (defined($dompriv)) {
5270: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5271: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5272: }
5273: if (($trest ne '') && (defined($coursepriv))) {
5274: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5275: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5276: }
5277: }
5278: }
5279: }
5280: }
5281:
5282: sub group_roleprivs {
5283: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5284: my $access = 1;
5285: my $now = time;
5286: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5287: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5288: if ($access) {
5289: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
5290: $$allgroups{$course}{$group} .=':'.$group_privs;
5291: }
5292: }
5293:
5294: sub standard_roleprivs {
5295: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5296: if (defined($pr{$trole.':s'})) {
5297: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5298: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5299: }
5300: if ($tdomain ne '') {
5301: if (defined($pr{$trole.':d'})) {
5302: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5303: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5304: }
5305: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5306: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5307: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5308: }
5309: }
5310: }
5311:
5312: sub set_userprivs {
5313: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
5314: my $author=0;
5315: my $adv=0;
5316: my %grouproles = ();
5317: if (keys(%{$allgroups}) > 0) {
5318: my @groupkeys;
5319: foreach my $role (keys(%{$allroles})) {
5320: push(@groupkeys,$role);
5321: }
5322: if (ref($groups_roles) eq 'HASH') {
5323: foreach my $key (keys(%{$groups_roles})) {
5324: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5325: push(@groupkeys,$key);
5326: }
5327: }
5328: }
5329: if (@groupkeys > 0) {
5330: foreach my $role (@groupkeys) {
5331: my ($trole,$area,$sec,$extendedarea);
5332: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5333: $trole = $1;
5334: $area = $2;
5335: $sec = $3;
5336: $extendedarea = $area.$sec;
5337: if (exists($$allgroups{$area})) {
5338: foreach my $group (keys(%{$$allgroups{$area}})) {
5339: my $spec = $trole.'.'.$extendedarea;
5340: $grouproles{$spec.'.'.$area.'/'.$group} =
5341: $$allgroups{$area}{$group};
5342: }
5343: }
5344: }
5345: }
5346: }
5347: }
5348: foreach my $group (keys(%grouproles)) {
5349: $$allroles{$group} = $grouproles{$group};
5350: }
5351: foreach my $role (keys(%{$allroles})) {
5352: my %thesepriv;
5353: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
5354: foreach my $item (split(/:/,$$allroles{$role})) {
5355: if ($item ne '') {
5356: my ($privilege,$restrictions)=split(/&/,$item);
5357: if ($restrictions eq '') {
5358: $thesepriv{$privilege}='F';
5359: } elsif ($thesepriv{$privilege} ne 'F') {
5360: $thesepriv{$privilege}.=$restrictions;
5361: }
5362: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5363: }
5364: }
5365: my $thesestr='';
5366: foreach my $priv (sort(keys(%thesepriv))) {
5367: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5368: }
5369: $userroles->{'user.priv.'.$role} = $thesestr;
5370: }
5371: return ($author,$adv);
5372: }
5373:
5374: sub role_status {
5375: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
5376: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
5377: my ($one,$two) = split(m{\./},$rolekey,2);
5378: (undef,undef,$$role) = split(/\./,$one,3);
5379: unless (!defined($$role) || $$role eq '') {
5380: $$where = '/'.$two;
5381: $$trolecode=$$role.'.'.$$where;
5382: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5383: $$tstatus='is';
5384: if ($$tstart && $$tstart>$update) {
5385: $$tstatus='future';
5386: if ($$tstart<$now) {
5387: if ($$tstart && $$tstart>$refresh) {
5388: if (($$where ne '') && ($$role ne '')) {
5389: my (%allroles,%allgroups,$group_privs,
5390: %groups_roles,@rolecodes);
5391: my %userroles = (
5392: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5393: );
5394: @rolecodes = ('cm');
5395: my $spec=$$role.'.'.$$where;
5396: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5397: if ($$role =~ /^cr\//) {
5398: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
5399: push(@rolecodes,'cr');
5400: } elsif ($$role eq 'gr') {
5401: push(@rolecodes,$$role);
5402: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5403: $env{'user.name'});
5404: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
5405: (undef,my $group_privs) = split(/\//,$trole);
5406: $group_privs = &unescape($group_privs);
5407: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
5408: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
5409: &get_groups_roles($tdomain,$trest,
5410: \%course_roles,\@rolecodes,
5411: \%groups_roles);
5412: } else {
5413: push(@rolecodes,$$role);
5414: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5415: }
5416: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5417: &appenv(\%userroles,\@rolecodes);
5418: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5419: }
5420: }
5421: $$tstatus = 'is';
5422: }
5423: }
5424: if ($$tend) {
5425: if ($$tend<$update) {
5426: $$tstatus='expired';
5427: } elsif ($$tend<$now) {
5428: $$tstatus='will_not';
5429: }
5430: }
5431: }
5432: }
5433: }
5434:
5435: sub get_groups_roles {
5436: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5437: return unless((ref($cdom_courseroles) eq 'HASH') &&
5438: (ref($rolecodes) eq 'ARRAY') &&
5439: (ref($groups_roles) eq 'HASH'));
5440: if (keys(%{$cdom_courseroles}) > 0) {
5441: my ($cnum) = ($rest =~ /^($match_courseid)/);
5442: if ($cdom ne '' && $cnum ne '') {
5443: foreach my $key (keys(%{$cdom_courseroles})) {
5444: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5445: my $crsrole = $1;
5446: my $crssec = $2;
5447: if ($crsrole =~ /^cr/) {
5448: unless (grep(/^cr$/,@{$rolecodes})) {
5449: push(@{$rolecodes},'cr');
5450: }
5451: } else {
5452: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5453: push(@{$rolecodes},$crsrole);
5454: }
5455: }
5456: my $rolekey = "$crsrole./$cdom/$cnum";
5457: if ($crssec ne '') {
5458: $rolekey .= "/$crssec";
5459: }
5460: $rolekey .= './';
5461: $groups_roles->{$rolekey} = $rolecodes;
5462: }
5463: }
5464: }
5465: }
5466: return;
5467: }
5468:
5469: sub delete_env_groupprivs {
5470: my ($where,$courseroles,$possroles) = @_;
5471: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5472: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5473: unless (ref($courseroles->{$udom}) eq 'HASH') {
5474: %{$courseroles->{$udom}} =
5475: &get_my_roles('','','userroles',['active'],
5476: $possroles,[$udom],1);
5477: }
5478: if (ref($courseroles->{$udom}) eq 'HASH') {
5479: foreach my $item (keys(%{$courseroles->{$udom}})) {
5480: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5481: my $area = '/'.$cdom.'/'.$cnum;
5482: my $privkey = "user.priv.$crsrole.$area";
5483: if ($crssec ne '') {
5484: $privkey .= '/'.$crssec;
5485: }
5486: $privkey .= ".$area/$group";
5487: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5488: }
5489: }
5490: return;
5491: }
5492:
5493: sub check_adhoc_privs {
5494: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
5495: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
5496: my $setprivs;
5497: if ($env{$cckey}) {
5498: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
5499: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
5500: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
5501: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
5502: $setprivs = 1;
5503: }
5504: } else {
5505: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
5506: $setprivs = 1;
5507: }
5508: return $setprivs;
5509: }
5510:
5511: sub set_adhoc_privileges {
5512: # role can be cc or ca
5513: my ($dcdom,$pickedcourse,$role,$caller) = @_;
5514: my $area = '/'.$dcdom.'/'.$pickedcourse;
5515: my $spec = $role.'.'.$area;
5516: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
5517: $env{'user.name'},1);
5518: my %ccrole = ();
5519: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5520: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5521: &appenv(\%userroles,[$role,'cm']);
5522: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5523: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5524: &appenv( {'request.role' => $spec,
5525: 'request.role.domain' => $dcdom,
5526: 'request.course.sec' => ''
5527: }
5528: );
5529: my $tadv=0;
5530: if (&allowed('adv') eq 'F') { $tadv=1; }
5531: &appenv({'request.role.adv' => $tadv});
5532: }
5533: }
5534:
5535: # --------------------------------------------------------------- get interface
5536:
5537: sub get {
5538: my ($namespace,$storearr,$udomain,$uname)=@_;
5539: my $items='';
5540: foreach my $item (@$storearr) {
5541: $items.=&escape($item).'&';
5542: }
5543: $items=~s/\&$//;
5544: if (!$udomain) { $udomain=$env{'user.domain'}; }
5545: if (!$uname) { $uname=$env{'user.name'}; }
5546: my $uhome=&homeserver($uname,$udomain);
5547:
5548: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
5549: my @pairs=split(/\&/,$rep);
5550: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5551: return @pairs;
5552: }
5553: my %returnhash=();
5554: my $i=0;
5555: foreach my $item (@$storearr) {
5556: $returnhash{$item}=&thaw_unescape($pairs[$i]);
5557: $i++;
5558: }
5559: return %returnhash;
5560: }
5561:
5562: # --------------------------------------------------------------- del interface
5563:
5564: sub del {
5565: my ($namespace,$storearr,$udomain,$uname)=@_;
5566: my $items='';
5567: foreach my $item (@$storearr) {
5568: $items.=&escape($item).'&';
5569: }
5570:
5571: $items=~s/\&$//;
5572: if (!$udomain) { $udomain=$env{'user.domain'}; }
5573: if (!$uname) { $uname=$env{'user.name'}; }
5574: my $uhome=&homeserver($uname,$udomain);
5575: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
5576: }
5577:
5578: # -------------------------------------------------------------- dump interface
5579:
5580: sub unserialize {
5581: my ($rep, $escapedkeys) = @_;
5582:
5583: return {} if $rep =~ /^error/;
5584:
5585: my %returnhash=();
5586: foreach my $item (split(/\&/,$rep)) {
5587: my ($key, $value) = split(/=/, $item, 2);
5588: $key = unescape($key) unless $escapedkeys;
5589: next if $key =~ /^error: 2 /;
5590: $returnhash{$key} = &thaw_unescape($value);
5591: }
5592: #return %returnhash;
5593: return \%returnhash;
5594: }
5595:
5596: # see Lond::dump_with_regexp
5597: # if $escapedkeys hash keys won't get unescaped.
5598: sub dump {
5599: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
5600: if (!$udomain) { $udomain=$env{'user.domain'}; }
5601: if (!$uname) { $uname=$env{'user.name'}; }
5602: my $uhome=&homeserver($uname,$udomain);
5603:
5604: my $reply;
5605: if (grep { $_ eq $uhome } current_machine_ids()) {
5606: # user is hosted on this machine
5607: $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
5608: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
5609: return %{unserialize($reply, $escapedkeys)};
5610: }
5611: if ($regexp) {
5612: $regexp=&escape($regexp);
5613: } else {
5614: $regexp='.';
5615: }
5616: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
5617: my @pairs=split(/\&/,$rep);
5618: my %returnhash=();
5619: if (!($rep =~ /^error/ )) {
5620: foreach my $item (@pairs) {
5621: my ($key,$value)=split(/=/,$item,2);
5622: $key = unescape($key) unless $escapedkeys;
5623: #$key = &unescape($key);
5624: next if ($key =~ /^error: 2 /);
5625: $returnhash{$key}=&thaw_unescape($value);
5626: }
5627: }
5628: return %returnhash;
5629: }
5630:
5631:
5632: # --------------------------------------------------------- dumpstore interface
5633:
5634: sub dumpstore {
5635: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
5636: # same as dump but keys must be escaped. They may contain colon separated
5637: # lists of values that may themself contain colons (e.g. symbs).
5638: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
5639: }
5640:
5641: # -------------------------------------------------------------- keys interface
5642:
5643: sub getkeys {
5644: my ($namespace,$udomain,$uname)=@_;
5645: if (!$udomain) { $udomain=$env{'user.domain'}; }
5646: if (!$uname) { $uname=$env{'user.name'}; }
5647: my $uhome=&homeserver($uname,$udomain);
5648: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5649: my @keyarray=();
5650: foreach my $key (split(/\&/,$rep)) {
5651: next if ($key =~ /^error: 2 /);
5652: push(@keyarray,&unescape($key));
5653: }
5654: return @keyarray;
5655: }
5656:
5657: # --------------------------------------------------------------- currentdump
5658: sub currentdump {
5659: my ($courseid,$sdom,$sname)=@_;
5660: $courseid = $env{'request.course.id'} if (! defined($courseid));
5661: $sdom = $env{'user.domain'} if (! defined($sdom));
5662: $sname = $env{'user.name'} if (! defined($sname));
5663: my $uhome = &homeserver($sname,$sdom);
5664: my $rep;
5665:
5666: if (grep { $_ eq $uhome } current_machine_ids()) {
5667: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5668: $courseid)));
5669: } else {
5670: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5671: }
5672:
5673: return if ($rep =~ /^(error:|no_such_host)/);
5674: #
5675: my %returnhash=();
5676: #
5677: if ($rep eq "unknown_cmd") {
5678: # an old lond will not know currentdump
5679: # Do a dump and make it look like a currentdump
5680: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
5681: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5682: my %hash = @tmp;
5683: @tmp=();
5684: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
5685: } else {
5686: my @pairs=split(/\&/,$rep);
5687: foreach my $pair (@pairs) {
5688: my ($key,$value)=split(/=/,$pair,2);
5689: my ($symb,$param) = split(/:/,$key);
5690: $returnhash{&unescape($symb)}->{&unescape($param)} =
5691: &thaw_unescape($value);
5692: }
5693: }
5694: return %returnhash;
5695: }
5696:
5697: sub convert_dump_to_currentdump{
5698: my %hash = %{shift()};
5699: my %returnhash;
5700: # Code ripped from lond, essentially. The only difference
5701: # here is the unescaping done by lonnet::dump(). Conceivably
5702: # we might run in to problems with parameter names =~ /^v\./
5703: while (my ($key,$value) = each(%hash)) {
5704: my ($v,$symb,$param) = split(/:/,$key);
5705: $symb = &unescape($symb);
5706: $param = &unescape($param);
5707: next if ($v eq 'version' || $symb eq 'keys');
5708: next if (exists($returnhash{$symb}) &&
5709: exists($returnhash{$symb}->{$param}) &&
5710: $returnhash{$symb}->{'v.'.$param} > $v);
5711: $returnhash{$symb}->{$param}=$value;
5712: $returnhash{$symb}->{'v.'.$param}=$v;
5713: }
5714: #
5715: # Remove all of the keys in the hashes which keep track of
5716: # the version of the parameter.
5717: while (my ($symb,$param_hash) = each(%returnhash)) {
5718: # use a foreach because we are going to delete from the hash.
5719: foreach my $key (keys(%$param_hash)) {
5720: delete($param_hash->{$key}) if ($key =~ /^v\./);
5721: }
5722: }
5723: return \%returnhash;
5724: }
5725:
5726: # ------------------------------------------------------ critical inc interface
5727:
5728: sub cinc {
5729: return &inc(@_,'critical');
5730: }
5731:
5732: # --------------------------------------------------------------- inc interface
5733:
5734: sub inc {
5735: my ($namespace,$store,$udomain,$uname,$critical) = @_;
5736: if (!$udomain) { $udomain=$env{'user.domain'}; }
5737: if (!$uname) { $uname=$env{'user.name'}; }
5738: my $uhome=&homeserver($uname,$udomain);
5739: my $items='';
5740: if (! ref($store)) {
5741: # got a single value, so use that instead
5742: $items = &escape($store).'=&';
5743: } elsif (ref($store) eq 'SCALAR') {
5744: $items = &escape($$store).'=&';
5745: } elsif (ref($store) eq 'ARRAY') {
5746: $items = join('=&',map {&escape($_);} @{$store});
5747: } elsif (ref($store) eq 'HASH') {
5748: while (my($key,$value) = each(%{$store})) {
5749: $items.= &escape($key).'='.&escape($value).'&';
5750: }
5751: }
5752: $items=~s/\&$//;
5753: if ($critical) {
5754: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5755: } else {
5756: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5757: }
5758: }
5759:
5760: # --------------------------------------------------------------- put interface
5761:
5762: sub put {
5763: my ($namespace,$storehash,$udomain,$uname)=@_;
5764: if (!$udomain) { $udomain=$env{'user.domain'}; }
5765: if (!$uname) { $uname=$env{'user.name'}; }
5766: my $uhome=&homeserver($uname,$udomain);
5767: my $items='';
5768: foreach my $item (keys(%$storehash)) {
5769: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5770: }
5771: $items=~s/\&$//;
5772: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
5773: }
5774:
5775: # ------------------------------------------------------------ newput interface
5776:
5777: sub newput {
5778: my ($namespace,$storehash,$udomain,$uname)=@_;
5779: if (!$udomain) { $udomain=$env{'user.domain'}; }
5780: if (!$uname) { $uname=$env{'user.name'}; }
5781: my $uhome=&homeserver($uname,$udomain);
5782: my $items='';
5783: foreach my $key (keys(%$storehash)) {
5784: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5785: }
5786: $items=~s/\&$//;
5787: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5788: }
5789:
5790: # --------------------------------------------------------- putstore interface
5791:
5792: sub putstore {
5793: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5794: if (!$udomain) { $udomain=$env{'user.domain'}; }
5795: if (!$uname) { $uname=$env{'user.name'}; }
5796: my $uhome=&homeserver($uname,$udomain);
5797: my $items='';
5798: foreach my $key (keys(%$storehash)) {
5799: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
5800: }
5801: $items=~s/\&$//;
5802: my $esc_symb=&escape($symb);
5803: my $esc_v=&escape($version);
5804: my $reply =
5805: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
5806: $uhome);
5807: if ($reply eq 'unknown_cmd') {
5808: # gfall back to way things use to be done
5809: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5810: $uname);
5811: }
5812: return $reply;
5813: }
5814:
5815: sub old_putstore {
5816: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5817: if (!$udomain) { $udomain=$env{'user.domain'}; }
5818: if (!$uname) { $uname=$env{'user.name'}; }
5819: my $uhome=&homeserver($uname,$udomain);
5820: my %newstorehash;
5821: foreach my $item (keys(%$storehash)) {
5822: my $key = $version.':'.&escape($symb).':'.$item;
5823: $newstorehash{$key} = $storehash->{$item};
5824: }
5825: my $items='';
5826: my %allitems = ();
5827: foreach my $item (keys(%newstorehash)) {
5828: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
5829: my $key = $1.':keys:'.$2;
5830: $allitems{$key} .= $3.':';
5831: }
5832: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
5833: }
5834: foreach my $item (keys(%allitems)) {
5835: $allitems{$item} =~ s/\:$//;
5836: $items.= $item.'='.$allitems{$item}.'&';
5837: }
5838: $items=~s/\&$//;
5839: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
5840: }
5841:
5842: # ------------------------------------------------------ critical put interface
5843:
5844: sub cput {
5845: my ($namespace,$storehash,$udomain,$uname)=@_;
5846: if (!$udomain) { $udomain=$env{'user.domain'}; }
5847: if (!$uname) { $uname=$env{'user.name'}; }
5848: my $uhome=&homeserver($uname,$udomain);
5849: my $items='';
5850: foreach my $item (keys(%$storehash)) {
5851: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5852: }
5853: $items=~s/\&$//;
5854: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
5855: }
5856:
5857: # -------------------------------------------------------------- eget interface
5858:
5859: sub eget {
5860: my ($namespace,$storearr,$udomain,$uname)=@_;
5861: my $items='';
5862: foreach my $item (@$storearr) {
5863: $items.=&escape($item).'&';
5864: }
5865: $items=~s/\&$//;
5866: if (!$udomain) { $udomain=$env{'user.domain'}; }
5867: if (!$uname) { $uname=$env{'user.name'}; }
5868: my $uhome=&homeserver($uname,$udomain);
5869: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
5870: my @pairs=split(/\&/,$rep);
5871: my %returnhash=();
5872: my $i=0;
5873: foreach my $item (@$storearr) {
5874: $returnhash{$item}=&thaw_unescape($pairs[$i]);
5875: $i++;
5876: }
5877: return %returnhash;
5878: }
5879:
5880: # ------------------------------------------------------------ tmpput interface
5881: sub tmpput {
5882: my ($storehash,$server,$context)=@_;
5883: my $items='';
5884: foreach my $item (keys(%$storehash)) {
5885: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5886: }
5887: $items=~s/\&$//;
5888: if (defined($context)) {
5889: $items .= ':'.&escape($context);
5890: }
5891: return &reply("tmpput:$items",$server);
5892: }
5893:
5894: # ------------------------------------------------------------ tmpget interface
5895: sub tmpget {
5896: my ($token,$server)=@_;
5897: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5898: my $rep=&reply("tmpget:$token",$server);
5899: my %returnhash;
5900: foreach my $item (split(/\&/,$rep)) {
5901: my ($key,$value)=split(/=/,$item);
5902: next if ($key =~ /^error: 2 /);
5903: $returnhash{&unescape($key)}=&thaw_unescape($value);
5904: }
5905: return %returnhash;
5906: }
5907:
5908: # ------------------------------------------------------------ tmpdel interface
5909: sub tmpdel {
5910: my ($token,$server)=@_;
5911: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5912: return &reply("tmpdel:$token",$server);
5913: }
5914:
5915: # ------------------------------------------------------------ get_timebased_id
5916:
5917: sub get_timebased_id {
5918: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5919: $maxtries) = @_;
5920: my ($newid,$error,$dellock);
5921: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5922: return ('','ok','invalid call to get suffix');
5923: }
5924:
5925: # set defaults for any optional args for which values were not supplied
5926: if ($who eq '') {
5927: $who = $env{'user.name'}.':'.$env{'user.domain'};
5928: }
5929: if (!$locktries) {
5930: $locktries = 3;
5931: }
5932: if (!$maxtries) {
5933: $maxtries = 10;
5934: }
5935:
5936: if (($cdom eq '') || ($cnum eq '')) {
5937: if ($env{'request.course.id'}) {
5938: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5939: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5940: }
5941: if (($cdom eq '') || ($cnum eq '')) {
5942: return ('','ok','call to get suffix not in course context');
5943: }
5944: }
5945:
5946: # construct locking item
5947: my $lockhash = {
5948: $prefix."\0".'locked_'.$keyid => $who,
5949: };
5950: my $tries = 0;
5951:
5952: # attempt to get lock on nohist_$namespace file
5953: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5954: while (($gotlock ne 'ok') && $tries <$locktries) {
5955: $tries ++;
5956: sleep 1;
5957: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5958: }
5959:
5960: # attempt to get unique identifier, based on current timestamp
5961: if ($gotlock eq 'ok') {
5962: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
5963: my $id = time;
5964: $newid = $id;
5965: my $idtries = 0;
5966: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
5967: if ($idtype eq 'concat') {
5968: $newid = $id.$idtries;
5969: } else {
5970: $newid ++;
5971: }
5972: $idtries ++;
5973: }
5974: if (!exists($inuse{$prefix."\0".$newid})) {
5975: my %new_item = (
5976: $prefix."\0".$newid => $who,
5977: );
5978: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
5979: $cdom,$cnum);
5980: if ($putresult ne 'ok') {
5981: undef($newid);
5982: $error = 'error saving new item: '.$putresult;
5983: }
5984: } else {
5985: $error = ('error: no unique suffix available for the new item ');
5986: }
5987: # remove lock
5988: my @del_lock = ($prefix."\0".'locked_'.$keyid);
5989: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
5990: } else {
5991: $error = "error: could not obtain lockfile\n";
5992: $dellock = 'ok';
5993: }
5994: return ($newid,$dellock,$error);
5995: }
5996:
5997: # -------------------------------------------------- portfolio access checking
5998:
5999: sub portfolio_access {
6000: my ($requrl) = @_;
6001: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
6002: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
6003: if ($result) {
6004: my %setters;
6005: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6006: my ($startblock,$endblock) =
6007: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6008: if ($startblock && $endblock) {
6009: return 'B';
6010: }
6011: } else {
6012: my ($startblock,$endblock) =
6013: &Apache::loncommon::blockcheck(\%setters,'port');
6014: if ($startblock && $endblock) {
6015: return 'B';
6016: }
6017: }
6018: }
6019: if ($result eq 'ok') {
6020: return 'F';
6021: } elsif ($result =~ /^[^:]+:guest_/) {
6022: return 'A';
6023: }
6024: return '';
6025: }
6026:
6027: sub get_portfolio_access {
6028: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
6029:
6030: if (!ref($access_hash)) {
6031: my $current_perms = &get_portfile_permissions($udom,$unum);
6032: my %access_controls = &get_access_controls($current_perms,$group,
6033: $file_name);
6034: $access_hash = $access_controls{$file_name};
6035: }
6036:
6037: my ($public,$guest,@domains,@users,@courses,@groups);
6038: my $now = time;
6039: if (ref($access_hash) eq 'HASH') {
6040: foreach my $key (keys(%{$access_hash})) {
6041: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6042: if ($start > $now) {
6043: next;
6044: }
6045: if ($end && $end<$now) {
6046: next;
6047: }
6048: if ($scope eq 'public') {
6049: $public = $key;
6050: last;
6051: } elsif ($scope eq 'guest') {
6052: $guest = $key;
6053: } elsif ($scope eq 'domains') {
6054: push(@domains,$key);
6055: } elsif ($scope eq 'users') {
6056: push(@users,$key);
6057: } elsif ($scope eq 'course') {
6058: push(@courses,$key);
6059: } elsif ($scope eq 'group') {
6060: push(@groups,$key);
6061: }
6062: }
6063: if ($public) {
6064: return 'ok';
6065: }
6066: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6067: if ($guest) {
6068: return $guest;
6069: }
6070: } else {
6071: if (@domains > 0) {
6072: foreach my $domkey (@domains) {
6073: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6074: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6075: return 'ok';
6076: }
6077: }
6078: }
6079: }
6080: if (@users > 0) {
6081: foreach my $userkey (@users) {
6082: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6083: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6084: if (ref($item) eq 'HASH') {
6085: if (($item->{'uname'} eq $env{'user.name'}) &&
6086: ($item->{'udom'} eq $env{'user.domain'})) {
6087: return 'ok';
6088: }
6089: }
6090: }
6091: }
6092: }
6093: }
6094: my %roleshash;
6095: my @courses_and_groups = @courses;
6096: push(@courses_and_groups,@groups);
6097: if (@courses_and_groups > 0) {
6098: my (%allgroups,%allroles);
6099: my ($start,$end,$role,$sec,$group);
6100: foreach my $envkey (%env) {
6101: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
6102: my $cid = $2.'_'.$3;
6103: if ($1 eq 'gr') {
6104: $group = $4;
6105: $allgroups{$cid}{$group} = $env{$envkey};
6106: } else {
6107: if ($4 eq '') {
6108: $sec = 'none';
6109: } else {
6110: $sec = $4;
6111: }
6112: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6113: }
6114: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
6115: my $cid = $2.'_'.$3;
6116: if ($4 eq '') {
6117: $sec = 'none';
6118: } else {
6119: $sec = $4;
6120: }
6121: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6122: }
6123: }
6124: if (keys(%allroles) == 0) {
6125: return;
6126: }
6127: foreach my $key (@courses_and_groups) {
6128: my %content = %{$$access_hash{$key}};
6129: my $cnum = $content{'number'};
6130: my $cdom = $content{'domain'};
6131: my $cid = $cdom.'_'.$cnum;
6132: if (!exists($allroles{$cid})) {
6133: next;
6134: }
6135: foreach my $role_id (keys(%{$content{'roles'}})) {
6136: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6137: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6138: my @status = @{$content{'roles'}{$role_id}{'access'}};
6139: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6140: foreach my $role (keys(%{$allroles{$cid}})) {
6141: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6142: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6143: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6144: if (grep/^all$/,@sections) {
6145: return 'ok';
6146: } else {
6147: if (grep/^$sec$/,@sections) {
6148: return 'ok';
6149: }
6150: }
6151: }
6152: }
6153: if (keys(%{$allgroups{$cid}}) == 0) {
6154: if (grep/^none$/,@groups) {
6155: return 'ok';
6156: }
6157: } else {
6158: if (grep/^all$/,@groups) {
6159: return 'ok';
6160: }
6161: foreach my $group (keys(%{$allgroups{$cid}})) {
6162: if (grep/^$group$/,@groups) {
6163: return 'ok';
6164: }
6165: }
6166: }
6167: }
6168: }
6169: }
6170: }
6171: }
6172: if ($guest) {
6173: return $guest;
6174: }
6175: }
6176: }
6177: return;
6178: }
6179:
6180: sub course_group_datechecker {
6181: my ($dates,$now,$status) = @_;
6182: my ($start,$end) = split(/\./,$dates);
6183: if (!$start && !$end) {
6184: return 'ok';
6185: }
6186: if (grep/^active$/,@{$status}) {
6187: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6188: return 'ok';
6189: }
6190: }
6191: if (grep/^previous$/,@{$status}) {
6192: if ($end > $now ) {
6193: return 'ok';
6194: }
6195: }
6196: if (grep/^future$/,@{$status}) {
6197: if ($start > $now) {
6198: return 'ok';
6199: }
6200: }
6201: return;
6202: }
6203:
6204: sub parse_portfolio_url {
6205: my ($url) = @_;
6206:
6207: my ($type,$udom,$unum,$group,$file_name);
6208:
6209: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
6210: $type = 1;
6211: $udom = $1;
6212: $unum = $2;
6213: $file_name = $3;
6214: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
6215: $type = 2;
6216: $udom = $1;
6217: $unum = $2;
6218: $group = $3;
6219: $file_name = $3.'/'.$4;
6220: }
6221: if (wantarray) {
6222: return ($type,$udom,$unum,$file_name,$group);
6223: }
6224: return $type;
6225: }
6226:
6227: sub is_portfolio_url {
6228: my ($url) = @_;
6229: return scalar(&parse_portfolio_url($url));
6230: }
6231:
6232: sub is_portfolio_file {
6233: my ($file) = @_;
6234: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
6235: return 1;
6236: }
6237: return;
6238: }
6239:
6240: sub usertools_access {
6241: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
6242: my ($access,%tools);
6243: if ($context eq '') {
6244: $context = 'tools';
6245: }
6246: if ($context eq 'requestcourses') {
6247: %tools = (
6248: official => 1,
6249: unofficial => 1,
6250: community => 1,
6251: textbook => 1,
6252: );
6253: } elsif ($context eq 'requestauthor') {
6254: %tools = (
6255: requestauthor => 1,
6256: );
6257: } else {
6258: %tools = (
6259: aboutme => 1,
6260: blog => 1,
6261: webdav => 1,
6262: portfolio => 1,
6263: );
6264: }
6265: return if (!defined($tools{$tool}));
6266:
6267: if (($udom eq '') || ($uname eq '')) {
6268: $udom = $env{'user.domain'};
6269: $uname = $env{'user.name'};
6270: }
6271:
6272: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6273: if ($action ne 'reload') {
6274: if ($context eq 'requestcourses') {
6275: return $env{'environment.canrequest.'.$tool};
6276: } elsif ($context eq 'requestauthor') {
6277: return $env{'environment.canrequest.author'};
6278: } else {
6279: return $env{'environment.availabletools.'.$tool};
6280: }
6281: }
6282: }
6283:
6284: my ($toolstatus,$inststatus,$envkey);
6285: if ($context eq 'requestauthor') {
6286: $envkey = $context;
6287: } else {
6288: $envkey = $context.'.'.$tool;
6289: }
6290:
6291: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6292: ($action ne 'reload')) {
6293: $toolstatus = $env{'environment.'.$envkey};
6294: $inststatus = $env{'environment.inststatus'};
6295: } else {
6296: if (ref($userenvref) eq 'HASH') {
6297: $toolstatus = $userenvref->{$envkey};
6298: $inststatus = $userenvref->{'inststatus'};
6299: } else {
6300: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6301: $toolstatus = $userenv{$envkey};
6302: $inststatus = $userenv{'inststatus'};
6303: }
6304: }
6305:
6306: if ($toolstatus ne '') {
6307: if ($toolstatus) {
6308: $access = 1;
6309: } else {
6310: $access = 0;
6311: }
6312: return $access;
6313: }
6314:
6315: my ($is_adv,%domdef);
6316: if (ref($is_advref) eq 'HASH') {
6317: $is_adv = $is_advref->{'is_adv'};
6318: } else {
6319: $is_adv = &is_advanced_user($udom,$uname);
6320: }
6321: if (ref($domdefref) eq 'HASH') {
6322: %domdef = %{$domdefref};
6323: } else {
6324: %domdef = &get_domain_defaults($udom);
6325: }
6326: if (ref($domdef{$tool}) eq 'HASH') {
6327: if ($is_adv) {
6328: if ($domdef{$tool}{'_LC_adv'} ne '') {
6329: if ($domdef{$tool}{'_LC_adv'}) {
6330: $access = 1;
6331: } else {
6332: $access = 0;
6333: }
6334: return $access;
6335: }
6336: }
6337: if ($inststatus ne '') {
6338: my ($hasaccess,$hasnoaccess);
6339: foreach my $affiliation (split(/:/,$inststatus)) {
6340: if ($domdef{$tool}{$affiliation} ne '') {
6341: if ($domdef{$tool}{$affiliation}) {
6342: $hasaccess = 1;
6343: } else {
6344: $hasnoaccess = 1;
6345: }
6346: }
6347: }
6348: if ($hasaccess || $hasnoaccess) {
6349: if ($hasaccess) {
6350: $access = 1;
6351: } elsif ($hasnoaccess) {
6352: $access = 0;
6353: }
6354: return $access;
6355: }
6356: } else {
6357: if ($domdef{$tool}{'default'} ne '') {
6358: if ($domdef{$tool}{'default'}) {
6359: $access = 1;
6360: } elsif ($domdef{$tool}{'default'} == 0) {
6361: $access = 0;
6362: }
6363: return $access;
6364: }
6365: }
6366: } else {
6367: if (($context eq 'tools') && ($tool ne 'webdav')) {
6368: $access = 1;
6369: } else {
6370: $access = 0;
6371: }
6372: return $access;
6373: }
6374: }
6375:
6376: sub is_course_owner {
6377: my ($cdom,$cnum,$udom,$uname) = @_;
6378: if (($udom eq '') || ($uname eq '')) {
6379: $udom = $env{'user.domain'};
6380: $uname = $env{'user.name'};
6381: }
6382: unless (($udom eq '') || ($uname eq '')) {
6383: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6384: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6385: return 1;
6386: } else {
6387: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6388: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6389: return 1;
6390: }
6391: }
6392: }
6393: }
6394: return;
6395: }
6396:
6397: sub is_advanced_user {
6398: my ($udom,$uname) = @_;
6399: if ($udom ne '' && $uname ne '') {
6400: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6401: if (wantarray) {
6402: return ($env{'user.adv'},$env{'user.author'});
6403: } else {
6404: return $env{'user.adv'};
6405: }
6406: }
6407: }
6408: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6409: my %allroles;
6410: my ($is_adv,$is_author);
6411: foreach my $role (keys(%roleshash)) {
6412: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6413: my $area = '/'.$tdomain.'/'.$trest;
6414: if ($sec ne '') {
6415: $area .= '/'.$sec;
6416: }
6417: if (($area ne '') && ($trole ne '')) {
6418: my $spec=$trole.'.'.$area;
6419: if ($trole =~ /^cr\//) {
6420: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6421: } elsif ($trole ne 'gr') {
6422: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6423: }
6424: if ($trole eq 'au') {
6425: $is_author = 1;
6426: }
6427: }
6428: }
6429: foreach my $role (keys(%allroles)) {
6430: last if ($is_adv);
6431: foreach my $item (split(/:/,$allroles{$role})) {
6432: if ($item ne '') {
6433: my ($privilege,$restrictions)=split(/&/,$item);
6434: if ($privilege eq 'adv') {
6435: $is_adv = 1;
6436: last;
6437: }
6438: }
6439: }
6440: }
6441: if (wantarray) {
6442: return ($is_adv,$is_author);
6443: }
6444: return $is_adv;
6445: }
6446:
6447: sub check_can_request {
6448: my ($dom,$can_request,$request_domains) = @_;
6449: my $canreq = 0;
6450: my ($types,$typename) = &Apache::loncommon::course_types();
6451: my @options = ('approval','validate','autolimit');
6452: my $optregex = join('|',@options);
6453: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6454: foreach my $type (@{$types}) {
6455: if (&usertools_access($env{'user.name'},
6456: $env{'user.domain'},
6457: $type,undef,'requestcourses')) {
6458: $canreq ++;
6459: if (ref($request_domains) eq 'HASH') {
6460: push(@{$request_domains->{$type}},$env{'user.domain'});
6461: }
6462: if ($dom eq $env{'user.domain'}) {
6463: $can_request->{$type} = 1;
6464: }
6465: }
6466: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6467: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6468: if (@curr > 0) {
6469: foreach my $item (@curr) {
6470: if (ref($request_domains) eq 'HASH') {
6471: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6472: if ($otherdom ne '') {
6473: if (ref($request_domains->{$type}) eq 'ARRAY') {
6474: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6475: push(@{$request_domains->{$type}},$otherdom);
6476: }
6477: } else {
6478: push(@{$request_domains->{$type}},$otherdom);
6479: }
6480: }
6481: }
6482: }
6483: unless($dom eq $env{'user.domain'}) {
6484: $canreq ++;
6485: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6486: $can_request->{$type} = 1;
6487: }
6488: }
6489: }
6490: }
6491: }
6492: }
6493: return $canreq;
6494: }
6495:
6496: # ---------------------------------------------- Custom access rule evaluation
6497:
6498: sub customaccess {
6499: my ($priv,$uri)=@_;
6500: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
6501: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
6502: $udom = &LONCAPA::clean_domain($udom);
6503: $ucrs = &LONCAPA::clean_username($ucrs);
6504: my $access=0;
6505: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
6506: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6507: if ($type eq 'user') {
6508: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6509: my ($tdom,$tuname)=split(m{/},$scope);
6510: if ($tdom) {
6511: if ($tdom ne $env{'user.domain'}) { next; }
6512: }
6513: if ($tuname) {
6514: if ($tuname ne $env{'user.name'}) { next; }
6515: }
6516: $access=($effect eq 'allow');
6517: last;
6518: }
6519: } else {
6520: if ($role) {
6521: if ($role ne $urole) { next; }
6522: }
6523: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6524: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6525: if ($tdom) {
6526: if ($tdom ne $udom) { next; }
6527: }
6528: if ($tcrs) {
6529: if ($tcrs ne $ucrs) { next; }
6530: }
6531: if ($tsec) {
6532: if ($tsec ne $usec) { next; }
6533: }
6534: $access=($effect eq 'allow');
6535: last;
6536: }
6537: if ($realm eq '' && $role eq '') {
6538: $access=($effect eq 'allow');
6539: }
6540: }
6541: }
6542: return $access;
6543: }
6544:
6545: # ------------------------------------------------- Check for a user privilege
6546:
6547: sub allowed {
6548: my ($priv,$uri,$symb,$role)=@_;
6549: my $ver_orguri=$uri;
6550: $uri=&deversion($uri);
6551: my $orguri=$uri;
6552: $uri=&declutter($uri);
6553:
6554: if ($priv eq 'evb') {
6555: # Evade communication block restrictions for specified role in a course
6556: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6557: return $1;
6558: } else {
6559: return;
6560: }
6561: }
6562:
6563: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
6564: # Free bre access to adm and meta resources
6565: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
6566: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6567: && ($priv eq 'bre')) {
6568: return 'F';
6569: }
6570:
6571: # Free bre access to user's own portfolio contents
6572: my ($space,$domain,$name,@dir)=split('/',$uri);
6573: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
6574: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
6575: my %setters;
6576: my ($startblock,$endblock) =
6577: &Apache::loncommon::blockcheck(\%setters,'port');
6578: if ($startblock && $endblock) {
6579: return 'B';
6580: } else {
6581: return 'F';
6582: }
6583: }
6584:
6585: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
6586: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6587: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6588: if (exists($env{'request.course.id'})) {
6589: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6590: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6591: if (($domain eq $cdom) && ($name eq $cnum)) {
6592: my $courseprivid=$env{'request.course.id'};
6593: $courseprivid=~s/\_/\//;
6594: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6595: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6596: return $1;
6597: } else {
6598: if ($env{'request.course.sec'}) {
6599: $courseprivid.='/'.$env{'request.course.sec'};
6600: }
6601: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6602: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6603: return $2;
6604: }
6605: }
6606: }
6607: }
6608: }
6609:
6610: # Free bre to public access
6611:
6612: if ($priv eq 'bre') {
6613: my $copyright=&metadata($uri,'copyright');
6614: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
6615: return 'F';
6616: }
6617: if ($copyright eq 'priv') {
6618: $uri=~/([^\/]+)\/([^\/]+)\//;
6619: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
6620: return '';
6621: }
6622: }
6623: if ($copyright eq 'domain') {
6624: $uri=~/([^\/]+)\/([^\/]+)\//;
6625: unless (($env{'user.domain'} eq $1) ||
6626: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
6627: return '';
6628: }
6629: }
6630: if ($env{'request.role'}=~ /li\.\//) {
6631: # Library role, so allow browsing of resources in this domain.
6632: return 'F';
6633: }
6634: if ($copyright eq 'custom') {
6635: unless (&customaccess($priv,$uri)) { return ''; }
6636: }
6637: }
6638: # Domain coordinator is trying to create a course
6639: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
6640: # uri is the requested domain in this case.
6641: # comparison to 'request.role.domain' shows if the user has selected
6642: # a role of dc for the domain in question.
6643: return 'F' if ($uri eq $env{'request.role.domain'});
6644: }
6645:
6646: my $thisallowed='';
6647: my $statecond=0;
6648: my $courseprivid='';
6649:
6650: my $ownaccess;
6651: # Community Coordinator or Assistant Co-author browsing resource space.
6652: if (($priv eq 'bro') && ($env{'user.author'})) {
6653: if ($uri eq '') {
6654: $ownaccess = 1;
6655: } else {
6656: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6657: my $udom = $env{'user.domain'};
6658: my $uname = $env{'user.name'};
6659: if ($uri =~ m{^\Q$udom\E/?$}) {
6660: $ownaccess = 1;
6661: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
6662: unless ($uri =~ m{\.\./}) {
6663: $ownaccess = 1;
6664: }
6665: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6666: my $now = time;
6667: if ($uri =~ m{^([^/]+)/?$}) {
6668: my $adom = $1;
6669: foreach my $key (keys(%env)) {
6670: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
6671: my ($start,$end) = split('.',$env{$key});
6672: if (($now >= $start) && (!$end || $end < $now)) {
6673: $ownaccess = 1;
6674: last;
6675: }
6676: }
6677: }
6678: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6679: my $adom = $1;
6680: my $aname = $2;
6681: foreach my $role ('ca','aa') {
6682: if ($env{"user.role.$role./$adom/$aname"}) {
6683: my ($start,$end) =
6684: split('.',$env{"user.role.$role./$adom/$aname"});
6685: if (($now >= $start) && (!$end || $end < $now)) {
6686: $ownaccess = 1;
6687: last;
6688: }
6689: }
6690: }
6691: }
6692: }
6693: }
6694: }
6695: }
6696:
6697: # Course
6698:
6699: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
6700: unless (($priv eq 'bro') && (!$ownaccess)) {
6701: $thisallowed.=$1;
6702: }
6703: }
6704:
6705: # Domain
6706:
6707: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
6708: =~/\Q$priv\E\&([^\:]*)/) {
6709: unless (($priv eq 'bro') && (!$ownaccess)) {
6710: $thisallowed.=$1;
6711: }
6712: }
6713:
6714: # User who is not author or co-author might still be able to edit
6715: # resource of an author in the domain (e.g., if Domain Coordinator).
6716: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6717: (&allowed('mdc',$env{'request.course.id'}))) {
6718: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6719: $thisallowed.=$1;
6720: }
6721: }
6722:
6723: # Course: uri itself is a course
6724: my $courseuri=$uri;
6725: $courseuri=~s/\_(\d)/\/$1/;
6726: $courseuri=~s/^([^\/])/\/$1/;
6727:
6728: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
6729: =~/\Q$priv\E\&([^\:]*)/) {
6730: unless (($priv eq 'bro') && (!$ownaccess)) {
6731: $thisallowed.=$1;
6732: }
6733: }
6734:
6735: # URI is an uploaded document for this course, default permissions don't matter
6736: # not allowing 'edit' access (editupload) to uploaded course docs
6737: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
6738: $thisallowed='';
6739: my ($match)=&is_on_map($uri);
6740: if ($match) {
6741: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6742: =~/\Q$priv\E\&([^\:]*)/) {
6743: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6744: if (@blockers > 0) {
6745: $thisallowed = 'B';
6746: } else {
6747: $thisallowed.=$1;
6748: }
6749: }
6750: } else {
6751: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
6752: if ($refuri) {
6753: if ($refuri =~ m|^/adm/|) {
6754: $thisallowed='F';
6755: } else {
6756: $refuri=&declutter($refuri);
6757: my ($match) = &is_on_map($refuri);
6758: if ($match) {
6759: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6760: if (@blockers > 0) {
6761: $thisallowed = 'B';
6762: } else {
6763: $thisallowed='F';
6764: }
6765: }
6766: }
6767: }
6768: }
6769: }
6770:
6771: if ($priv eq 'bre'
6772: && $thisallowed ne 'F'
6773: && $thisallowed ne '2'
6774: && &is_portfolio_url($uri)) {
6775: $thisallowed = &portfolio_access($uri);
6776: }
6777:
6778: # Full access at system, domain or course-wide level? Exit.
6779: if ($thisallowed=~/F/) {
6780: return 'F';
6781: }
6782:
6783: # If this is generating or modifying users, exit with special codes
6784:
6785: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6786: if (($priv eq 'cca') || ($priv eq 'caa')) {
6787: my ($audom,$auname)=split('/',$uri);
6788: # no author name given, so this just checks on the general right to make a co-author in this domain
6789: unless ($auname) { return $thisallowed; }
6790: # an author name is given, so we are about to actually make a co-author for a certain account
6791: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6792: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6793: ($audom ne $env{'request.role.domain'}))) { return ''; }
6794: }
6795: return $thisallowed;
6796: }
6797: #
6798: # Gathered so far: system, domain and course wide privileges
6799: #
6800: # Course: See if uri or referer is an individual resource that is part of
6801: # the course
6802:
6803: if ($env{'request.course.id'}) {
6804:
6805: $courseprivid=$env{'request.course.id'};
6806: if ($env{'request.course.sec'}) {
6807: $courseprivid.='/'.$env{'request.course.sec'};
6808: }
6809: $courseprivid=~s/\_/\//;
6810: my $checkreferer=1;
6811: my ($match,$cond)=&is_on_map($uri);
6812: if ($match) {
6813: $statecond=$cond;
6814: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
6815: =~/\Q$priv\E\&([^\:]*)/) {
6816: my $value = $1;
6817: if ($priv eq 'bre') {
6818: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6819: if (@blockers > 0) {
6820: $thisallowed = 'B';
6821: } else {
6822: $thisallowed.=$value;
6823: }
6824: } else {
6825: $thisallowed.=$value;
6826: }
6827: $checkreferer=0;
6828: }
6829: }
6830:
6831: if ($checkreferer) {
6832: my $refuri=$env{'httpref.'.$orguri};
6833: unless ($refuri) {
6834: foreach my $key (keys(%env)) {
6835: if ($key=~/^httpref\..*\*/) {
6836: my $pattern=$key;
6837: $pattern=~s/^httpref\.\/res\///;
6838: $pattern=~s/\*/\[\^\/\]\+/g;
6839: $pattern=~s/\//\\\//g;
6840: if ($orguri=~/$pattern/) {
6841: $refuri=$env{$key};
6842: }
6843: }
6844: }
6845: }
6846:
6847: if ($refuri) {
6848: $refuri=&declutter($refuri);
6849: my ($match,$cond)=&is_on_map($refuri);
6850: if ($match) {
6851: my $refstatecond=$cond;
6852: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
6853: =~/\Q$priv\E\&([^\:]*)/) {
6854: my $value = $1;
6855: if ($priv eq 'bre') {
6856: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6857: if (@blockers > 0) {
6858: $thisallowed = 'B';
6859: } else {
6860: $thisallowed.=$value;
6861: }
6862: } else {
6863: $thisallowed.=$value;
6864: }
6865: $uri=$refuri;
6866: $statecond=$refstatecond;
6867: }
6868: }
6869: }
6870: }
6871: }
6872:
6873: #
6874: # Gathered now: all privileges that could apply, and condition number
6875: #
6876: #
6877: # Full or no access?
6878: #
6879:
6880: if ($thisallowed=~/F/) {
6881: return 'F';
6882: }
6883:
6884: unless ($thisallowed) {
6885: return '';
6886: }
6887:
6888: # Restrictions exist, deal with them
6889: #
6890: # C:according to course preferences
6891: # R:according to resource settings
6892: # L:unless locked
6893: # X:according to user session state
6894: #
6895:
6896: # Possibly locked functionality, check all courses
6897: # Locks might take effect only after 10 minutes cache expiration for other
6898: # courses, and 2 minutes for current course
6899:
6900: my $envkey;
6901: if ($thisallowed=~/L/) {
6902: foreach $envkey (keys(%env)) {
6903: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6904: my $courseid=$2;
6905: my $roleid=$1.'.'.$2;
6906: $courseid=~s/^\///;
6907: my $expiretime=600;
6908: if ($env{'request.role'} eq $roleid) {
6909: $expiretime=120;
6910: }
6911: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6912: my $prefix='course.'.$cdom.'_'.$cnum.'.';
6913: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
6914: &coursedescription($courseid,{'freshen_cache' => 1});
6915: }
6916: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6917: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6918: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6919: &log($env{'user.domain'},$env{'user.name'},
6920: $env{'user.home'},
6921: 'Locked by res: '.$priv.' for '.$uri.' due to '.
6922: $cdom.'/'.$cnum.'/'.$csec.' expire '.
6923: $env{$prefix.'priv.'.$priv.'.lock.expire'});
6924: return '';
6925: }
6926: }
6927: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6928: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6929: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6930: &log($env{'user.domain'},$env{'user.name'},
6931: $env{'user.home'},
6932: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
6933: $cdom.'/'.$cnum.'/'.$csec.' expire '.
6934: $env{$prefix.'priv.'.$priv.'.lock.expire'});
6935: return '';
6936: }
6937: }
6938: }
6939: }
6940: }
6941:
6942: #
6943: # Rest of the restrictions depend on selected course
6944: #
6945:
6946: unless ($env{'request.course.id'}) {
6947: if ($thisallowed eq 'A') {
6948: return 'A';
6949: } elsif ($thisallowed eq 'B') {
6950: return 'B';
6951: } else {
6952: return '1';
6953: }
6954: }
6955:
6956: #
6957: # Now user is definitely in a course
6958: #
6959:
6960:
6961: # Course preferences
6962:
6963: if ($thisallowed=~/C/) {
6964: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6965: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6966: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
6967: =~/\Q$rolecode\E/) {
6968: if (($priv ne 'pch') && ($priv ne 'plc')) {
6969: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6970: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6971: $env{'request.course.id'});
6972: }
6973: return '';
6974: }
6975:
6976: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
6977: =~/\Q$unamedom\E/) {
6978: if (($priv ne 'pch') && ($priv ne 'plc')) {
6979: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6980: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6981: $env{'request.course.id'});
6982: }
6983: return '';
6984: }
6985: }
6986:
6987: # Resource preferences
6988:
6989: if ($thisallowed=~/R/) {
6990: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6991: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
6992: if (($priv ne 'pch') && ($priv ne 'plc')) {
6993: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6994: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6995: }
6996: return '';
6997: }
6998: }
6999:
7000: # Restricted by state or randomout?
7001:
7002: if ($thisallowed=~/X/) {
7003: if ($env{'acc.randomout'}) {
7004: if (!$symb) { $symb=&symbread($uri,1); }
7005: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
7006: return '';
7007: }
7008: }
7009: if (&condval($statecond)) {
7010: return '2';
7011: } else {
7012: return '';
7013: }
7014: }
7015:
7016: if ($thisallowed eq 'A') {
7017: return 'A';
7018: } elsif ($thisallowed eq 'B') {
7019: return 'B';
7020: }
7021: return 'F';
7022: }
7023:
7024: # ------------------------------------------- Check construction space access
7025:
7026: sub constructaccess {
7027: my ($url,$setpriv)=@_;
7028:
7029: # We do not allow editing of previous versions of files
7030: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7031:
7032: # Get username and domain from URL
7033: my ($ownername,$ownerdomain,$ownerhome);
7034:
7035: ($ownerdomain,$ownername) =
7036: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7037:
7038: # The URL does not really point to any authorspace, forget it
7039: unless (($ownername) && ($ownerdomain)) { return ''; }
7040:
7041: # Now we need to see if the user has access to the authorspace of
7042: # $ownername at $ownerdomain
7043:
7044: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7045: # Real author for this?
7046: $ownerhome = $env{'user.home'};
7047: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7048: return ($ownername,$ownerdomain,$ownerhome);
7049: }
7050: } else {
7051: # Co-author for this?
7052: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7053: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7054: $ownerhome = &homeserver($ownername,$ownerdomain);
7055: return ($ownername,$ownerdomain,$ownerhome);
7056: }
7057: }
7058:
7059: # We don't have any access right now. If we are not possibly going to do anything about this,
7060: # we might as well leave
7061: unless ($setpriv) { return ''; }
7062:
7063: # Backdoor access?
7064: my $allowed=&allowed('eco',$ownerdomain);
7065: # Nope
7066: unless ($allowed) { return ''; }
7067: # Looks like we may have access, but could be locked by the owner of the construction space
7068: if ($allowed eq 'U') {
7069: my %blocked=&get('environment',['domcoord.author'],
7070: $ownerdomain,$ownername);
7071: # Is blocked by owner
7072: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7073: }
7074: if (($allowed eq 'F') || ($allowed eq 'U')) {
7075: # Grant temporary access
7076: my $then=$env{'user.login.time'};
7077: my $update=$env{'user.update.time'};
7078: if (!$update) { $update = $then; }
7079: my $refresh=$env{'user.refresh.time'};
7080: if (!$refresh) { $refresh = $update; }
7081: my $now = time;
7082: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7083: $now,'ca','constructaccess');
7084: $ownerhome = &homeserver($ownername,$ownerdomain);
7085: return($ownername,$ownerdomain,$ownerhome);
7086: }
7087: # No business here
7088: return '';
7089: }
7090:
7091: sub get_comm_blocks {
7092: my ($cdom,$cnum) = @_;
7093: if ($cdom eq '' || $cnum eq '') {
7094: return unless ($env{'request.course.id'});
7095: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7096: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7097: }
7098: my %commblocks;
7099: my $hashid=$cdom.'_'.$cnum;
7100: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7101: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7102: %commblocks = %{$blocksref};
7103: } else {
7104: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7105: my $cachetime = 600;
7106: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7107: }
7108: return %commblocks;
7109: }
7110:
7111: sub has_comm_blocking {
7112: my ($priv,$symb,$uri,$blocks) = @_;
7113: return unless ($env{'request.course.id'});
7114: return unless ($priv eq 'bre');
7115: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7116: my %commblocks;
7117: if (ref($blocks) eq 'HASH') {
7118: %commblocks = %{$blocks};
7119: } else {
7120: %commblocks = &get_comm_blocks();
7121: }
7122: return unless (keys(%commblocks) > 0);
7123: if (!$symb) { $symb=&symbread($uri,1); }
7124: my ($map,$resid,undef)=&decode_symb($symb);
7125: my %tocheck = (
7126: maps => $map,
7127: resources => $symb,
7128: );
7129: my @blockers;
7130: my $now = time;
7131: my $navmap = Apache::lonnavmaps::navmap->new();
7132: foreach my $block (keys(%commblocks)) {
7133: if ($block =~ /^(\d+)____(\d+)$/) {
7134: my ($start,$end) = ($1,$2);
7135: if ($start <= $now && $end >= $now) {
7136: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7137: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7138: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7139: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7140: unless (grep(/^\Q$block\E$/,@blockers)) {
7141: push(@blockers,$block);
7142: }
7143: }
7144: }
7145: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7146: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7147: unless (grep(/^\Q$block\E$/,@blockers)) {
7148: push(@blockers,$block);
7149: }
7150: }
7151: }
7152: }
7153: }
7154: }
7155: } elsif ($block =~ /^firstaccess____(.+)$/) {
7156: my $item = $1;
7157: my @to_test;
7158: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7159: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7160: my $check_interval;
7161: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7162: my @interval;
7163: my $type = 'map';
7164: if ($item eq 'course') {
7165: $type = 'course';
7166: @interval=&EXT("resource.0.interval");
7167: } else {
7168: if ($item =~ /___\d+___/) {
7169: $type = 'resource';
7170: @interval=&EXT("resource.0.interval",$item);
7171: if (ref($navmap)) {
7172: my $res = $navmap->getBySymb($item);
7173: push(@to_test,$res);
7174: }
7175: } else {
7176: my $mapsymb = &symbread($item,1);
7177: if ($mapsymb) {
7178: if (ref($navmap)) {
7179: my $mapres = $navmap->getBySymb($mapsymb);
7180: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7181: foreach my $res (@to_test) {
7182: my $symb = $res->symb();
7183: next if ($symb eq $mapsymb);
7184: if ($symb ne '') {
7185: @interval=&EXT("resource.0.interval",$symb);
7186: last;
7187: }
7188: }
7189: }
7190: }
7191: }
7192: }
7193: if ($interval[0] =~ /\d+/) {
7194: my $first_access;
7195: if ($type eq 'resource') {
7196: $first_access=&get_first_access($interval[1],$item);
7197: } elsif ($type eq 'map') {
7198: $first_access=&get_first_access($interval[1],undef,$item);
7199: } else {
7200: $first_access=&get_first_access($interval[1]);
7201: }
7202: if ($first_access) {
7203: my $timesup = $first_access+$interval[0];
7204: if ($timesup > $now) {
7205: foreach my $res (@to_test) {
7206: if ($res->is_problem()) {
7207: if ($res->completable()) {
7208: unless (grep(/^\Q$block\E$/,@blockers)) {
7209: push(@blockers,$block);
7210: }
7211: last;
7212: }
7213: }
7214: }
7215: }
7216: }
7217: }
7218: }
7219: }
7220: }
7221: }
7222: }
7223: return @blockers;
7224: }
7225:
7226: sub check_docs_block {
7227: my ($docsblock,$tocheck) =@_;
7228: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7229: return;
7230: }
7231: if (ref($docsblock->{'maps'}) eq 'HASH') {
7232: if ($tocheck->{'maps'}) {
7233: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7234: return 1;
7235: }
7236: }
7237: }
7238: if (ref($docsblock->{'resources'}) eq 'HASH') {
7239: if ($tocheck->{'resources'}) {
7240: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7241: return 1;
7242: }
7243: }
7244: }
7245: return;
7246: }
7247:
7248: #
7249: # Removes the versino from a URI and
7250: # splits it in to its filename and path to the filename.
7251: # Seems like File::Basename could have done this more clearly.
7252: # Parameters:
7253: # $uri - input URI
7254: # Returns:
7255: # Two element list consisting of
7256: # $pathname - the URI up to and excluding the trailing /
7257: # $filename - The part of the URI following the last /
7258: # NOTE:
7259: # Another realization of this is simply:
7260: # use File::Basename;
7261: # ...
7262: # $uri = shift;
7263: # $filename = basename($uri);
7264: # $path = dirname($uri);
7265: # return ($filename, $path);
7266: #
7267: # The implementation below is probably faster however.
7268: #
7269: sub split_uri_for_cond {
7270: my $uri=&deversion(&declutter(shift));
7271: my @uriparts=split(/\//,$uri);
7272: my $filename=pop(@uriparts);
7273: my $pathname=join('/',@uriparts);
7274: return ($pathname,$filename);
7275: }
7276: # --------------------------------------------------- Is a resource on the map?
7277:
7278: sub is_on_map {
7279: my ($pathname,$filename) = &split_uri_for_cond(shift);
7280: #Trying to find the conditional for the file
7281: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
7282: /\&\Q$filename\E\:([\d\|]+)\&/);
7283: if ($match) {
7284: return (1,$1);
7285: } else {
7286: return (0,0);
7287: }
7288: }
7289:
7290: # --------------------------------------------------------- Get symb from alias
7291:
7292: sub get_symb_from_alias {
7293: my $symb=shift;
7294: my ($map,$resid,$url)=&decode_symb($symb);
7295: # Already is a symb
7296: if ($url) { return $symb; }
7297: # Must be an alias
7298: my $aliassymb='';
7299: my %bighash;
7300: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7301: &GDBM_READER(),0640)) {
7302: my $rid=$bighash{'mapalias_'.$symb};
7303: if ($rid) {
7304: my ($mapid,$resid)=split(/\./,$rid);
7305: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7306: $resid,$bighash{'src_'.$rid});
7307: }
7308: untie %bighash;
7309: }
7310: return $aliassymb;
7311: }
7312:
7313: # ----------------------------------------------------------------- Define Role
7314:
7315: sub definerole {
7316: if (allowed('mcr','/')) {
7317: my ($rolename,$sysrole,$domrole,$courole)=@_;
7318: foreach my $role (split(':',$sysrole)) {
7319: my ($crole,$cqual)=split(/\&/,$role);
7320: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7321: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7322: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
7323: return "refused:s:$crole&$cqual";
7324: }
7325: }
7326: }
7327: foreach my $role (split(':',$domrole)) {
7328: my ($crole,$cqual)=split(/\&/,$role);
7329: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7330: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7331: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
7332: return "refused:d:$crole&$cqual";
7333: }
7334: }
7335: }
7336: foreach my $role (split(':',$courole)) {
7337: my ($crole,$cqual)=split(/\&/,$role);
7338: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7339: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7340: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
7341: return "refused:c:$crole&$cqual";
7342: }
7343: }
7344: }
7345: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7346: "$env{'user.domain'}:$env{'user.name'}:".
7347: "rolesdef_$rolename=".
7348: escape($sysrole.'_'.$domrole.'_'.$courole);
7349: return reply($command,$env{'user.home'});
7350: } else {
7351: return 'refused';
7352: }
7353: }
7354:
7355: # ---------------- Make a metadata query against the network of library servers
7356:
7357: sub metadata_query {
7358: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
7359: my %rhash;
7360: my %libserv = &all_library();
7361: my @server_list = (defined($server_array) ? @$server_array
7362: : keys(%libserv) );
7363: for my $server (@server_list) {
7364: my $domains = '';
7365: if (ref($domains_hash) eq 'HASH') {
7366: $domains = $domains_hash->{$server};
7367: }
7368: unless ($custom or $customshow) {
7369: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
7370: $rhash{$server}=$reply;
7371: }
7372: else {
7373: my $reply=&reply("querysend:".&escape($query).':'.
7374: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
7375: $server);
7376: $rhash{$server}=$reply;
7377: }
7378: }
7379: return \%rhash;
7380: }
7381:
7382: # ----------------------------------------- Send log queries and wait for reply
7383:
7384: sub log_query {
7385: my ($uname,$udom,$query,%filters)=@_;
7386: my $uhome=&homeserver($uname,$udom);
7387: if ($uhome eq 'no_host') { return 'error: no_host'; }
7388: my $uhost=&hostname($uhome);
7389: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
7390: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7391: $uhome);
7392: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
7393: return get_query_reply($queryid);
7394: }
7395:
7396: # -------------------------- Update MySQL table for portfolio file
7397:
7398: sub update_portfolio_table {
7399: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
7400: if ($group ne '') {
7401: $file_name =~s /^\Q$group\E//;
7402: }
7403: my $homeserver = &homeserver($uname,$udom);
7404: my $queryid=
7405: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7406: ':'.&escape($file_name).':'.$action,$homeserver);
7407: my $reply = &get_query_reply($queryid);
7408: return $reply;
7409: }
7410:
7411: # -------------------------- Update MySQL allusers table
7412:
7413: sub update_allusers_table {
7414: my ($uname,$udom,$names) = @_;
7415: my $homeserver = &homeserver($uname,$udom);
7416: my $queryid=
7417: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7418: 'lastname='.&escape($names->{'lastname'}).'%%'.
7419: 'firstname='.&escape($names->{'firstname'}).'%%'.
7420: 'middlename='.&escape($names->{'middlename'}).'%%'.
7421: 'generation='.&escape($names->{'generation'}).'%%'.
7422: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7423: 'id='.&escape($names->{'id'}),$homeserver);
7424: return;
7425: }
7426:
7427: # ------- Request retrieval of institutional classlists for course(s)
7428:
7429: sub fetch_enrollment_query {
7430: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
7431: my $homeserver;
7432: my $maxtries = 1;
7433: if ($context eq 'automated') {
7434: $homeserver = $perlvar{'lonHostID'};
7435: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
7436: } else {
7437: $homeserver = &homeserver($cnum,$dom);
7438: }
7439: my $host=&hostname($homeserver);
7440: my $cmd = '';
7441: foreach my $affiliate (keys(%{$affiliatesref})) {
7442: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
7443: }
7444: $cmd =~ s/%%$//;
7445: $cmd = &escape($cmd);
7446: my $query = 'fetchenrollment';
7447: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
7448: unless ($queryid=~/^\Q$host\E\_/) {
7449: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7450: return 'error: '.$queryid;
7451: }
7452: my $reply = &get_query_reply($queryid);
7453: my $tries = 1;
7454: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7455: $reply = &get_query_reply($queryid);
7456: $tries ++;
7457: }
7458: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7459: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7460: } else {
7461: my @responses = split(/:/,$reply);
7462: if ($homeserver eq $perlvar{'lonHostID'}) {
7463: foreach my $line (@responses) {
7464: my ($key,$value) = split(/=/,$line,2);
7465: $$replyref{$key} = $value;
7466: }
7467: } else {
7468: my $pathname = LONCAPA::tempdir();
7469: foreach my $line (@responses) {
7470: my ($key,$value) = split(/=/,$line);
7471: $$replyref{$key} = $value;
7472: if ($value > 0) {
7473: foreach my $item (@{$$affiliatesref{$key}}) {
7474: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
7475: my $destname = $pathname.'/'.$filename;
7476: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
7477: if ($xml_classlist =~ /^error/) {
7478: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7479: } else {
7480: if ( open(FILE,">$destname") ) {
7481: print FILE &unescape($xml_classlist);
7482: close(FILE);
7483: } else {
7484: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
7485: }
7486: }
7487: }
7488: }
7489: }
7490: }
7491: return 'ok';
7492: }
7493: return 'error';
7494: }
7495:
7496: sub get_query_reply {
7497: my $queryid=shift;
7498: my $replyfile=LONCAPA::tempdir().$queryid;
7499: my $reply='';
7500: for (1..100) {
7501: sleep 2;
7502: if (-e $replyfile.'.end') {
7503: if (open(my $fh,$replyfile)) {
7504: $reply = join('',<$fh>);
7505: close($fh);
7506: } else { return 'error: reply_file_error'; }
7507: return &unescape($reply);
7508: }
7509: }
7510: return 'timeout:'.$queryid;
7511: }
7512:
7513: sub courselog_query {
7514: #
7515: # possible filters:
7516: # url: url or symb
7517: # username
7518: # domain
7519: # action: view, submit, grade
7520: # start: timestamp
7521: # end: timestamp
7522: #
7523: my (%filters)=@_;
7524: unless ($env{'request.course.id'}) { return 'no_course'; }
7525: if ($filters{'url'}) {
7526: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7527: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7528: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7529: }
7530: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7531: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7532: return &log_query($cname,$cdom,'courselog',%filters);
7533: }
7534:
7535: sub userlog_query {
7536: #
7537: # possible filters:
7538: # action: log check role
7539: # start: timestamp
7540: # end: timestamp
7541: #
7542: my ($uname,$udom,%filters)=@_;
7543: return &log_query($uname,$udom,'userlog',%filters);
7544: }
7545:
7546: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7547:
7548: sub auto_run {
7549: my ($cnum,$cdom) = @_;
7550: my $response = 0;
7551: my $settings;
7552: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7553: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7554: $settings = $domconfig{'autoenroll'};
7555: if ($settings->{'run'} eq '1') {
7556: $response = 1;
7557: }
7558: } else {
7559: my $homeserver;
7560: if (&is_course($cdom,$cnum)) {
7561: $homeserver = &homeserver($cnum,$cdom);
7562: } else {
7563: $homeserver = &domain($cdom,'primary');
7564: }
7565: if ($homeserver ne 'no_host') {
7566: $response = &reply('autorun:'.$cdom,$homeserver);
7567: }
7568: }
7569: return $response;
7570: }
7571:
7572: sub auto_get_sections {
7573: my ($cnum,$cdom,$inst_coursecode) = @_;
7574: my $homeserver;
7575: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7576: $homeserver = &homeserver($cnum,$cdom);
7577: }
7578: if (!defined($homeserver)) {
7579: if ($cdom =~ /^$match_domain$/) {
7580: $homeserver = &domain($cdom,'primary');
7581: }
7582: }
7583: my @secs;
7584: if (defined($homeserver)) {
7585: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7586: unless ($response eq 'refused') {
7587: @secs = split(/:/,$response);
7588: }
7589: }
7590: return @secs;
7591: }
7592:
7593: sub auto_new_course {
7594: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
7595: my $homeserver = &homeserver($cnum,$cdom);
7596: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
7597: return $response;
7598: }
7599:
7600: sub auto_validate_courseID {
7601: my ($cnum,$cdom,$inst_course_id) = @_;
7602: my $homeserver = &homeserver($cnum,$cdom);
7603: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
7604: return $response;
7605: }
7606:
7607: sub auto_validate_instcode {
7608: my ($cnum,$cdom,$instcode,$owner) = @_;
7609: my ($homeserver,$response);
7610: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7611: $homeserver = &homeserver($cnum,$cdom);
7612: }
7613: if (!defined($homeserver)) {
7614: if ($cdom =~ /^$match_domain$/) {
7615: $homeserver = &domain($cdom,'primary');
7616: }
7617: }
7618: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7619: &escape($instcode).':'.&escape($owner),$homeserver));
7620: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7621: return ($outcome,$description,$defaultcredits);
7622: }
7623:
7624: sub auto_create_password {
7625: my ($cnum,$cdom,$authparam,$udom) = @_;
7626: my ($homeserver,$response);
7627: my $create_passwd = 0;
7628: my $authchk = '';
7629: if ($udom =~ /^$match_domain$/) {
7630: $homeserver = &domain($udom,'primary');
7631: }
7632: if ($homeserver eq '') {
7633: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7634: $homeserver = &homeserver($cnum,$cdom);
7635: }
7636: }
7637: if ($homeserver eq '') {
7638: $authchk = 'nodomain';
7639: } else {
7640: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7641: if ($response eq 'refused') {
7642: $authchk = 'refused';
7643: } else {
7644: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
7645: }
7646: }
7647: return ($authparam,$create_passwd,$authchk);
7648: }
7649:
7650: sub auto_photo_permission {
7651: my ($cnum,$cdom,$students) = @_;
7652: my $homeserver = &homeserver($cnum,$cdom);
7653: my ($outcome,$perm_reqd,$conditions) =
7654: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
7655: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7656: return (undef,undef);
7657: }
7658: return ($outcome,$perm_reqd,$conditions);
7659: }
7660:
7661: sub auto_checkphotos {
7662: my ($uname,$udom,$pid) = @_;
7663: my $homeserver = &homeserver($uname,$udom);
7664: my ($result,$resulttype);
7665: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
7666: &escape($uname).':'.&escape($pid),
7667: $homeserver));
7668: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7669: return (undef,undef);
7670: }
7671: if ($outcome) {
7672: ($result,$resulttype) = split(/:/,$outcome);
7673: }
7674: return ($result,$resulttype);
7675: }
7676:
7677: sub auto_photochoice {
7678: my ($cnum,$cdom) = @_;
7679: my $homeserver = &homeserver($cnum,$cdom);
7680: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
7681: &escape($cdom),
7682: $homeserver)));
7683: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7684: return (undef,undef);
7685: }
7686: return ($update,$comment);
7687: }
7688:
7689: sub auto_photoupdate {
7690: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7691: my $homeserver = &homeserver($cnum,$dom);
7692: my $host=&hostname($homeserver);
7693: my $cmd = '';
7694: my $maxtries = 1;
7695: foreach my $affiliate (keys(%{$affiliatesref})) {
7696: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
7697: }
7698: $cmd =~ s/%%$//;
7699: $cmd = &escape($cmd);
7700: my $query = 'institutionalphotos';
7701: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7702: unless ($queryid=~/^\Q$host\E\_/) {
7703: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7704: return 'error: '.$queryid;
7705: }
7706: my $reply = &get_query_reply($queryid);
7707: my $tries = 1;
7708: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7709: $reply = &get_query_reply($queryid);
7710: $tries ++;
7711: }
7712: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7713: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7714: } else {
7715: my @responses = split(/:/,$reply);
7716: my $outcome = shift(@responses);
7717: foreach my $item (@responses) {
7718: my ($key,$value) = split(/=/,$item);
7719: $$photo{$key} = $value;
7720: }
7721: return $outcome;
7722: }
7723: return 'error';
7724: }
7725:
7726: sub auto_instcode_format {
7727: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7728: $cat_order) = @_;
7729: my $courses = '';
7730: my @homeservers;
7731: if ($caller eq 'global') {
7732: my %servers = &get_servers($codedom,'library');
7733: foreach my $tryserver (keys(%servers)) {
7734: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7735: push(@homeservers,$tryserver);
7736: }
7737: }
7738: } elsif ($caller eq 'requests') {
7739: if ($codedom =~ /^$match_domain$/) {
7740: my $chome = &domain($codedom,'primary');
7741: unless ($chome eq 'no_host') {
7742: push(@homeservers,$chome);
7743: }
7744: }
7745: } else {
7746: push(@homeservers,&homeserver($caller,$codedom));
7747: }
7748: foreach my $code (keys(%{$instcodes})) {
7749: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
7750: }
7751: chop($courses);
7752: my $ok_response = 0;
7753: my $response;
7754: while (@homeservers > 0 && $ok_response == 0) {
7755: my $server = shift(@homeservers);
7756: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7757: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7758: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
7759: split(/:/,$response);
7760: %{$codes} = (%{$codes},&str2hash($codes_str));
7761: push(@{$codetitles},&str2array($codetitles_str));
7762: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7763: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7764: $ok_response = 1;
7765: }
7766: }
7767: if ($ok_response) {
7768: return 'ok';
7769: } else {
7770: return $response;
7771: }
7772: }
7773:
7774: sub auto_instcode_defaults {
7775: my ($domain,$returnhash,$code_order) = @_;
7776: my @homeservers;
7777:
7778: my %servers = &get_servers($domain,'library');
7779: foreach my $tryserver (keys(%servers)) {
7780: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7781: push(@homeservers,$tryserver);
7782: }
7783: }
7784:
7785: my $response;
7786: foreach my $server (@homeservers) {
7787: $response=&reply('autoinstcodedefaults:'.$domain,$server);
7788: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7789:
7790: foreach my $pair (split(/\&/,$response)) {
7791: my ($name,$value)=split(/\=/,$pair);
7792: if ($name eq 'code_order') {
7793: @{$code_order} = split(/\&/,&unescape($value));
7794: } else {
7795: $returnhash->{&unescape($name)}=&unescape($value);
7796: }
7797: }
7798: return 'ok';
7799: }
7800:
7801: return $response;
7802: }
7803:
7804: sub auto_possible_instcodes {
7805: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7806: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7807: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7808: return;
7809: }
7810: my (@homeservers,$uhome);
7811: if (defined(&domain($domain,'primary'))) {
7812: $uhome=&domain($domain,'primary');
7813: push(@homeservers,&domain($domain,'primary'));
7814: } else {
7815: my %servers = &get_servers($domain,'library');
7816: foreach my $tryserver (keys(%servers)) {
7817: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7818: push(@homeservers,$tryserver);
7819: }
7820: }
7821: }
7822: my $response;
7823: foreach my $server (@homeservers) {
7824: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7825: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7826: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7827: split(':',$response);
7828: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7829: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
7830: foreach my $item (split('&',$cat_title)) {
7831: my ($name,$value)=split('=',$item);
7832: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
7833: }
7834: foreach my $item (split('&',$cat_order)) {
7835: my ($name,$value)=split('=',$item);
7836: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
7837: }
7838: return 'ok';
7839: }
7840: return $response;
7841: }
7842:
7843: sub auto_courserequest_checks {
7844: my ($dom) = @_;
7845: my ($homeserver,%validations);
7846: if ($dom =~ /^$match_domain$/) {
7847: $homeserver = &domain($dom,'primary');
7848: }
7849: unless ($homeserver eq 'no_host') {
7850: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7851: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7852: my @items = split(/&/,$response);
7853: foreach my $item (@items) {
7854: my ($key,$value) = split('=',$item);
7855: $validations{&unescape($key)} = &thaw_unescape($value);
7856: }
7857: }
7858: }
7859: return %validations;
7860: }
7861:
7862: sub auto_courserequest_validation {
7863: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
7864: my ($homeserver,$response);
7865: if ($dom =~ /^$match_domain$/) {
7866: $homeserver = &domain($dom,'primary');
7867: }
7868: unless ($homeserver eq 'no_host') {
7869:
7870: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
7871: ':'.&escape($crstype).':'.&escape($inststatuslist).
7872: ':'.&escape($instcode).':'.&escape($instseclist),
7873: $homeserver));
7874: }
7875: return $response;
7876: }
7877:
7878: sub auto_validate_class_sec {
7879: my ($cdom,$cnum,$owners,$inst_class) = @_;
7880: my $homeserver = &homeserver($cnum,$cdom);
7881: my $ownerlist;
7882: if (ref($owners) eq 'ARRAY') {
7883: $ownerlist = join(',',@{$owners});
7884: } else {
7885: $ownerlist = $owners;
7886: }
7887: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
7888: &escape($ownerlist).':'.$cdom,$homeserver);
7889: return $response;
7890: }
7891:
7892: sub auto_crsreq_update {
7893: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
7894: $code,$inbound) = @_;
7895: my ($homeserver,%crsreqresponse);
7896: if ($cdom =~ /^$match_domain$/) {
7897: $homeserver = &domain($cdom,'primary');
7898: }
7899: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
7900: my $info;
7901: if (ref($inbound) eq 'HASH') {
7902: $info = &freeze_escape($inbound);
7903: }
7904: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
7905: ':'.&escape($action).':'.&escape($ownername).':'.
7906: &escape($ownerdomain).':'.&escape($fullname).':'.
7907: &escape($title).':'.&escape($code).':'.$info,$homeserver);
7908: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7909: my @items = split(/&/,$response);
7910: foreach my $item (@items) {
7911: my ($key,$value) = split('=',$item);
7912: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
7913: }
7914: }
7915: }
7916: return \%crsreqresponse;
7917: }
7918:
7919: # ------------------------------------------------------- Course Group routines
7920:
7921: sub get_coursegroups {
7922: my ($cdom,$cnum,$group,$namespace) = @_;
7923: return(&dump($namespace,$cdom,$cnum,$group));
7924: }
7925:
7926: sub modify_coursegroup {
7927: my ($cdom,$cnum,$groupsettings) = @_;
7928: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7929: }
7930:
7931: sub toggle_coursegroup_status {
7932: my ($cdom,$cnum,$group,$action) = @_;
7933: my ($from_namespace,$to_namespace);
7934: if ($action eq 'delete') {
7935: $from_namespace = 'coursegroups';
7936: $to_namespace = 'deleted_groups';
7937: } else {
7938: $from_namespace = 'deleted_groups';
7939: $to_namespace = 'coursegroups';
7940: }
7941: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
7942: if (my $tmp = &error(%curr_group)) {
7943: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7944: return ('read error',$tmp);
7945: } else {
7946: my %savedsettings = %curr_group;
7947: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
7948: my $deloutcome;
7949: if ($result eq 'ok') {
7950: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
7951: } else {
7952: return ('write error',$result);
7953: }
7954: if ($deloutcome eq 'ok') {
7955: return 'ok';
7956: } else {
7957: return ('delete error',$deloutcome);
7958: }
7959: }
7960: }
7961:
7962: sub modify_group_roles {
7963: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
7964: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7965: my $role = 'gr/'.&escape($userprivs);
7966: my ($uname,$udom) = split(/:/,$user);
7967: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
7968: if ($result eq 'ok') {
7969: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7970: }
7971: return $result;
7972: }
7973:
7974: sub modify_coursegroup_membership {
7975: my ($cdom,$cnum,$membership) = @_;
7976: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7977: return $result;
7978: }
7979:
7980: sub get_active_groups {
7981: my ($udom,$uname,$cdom,$cnum) = @_;
7982: my $now = time;
7983: my %groups = ();
7984: foreach my $key (keys(%env)) {
7985: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
7986: my ($start,$end) = split(/\./,$env{$key});
7987: if (($end!=0) && ($end<$now)) { next; }
7988: if (($start!=0) && ($start>$now)) { next; }
7989: if ($1 eq $cdom && $2 eq $cnum) {
7990: $groups{$3} = $env{$key} ;
7991: }
7992: }
7993: }
7994: return %groups;
7995: }
7996:
7997: sub get_group_membership {
7998: my ($cdom,$cnum,$group) = @_;
7999: return(&dump('groupmembership',$cdom,$cnum,$group));
8000: }
8001:
8002: sub get_users_groups {
8003: my ($udom,$uname,$courseid) = @_;
8004: my @usersgroups;
8005: my $cachetime=1800;
8006:
8007: my $hashid="$udom:$uname:$courseid";
8008: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8009: if (defined($cached)) {
8010: @usersgroups = split(/:/,$grouplist);
8011: } else {
8012: $grouplist = '';
8013: my $courseurl = &courseid_to_courseurl($courseid);
8014: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
8015: my $access_end = $env{'course.'.$courseid.
8016: '.default_enrollment_end_date'};
8017: my $now = time;
8018: foreach my $key (keys(%roleshash)) {
8019: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8020: my $group = $1;
8021: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8022: my $start = $2;
8023: my $end = $1;
8024: if ($start == -1) { next; } # deleted from group
8025: if (($start!=0) && ($start>$now)) { next; }
8026: if (($end!=0) && ($end<$now)) {
8027: if ($access_end && $access_end < $now) {
8028: if ($access_end - $end < 86400) {
8029: push(@usersgroups,$group);
8030: }
8031: }
8032: next;
8033: }
8034: push(@usersgroups,$group);
8035: }
8036: }
8037: }
8038: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8039: $grouplist = join(':',@usersgroups);
8040: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
8041: }
8042: return @usersgroups;
8043: }
8044:
8045: sub devalidate_getgroups_cache {
8046: my ($udom,$uname,$cdom,$cnum)=@_;
8047: my $courseid = $cdom.'_'.$cnum;
8048:
8049: my $hashid="$udom:$uname:$courseid";
8050: &devalidate_cache_new('getgroups',$hashid);
8051: }
8052:
8053: # ------------------------------------------------------------------ Plain Text
8054:
8055: sub plaintext {
8056: my ($short,$type,$cid,$forcedefault) = @_;
8057: if ($short =~ m{^cr/}) {
8058: return (split('/',$short))[-1];
8059: }
8060: if (!defined($cid)) {
8061: $cid = $env{'request.course.id'};
8062: }
8063: my %rolenames = (
8064: Course => 'std',
8065: Community => 'alt1',
8066: );
8067: if ($cid ne '') {
8068: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8069: unless ($forcedefault) {
8070: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8071: &Apache::lonlocal::mt_escape(\$roletext);
8072: return &Apache::lonlocal::mt($roletext);
8073: }
8074: }
8075: }
8076: if ((defined($type)) && (defined($rolenames{$type})) &&
8077: (defined($rolenames{$type})) &&
8078: (defined($prp{$short}{$rolenames{$type}}))) {
8079: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
8080: } elsif ($cid ne '') {
8081: my $crstype = $env{'course.'.$cid.'.type'};
8082: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8083: (defined($prp{$short}{$rolenames{$crstype}}))) {
8084: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8085: }
8086: }
8087: return &Apache::lonlocal::mt($prp{$short}{'std'});
8088: }
8089:
8090: # ----------------------------------------------------------------- Assign Role
8091:
8092: sub assignrole {
8093: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8094: $context)=@_;
8095: my $mrole;
8096: if ($role =~ /^cr\//) {
8097: my $cwosec=$url;
8098: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
8099: unless (&allowed('ccr',$cwosec)) {
8100: my $refused = 1;
8101: if ($context eq 'requestcourses') {
8102: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8103: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8104: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8105: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8106: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8107: if ($crsenv{'internal.courseowner'} eq
8108: $env{'user.name'}.':'.$env{'user.domain'}) {
8109: $refused = '';
8110: }
8111: }
8112: }
8113: }
8114: }
8115: if ($refused) {
8116: &logthis('Refused custom assignrole: '.
8117: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8118: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8119: return 'refused';
8120: }
8121: }
8122: $mrole='cr';
8123: } elsif ($role =~ /^gr\//) {
8124: my $cwogrp=$url;
8125: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
8126: unless (&allowed('mdg',$cwogrp)) {
8127: &logthis('Refused group assignrole: '.
8128: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8129: $env{'user.name'}.' at '.$env{'user.domain'});
8130: return 'refused';
8131: }
8132: $mrole='gr';
8133: } else {
8134: my $cwosec=$url;
8135: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
8136: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8137: my $refused;
8138: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8139: if (!(&allowed('c'.$role,$url))) {
8140: $refused = 1;
8141: }
8142: } else {
8143: $refused = 1;
8144: }
8145: if ($refused) {
8146: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8147: if (!$selfenroll && $context eq 'course') {
8148: my %crsenv;
8149: if ($role eq 'cc' || $role eq 'co') {
8150: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8151: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8152: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8153: if ($crsenv{'internal.courseowner'} eq
8154: $env{'user.name'}.':'.$env{'user.domain'}) {
8155: $refused = '';
8156: }
8157: }
8158: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8159: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8160: if ($crsenv{'internal.courseowner'} eq
8161: $env{'user.name'}.':'.$env{'user.domain'}) {
8162: $refused = '';
8163: }
8164: }
8165: }
8166: }
8167: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
8168: $refused = '';
8169: } elsif ($context eq 'requestcourses') {
8170: my @possroles = ('st','ta','ep','in','cc','co');
8171: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
8172: my $wrongcc;
8173: if ($cnum =~ /^$match_community$/) {
8174: $wrongcc = 1 if ($role eq 'cc');
8175: } else {
8176: $wrongcc = 1 if ($role eq 'co');
8177: }
8178: unless ($wrongcc) {
8179: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8180: if ($crsenv{'internal.courseowner'} eq
8181: $env{'user.name'}.':'.$env{'user.domain'}) {
8182: $refused = '';
8183: }
8184: }
8185: }
8186: } elsif ($context eq 'requestauthor') {
8187: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8188: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8189: if ($env{'environment.requestauthor'} eq 'automatic') {
8190: $refused = '';
8191: } else {
8192: my %domdefaults = &get_domain_defaults($udom);
8193: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8194: my $checkbystatus;
8195: if ($env{'user.adv'}) {
8196: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8197: if ($disposition eq 'automatic') {
8198: $refused = '';
8199: } elsif ($disposition eq '') {
8200: $checkbystatus = 1;
8201: }
8202: } else {
8203: $checkbystatus = 1;
8204: }
8205: if ($checkbystatus) {
8206: if ($env{'environment.inststatus'}) {
8207: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8208: foreach my $type (@inststatuses) {
8209: if (($type ne '') &&
8210: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8211: $refused = '';
8212: }
8213: }
8214: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8215: $refused = '';
8216: }
8217: }
8218: }
8219: }
8220: }
8221: }
8222: if ($refused) {
8223: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8224: ' '.$role.' '.$end.' '.$start.' by '.
8225: $env{'user.name'}.' at '.$env{'user.domain'});
8226: return 'refused';
8227: }
8228: }
8229: } elsif ($role eq 'au') {
8230: if ($url ne '/'.$udom.'/') {
8231: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8232: ' to assign author role for '.$uname.':'.$udom.
8233: ' in domain: '.$url.' refused (wrong domain).');
8234: return 'refused';
8235: }
8236: }
8237: $mrole=$role;
8238: }
8239: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
8240: "$udom:$uname:$url".'_'."$mrole=$role";
8241: if ($end) { $command.='_'.$end; }
8242: if ($start) {
8243: if ($end) {
8244: $command.='_'.$start;
8245: } else {
8246: $command.='_0_'.$start;
8247: }
8248: }
8249: my $origstart = $start;
8250: my $origend = $end;
8251: my $delflag;
8252: # actually delete
8253: if ($deleteflag) {
8254: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
8255: # modify command to delete the role
8256: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
8257: "$udom:$uname:$url".'_'."$mrole";
8258: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
8259: # set start and finish to negative values for userrolelog
8260: $start=-1;
8261: $end=-1;
8262: $delflag = 1;
8263: }
8264: }
8265: # send command
8266: my $answer=&reply($command,&homeserver($uname,$udom));
8267: # log new user role if status is ok
8268: if ($answer eq 'ok') {
8269: &userrolelog($role,$uname,$udom,$url,$start,$end);
8270: if (($role eq 'cc') || ($role eq 'in') ||
8271: ($role eq 'ep') || ($role eq 'ad') ||
8272: ($role eq 'ta') || ($role eq 'st') ||
8273: ($role=~/^cr/) || ($role eq 'gr') ||
8274: ($role eq 'co')) {
8275: # for course roles, perform group memberships changes triggered by role change.
8276: unless ($role =~ /^gr/) {
8277: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8278: $origstart,$selfenroll,$context);
8279: }
8280: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8281: $selfenroll,$context);
8282: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8283: ($role eq 'au') || ($role eq 'dc')) {
8284: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8285: $context);
8286: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8287: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8288: $context);
8289: }
8290: if ($role eq 'cc') {
8291: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8292: }
8293: }
8294: return $answer;
8295: }
8296:
8297: sub autoupdate_coowners {
8298: my ($url,$end,$start,$uname,$udom) = @_;
8299: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8300: if (($cdom ne '') && ($cnum ne '')) {
8301: my $now = time;
8302: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8303: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8304: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8305: my $instcode = $coursehash{'internal.coursecode'};
8306: if ($instcode ne '') {
8307: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8308: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
8309: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
8310: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8311: if ($result eq 'valid') {
8312: if ($coursehash{'internal.co-owners'}) {
8313: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8314: push(@newcoowners,$coowner);
8315: }
8316: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8317: push(@newcoowners,$uname.':'.$udom);
8318: }
8319: @newcoowners = sort(@newcoowners);
8320: } else {
8321: push(@newcoowners,$uname.':'.$udom);
8322: }
8323: } else {
8324: if ($coursehash{'internal.co-owners'}) {
8325: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8326: unless ($coowner eq $uname.':'.$udom) {
8327: push(@newcoowners,$coowner);
8328: }
8329: }
8330: unless (@newcoowners > 0) {
8331: $delcoowners = 1;
8332: $coowners = '';
8333: }
8334: }
8335: }
8336: if (@newcoowners || $delcoowners) {
8337: &store_coowners($cdom,$cnum,$coursehash{'home'},
8338: $delcoowners,@newcoowners);
8339: }
8340: }
8341: }
8342: }
8343: }
8344: }
8345: }
8346:
8347: sub store_coowners {
8348: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8349: my $cid = $cdom.'_'.$cnum;
8350: my ($coowners,$delresult,$putresult);
8351: if (@newcoowners) {
8352: $coowners = join(',',@newcoowners);
8353: my %coownershash = (
8354: 'internal.co-owners' => $coowners,
8355: );
8356: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8357: if ($putresult eq 'ok') {
8358: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8359: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8360: }
8361: }
8362: }
8363: if ($delcoowners) {
8364: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8365: if ($delresult eq 'ok') {
8366: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8367: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8368: }
8369: }
8370: }
8371: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8372: my %crsinfo =
8373: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8374: if (ref($crsinfo{$cid}) eq 'HASH') {
8375: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8376: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8377: }
8378: }
8379: }
8380:
8381: # -------------------------------------------------- Modify user authentication
8382: # Overrides without validation
8383:
8384: sub modifyuserauth {
8385: my ($udom,$uname,$umode,$upass)=@_;
8386: my $uhome=&homeserver($uname,$udom);
8387: unless (&allowed('mau',$udom)) { return 'refused'; }
8388: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
8389: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8390: ' in domain '.$env{'request.role.domain'});
8391: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8392: &escape($upass),$uhome);
8393: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
8394: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8395: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8396: &log($udom,,$uname,$uhome,
8397: 'Authentication changed by '.$env{'user.domain'}.', '.
8398: $env{'user.name'}.', '.$umode.
8399: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8400: unless ($reply eq 'ok') {
8401: &logthis('Authentication mode error: '.$reply);
8402: return 'error: '.$reply;
8403: }
8404: return 'ok';
8405: }
8406:
8407: # --------------------------------------------------------------- Modify a user
8408:
8409: sub modifyuser {
8410: my ($udom, $uname, $uid,
8411: $umode, $upass, $first,
8412: $middle, $last, $gene,
8413: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
8414: $udom= &LONCAPA::clean_domain($udom);
8415: $uname=&LONCAPA::clean_username($uname);
8416: my $showcandelete = 'none';
8417: if (ref($candelete) eq 'ARRAY') {
8418: if (@{$candelete} > 0) {
8419: $showcandelete = join(', ',@{$candelete});
8420: }
8421: }
8422: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
8423: $umode.', '.$first.', '.$middle.', '.
8424: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
8425: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8426: ' desiredhome not specified').
8427: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8428: ' in domain '.$env{'request.role.domain'});
8429: my $uhome=&homeserver($uname,$udom,'true');
8430: my $newuser;
8431: if ($uhome eq 'no_host') {
8432: $newuser = 1;
8433: }
8434: # ----------------------------------------------------------------- Create User
8435: if (($uhome eq 'no_host') &&
8436: (($umode && $upass) || ($umode eq 'localauth'))) {
8437: my $unhome='';
8438: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
8439: $unhome = $desiredhome;
8440: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8441: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
8442: } else { # load balancing routine for determining $unhome
8443: my $loadm=10000000;
8444: my %servers = &get_servers($udom,'library');
8445: foreach my $tryserver (keys(%servers)) {
8446: my $answer=reply('load',$tryserver);
8447: if (($answer=~/\d+/) && ($answer<$loadm)) {
8448: $loadm=$answer;
8449: $unhome=$tryserver;
8450: }
8451: }
8452: }
8453: if (($unhome eq '') || ($unhome eq 'no_host')) {
8454: return 'error: unable to find a home server for '.$uname.
8455: ' in domain '.$udom;
8456: }
8457: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8458: &escape($upass),$unhome);
8459: unless ($reply eq 'ok') {
8460: return 'error: '.$reply;
8461: }
8462: $uhome=&homeserver($uname,$udom,'true');
8463: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
8464: return 'error: unable verify users home machine.';
8465: }
8466: } # End of creation of new user
8467: # ---------------------------------------------------------------------- Add ID
8468: if ($uid) {
8469: $uid=~tr/A-Z/a-z/;
8470: my %uidhash=&idrget($udom,$uname);
8471: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8472: && (!$forceid)) {
8473: unless ($uid eq $uidhash{$uname}) {
8474: return 'error: user id "'.$uid.'" does not match '.
8475: 'current user id "'.$uidhash{$uname}.'".';
8476: }
8477: } else {
8478: &idput($udom,($uname => $uid));
8479: }
8480: }
8481: # -------------------------------------------------------------- Add names, etc
8482: my @tmp=&get('environment',
8483: ['firstname','middlename','lastname','generation','id',
8484: 'permanentemail','inststatus'],
8485: $udom,$uname);
8486: my (%names,%oldnames);
8487: if ($tmp[0] =~ m/^error:.*/) {
8488: %names=();
8489: } else {
8490: %names = @tmp;
8491: %oldnames = %names;
8492: }
8493: #
8494: # If name, email and/or uid are blank (e.g., because an uploaded file
8495: # of users did not contain them), do not overwrite existing values
8496: # unless field is in $candelete array ref.
8497: #
8498:
8499: my @fields = ('firstname','middlename','lastname','generation',
8500: 'permanentemail','id');
8501: my %newvalues;
8502: if (ref($candelete) eq 'ARRAY') {
8503: foreach my $field (@fields) {
8504: if (grep(/^\Q$field\E$/,@{$candelete})) {
8505: if ($field eq 'firstname') {
8506: $names{$field} = $first;
8507: } elsif ($field eq 'middlename') {
8508: $names{$field} = $middle;
8509: } elsif ($field eq 'lastname') {
8510: $names{$field} = $last;
8511: } elsif ($field eq 'generation') {
8512: $names{$field} = $gene;
8513: } elsif ($field eq 'permanentemail') {
8514: $names{$field} = $email;
8515: } elsif ($field eq 'id') {
8516: $names{$field} = $uid;
8517: }
8518: }
8519: }
8520: }
8521: if ($first) { $names{'firstname'} = $first; }
8522: if (defined($middle)) { $names{'middlename'} = $middle; }
8523: if ($last) { $names{'lastname'} = $last; }
8524: if (defined($gene)) { $names{'generation'} = $gene; }
8525: if ($email) {
8526: $email=~s/[^\w\@\.\-\,]//gs;
8527: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
8528: }
8529: if ($uid) { $names{'id'} = $uid; }
8530: if (defined($inststatus)) {
8531: $names{'inststatus'} = '';
8532: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8533: if (ref($usertypes) eq 'HASH') {
8534: my @okstatuses;
8535: foreach my $item (split(/:/,$inststatus)) {
8536: if (defined($usertypes->{$item})) {
8537: push(@okstatuses,$item);
8538: }
8539: }
8540: if (@okstatuses) {
8541: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8542: }
8543: }
8544: }
8545: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
8546: $umode.', '.$first.', '.$middle.', '.
8547: $last.', '.$gene.', '.$email.', '.$inststatus;
8548: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8549: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8550: } else {
8551: $logmsg .= ' during self creation';
8552: }
8553: my $changed;
8554: if ($newuser) {
8555: $changed = 1;
8556: } else {
8557: foreach my $field (@fields) {
8558: if ($names{$field} ne $oldnames{$field}) {
8559: $changed = 1;
8560: last;
8561: }
8562: }
8563: }
8564: unless ($changed) {
8565: $logmsg = 'No changes in user information needed for: '.$logmsg;
8566: &logthis($logmsg);
8567: return 'ok';
8568: }
8569: my $reply = &put('environment', \%names, $udom,$uname);
8570: if ($reply ne 'ok') {
8571: return 'error: '.$reply;
8572: }
8573: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8574: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8575: }
8576: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8577: &devalidate_cache_new('namescache',$uname.':'.$udom);
8578: $logmsg = 'Success modifying user '.$logmsg;
8579: &logthis($logmsg);
8580: return 'ok';
8581: }
8582:
8583: # -------------------------------------------------------------- Modify student
8584:
8585: sub modifystudent {
8586: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
8587: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
8588: $selfenroll,$context,$inststatus,$credits)=@_;
8589: if (!$cid) {
8590: unless ($cid=$env{'request.course.id'}) {
8591: return 'not_in_class';
8592: }
8593: }
8594: # --------------------------------------------------------------- Make the user
8595: my $reply=&modifyuser
8596: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
8597: $desiredhome,$email,$inststatus);
8598: unless ($reply eq 'ok') { return $reply; }
8599: # This will cause &modify_student_enrollment to get the uid from the
8600: # student's environment
8601: $uid = undef if (!$forceid);
8602: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
8603: $gene,$usec,$end,$start,$type,$locktype,
8604: $cid,$selfenroll,$context,$credits);
8605: return $reply;
8606: }
8607:
8608: sub modify_student_enrollment {
8609: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8610: $locktype,$cid,$selfenroll,$context,$credits) = @_;
8611: my ($cdom,$cnum,$chome);
8612: if (!$cid) {
8613: unless ($cid=$env{'request.course.id'}) {
8614: return 'not_in_class';
8615: }
8616: $cdom=$env{'course.'.$cid.'.domain'};
8617: $cnum=$env{'course.'.$cid.'.num'};
8618: } else {
8619: ($cdom,$cnum)=split(/_/,$cid);
8620: }
8621: $chome=$env{'course.'.$cid.'.home'};
8622: if (!$chome) {
8623: $chome=&homeserver($cnum,$cdom);
8624: }
8625: if (!$chome) { return 'unknown_course'; }
8626: # Make sure the user exists
8627: my $uhome=&homeserver($uname,$udom);
8628: if (($uhome eq '') || ($uhome eq 'no_host')) {
8629: return 'error: no such user';
8630: }
8631: # Get student data if we were not given enough information
8632: if (!defined($first) || $first eq '' ||
8633: !defined($last) || $last eq '' ||
8634: !defined($uid) || $uid eq '' ||
8635: !defined($middle) || $middle eq '' ||
8636: !defined($gene) || $gene eq '') {
8637: # They did not supply us with enough data to enroll the student, so
8638: # we need to pick up more information.
8639: my %tmp = &get('environment',
8640: ['firstname','middlename','lastname', 'generation','id']
8641: ,$udom,$uname);
8642:
8643: #foreach my $key (keys(%tmp)) {
8644: # &logthis("key $key = ".$tmp{$key});
8645: #}
8646: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8647: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8648: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
8649: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
8650: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8651: }
8652: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
8653: my $user = "$uname:$udom";
8654: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
8655: my $reply=cput('classlist',
8656: {$user =>
8657: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
8658: $cdom,$cnum);
8659: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8660: &devalidate_getsection_cache($udom,$uname,$cid);
8661: } else {
8662: return 'error: '.$reply;
8663: }
8664: # Add student role to user
8665: my $uurl='/'.$cid;
8666: $uurl=~s/\_/\//g;
8667: if ($usec) {
8668: $uurl.='/'.$usec;
8669: }
8670: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8671: $selfenroll,$context);
8672: if ($result ne 'ok') {
8673: if ($old_entry{$user} ne '') {
8674: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8675: } else {
8676: $reply = &del('classlist',[$user],$cdom,$cnum);
8677: }
8678: }
8679: return $result;
8680: }
8681:
8682: sub format_name {
8683: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8684: my $name;
8685: if ($first ne 'lastname') {
8686: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8687: } else {
8688: if ($lastname=~/\S/) {
8689: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8690: $name=~s/\s+,/,/;
8691: } else {
8692: $name.= $firstname.' '.$middlename.' '.$generation;
8693: }
8694: }
8695: $name=~s/^\s+//;
8696: $name=~s/\s+$//;
8697: $name=~s/\s+/ /g;
8698: return $name;
8699: }
8700:
8701: # ------------------------------------------------- Write to course preferences
8702:
8703: sub writecoursepref {
8704: my ($courseid,%prefs)=@_;
8705: $courseid=~s/^\///;
8706: $courseid=~s/\_/\//g;
8707: my ($cdomain,$cnum)=split(/\//,$courseid);
8708: my $chome=homeserver($cnum,$cdomain);
8709: if (($chome eq '') || ($chome eq 'no_host')) {
8710: return 'error: no such course';
8711: }
8712: my $cstring='';
8713: foreach my $pref (keys(%prefs)) {
8714: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
8715: }
8716: $cstring=~s/\&$//;
8717: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8718: }
8719:
8720: # ---------------------------------------------------------- Make/modify course
8721:
8722: sub createcourse {
8723: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
8724: $course_owner,$crstype,$cnum,$context,$category)=@_;
8725: $url=&declutter($url);
8726: my $cid='';
8727: if ($context eq 'requestcourses') {
8728: my $can_create = 0;
8729: my ($ownername,$ownerdom) = split(':',$course_owner);
8730: if ($udom eq $ownerdom) {
8731: if (&usertools_access($ownername,$ownerdom,$category,undef,
8732: $context)) {
8733: $can_create = 1;
8734: }
8735: } else {
8736: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8737: $category);
8738: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8739: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8740: if (@curr > 0) {
8741: my @options = qw(approval validate autolimit);
8742: my $optregex = join('|',@options);
8743: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8744: $can_create = 1;
8745: }
8746: }
8747: }
8748: }
8749: if ($can_create) {
8750: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8751: unless (&allowed('ccc',$udom)) {
8752: return 'refused';
8753: }
8754: }
8755: } else {
8756: return 'refused';
8757: }
8758: } elsif (!&allowed('ccc',$udom)) {
8759: return 'refused';
8760: }
8761: # --------------------------------------------------------------- Get Unique ID
8762: my $uname;
8763: if ($cnum =~ /^$match_courseid$/) {
8764: my $chome=&homeserver($cnum,$udom,'true');
8765: if (($chome eq '') || ($chome eq 'no_host')) {
8766: $uname = $cnum;
8767: } else {
8768: $uname = &generate_coursenum($udom,$crstype);
8769: }
8770: } else {
8771: $uname = &generate_coursenum($udom,$crstype);
8772: }
8773: return $uname if ($uname =~ /^error/);
8774: # -------------------------------------------------- Check supplied server name
8775: if (!defined($course_server)) {
8776: if (defined(&domain($udom,'primary'))) {
8777: $course_server = &domain($udom,'primary');
8778: } else {
8779: $course_server = $env{'user.home'};
8780: }
8781: }
8782: my %host_servers =
8783: &Apache::lonnet::get_servers($udom,'library');
8784: unless ($host_servers{$course_server}) {
8785: return 'error: invalid home server for course: '.$course_server;
8786: }
8787: # ------------------------------------------------------------- Make the course
8788: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
8789: $course_server);
8790: unless ($reply eq 'ok') { return 'error: '.$reply; }
8791: my $uhome=&homeserver($uname,$udom,'true');
8792: if (($uhome eq '') || ($uhome eq 'no_host')) {
8793: return 'error: no such course';
8794: }
8795: # ----------------------------------------------------------------- Course made
8796: # log existence
8797: my $now = time;
8798: my $newcourse = {
8799: $udom.'_'.$uname => {
8800: description => $description,
8801: inst_code => $inst_code,
8802: owner => $course_owner,
8803: type => $crstype,
8804: creator => $env{'user.name'}.':'.
8805: $env{'user.domain'},
8806: created => $now,
8807: context => $context,
8808: },
8809: };
8810: &courseidput($udom,$newcourse,$uhome,'notime');
8811: # set toplevel url
8812: my $topurl=$url;
8813: unless ($nonstandard) {
8814: # ------------------------------------------ For standard courses, make top url
8815: my $mapurl=&clutter($url);
8816: if ($mapurl eq '/res/') { $mapurl=''; }
8817: $env{'form.initmap'}=(<<ENDINITMAP);
8818: <map>
8819: <resource id="1" type="start"></resource>
8820: <resource id="2" src="$mapurl"></resource>
8821: <resource id="3" type="finish"></resource>
8822: <link index="1" from="1" to="2"></link>
8823: <link index="2" from="2" to="3"></link>
8824: </map>
8825: ENDINITMAP
8826: $topurl=&declutter(
8827: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
8828: );
8829: }
8830: # ----------------------------------------------------------- Write preferences
8831: &writecoursepref($udom.'_'.$uname,
8832: ('description' => $description,
8833: 'url' => $topurl,
8834: 'internal.creator' => $env{'user.name'}.':'.
8835: $env{'user.domain'},
8836: 'internal.created' => $now,
8837: 'internal.creationcontext' => $context)
8838: );
8839: return '/'.$udom.'/'.$uname;
8840: }
8841:
8842: # ------------------------------------------------------------------- Create ID
8843: sub generate_coursenum {
8844: my ($udom,$crstype) = @_;
8845: my $domdesc = &domain($udom);
8846: return 'error: invalid domain' if ($domdesc eq '');
8847: my $first;
8848: if ($crstype eq 'Community') {
8849: $first = '0';
8850: } else {
8851: $first = int(1+rand(9));
8852: }
8853: my $uname=$first.
8854: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8855: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8856: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8857: # ----------------------------------------------- Make sure that does not exist
8858: my $uhome=&homeserver($uname,$udom,'true');
8859: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8860: if ($crstype eq 'Community') {
8861: $first = '0';
8862: } else {
8863: $first = int(1+rand(9));
8864: }
8865: $uname=$first.
8866: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8867: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8868: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8869: $uhome=&homeserver($uname,$udom,'true');
8870: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8871: return 'error: unable to generate unique course-ID';
8872: }
8873: }
8874: return $uname;
8875: }
8876:
8877: sub is_course {
8878: my ($cdom, $cnum) = scalar(@_) == 1 ?
8879: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8880:
8881: return unless $cdom and $cnum;
8882:
8883: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8884: '.');
8885:
8886: return unless(exists($courses{$cdom.'_'.$cnum}));
8887: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
8888: }
8889:
8890: sub store_userdata {
8891: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
8892: my $result;
8893: if ($datakey ne '') {
8894: if (ref($storehash) eq 'HASH') {
8895: if ($udom eq '' || $uname eq '') {
8896: $udom = $env{'user.domain'};
8897: $uname = $env{'user.name'};
8898: }
8899: my $uhome=&homeserver($uname,$udom);
8900: if (($uhome eq '') || ($uhome eq 'no_host')) {
8901: $result = 'error: no_host';
8902: } else {
8903: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8904: $storehash->{'host'} = $perlvar{'lonHostID'};
8905:
8906: my $namevalue='';
8907: foreach my $key (keys(%{$storehash})) {
8908: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8909: }
8910: $namevalue=~s/\&$//;
8911: unless ($namespace eq 'courserequests') {
8912: $datakey = &escape($datakey);
8913: }
8914: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8915: $namevalue,$uhome);
8916: }
8917: } else {
8918: $result = 'error: data to store was not a hash reference';
8919: }
8920: } else {
8921: $result= 'error: invalid requestkey';
8922: }
8923: return $result;
8924: }
8925:
8926: # ---------------------------------------------------------- Assign Custom Role
8927:
8928: sub assigncustomrole {
8929: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
8930: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
8931: $end,$start,$deleteflag,$selfenroll,$context);
8932: }
8933:
8934: # ----------------------------------------------------------------- Revoke Role
8935:
8936: sub revokerole {
8937: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
8938: my $now=time;
8939: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
8940: }
8941:
8942: # ---------------------------------------------------------- Revoke Custom Role
8943:
8944: sub revokecustomrole {
8945: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
8946: my $now=time;
8947: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
8948: $deleteflag,$selfenroll,$context);
8949: }
8950:
8951: # ------------------------------------------------------------ Disk usage
8952: sub diskusage {
8953: my ($udom,$uname,$directorypath,$getpropath)=@_;
8954: $directorypath =~ s/\/$//;
8955: my $listing=&reply('du2:'.&escape($directorypath).':'
8956: .&escape($getpropath).':'.&escape($uname).':'
8957: .&escape($udom),homeserver($uname,$udom));
8958: if ($listing eq 'unknown_cmd') {
8959: if ($getpropath) {
8960: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8961: }
8962: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8963: }
8964: return $listing;
8965: }
8966:
8967: sub is_locked {
8968: my ($file_name, $domain, $user, $which) = @_;
8969: my @check;
8970: my $is_locked;
8971: push (@check,$file_name);
8972: my %locked = &get('file_permissions',\@check,
8973: $env{'user.domain'},$env{'user.name'});
8974: my ($tmp)=keys(%locked);
8975: if ($tmp=~/^error:/) { undef(%locked); }
8976:
8977: if (ref($locked{$file_name}) eq 'ARRAY') {
8978: $is_locked = 'false';
8979: foreach my $entry (@{$locked{$file_name}}) {
8980: if (ref($entry) eq 'ARRAY') {
8981: $is_locked = 'true';
8982: if (ref($which) eq 'ARRAY') {
8983: push(@{$which},$entry);
8984: } else {
8985: last;
8986: }
8987: }
8988: }
8989: } else {
8990: $is_locked = 'false';
8991: }
8992: return $is_locked;
8993: }
8994:
8995: sub declutter_portfile {
8996: my ($file) = @_;
8997: $file =~ s{^(/portfolio/|portfolio/)}{/};
8998: return $file;
8999: }
9000:
9001: # ------------------------------------------------------------- Mark as Read Only
9002:
9003: sub mark_as_readonly {
9004: my ($domain,$user,$files,$what) = @_;
9005: my %current_permissions = &dump('file_permissions',$domain,$user);
9006: my ($tmp)=keys(%current_permissions);
9007: if ($tmp=~/^error:/) { undef(%current_permissions); }
9008: foreach my $file (@{$files}) {
9009: $file = &declutter_portfile($file);
9010: push(@{$current_permissions{$file}},$what);
9011: }
9012: &put('file_permissions',\%current_permissions,$domain,$user);
9013: return;
9014: }
9015:
9016: # ------------------------------------------------------------Save Selected Files
9017:
9018: sub save_selected_files {
9019: my ($user, $path, @files) = @_;
9020: my $filename = $user."savedfiles";
9021: my @other_files = &files_not_in_path($user, $path);
9022: open (OUT, '>'.$tmpdir.$filename);
9023: foreach my $file (@files) {
9024: print (OUT $env{'form.currentpath'}.$file."\n");
9025: }
9026: foreach my $file (@other_files) {
9027: print (OUT $file."\n");
9028: }
9029: close (OUT);
9030: return 'ok';
9031: }
9032:
9033: sub clear_selected_files {
9034: my ($user) = @_;
9035: my $filename = $user."savedfiles";
9036: open (OUT, '>'.LONCAPA::tempdir().$filename);
9037: print (OUT undef);
9038: close (OUT);
9039: return ("ok");
9040: }
9041:
9042: sub files_in_path {
9043: my ($user, $path) = @_;
9044: my $filename = $user."savedfiles";
9045: my %return_files;
9046: open (IN, '<'.LONCAPA::tempdir().$filename);
9047: while (my $line_in = <IN>) {
9048: chomp ($line_in);
9049: my @paths_and_file = split (m!/!, $line_in);
9050: my $file_part = pop (@paths_and_file);
9051: my $path_part = join ('/', @paths_and_file);
9052: $path_part.='/';
9053: my $path_and_file = $path_part.$file_part;
9054: if ($path_part eq $path) {
9055: $return_files{$file_part}= 'selected';
9056: }
9057: }
9058: close (IN);
9059: return (\%return_files);
9060: }
9061:
9062: # called in portfolio select mode, to show files selected NOT in current directory
9063: sub files_not_in_path {
9064: my ($user, $path) = @_;
9065: my $filename = $user."savedfiles";
9066: my @return_files;
9067: my $path_part;
9068: open(IN, '<'.LONCAPA::.$filename);
9069: while (my $line = <IN>) {
9070: #ok, I know it's clunky, but I want it to work
9071: my @paths_and_file = split(m|/|, $line);
9072: my $file_part = pop(@paths_and_file);
9073: chomp($file_part);
9074: my $path_part = join('/', @paths_and_file);
9075: $path_part .= '/';
9076: my $path_and_file = $path_part.$file_part;
9077: if ($path_part ne $path) {
9078: push(@return_files, ($path_and_file));
9079: }
9080: }
9081: close(OUT);
9082: return (@return_files);
9083: }
9084:
9085: #----------------------------------------------Get portfolio file permissions
9086:
9087: sub get_portfile_permissions {
9088: my ($domain,$user) = @_;
9089: my %current_permissions = &dump('file_permissions',$domain,$user);
9090: my ($tmp)=keys(%current_permissions);
9091: if ($tmp=~/^error:/) { undef(%current_permissions); }
9092: return \%current_permissions;
9093: }
9094:
9095: #---------------------------------------------Get portfolio file access controls
9096:
9097: sub get_access_controls {
9098: my ($current_permissions,$group,$file) = @_;
9099: my %access;
9100: my $real_file = $file;
9101: $file =~ s/\.meta$//;
9102: if (defined($file)) {
9103: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9104: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
9105: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
9106: }
9107: }
9108: } else {
9109: foreach my $key (keys(%{$current_permissions})) {
9110: if ($key =~ /\0accesscontrol$/) {
9111: if (defined($group)) {
9112: if ($key !~ m-^\Q$group\E/-) {
9113: next;
9114: }
9115: }
9116: my ($fullpath) = split(/\0/,$key);
9117: if (ref($$current_permissions{$key}) eq 'HASH') {
9118: foreach my $control (keys(%{$$current_permissions{$key}})) {
9119: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9120: }
9121: }
9122: }
9123: }
9124: }
9125: return %access;
9126: }
9127:
9128: sub modify_access_controls {
9129: my ($file_name,$changes,$domain,$user)=@_;
9130: my ($outcome,$deloutcome);
9131: my %store_permissions;
9132: my %new_values;
9133: my %new_control;
9134: my %translation;
9135: my @deletions = ();
9136: my $now = time;
9137: if (exists($$changes{'activate'})) {
9138: if (ref($$changes{'activate'}) eq 'HASH') {
9139: my @newitems = sort(keys(%{$$changes{'activate'}}));
9140: my $numnew = scalar(@newitems);
9141: for (my $i=0; $i<$numnew; $i++) {
9142: my $newkey = $newitems[$i];
9143: my $newid = &Apache::loncommon::get_cgi_id();
9144: if ($newkey =~ /^\d+:/) {
9145: $newkey =~ s/^(\d+)/$newid/;
9146: $translation{$1} = $newid;
9147: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9148: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9149: $translation{$1} = $newid;
9150: }
9151: $new_values{$file_name."\0".$newkey} =
9152: $$changes{'activate'}{$newitems[$i]};
9153: $new_control{$newkey} = $now;
9154: }
9155: }
9156: }
9157: my %todelete;
9158: my %changed_items;
9159: foreach my $action ('delete','update') {
9160: if (exists($$changes{$action})) {
9161: if (ref($$changes{$action}) eq 'HASH') {
9162: foreach my $key (keys(%{$$changes{$action}})) {
9163: my ($itemnum) = ($key =~ /^([^:]+):/);
9164: if ($action eq 'delete') {
9165: $todelete{$itemnum} = 1;
9166: } else {
9167: $changed_items{$itemnum} = $key;
9168: }
9169: }
9170: }
9171: }
9172: }
9173: # get lock on access controls for file.
9174: my $lockhash = {
9175: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9176: ':'.$env{'user.domain'},
9177: };
9178: my $tries = 0;
9179: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9180:
9181: while (($gotlock ne 'ok') && $tries <3) {
9182: $tries ++;
9183: sleep 1;
9184: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9185: }
9186: if ($gotlock eq 'ok') {
9187: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9188: my ($tmp)=keys(%curr_permissions);
9189: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9190: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9191: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9192: if (ref($curr_controls) eq 'HASH') {
9193: foreach my $control_item (keys(%{$curr_controls})) {
9194: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9195: if (defined($todelete{$itemnum})) {
9196: push(@deletions,$file_name."\0".$control_item);
9197: } else {
9198: if (defined($changed_items{$itemnum})) {
9199: $new_control{$changed_items{$itemnum}} = $now;
9200: push(@deletions,$file_name."\0".$control_item);
9201: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9202: } else {
9203: $new_control{$control_item} = $$curr_controls{$control_item};
9204: }
9205: }
9206: }
9207: }
9208: }
9209: my ($group);
9210: if (&is_course($domain,$user)) {
9211: ($group,my $file) = split(/\//,$file_name,2);
9212: }
9213: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9214: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9215: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9216: # remove lock
9217: my @del_lock = ($file_name."\0".'locked_access_records');
9218: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
9219: my $sqlresult =
9220: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
9221: $group);
9222: } else {
9223: $outcome = "error: could not obtain lockfile\n";
9224: }
9225: return ($outcome,$deloutcome,\%new_values,\%translation);
9226: }
9227:
9228: sub make_public_indefinitely {
9229: my ($requrl) = @_;
9230: my $now = time;
9231: my $action = 'activate';
9232: my $aclnum = 0;
9233: if (&is_portfolio_url($requrl)) {
9234: my (undef,$udom,$unum,$file_name,$group) =
9235: &parse_portfolio_url($requrl);
9236: my $current_perms = &get_portfile_permissions($udom,$unum);
9237: my %access_controls = &get_access_controls($current_perms,
9238: $group,$file_name);
9239: foreach my $key (keys(%{$access_controls{$file_name}})) {
9240: my ($num,$scope,$end,$start) =
9241: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9242: if ($scope eq 'public') {
9243: if ($start <= $now && $end == 0) {
9244: $action = 'none';
9245: } else {
9246: $action = 'update';
9247: $aclnum = $num;
9248: }
9249: last;
9250: }
9251: }
9252: if ($action eq 'none') {
9253: return 'ok';
9254: } else {
9255: my %changes;
9256: my $newend = 0;
9257: my $newstart = $now;
9258: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9259: $changes{$action}{$newkey} = {
9260: type => 'public',
9261: time => {
9262: start => $newstart,
9263: end => $newend,
9264: },
9265: };
9266: my ($outcome,$deloutcome,$new_values,$translation) =
9267: &modify_access_controls($file_name,\%changes,$udom,$unum);
9268: return $outcome;
9269: }
9270: } else {
9271: return 'invalid';
9272: }
9273: }
9274:
9275: #------------------------------------------------------Get Marked as Read Only
9276:
9277: sub get_marked_as_readonly {
9278: my ($domain,$user,$what,$group) = @_;
9279: my $current_permissions = &get_portfile_permissions($domain,$user);
9280: my @readonly_files;
9281: my $cmp1=$what;
9282: if (ref($what)) { $cmp1=join('',@{$what}) };
9283: while (my ($file_name,$value) = each(%{$current_permissions})) {
9284: if (defined($group)) {
9285: if ($file_name !~ m-^\Q$group\E/-) {
9286: next;
9287: }
9288: }
9289: if (ref($value) eq "ARRAY"){
9290: foreach my $stored_what (@{$value}) {
9291: my $cmp2=$stored_what;
9292: if (ref($stored_what) eq 'ARRAY') {
9293: $cmp2=join('',@{$stored_what});
9294: }
9295: if ($cmp1 eq $cmp2) {
9296: push(@readonly_files, $file_name);
9297: last;
9298: } elsif (!defined($what)) {
9299: push(@readonly_files, $file_name);
9300: last;
9301: }
9302: }
9303: }
9304: }
9305: return @readonly_files;
9306: }
9307: #-----------------------------------------------------------Get Marked as Read Only Hash
9308:
9309: sub get_marked_as_readonly_hash {
9310: my ($current_permissions,$group,$what) = @_;
9311: my %readonly_files;
9312: while (my ($file_name,$value) = each(%{$current_permissions})) {
9313: if (defined($group)) {
9314: if ($file_name !~ m-^\Q$group\E/-) {
9315: next;
9316: }
9317: }
9318: if (ref($value) eq "ARRAY"){
9319: foreach my $stored_what (@{$value}) {
9320: if (ref($stored_what) eq 'ARRAY') {
9321: foreach my $lock_descriptor(@{$stored_what}) {
9322: if ($lock_descriptor eq 'graded') {
9323: $readonly_files{$file_name} = 'graded';
9324: } elsif ($lock_descriptor eq 'handback') {
9325: $readonly_files{$file_name} = 'handback';
9326: } else {
9327: if (!exists($readonly_files{$file_name})) {
9328: $readonly_files{$file_name} = 'locked';
9329: }
9330: }
9331: }
9332: }
9333: }
9334: }
9335: }
9336: return %readonly_files;
9337: }
9338: # ------------------------------------------------------------ Unmark as Read Only
9339:
9340: sub unmark_as_readonly {
9341: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9342: # for portfolio submissions, $what contains [$symb,$crsid]
9343: my ($domain,$user,$what,$file_name,$group) = @_;
9344: $file_name = &declutter_portfile($file_name);
9345: my $symb_crs = $what;
9346: if (ref($what)) { $symb_crs=join('',@$what); }
9347: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
9348: my ($tmp)=keys(%current_permissions);
9349: if ($tmp=~/^error:/) { undef(%current_permissions); }
9350: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
9351: foreach my $file (@readonly_files) {
9352: my $clean_file = &declutter_portfile($file);
9353: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
9354: my $current_locks = $current_permissions{$file};
9355: my @new_locks;
9356: my @del_keys;
9357: if (ref($current_locks) eq "ARRAY"){
9358: foreach my $locker (@{$current_locks}) {
9359: my $compare=$locker;
9360: if (ref($locker) eq 'ARRAY') {
9361: $compare=join('',@{$locker});
9362: if ($compare ne $symb_crs) {
9363: push(@new_locks, $locker);
9364: }
9365: }
9366: }
9367: if (scalar(@new_locks) > 0) {
9368: $current_permissions{$file} = \@new_locks;
9369: } else {
9370: push(@del_keys, $file);
9371: &del('file_permissions',\@del_keys, $domain, $user);
9372: delete($current_permissions{$file});
9373: }
9374: }
9375: }
9376: &put('file_permissions',\%current_permissions,$domain,$user);
9377: return;
9378: }
9379:
9380: # ------------------------------------------------------------ Directory lister
9381:
9382: sub dirlist {
9383: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
9384: $uri=~s/^\///;
9385: $uri=~s/\/$//;
9386: my ($udom, $uname);
9387: if ($getuserdir) {
9388: $udom = $userdomain;
9389: $uname = $username;
9390: } else {
9391: (undef,$udom,$uname)=split(/\//,$uri);
9392: if(defined($userdomain)) {
9393: $udom = $userdomain;
9394: }
9395: if(defined($username)) {
9396: $uname = $username;
9397: }
9398: }
9399: my ($dirRoot,$listing,@listing_results);
9400:
9401: $dirRoot = $perlvar{'lonDocRoot'};
9402: if (defined($getpropath)) {
9403: $dirRoot = &propath($udom,$uname);
9404: $dirRoot =~ s/\/$//;
9405: } elsif (defined($getuserdir)) {
9406: my $subdir=$uname.'__';
9407: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9408: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9409: ."/$udom/$subdir/$uname";
9410: } elsif (defined($alternateRoot)) {
9411: $dirRoot = $alternateRoot;
9412: }
9413:
9414: if($udom) {
9415: if($uname) {
9416: my $uhome = &homeserver($uname,$udom);
9417: if ($uhome eq 'no_host') {
9418: return ([],'no_host');
9419: }
9420: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
9421: .$getuserdir.':'.&escape($dirRoot)
9422: .':'.&escape($uname).':'.&escape($udom),$uhome);
9423: if ($listing eq 'unknown_cmd') {
9424: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
9425: } else {
9426: @listing_results = map { &unescape($_); } split(/:/,$listing);
9427: }
9428: if ($listing eq 'unknown_cmd') {
9429: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
9430: @listing_results = split(/:/,$listing);
9431: } else {
9432: @listing_results = map { &unescape($_); } split(/:/,$listing);
9433: }
9434: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9435: ($listing eq 'rejected') || ($listing eq 'refused') ||
9436: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9437: return ([],$listing);
9438: } else {
9439: return (\@listing_results);
9440: }
9441: } elsif(!$alternateRoot) {
9442: my (%allusers,%listerror);
9443: my %servers = &get_servers($udom,'library');
9444: foreach my $tryserver (keys(%servers)) {
9445: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9446: &escape($udom),$tryserver);
9447: if ($listing eq 'unknown_cmd') {
9448: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9449: $udom, $tryserver);
9450: } else {
9451: @listing_results = map { &unescape($_); } split(/:/,$listing);
9452: }
9453: if ($listing eq 'unknown_cmd') {
9454: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9455: $udom, $tryserver);
9456: @listing_results = split(/:/,$listing);
9457: } else {
9458: @listing_results =
9459: map { &unescape($_); } split(/:/,$listing);
9460: }
9461: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9462: ($listing eq 'rejected') || ($listing eq 'refused') ||
9463: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9464: $listerror{$tryserver} = $listing;
9465: } else {
9466: foreach my $line (@listing_results) {
9467: my ($entry) = split(/&/,$line,2);
9468: $allusers{$entry} = 1;
9469: }
9470: }
9471: }
9472: my @alluserslist=();
9473: foreach my $user (sort(keys(%allusers))) {
9474: push(@alluserslist,$user.'&user');
9475: }
9476: return (\@alluserslist);
9477: } else {
9478: return ([],'missing username');
9479: }
9480: } elsif(!defined($getpropath)) {
9481: my $path = $perlvar{'lonDocRoot'}.'/res/';
9482: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9483: return (\@all_domains);
9484: } else {
9485: return ([],'missing domain');
9486: }
9487: }
9488:
9489: # --------------------------------------------- GetFileTimestamp
9490: # This function utilizes dirlist and returns the date stamp for
9491: # when it was last modified. It will also return an error of -1
9492: # if an error occurs
9493:
9494: sub GetFileTimestamp {
9495: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
9496: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9497: $studentName = &LONCAPA::clean_username($studentName);
9498: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9499: undef,$getuserdir);
9500: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9501: return -1;
9502: }
9503: if (ref($fileref) eq 'ARRAY') {
9504: my @stats = split('&',$fileref->[0]);
9505: # @stats contains first the filename, then the stat output
9506: return $stats[10]; # so this is 10 instead of 9.
9507: } else {
9508: return -1;
9509: }
9510: }
9511:
9512: sub stat_file {
9513: my ($uri) = @_;
9514: $uri = &clutter_with_no_wrapper($uri);
9515:
9516: my ($udom,$uname,$file);
9517: if ($uri =~ m-^/(uploaded|editupload)/-) {
9518: ($udom,$uname,$file) =
9519: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
9520: $file = 'userfiles/'.$file;
9521: }
9522: if ($uri =~ m-^/res/-) {
9523: ($udom,$uname) =
9524: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
9525: $file = $uri;
9526: }
9527:
9528: if (!$udom || !$uname || !$file) {
9529: # unable to handle the uri
9530: return ();
9531: }
9532: my $getpropath;
9533: if ($file =~ /^userfiles\//) {
9534: $getpropath = 1;
9535: }
9536: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9537: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9538: return ();
9539: } else {
9540: if (ref($listref) eq 'ARRAY') {
9541: my @stats = split('&',$listref->[0]);
9542: shift(@stats); #filename is first
9543: return @stats;
9544: }
9545: }
9546: return ();
9547: }
9548:
9549: # -------------------------------------------------------- Value of a Condition
9550:
9551: # gets the value of a specific preevaluated condition
9552: # stored in the string $env{user.state.<cid>}
9553: # or looks up a condition reference in the bighash and if if hasn't
9554: # already been evaluated recurses into docondval to get the value of
9555: # the condition, then memoizing it to
9556: # $env{user.state.<cid>.<condition>}
9557: sub directcondval {
9558: my $number=shift;
9559: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
9560: &Apache::lonuserstate::evalstate();
9561: }
9562: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9563: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9564: } elsif ($number =~ /^_/) {
9565: my $sub_condition;
9566: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9567: &GDBM_READER(),0640)) {
9568: $sub_condition=$bighash{'conditions'.$number};
9569: untie(%bighash);
9570: }
9571: my $value = &docondval($sub_condition);
9572: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
9573: return $value;
9574: }
9575: if ($env{'user.state.'.$env{'request.course.id'}}) {
9576: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
9577: } else {
9578: return 2;
9579: }
9580: }
9581:
9582: # get the collection of conditions for this resource
9583: sub condval {
9584: my $condidx=shift;
9585: my $allpathcond='';
9586: foreach my $cond (split(/\|/,$condidx)) {
9587: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9588: $allpathcond.=
9589: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9590: }
9591: }
9592: $allpathcond=~s/\|$//;
9593: return &docondval($allpathcond);
9594: }
9595:
9596: #evaluates an expression of conditions
9597: sub docondval {
9598: my ($allpathcond) = @_;
9599: my $result=0;
9600: if ($env{'request.course.id'}
9601: && defined($allpathcond)) {
9602: my $operand='|';
9603: my @stack;
9604: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9605: if ($chunk eq '(') {
9606: push @stack,($operand,$result);
9607: } elsif ($chunk eq ')') {
9608: my $before=pop @stack;
9609: if (pop @stack eq '&') {
9610: $result=$result>$before?$before:$result;
9611: } else {
9612: $result=$result>$before?$result:$before;
9613: }
9614: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9615: $operand=$chunk;
9616: } else {
9617: my $new=directcondval($chunk);
9618: if ($operand eq '&') {
9619: $result=$result>$new?$new:$result;
9620: } else {
9621: $result=$result>$new?$result:$new;
9622: }
9623: }
9624: }
9625: }
9626: return $result;
9627: }
9628:
9629: # ---------------------------------------------------- Devalidate courseresdata
9630:
9631: sub devalidatecourseresdata {
9632: my ($coursenum,$coursedomain)=@_;
9633: my $hashid=$coursenum.':'.$coursedomain;
9634: &devalidate_cache_new('courseres',$hashid);
9635: }
9636:
9637:
9638: # --------------------------------------------------- Course Resourcedata Query
9639: #
9640: # Parameters:
9641: # $coursenum - Number of the course.
9642: # $coursedomain - Domain at which the course was created.
9643: # Returns:
9644: # A hash of the course parameters along (I think) with timestamps
9645: # and version info.
9646:
9647: sub get_courseresdata {
9648: my ($coursenum,$coursedomain)=@_;
9649: my $coursehom=&homeserver($coursenum,$coursedomain);
9650: my $hashid=$coursenum.':'.$coursedomain;
9651: my ($result,$cached)=&is_cached_new('courseres',$hashid);
9652: my %dumpreply;
9653: unless (defined($cached)) {
9654: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
9655: $result=\%dumpreply;
9656: my ($tmp) = keys(%dumpreply);
9657: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9658: &do_cache_new('courseres',$hashid,$result,600);
9659: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9660: return $tmp;
9661: } elsif ($tmp =~ /^(error)/) {
9662: $result=undef;
9663: &do_cache_new('courseres',$hashid,$result,600);
9664: }
9665: }
9666: return $result;
9667: }
9668:
9669: sub devalidateuserresdata {
9670: my ($uname,$udom)=@_;
9671: my $hashid="$udom:$uname";
9672: &devalidate_cache_new('userres',$hashid);
9673: }
9674:
9675: sub get_userresdata {
9676: my ($uname,$udom)=@_;
9677: #most student don\'t have any data set, check if there is some data
9678: if (&EXT_cache_status($udom,$uname)) { return undef; }
9679:
9680: my $hashid="$udom:$uname";
9681: my ($result,$cached)=&is_cached_new('userres',$hashid);
9682: if (!defined($cached)) {
9683: my %resourcedata=&dump('resourcedata',$udom,$uname);
9684: $result=\%resourcedata;
9685: &do_cache_new('userres',$hashid,$result,600);
9686: }
9687: my ($tmp)=keys(%$result);
9688: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9689: return $result;
9690: }
9691: #error 2 occurs when the .db doesn't exist
9692: if ($tmp!~/error: 2 /) {
9693: &logthis("<font color=\"blue\">WARNING:".
9694: " Trying to get resource data for ".
9695: $uname." at ".$udom.": ".
9696: $tmp."</font>");
9697: } elsif ($tmp=~/error: 2 /) {
9698: #&EXT_cache_set($udom,$uname);
9699: &do_cache_new('userres',$hashid,undef,600);
9700: undef($tmp); # not really an error so don't send it back
9701: }
9702: return $tmp;
9703: }
9704: #----------------------------------------------- resdata - return resource data
9705: # Purpose:
9706: # Return resource data for either users or for a course.
9707: # Parameters:
9708: # $name - Course/user name.
9709: # $domain - Name of the domain the user/course is registered on.
9710: # $type - Type of thing $name is (must be 'course' or 'user'
9711: # @which - Array of names of resources desired.
9712: # Returns:
9713: # The value of the first reasource in @which that is found in the
9714: # resource hash.
9715: # Exceptional Conditions:
9716: # If the $type passed in is not valid (not the string 'course' or
9717: # 'user', an undefined reference is returned.
9718: # If none of the resources are found, an undef is returned
9719: sub resdata {
9720: my ($name,$domain,$type,@which)=@_;
9721: my $result;
9722: if ($type eq 'course') {
9723: $result=&get_courseresdata($name,$domain);
9724: } elsif ($type eq 'user') {
9725: $result=&get_userresdata($name,$domain);
9726: }
9727: if (!ref($result)) { return $result; }
9728: foreach my $item (@which) {
9729: if (defined($result->{$item->[0]})) {
9730: return [$result->{$item->[0]},$item->[1]];
9731: }
9732: }
9733: return undef;
9734: }
9735:
9736: sub get_numsuppfiles {
9737: my ($cnum,$cdom,$ignorecache)=@_;
9738: my $hashid=$cnum.':'.$cdom;
9739: my ($suppcount,$cached);
9740: unless ($ignorecache) {
9741: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
9742: }
9743: unless (defined($cached)) {
9744: my $chome=&homeserver($cnum,$cdom);
9745: unless ($chome eq 'no_host') {
9746: ($suppcount,my $errors) = (0,0);
9747: my $suppmap = 'supplemental.sequence';
9748: ($suppcount,$errors) =
9749: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
9750: }
9751: &do_cache_new('suppcount',$hashid,$suppcount,600);
9752: }
9753: return $suppcount;
9754: }
9755:
9756: #
9757: # EXT resource caching routines
9758: #
9759:
9760: sub clear_EXT_cache_status {
9761: &delenv('cache.EXT.');
9762: }
9763:
9764: sub EXT_cache_status {
9765: my ($target_domain,$target_user) = @_;
9766: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
9767: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
9768: # We know already the user has no data
9769: return 1;
9770: } else {
9771: return 0;
9772: }
9773: }
9774:
9775: sub EXT_cache_set {
9776: my ($target_domain,$target_user) = @_;
9777: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
9778: #&appenv({$cachename => time});
9779: }
9780:
9781: # --------------------------------------------------------- Value of a Variable
9782: sub EXT {
9783:
9784: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
9785: unless ($varname) { return ''; }
9786: #get real user name/domain, courseid and symb
9787: my $courseid;
9788: my $publicuser;
9789: if ($symbparm) {
9790: $symbparm=&get_symb_from_alias($symbparm);
9791: }
9792: if (!($uname && $udom)) {
9793: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
9794: if (!$symbparm) { $symbparm=$cursymb; }
9795: } else {
9796: $courseid=$env{'request.course.id'};
9797: }
9798: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9799: my $rest;
9800: if (defined($therest[0])) {
9801: $rest=join('.',@therest);
9802: } else {
9803: $rest='';
9804: }
9805:
9806: my $qualifierrest=$qualifier;
9807: if ($rest) { $qualifierrest.='.'.$rest; }
9808: my $spacequalifierrest=$space;
9809: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
9810: if ($realm eq 'user') {
9811: # --------------------------------------------------------------- user.resource
9812: if ($space eq 'resource') {
9813: if ( (defined($Apache::lonhomework::parsing_a_problem)
9814: || defined($Apache::lonhomework::parsing_a_task))
9815: &&
9816: ($symbparm eq &symbread()) ) {
9817: # if we are in the middle of processing the resource the
9818: # get the value we are planning on committing
9819: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9820: return $Apache::lonhomework::results{$qualifierrest};
9821: } else {
9822: return $Apache::lonhomework::history{$qualifierrest};
9823: }
9824: } else {
9825: my %restored;
9826: if ($publicuser || $env{'request.state'} eq 'construct') {
9827: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9828: } else {
9829: %restored=&restore($symbparm,$courseid,$udom,$uname);
9830: }
9831: return $restored{$qualifierrest};
9832: }
9833: # ----------------------------------------------------------------- user.access
9834: } elsif ($space eq 'access') {
9835: # FIXME - not supporting calls for a specific user
9836: return &allowed($qualifier,$rest);
9837: # ------------------------------------------ user.preferences, user.environment
9838: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
9839: if (($uname eq $env{'user.name'}) &&
9840: ($udom eq $env{'user.domain'})) {
9841: return $env{join('.',('environment',$qualifierrest))};
9842: } else {
9843: my %returnhash;
9844: if (!$publicuser) {
9845: %returnhash=&userenvironment($udom,$uname,
9846: $qualifierrest);
9847: }
9848: return $returnhash{$qualifierrest};
9849: }
9850: # ----------------------------------------------------------------- user.course
9851: } elsif ($space eq 'course') {
9852: # FIXME - not supporting calls for a specific user
9853: return $env{join('.',('request.course',$qualifier))};
9854: # ------------------------------------------------------------------- user.role
9855: } elsif ($space eq 'role') {
9856: # FIXME - not supporting calls for a specific user
9857: my ($role,$where)=split(/\./,$env{'request.role'});
9858: if ($qualifier eq 'value') {
9859: return $role;
9860: } elsif ($qualifier eq 'extent') {
9861: return $where;
9862: }
9863: # ----------------------------------------------------------------- user.domain
9864: } elsif ($space eq 'domain') {
9865: return $udom;
9866: # ------------------------------------------------------------------- user.name
9867: } elsif ($space eq 'name') {
9868: return $uname;
9869: # ---------------------------------------------------- Any other user namespace
9870: } else {
9871: my %reply;
9872: if (!$publicuser) {
9873: %reply=&get($space,[$qualifierrest],$udom,$uname);
9874: }
9875: return $reply{$qualifierrest};
9876: }
9877: } elsif ($realm eq 'query') {
9878: # ---------------------------------------------- pull stuff out of query string
9879: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9880: [$spacequalifierrest]);
9881: return $env{'form.'.$spacequalifierrest};
9882: } elsif ($realm eq 'request') {
9883: # ------------------------------------------------------------- request.browser
9884: if ($space eq 'browser') {
9885: return $env{'browser.'.$qualifier};
9886: # ------------------------------------------------------------ request.filename
9887: } else {
9888: return $env{'request.'.$spacequalifierrest};
9889: }
9890: } elsif ($realm eq 'course') {
9891: # ---------------------------------------------------------- course.description
9892: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
9893: } elsif ($realm eq 'resource') {
9894:
9895: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
9896: if (!$symbparm) { $symbparm=&symbread(); }
9897: }
9898:
9899: if ($qualifier eq '') {
9900: if ($space eq 'title') {
9901: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9902: return &gettitle($symbparm);
9903: }
9904:
9905: if ($space eq 'map') {
9906: my ($map) = &decode_symb($symbparm);
9907: return &symbread($map);
9908: }
9909: if ($space eq 'maptitle') {
9910: my ($map) = &decode_symb($symbparm);
9911: return &gettitle($map);
9912: }
9913: if ($space eq 'filename') {
9914: if ($symbparm) {
9915: return &clutter((&decode_symb($symbparm))[2]);
9916: }
9917: return &hreflocation('',$env{'request.filename'});
9918: }
9919:
9920: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
9921: if ($space eq 'visibleparts') {
9922: my $navmap = Apache::lonnavmaps::navmap->new();
9923: my $item;
9924: if (ref($navmap)) {
9925: my $res = $navmap->getBySymb($symbparm);
9926: my $parts = $res->parts();
9927: if (ref($parts) eq 'ARRAY') {
9928: $item = join(',',@{$parts});
9929: }
9930: undef($navmap);
9931: }
9932: return $item;
9933: }
9934: }
9935: }
9936:
9937: my ($section, $group, @groups);
9938: my ($courselevelm,$courselevel);
9939: if (($courseid eq '') && ($cid)) {
9940: $courseid = $cid;
9941: }
9942: if (($symbparm && $courseid) &&
9943: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
9944:
9945: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
9946:
9947: # ----------------------------------------------------- Cascading lookup scheme
9948: my $symbp=$symbparm;
9949: my $mapp=&deversion((&decode_symb($symbp))[0]);
9950:
9951: my $symbparm=$symbp.'.'.$spacequalifierrest;
9952: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9953:
9954: if (($env{'user.name'} eq $uname) &&
9955: ($env{'user.domain'} eq $udom)) {
9956: $section=$env{'request.course.sec'};
9957: @groups = split(/:/,$env{'request.course.groups'});
9958: @groups=&sort_course_groups($courseid,@groups);
9959: } else {
9960: if (! defined($usection)) {
9961: $section=&getsection($udom,$uname,$courseid);
9962: } else {
9963: $section = $usection;
9964: }
9965: @groups = &get_users_groups($udom,$uname,$courseid);
9966: }
9967:
9968: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9969: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9970: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9971:
9972: $courselevel=$courseid.'.'.$spacequalifierrest;
9973: my $courselevelr=$courseid.'.'.$symbparm;
9974: $courselevelm=$courseid.'.'.$mapparm;
9975:
9976: # ----------------------------------------------------------- first, check user
9977:
9978: my $userreply=&resdata($uname,$udom,'user',
9979: ([$courselevelr,'resource'],
9980: [$courselevelm,'map' ],
9981: [$courselevel, 'course' ]));
9982: if (defined($userreply)) { return &get_reply($userreply); }
9983:
9984: # ------------------------------------------------ second, check some of course
9985: my $coursereply;
9986: if (@groups > 0) {
9987: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9988: $mapparm,$spacequalifierrest);
9989: if (defined($coursereply)) { return &get_reply($coursereply); }
9990: }
9991:
9992: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9993: $env{'course.'.$courseid.'.domain'},
9994: 'course',
9995: ([$seclevelr, 'resource'],
9996: [$seclevelm, 'map' ],
9997: [$seclevel, 'course' ],
9998: [$courselevelr,'resource']));
9999: if (defined($coursereply)) { return &get_reply($coursereply); }
10000:
10001: # ------------------------------------------------------ third, check map parms
10002: my %parmhash=();
10003: my $thisparm='';
10004: if (tie(%parmhash,'GDBM_File',
10005: $env{'request.course.fn'}.'_parms.db',
10006: &GDBM_READER(),0640)) {
10007: $thisparm=$parmhash{$symbparm};
10008: untie(%parmhash);
10009: }
10010: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
10011: }
10012: # ------------------------------------------ fourth, look in resource metadata
10013:
10014: $spacequalifierrest=~s/\./\_/;
10015: my $filename;
10016: if (!$symbparm) { $symbparm=&symbread(); }
10017: if ($symbparm) {
10018: $filename=(&decode_symb($symbparm))[2];
10019: } else {
10020: $filename=$env{'request.filename'};
10021: }
10022: my $metadata=&metadata($filename,$spacequalifierrest);
10023: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10024: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
10025: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10026:
10027: # ---------------------------------------------- fourth, look in rest of course
10028: if ($symbparm && defined($courseid) &&
10029: $courseid eq $env{'request.course.id'}) {
10030: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10031: $env{'course.'.$courseid.'.domain'},
10032: 'course',
10033: ([$courselevelm,'map' ],
10034: [$courselevel, 'course']));
10035: if (defined($coursereply)) { return &get_reply($coursereply); }
10036: }
10037: # ------------------------------------------------------------------ Cascade up
10038: unless ($space eq '0') {
10039: my @parts=split(/_/,$space);
10040: my $id=pop(@parts);
10041: my $part=join('_',@parts);
10042: if ($part eq '') { $part='0'; }
10043: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
10044: $symbparm,$udom,$uname,$section,1);
10045: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
10046: }
10047: if ($recurse) { return undef; }
10048: my $pack_def=&packages_tab_default($filename,$varname);
10049: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
10050: # ---------------------------------------------------- Any other user namespace
10051: } elsif ($realm eq 'environment') {
10052: # ----------------------------------------------------------------- environment
10053: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10054: return $env{'environment.'.$spacequalifierrest};
10055: } else {
10056: if ($uname eq 'anonymous' && $udom eq '') {
10057: return '';
10058: }
10059: my %returnhash=&userenvironment($udom,$uname,
10060: $spacequalifierrest);
10061: return $returnhash{$spacequalifierrest};
10062: }
10063: } elsif ($realm eq 'system') {
10064: # ----------------------------------------------------------------- system.time
10065: if ($space eq 'time') {
10066: return time;
10067: }
10068: } elsif ($realm eq 'server') {
10069: # ----------------------------------------------------------------- system.time
10070: if ($space eq 'name') {
10071: return $ENV{'SERVER_NAME'};
10072: }
10073: }
10074: return '';
10075: }
10076:
10077: sub get_reply {
10078: my ($reply_value) = @_;
10079: if (ref($reply_value) eq 'ARRAY') {
10080: if (wantarray) {
10081: return @$reply_value;
10082: }
10083: return $reply_value->[0];
10084: } else {
10085: return $reply_value;
10086: }
10087: }
10088:
10089: sub check_group_parms {
10090: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10091: my @groupitems = ();
10092: my $resultitem;
10093: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
10094: foreach my $group (@{$groups}) {
10095: foreach my $level (@levels) {
10096: my $item = $courseid.'.['.$group.'].'.$level->[0];
10097: push(@groupitems,[$item,$level->[1]]);
10098: }
10099: }
10100: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10101: $env{'course.'.$courseid.'.domain'},
10102: 'course',@groupitems);
10103: return $coursereply;
10104: }
10105:
10106: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
10107: my ($courseid,@groups) = @_;
10108: @groups = sort(@groups);
10109: return @groups;
10110: }
10111:
10112: sub packages_tab_default {
10113: my ($uri,$varname)=@_;
10114: my (undef,$part,$name)=split(/\./,$varname);
10115:
10116: my (@extension,@specifics,$do_default);
10117: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
10118: my ($pack_type,$pack_part)=split(/_/,$package,2);
10119: if ($pack_type eq 'default') {
10120: $do_default=1;
10121: } elsif ($pack_type eq 'extension') {
10122: push(@extension,[$package,$pack_type,$pack_part]);
10123: } elsif ($pack_part eq $part || $pack_type eq 'part') {
10124: # only look at packages defaults for packages that this id is
10125: push(@specifics,[$package,$pack_type,$pack_part]);
10126: }
10127: }
10128: # first look for a package that matches the requested part id
10129: foreach my $package (@specifics) {
10130: my (undef,$pack_type,$pack_part)=@{$package};
10131: next if ($pack_part ne $part);
10132: if (defined($packagetab{"$pack_type&$name&default"})) {
10133: return $packagetab{"$pack_type&$name&default"};
10134: }
10135: }
10136: # look for any possible matching non extension_ package
10137: foreach my $package (@specifics) {
10138: my (undef,$pack_type,$pack_part)=@{$package};
10139: if (defined($packagetab{"$pack_type&$name&default"})) {
10140: return $packagetab{"$pack_type&$name&default"};
10141: }
10142: if ($pack_type eq 'part') { $pack_part='0'; }
10143: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10144: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
10145: }
10146: }
10147: # look for any posible extension_ match
10148: foreach my $package (@extension) {
10149: my ($package,$pack_type)=@{$package};
10150: if (defined($packagetab{"$pack_type&$name&default"})) {
10151: return $packagetab{"$pack_type&$name&default"};
10152: }
10153: if (defined($packagetab{$package."&$name&default"})) {
10154: return $packagetab{$package."&$name&default"};
10155: }
10156: }
10157: # look for a global default setting
10158: if ($do_default && defined($packagetab{"default&$name&default"})) {
10159: return $packagetab{"default&$name&default"};
10160: }
10161: return undef;
10162: }
10163:
10164: sub add_prefix_and_part {
10165: my ($prefix,$part)=@_;
10166: my $keyroot;
10167: if (defined($prefix) && $prefix !~ /^__/) {
10168: # prefix that has a part already
10169: $keyroot=$prefix;
10170: } elsif (defined($prefix)) {
10171: # prefix that is missing a part
10172: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10173: } else {
10174: # no prefix at all
10175: if (defined($part)) { $keyroot='_'.$part; }
10176: }
10177: return $keyroot;
10178: }
10179:
10180: # ---------------------------------------------------------------- Get metadata
10181:
10182: my %metaentry;
10183: my %importedpartids;
10184: sub metadata {
10185: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
10186: $uri=&declutter($uri);
10187: # if it is a non metadata possible uri return quickly
10188: if (($uri eq '') ||
10189: (($uri =~ m|^/*adm/|) &&
10190: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
10191: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
10192: return undef;
10193: }
10194: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
10195: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
10196: return undef;
10197: }
10198: my $filename=$uri;
10199: $uri=~s/\.meta$//;
10200: #
10201: # Is the metadata already cached?
10202: # Look at timestamp of caching
10203: # Everything is cached by the main uri, libraries are never directly cached
10204: #
10205: if (!defined($liburi)) {
10206: my ($result,$cached)=&is_cached_new('meta',$uri);
10207: if (defined($cached)) { return $result->{':'.$what}; }
10208: }
10209: {
10210: # Imported parts would go here
10211: my %importedids=();
10212: my @origfileimportpartids=();
10213: my $importedparts=0;
10214: #
10215: # Is this a recursive call for a library?
10216: #
10217: # if (! exists($metacache{$uri})) {
10218: # $metacache{$uri}={};
10219: # }
10220: my $cachetime = 60*60;
10221: if ($liburi) {
10222: $liburi=&declutter($liburi);
10223: $filename=$liburi;
10224: } else {
10225: &devalidate_cache_new('meta',$uri);
10226: undef(%metaentry);
10227: }
10228: my %metathesekeys=();
10229: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
10230: my $metastring;
10231: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
10232: my $which = &hreflocation('','/'.($liburi || $uri));
10233: $metastring =
10234: &Apache::lonnet::ssi_body($which,
10235: ('grade_target' => 'meta'));
10236: $cachetime = 1; # only want this cached in the child not long term
10237: } elsif (($uri !~ m -^(editupload)/-) &&
10238: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
10239: my $file=&filelocation('',&clutter($filename));
10240: #push(@{$metaentry{$uri.'.file'}},$file);
10241: $metastring=&getfile($file);
10242: }
10243: my $parser=HTML::LCParser->new(\$metastring);
10244: my $token;
10245: undef %metathesekeys;
10246: while ($token=$parser->get_token) {
10247: if ($token->[0] eq 'S') {
10248: if (defined($token->[2]->{'package'})) {
10249: #
10250: # This is a package - get package info
10251: #
10252: my $package=$token->[2]->{'package'};
10253: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10254: if (defined($token->[2]->{'id'})) {
10255: $keyroot.='_'.$token->[2]->{'id'};
10256: }
10257: if ($metaentry{':packages'}) {
10258: $metaentry{':packages'}.=','.$package.$keyroot;
10259: } else {
10260: $metaentry{':packages'}=$package.$keyroot;
10261: }
10262: foreach my $pack_entry (keys(%packagetab)) {
10263: my $part=$keyroot;
10264: $part=~s/^\_//;
10265: if ($pack_entry=~/^\Q$package\E\&/ ||
10266: $pack_entry=~/^\Q$package\E_0\&/) {
10267: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10268: # ignore package.tab specified default values
10269: # here &package_tab_default() will fetch those
10270: if ($subp eq 'default') { next; }
10271: my $value=$packagetab{$pack_entry};
10272: my $unikey;
10273: if ($pack =~ /_0$/) {
10274: $unikey='parameter_0_'.$name;
10275: $part=0;
10276: } else {
10277: $unikey='parameter'.$keyroot.'_'.$name;
10278: }
10279: if ($subp eq 'display') {
10280: $value.=' [Part: '.$part.']';
10281: }
10282: $metaentry{':'.$unikey.'.part'}=$part;
10283: $metathesekeys{$unikey}=1;
10284: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10285: $metaentry{':'.$unikey.'.'.$subp}=$value;
10286: }
10287: if (defined($metaentry{':'.$unikey.'.default'})) {
10288: $metaentry{':'.$unikey}=
10289: $metaentry{':'.$unikey.'.default'};
10290: }
10291: }
10292: }
10293: } else {
10294: #
10295: # This is not a package - some other kind of start tag
10296: #
10297: my $entry=$token->[1];
10298: my $unikey='';
10299:
10300: if ($entry eq 'import') {
10301: #
10302: # Importing a library here
10303: #
10304: my $location=$parser->get_text('/import');
10305: my $dir=$filename;
10306: $dir=~s|[^/]*$||;
10307: $location=&filelocation($dir,$location);
10308:
10309: my $importmode=$token->[2]->{'importmode'};
10310: if ($importmode eq 'problem') {
10311: # Import as problem/response
10312: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10313: } elsif ($importmode eq 'part') {
10314: # Import as part(s)
10315: $importedparts=1;
10316: # We need to get the original file and the imported file to get the part order correct
10317: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10318: # Load and inspect original file
10319: if ($#origfileimportpartids<0) {
10320: undef(%importedpartids);
10321: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10322: my $origfile=&getfile($origfilelocation);
10323: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10324: }
10325:
10326: # Load and inspect imported file
10327: my $impfile=&getfile($location);
10328: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10329: if ($#impfilepartids>=0) {
10330: # This problem had parts
10331: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10332: } else {
10333: # Importing by turning a single problem into a problem part
10334: # It gets the import-tags ID as part-ID
10335: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10336: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10337: }
10338: } else {
10339: # Normal import
10340: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10341: if (defined($token->[2]->{'id'})) {
10342: $unikey.='_'.$token->[2]->{'id'};
10343: }
10344: }
10345:
10346: if ($depthcount<20) {
10347: my $metadata =
10348: &metadata($uri,'keys', $location,$unikey,
10349: $depthcount+1);
10350: foreach my $meta (split(',',$metadata)) {
10351: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10352: $metathesekeys{$meta}=1;
10353: }
10354:
10355: }
10356: } else {
10357: #
10358: # Not importing, some other kind of non-package, non-library start tag
10359: #
10360: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10361: if (defined($token->[2]->{'id'})) {
10362: $unikey.='_'.$token->[2]->{'id'};
10363: }
10364: if (defined($token->[2]->{'name'})) {
10365: $unikey.='_'.$token->[2]->{'name'};
10366: }
10367: $metathesekeys{$unikey}=1;
10368: foreach my $param (@{$token->[3]}) {
10369: $metaentry{':'.$unikey.'.'.$param} =
10370: $token->[2]->{$param};
10371: }
10372: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10373: my $default=$metaentry{':'.$unikey.'.default'};
10374: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10375: # only ws inside the tag, and not in default, so use default
10376: # as value
10377: $metaentry{':'.$unikey}=$default;
10378: } elsif ( $internaltext =~ /\S/ ) {
10379: # something interesting inside the tag
10380: $metaentry{':'.$unikey}=$internaltext;
10381: } else {
10382: # no interesting values, don't set a default
10383: }
10384: # end of not-a-package not-a-library import
10385: }
10386: # end of not-a-package start tag
10387: }
10388: # the next is the end of "start tag"
10389: }
10390: }
10391: my ($extension) = ($uri =~ /\.(\w+)$/);
10392: $extension = lc($extension);
10393: if ($extension eq 'htm') { $extension='html'; }
10394:
10395: foreach my $key (keys(%packagetab)) {
10396: #no specific packages #how's our extension
10397: if ($key!~/^extension_\Q$extension\E&/) { next; }
10398: &metadata_create_package_def($uri,$key,'extension_'.$extension,
10399: \%metathesekeys);
10400: }
10401:
10402: if (!exists($metaentry{':packages'})
10403: || $packagetab{"import_defaults&extension_$extension"}) {
10404: foreach my $key (keys(%packagetab)) {
10405: #no specific packages well let's get default then
10406: if ($key!~/^default&/) { next; }
10407: &metadata_create_package_def($uri,$key,'default',
10408: \%metathesekeys);
10409: }
10410: }
10411: # are there custom rights to evaluate
10412: if ($metaentry{':copyright'} eq 'custom') {
10413:
10414: #
10415: # Importing a rights file here
10416: #
10417: unless ($depthcount) {
10418: my $location=$metaentry{':customdistributionfile'};
10419: my $dir=$filename;
10420: $dir=~s|[^/]*$||;
10421: $location=&filelocation($dir,$location);
10422: my $rights_metadata =
10423: &metadata($uri,'keys',$location,'_rights',
10424: $depthcount+1);
10425: foreach my $rights (split(',',$rights_metadata)) {
10426: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10427: $metathesekeys{$rights}=1;
10428: }
10429: }
10430: }
10431: # uniqifiy package listing
10432: my %seen;
10433: my @uniq_packages =
10434: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10435: $metaentry{':packages'} = join(',',@uniq_packages);
10436:
10437: if ($importedparts) {
10438: # We had imported parts and need to rebuild partorder
10439: $metaentry{':partorder'}='';
10440: $metathesekeys{'partorder'}=1;
10441: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10442: if ($origfileimportpartids[$index] eq 'part') {
10443: # original part, part of the problem
10444: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10445: } else {
10446: # we have imported parts at this position
10447: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10448: }
10449: }
10450: $metaentry{':partorder'}=~s/^\,//;
10451: }
10452:
10453: $metaentry{':keys'} = join(',',keys(%metathesekeys));
10454: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10455: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
10456: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
10457: # this is the end of "was not already recently cached
10458: }
10459: return $metaentry{':'.$what};
10460: }
10461:
10462: sub metadata_create_package_def {
10463: my ($uri,$key,$package,$metathesekeys)=@_;
10464: my ($pack,$name,$subp)=split(/\&/,$key);
10465: if ($subp eq 'default') { next; }
10466:
10467: if (defined($metaentry{':packages'})) {
10468: $metaentry{':packages'}.=','.$package;
10469: } else {
10470: $metaentry{':packages'}=$package;
10471: }
10472: my $value=$packagetab{$key};
10473: my $unikey;
10474: $unikey='parameter_0_'.$name;
10475: $metaentry{':'.$unikey.'.part'}=0;
10476: $$metathesekeys{$unikey}=1;
10477: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10478: $metaentry{':'.$unikey.'.'.$subp}=$value;
10479: }
10480: if (defined($metaentry{':'.$unikey.'.default'})) {
10481: $metaentry{':'.$unikey}=
10482: $metaentry{':'.$unikey.'.default'};
10483: }
10484: }
10485:
10486: sub metadata_generate_part0 {
10487: my ($metadata,$metacache,$uri) = @_;
10488: my %allnames;
10489: foreach my $metakey (keys(%$metadata)) {
10490: if ($metakey=~/^parameter\_(.*)/) {
10491: my $part=$$metacache{':'.$metakey.'.part'};
10492: my $name=$$metacache{':'.$metakey.'.name'};
10493: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10494: $allnames{$name}=$part;
10495: }
10496: }
10497: }
10498: foreach my $name (keys(%allnames)) {
10499: $$metadata{"parameter_0_$name"}=1;
10500: my $key=":parameter_0_$name";
10501: $$metacache{"$key.part"}='0';
10502: $$metacache{"$key.name"}=$name;
10503: $$metacache{"$key.type"}=$$metacache{':parameter_'.
10504: $allnames{$name}.'_'.$name.
10505: '.type'};
10506: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10507: '.display'};
10508: my $expr='[Part: '.$allnames{$name}.']';
10509: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10510: $$metacache{"$key.display"}=$olddis;
10511: }
10512: }
10513:
10514: # ------------------------------------------------------ Devalidate title cache
10515:
10516: sub devalidate_title_cache {
10517: my ($url)=@_;
10518: if (!$env{'request.course.id'}) { return; }
10519: my $symb=&symbread($url);
10520: if (!$symb) { return; }
10521: my $key=$env{'request.course.id'}."\0".$symb;
10522: &devalidate_cache_new('title',$key);
10523: }
10524:
10525: # ------------------------------------------------- Get the title of a course
10526:
10527: sub current_course_title {
10528: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10529: }
10530: # ------------------------------------------------- Get the title of a resource
10531:
10532: sub gettitle {
10533: my $urlsymb=shift;
10534: my $symb=&symbread($urlsymb);
10535: if ($symb) {
10536: my $key=$env{'request.course.id'}."\0".$symb;
10537: my ($result,$cached)=&is_cached_new('title',$key);
10538: if (defined($cached)) {
10539: return $result;
10540: }
10541: my ($map,$resid,$url)=&decode_symb($symb);
10542: my $title='';
10543: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10544: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10545: } else {
10546: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10547: &GDBM_READER(),0640)) {
10548: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10549: $title=$bighash{'title_'.$mapid.'.'.$resid};
10550: untie(%bighash);
10551: }
10552: }
10553: $title=~s/\&colon\;/\:/gs;
10554: if ($title) {
10555: # Remember both $symb and $title for dynamic metadata
10556: $accesshash{$symb.'___crstitle'}=$title;
10557: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10558: # Cache this title and then return it
10559: return &do_cache_new('title',$key,$title,600);
10560: }
10561: $urlsymb=$url;
10562: }
10563: my $title=&metadata($urlsymb,'title');
10564: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10565: return $title;
10566: }
10567:
10568: sub get_slot {
10569: my ($which,$cnum,$cdom)=@_;
10570: if (!$cnum || !$cdom) {
10571: (undef,my $courseid)=&whichuser();
10572: $cdom=$env{'course.'.$courseid.'.domain'};
10573: $cnum=$env{'course.'.$courseid.'.num'};
10574: }
10575: my $key=join("\0",'slots',$cdom,$cnum,$which);
10576: my %slotinfo;
10577: if (exists($remembered{$key})) {
10578: $slotinfo{$which} = $remembered{$key};
10579: } else {
10580: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10581: &Apache::lonhomework::showhash(%slotinfo);
10582: my ($tmp)=keys(%slotinfo);
10583: if ($tmp=~/^error:/) { return (); }
10584: $remembered{$key} = $slotinfo{$which};
10585: }
10586: if (ref($slotinfo{$which}) eq 'HASH') {
10587: return %{$slotinfo{$which}};
10588: }
10589: return $slotinfo{$which};
10590: }
10591:
10592: sub get_reservable_slots {
10593: my ($cnum,$cdom,$uname,$udom) = @_;
10594: my $now = time;
10595: my $reservable_info;
10596: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10597: if (exists($remembered{$key})) {
10598: $reservable_info = $remembered{$key};
10599: } else {
10600: my %resv;
10601: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10602: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10603: $reservable_info = \%resv;
10604: $remembered{$key} = $reservable_info;
10605: }
10606: return $reservable_info;
10607: }
10608:
10609: sub get_course_slots {
10610: my ($cnum,$cdom) = @_;
10611: my $hashid=$cnum.':'.$cdom;
10612: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10613: if (defined($cached)) {
10614: if (ref($result) eq 'HASH') {
10615: return %{$result};
10616: }
10617: } else {
10618: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10619: my ($tmp) = keys(%slots);
10620: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10621: &do_cache_new('allslots',$hashid,\%slots,600);
10622: return %slots;
10623: }
10624: }
10625: return;
10626: }
10627:
10628: sub devalidate_slots_cache {
10629: my ($cnum,$cdom)=@_;
10630: my $hashid=$cnum.':'.$cdom;
10631: &devalidate_cache_new('allslots',$hashid);
10632: }
10633:
10634: sub get_coursechange {
10635: my ($cdom,$cnum) = @_;
10636: if ($cdom eq '' || $cnum eq '') {
10637: return unless ($env{'request.course.id'});
10638: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10639: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10640: }
10641: my $hashid=$cdom.'_'.$cnum;
10642: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10643: if ((defined($cached)) && ($change ne '')) {
10644: return $change;
10645: } else {
10646: my %crshash;
10647: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10648: if ($crshash{'internal.contentchange'} eq '') {
10649: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10650: if ($change eq '') {
10651: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10652: $change = $crshash{'internal.created'};
10653: }
10654: } else {
10655: $change = $crshash{'internal.contentchange'};
10656: }
10657: my $cachetime = 600;
10658: &do_cache_new('crschange',$hashid,$change,$cachetime);
10659: }
10660: return $change;
10661: }
10662:
10663: sub devalidate_coursechange_cache {
10664: my ($cnum,$cdom)=@_;
10665: my $hashid=$cnum.':'.$cdom;
10666: &devalidate_cache_new('crschange',$hashid);
10667: }
10668:
10669: # ------------------------------------------------- Update symbolic store links
10670:
10671: sub symblist {
10672: my ($mapname,%newhash)=@_;
10673: $mapname=&deversion(&declutter($mapname));
10674: my %hash;
10675: if (($env{'request.course.fn'}) && (%newhash)) {
10676: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10677: &GDBM_WRCREAT(),0640)) {
10678: foreach my $url (keys(%newhash)) {
10679: next if ($url eq 'last_known'
10680: && $env{'form.no_update_last_known'});
10681: $hash{declutter($url)}=&encode_symb($mapname,
10682: $newhash{$url}->[1],
10683: $newhash{$url}->[0]);
10684: }
10685: if (untie(%hash)) {
10686: return 'ok';
10687: }
10688: }
10689: }
10690: return 'error';
10691: }
10692:
10693: # --------------------------------------------------------------- Verify a symb
10694:
10695: sub symbverify {
10696: my ($symb,$thisurl,$encstate)=@_;
10697: my $thisfn=$thisurl;
10698: $thisfn=&declutter($thisfn);
10699: # direct jump to resource in page or to a sequence - will construct own symbs
10700: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10701: # check URL part
10702: my ($map,$resid,$url)=&decode_symb($symb);
10703:
10704: unless ($url eq $thisfn) { return 0; }
10705:
10706: $symb=&symbclean($symb);
10707: $thisurl=&deversion($thisurl);
10708: $thisfn=&deversion($thisfn);
10709:
10710: my %bighash;
10711: my $okay=0;
10712:
10713: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10714: &GDBM_READER(),0640)) {
10715: my $noclutter;
10716: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10717: $thisurl =~ s/\?.+$//;
10718: if ($map =~ m{^uploaded/.+\.page$}) {
10719: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10720: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10721: $noclutter = 1;
10722: }
10723: }
10724: my $ids;
10725: if ($noclutter) {
10726: $ids=$bighash{'ids_'.$thisurl};
10727: } else {
10728: $ids=$bighash{'ids_'.&clutter($thisurl)};
10729: }
10730: unless ($ids) {
10731: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
10732: $ids=$bighash{$idkey};
10733: }
10734: if ($ids) {
10735: # ------------------------------------------------------------------- Has ID(s)
10736: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10737: $symb =~ s/\?.+$//;
10738: }
10739: foreach my $id (split(/\,/,$ids)) {
10740: my ($mapid,$resid)=split(/\./,$id);
10741: if (
10742: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10743: eq $symb) {
10744: if (ref($encstate)) {
10745: $$encstate = $bighash{'encrypted_'.$id};
10746: }
10747: if (($env{'request.role.adv'}) ||
10748: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10749: ($thisurl eq '/adm/navmaps')) {
10750: $okay=1;
10751: last;
10752: }
10753: }
10754: }
10755: }
10756: untie(%bighash);
10757: }
10758: return $okay;
10759: }
10760:
10761: # --------------------------------------------------------------- Clean-up symb
10762:
10763: sub symbclean {
10764: my $symb=shift;
10765: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10766: # remove version from map
10767: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10768:
10769: # remove version from URL
10770: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10771:
10772: # remove wrapper
10773:
10774: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10775: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10776: return $symb;
10777: }
10778:
10779: # ---------------------------------------------- Split symb to find map and url
10780:
10781: sub encode_symb {
10782: my ($map,$resid,$url)=@_;
10783: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10784: }
10785:
10786: sub decode_symb {
10787: my $symb=shift;
10788: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10789: my ($map,$resid,$url)=split(/___/,$symb);
10790: return (&fixversion($map),$resid,&fixversion($url));
10791: }
10792:
10793: sub fixversion {
10794: my $fn=shift;
10795: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10796: my %bighash;
10797: my $uri=&clutter($fn);
10798: my $key=$env{'request.course.id'}.'_'.$uri;
10799: # is this cached?
10800: my ($result,$cached)=&is_cached_new('courseresversion',$key);
10801: if (defined($cached)) { return $result; }
10802: # unfortunately not cached, or expired
10803: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10804: &GDBM_READER(),0640)) {
10805: if ($bighash{'version_'.$uri}) {
10806: my $version=$bighash{'version_'.$uri};
10807: unless (($version eq 'mostrecent') ||
10808: ($version==&getversion($uri))) {
10809: $uri=~s/\.(\w+)$/\.$version\.$1/;
10810: }
10811: }
10812: untie %bighash;
10813: }
10814: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10815: }
10816:
10817: sub deversion {
10818: my $url=shift;
10819: $url=~s/\.\d+\.(\w+)$/\.$1/;
10820: return $url;
10821: }
10822:
10823: # ------------------------------------------------------ Return symb list entry
10824:
10825: sub symbread {
10826: my ($thisfn,$donotrecurse)=@_;
10827: my $cache_str;
10828: if ($thisfn ne '') {
10829: $cache_str='request.symbread.cached.'.$thisfn;
10830: if ($env{$cache_str} ne '') {
10831: return $env{$cache_str};
10832: }
10833: } else {
10834: # no filename provided? try from environment
10835: if ($env{'request.symb'}) {
10836: return $env{$cache_str}=&symbclean($env{'request.symb'});
10837: }
10838: $thisfn=$env{'request.filename'};
10839: }
10840: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10841: # is that filename actually a symb? Verify, clean, and return
10842: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10843: if (&symbverify($thisfn,$1)) {
10844: return $env{$cache_str}=&symbclean($thisfn);
10845: }
10846: }
10847: $thisfn=declutter($thisfn);
10848: my %hash;
10849: my %bighash;
10850: my $syval='';
10851: if (($env{'request.course.fn'}) && ($thisfn)) {
10852: my $targetfn = $thisfn;
10853: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10854: $targetfn = 'adm/wrapper/'.$thisfn;
10855: }
10856: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10857: $targetfn=$1;
10858: }
10859: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10860: &GDBM_READER(),0640)) {
10861: $syval=$hash{$targetfn};
10862: untie(%hash);
10863: }
10864: # ---------------------------------------------------------- There was an entry
10865: if ($syval) {
10866: #unless ($syval=~/\_\d+$/) {
10867: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10868: #&appenv({'request.ambiguous' => $thisfn});
10869: #return $env{$cache_str}='';
10870: #}
10871: #$syval.=$1;
10872: #}
10873: } else {
10874: # ------------------------------------------------------- Was not in symb table
10875: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10876: &GDBM_READER(),0640)) {
10877: # ---------------------------------------------- Get ID(s) for current resource
10878: my $ids=$bighash{'ids_'.&clutter($thisfn)};
10879: unless ($ids) {
10880: $ids=$bighash{'ids_/'.$thisfn};
10881: }
10882: unless ($ids) {
10883: # alias?
10884: $ids=$bighash{'mapalias_'.$thisfn};
10885: }
10886: if ($ids) {
10887: # ------------------------------------------------------------------- Has ID(s)
10888: my @possibilities=split(/\,/,$ids);
10889: if ($#possibilities==0) {
10890: # ----------------------------------------------- There is only one possibility
10891: my ($mapid,$resid)=split(/\./,$ids);
10892: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10893: $resid,$thisfn);
10894: } elsif (!$donotrecurse) {
10895: # ------------------------------------------ There is more than one possibility
10896: my $realpossible=0;
10897: foreach my $id (@possibilities) {
10898: my $file=$bighash{'src_'.$id};
10899: if (&allowed('bre',$file)) {
10900: my ($mapid,$resid)=split(/\./,$id);
10901: if ($bighash{'map_type_'.$mapid} ne 'page') {
10902: $realpossible++;
10903: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10904: $resid,$thisfn);
10905: }
10906: }
10907: }
10908: if ($realpossible!=1) { $syval=''; }
10909: } else {
10910: $syval='';
10911: }
10912: }
10913: untie(%bighash)
10914: }
10915: }
10916: if ($syval) {
10917: return $env{$cache_str}=$syval;
10918: }
10919: }
10920: &appenv({'request.ambiguous' => $thisfn});
10921: return $env{$cache_str}='';
10922: }
10923:
10924: # ---------------------------------------------------------- Return random seed
10925:
10926: sub numval {
10927: my $txt=shift;
10928: $txt=~tr/A-J/0-9/;
10929: $txt=~tr/a-j/0-9/;
10930: $txt=~tr/K-T/0-9/;
10931: $txt=~tr/k-t/0-9/;
10932: $txt=~tr/U-Z/0-5/;
10933: $txt=~tr/u-z/0-5/;
10934: $txt=~s/\D//g;
10935: if ($_64bit) { if ($txt > 2**32) { return -1; } }
10936: return int($txt);
10937: }
10938:
10939: sub numval2 {
10940: my $txt=shift;
10941: $txt=~tr/A-J/0-9/;
10942: $txt=~tr/a-j/0-9/;
10943: $txt=~tr/K-T/0-9/;
10944: $txt=~tr/k-t/0-9/;
10945: $txt=~tr/U-Z/0-5/;
10946: $txt=~tr/u-z/0-5/;
10947: $txt=~s/\D//g;
10948: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10949: my $total;
10950: foreach my $val (@txts) { $total+=$val; }
10951: if ($_64bit) { if ($total > 2**32) { return -1; } }
10952: return int($total);
10953: }
10954:
10955: sub numval3 {
10956: use integer;
10957: my $txt=shift;
10958: $txt=~tr/A-J/0-9/;
10959: $txt=~tr/a-j/0-9/;
10960: $txt=~tr/K-T/0-9/;
10961: $txt=~tr/k-t/0-9/;
10962: $txt=~tr/U-Z/0-5/;
10963: $txt=~tr/u-z/0-5/;
10964: $txt=~s/\D//g;
10965: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10966: my $total;
10967: foreach my $val (@txts) { $total+=$val; }
10968: if ($_64bit) { $total=(($total<<32)>>32); }
10969: return $total;
10970: }
10971:
10972: sub digest {
10973: my ($data)=@_;
10974: my $digest=&Digest::MD5::md5($data);
10975: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10976: my ($e,$f);
10977: {
10978: use integer;
10979: $e=($a+$b);
10980: $f=($c+$d);
10981: if ($_64bit) {
10982: $e=(($e<<32)>>32);
10983: $f=(($f<<32)>>32);
10984: }
10985: }
10986: if (wantarray) {
10987: return ($e,$f);
10988: } else {
10989: my $g;
10990: {
10991: use integer;
10992: $g=($e+$f);
10993: if ($_64bit) {
10994: $g=(($g<<32)>>32);
10995: }
10996: }
10997: return $g;
10998: }
10999: }
11000:
11001: sub latest_rnd_algorithm_id {
11002: return '64bit5';
11003: }
11004:
11005: sub get_rand_alg {
11006: my ($courseid)=@_;
11007: if (!$courseid) { $courseid=(&whichuser())[1]; }
11008: if ($courseid) {
11009: return $env{"course.$courseid.rndseed"};
11010: }
11011: return &latest_rnd_algorithm_id();
11012: }
11013:
11014: sub validCODE {
11015: my ($CODE)=@_;
11016: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11017: return 0;
11018: }
11019:
11020: sub getCODE {
11021: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
11022: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11023: defined($Apache::lonhomework::parsing_a_task) ) &&
11024: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
11025: return $Apache::lonhomework::history{'resource.CODE'};
11026: }
11027: return undef;
11028: }
11029: #
11030: # Determines the random seed for a specific context:
11031: #
11032: # parameters:
11033: # symb - in course context the symb for the seed.
11034: # course_id - The course id of the form domain_coursenum.
11035: # domain - Domain for the user.
11036: # course - Course for the user.
11037: # cenv - environment of the course.
11038: #
11039: # NOTE:
11040: # All parameters are picked out of the environment if missing
11041: # or not defined.
11042: # If a symb cannot be determined the current time is used instead.
11043: #
11044: # For a given well defined symb, courside, domain, username,
11045: # and course environment, the seed is reproducible.
11046: #
11047: sub rndseed {
11048: my ($symb,$courseid,$domain,$username, $cenv)=@_;
11049: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
11050: if (!defined($symb)) {
11051: unless ($symb=$wsymb) { return time; }
11052: }
11053: if (!defined $courseid) {
11054: $courseid=$wcourseid;
11055: }
11056: if (!defined $domain) { $domain=$wdomain; }
11057: if (!defined $username) { $username=$wusername }
11058:
11059: my $which;
11060: if (defined($cenv->{'rndseed'})) {
11061: $which = $cenv->{'rndseed'};
11062: } else {
11063: $which =&get_rand_alg($courseid);
11064: }
11065: if (defined(&getCODE())) {
11066:
11067: if ($which eq '64bit5') {
11068: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11069: } elsif ($which eq '64bit4') {
11070: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11071: } else {
11072: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11073: }
11074: } elsif ($which eq '64bit5') {
11075: return &rndseed_64bit5($symb,$courseid,$domain,$username);
11076: } elsif ($which eq '64bit4') {
11077: return &rndseed_64bit4($symb,$courseid,$domain,$username);
11078: } elsif ($which eq '64bit3') {
11079: return &rndseed_64bit3($symb,$courseid,$domain,$username);
11080: } elsif ($which eq '64bit2') {
11081: return &rndseed_64bit2($symb,$courseid,$domain,$username);
11082: } elsif ($which eq '64bit') {
11083: return &rndseed_64bit($symb,$courseid,$domain,$username);
11084: }
11085: return &rndseed_32bit($symb,$courseid,$domain,$username);
11086: }
11087:
11088: sub rndseed_32bit {
11089: my ($symb,$courseid,$domain,$username)=@_;
11090: {
11091: use integer;
11092: my $symbchck=unpack("%32C*",$symb) << 27;
11093: my $symbseed=numval($symb) << 22;
11094: my $namechck=unpack("%32C*",$username) << 17;
11095: my $nameseed=numval($username) << 12;
11096: my $domainseed=unpack("%32C*",$domain) << 7;
11097: my $courseseed=unpack("%32C*",$courseid);
11098: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
11099: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11100: #&logthis("rndseed :$num:$symb");
11101: if ($_64bit) { $num=(($num<<32)>>32); }
11102: return $num;
11103: }
11104: }
11105:
11106: sub rndseed_64bit {
11107: my ($symb,$courseid,$domain,$username)=@_;
11108: {
11109: use integer;
11110: my $symbchck=unpack("%32S*",$symb) << 21;
11111: my $symbseed=numval($symb) << 10;
11112: my $namechck=unpack("%32S*",$username);
11113:
11114: my $nameseed=numval($username) << 21;
11115: my $domainseed=unpack("%32S*",$domain) << 10;
11116: my $courseseed=unpack("%32S*",$courseid);
11117:
11118: my $num1=$symbchck+$symbseed+$namechck;
11119: my $num2=$nameseed+$domainseed+$courseseed;
11120: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11121: #&logthis("rndseed :$num:$symb");
11122: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11123: return "$num1,$num2";
11124: }
11125: }
11126:
11127: sub rndseed_64bit2 {
11128: my ($symb,$courseid,$domain,$username)=@_;
11129: {
11130: use integer;
11131: # strings need to be an even # of cahracters long, it it is odd the
11132: # last characters gets thrown away
11133: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11134: my $symbseed=numval($symb) << 10;
11135: my $namechck=unpack("%32S*",$username.' ');
11136:
11137: my $nameseed=numval($username) << 21;
11138: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11139: my $courseseed=unpack("%32S*",$courseid.' ');
11140:
11141: my $num1=$symbchck+$symbseed+$namechck;
11142: my $num2=$nameseed+$domainseed+$courseseed;
11143: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11144: #&logthis("rndseed :$num:$symb");
11145: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11146: return "$num1,$num2";
11147: }
11148: }
11149:
11150: sub rndseed_64bit3 {
11151: my ($symb,$courseid,$domain,$username)=@_;
11152: {
11153: use integer;
11154: # strings need to be an even # of cahracters long, it it is odd the
11155: # last characters gets thrown away
11156: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11157: my $symbseed=numval2($symb) << 10;
11158: my $namechck=unpack("%32S*",$username.' ');
11159:
11160: my $nameseed=numval2($username) << 21;
11161: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11162: my $courseseed=unpack("%32S*",$courseid.' ');
11163:
11164: my $num1=$symbchck+$symbseed+$namechck;
11165: my $num2=$nameseed+$domainseed+$courseseed;
11166: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11167: #&logthis("rndseed :$num1:$num2:$_64bit");
11168: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11169:
11170: return "$num1:$num2";
11171: }
11172: }
11173:
11174: sub rndseed_64bit4 {
11175: my ($symb,$courseid,$domain,$username)=@_;
11176: {
11177: use integer;
11178: # strings need to be an even # of cahracters long, it it is odd the
11179: # last characters gets thrown away
11180: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11181: my $symbseed=numval3($symb) << 10;
11182: my $namechck=unpack("%32S*",$username.' ');
11183:
11184: my $nameseed=numval3($username) << 21;
11185: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11186: my $courseseed=unpack("%32S*",$courseid.' ');
11187:
11188: my $num1=$symbchck+$symbseed+$namechck;
11189: my $num2=$nameseed+$domainseed+$courseseed;
11190: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11191: #&logthis("rndseed :$num1:$num2:$_64bit");
11192: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11193:
11194: return "$num1:$num2";
11195: }
11196: }
11197:
11198: sub rndseed_64bit5 {
11199: my ($symb,$courseid,$domain,$username)=@_;
11200: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11201: return "$num1:$num2";
11202: }
11203:
11204: sub rndseed_CODE_64bit {
11205: my ($symb,$courseid,$domain,$username)=@_;
11206: {
11207: use integer;
11208: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11209: my $symbseed=numval2($symb);
11210: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11211: my $CODEseed=numval(&getCODE());
11212: my $courseseed=unpack("%32S*",$courseid.' ');
11213: my $num1=$symbseed+$CODEchck;
11214: my $num2=$CODEseed+$courseseed+$symbchck;
11215: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11216: #&logthis("rndseed :$num1:$num2:$symb");
11217: if ($_64bit) { $num1=(($num1<<32)>>32); }
11218: if ($_64bit) { $num2=(($num2<<32)>>32); }
11219: return "$num1:$num2";
11220: }
11221: }
11222:
11223: sub rndseed_CODE_64bit4 {
11224: my ($symb,$courseid,$domain,$username)=@_;
11225: {
11226: use integer;
11227: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11228: my $symbseed=numval3($symb);
11229: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11230: my $CODEseed=numval3(&getCODE());
11231: my $courseseed=unpack("%32S*",$courseid.' ');
11232: my $num1=$symbseed+$CODEchck;
11233: my $num2=$CODEseed+$courseseed+$symbchck;
11234: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11235: #&logthis("rndseed :$num1:$num2:$symb");
11236: if ($_64bit) { $num1=(($num1<<32)>>32); }
11237: if ($_64bit) { $num2=(($num2<<32)>>32); }
11238: return "$num1:$num2";
11239: }
11240: }
11241:
11242: sub rndseed_CODE_64bit5 {
11243: my ($symb,$courseid,$domain,$username)=@_;
11244: my $code = &getCODE();
11245: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11246: return "$num1:$num2";
11247: }
11248:
11249: sub setup_random_from_rndseed {
11250: my ($rndseed)=@_;
11251: if ($rndseed =~/([,:])/) {
11252: my ($num1,$num2)=split(/[,:]/,$rndseed);
11253: &Math::Random::random_set_seed(abs($num1),abs($num2));
11254: } else {
11255: &Math::Random::random_set_seed_from_phrase($rndseed);
11256: }
11257: }
11258:
11259: sub latest_receipt_algorithm_id {
11260: return 'receipt3';
11261: }
11262:
11263: sub recunique {
11264: my $fucourseid=shift;
11265: my $unique;
11266: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11267: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11268: $unique=$env{"course.$fucourseid.internal.encseed"};
11269: } else {
11270: $unique=$perlvar{'lonReceipt'};
11271: }
11272: return unpack("%32C*",$unique);
11273: }
11274:
11275: sub recprefix {
11276: my $fucourseid=shift;
11277: my $prefix;
11278: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11279: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11280: $prefix=$env{"course.$fucourseid.internal.encpref"};
11281: } else {
11282: $prefix=$perlvar{'lonHostID'};
11283: }
11284: return unpack("%32C*",$prefix);
11285: }
11286:
11287: sub ireceipt {
11288: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11289:
11290: my $return =&recprefix($fucourseid).'-';
11291:
11292: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11293: $env{'request.state'} eq 'construct') {
11294: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11295: return $return;
11296: }
11297:
11298: my $cuname=unpack("%32C*",$funame);
11299: my $cudom=unpack("%32C*",$fudom);
11300: my $cucourseid=unpack("%32C*",$fucourseid);
11301: my $cusymb=unpack("%32C*",$fusymb);
11302: my $cunique=&recunique($fucourseid);
11303: my $cpart=unpack("%32S*",$part);
11304: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11305:
11306: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
11307:
11308: $return.= ($cunique%$cuname+
11309: $cunique%$cudom+
11310: $cusymb%$cuname+
11311: $cusymb%$cudom+
11312: $cucourseid%$cuname+
11313: $cucourseid%$cudom+
11314: $cpart%$cuname+
11315: $cpart%$cudom);
11316: } else {
11317: $return.= ($cunique%$cuname+
11318: $cunique%$cudom+
11319: $cusymb%$cuname+
11320: $cusymb%$cudom+
11321: $cucourseid%$cuname+
11322: $cucourseid%$cudom);
11323: }
11324: return $return;
11325: }
11326:
11327: sub receipt {
11328: my ($part)=@_;
11329: my ($symb,$courseid,$domain,$name) = &whichuser();
11330: return &ireceipt($name,$domain,$courseid,$symb,$part);
11331: }
11332:
11333: sub whichuser {
11334: my ($passedsymb)=@_;
11335: my ($symb,$courseid,$domain,$name,$publicuser);
11336: if (defined($env{'form.grade_symb'})) {
11337: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11338: my $allowed=&allowed('vgr',$tmp_courseid);
11339: if (!$allowed &&
11340: exists($env{'request.course.sec'}) &&
11341: $env{'request.course.sec'} !~ /^\s*$/) {
11342: $allowed=&allowed('vgr',$tmp_courseid.
11343: '/'.$env{'request.course.sec'});
11344: }
11345: if ($allowed) {
11346: ($symb)=&get_env_multiple('form.grade_symb');
11347: $courseid=$tmp_courseid;
11348: ($domain)=&get_env_multiple('form.grade_domain');
11349: ($name)=&get_env_multiple('form.grade_username');
11350: return ($symb,$courseid,$domain,$name,$publicuser);
11351: }
11352: }
11353: if (!$passedsymb) {
11354: $symb=&symbread();
11355: } else {
11356: $symb=$passedsymb;
11357: }
11358: $courseid=$env{'request.course.id'};
11359: $domain=$env{'user.domain'};
11360: $name=$env{'user.name'};
11361: if ($name eq 'public' && $domain eq 'public') {
11362: if (!defined($env{'form.username'})) {
11363: $env{'form.username'}.=time.rand(10000000);
11364: }
11365: $name.=$env{'form.username'};
11366: }
11367: return ($symb,$courseid,$domain,$name,$publicuser);
11368:
11369: }
11370:
11371: # ------------------------------------------------------------ Serves up a file
11372: # returns either the contents of the file or
11373: # -1 if the file doesn't exist
11374: #
11375: # if the target is a file that was uploaded via DOCS,
11376: # a check will be made to see if a current copy exists on the local server,
11377: # if it does this will be served, otherwise a copy will be retrieved from
11378: # the home server for the course and stored in /home/httpd/html/userfiles on
11379: # the local server.
11380:
11381: sub getfile {
11382: my ($file) = @_;
11383: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11384: &repcopy($file);
11385: return &readfile($file);
11386: }
11387:
11388: sub repcopy_userfile {
11389: my ($file)=@_;
11390: my $londocroot = $perlvar{'lonDocRoot'};
11391: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11392: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11393: my ($cdom,$cnum,$filename) =
11394: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11395: my $uri="/uploaded/$cdom/$cnum/$filename";
11396: if (-e "$file") {
11397: # we already have a local copy, check it out
11398: my @fileinfo = stat($file);
11399: my $rtncode;
11400: my $info;
11401: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11402: if ($lwpresp ne 'ok') {
11403: # there is no such file anymore, even though we had a local copy
11404: if ($rtncode eq '404') {
11405: unlink($file);
11406: }
11407: return -1;
11408: }
11409: if ($info < $fileinfo[9]) {
11410: # nice, the file we have is up-to-date, just say okay
11411: return 'ok';
11412: } else {
11413: # the file is outdated, get rid of it
11414: unlink($file);
11415: }
11416: }
11417: # one way or the other, at this point, we don't have the file
11418: # construct the correct path for the file
11419: my @parts = ($cdom,$cnum);
11420: if ($filename =~ m|^(.+)/[^/]+$|) {
11421: push @parts, split(/\//,$1);
11422: }
11423: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11424: foreach my $part (@parts) {
11425: $path .= '/'.$part;
11426: if (!-e $path) {
11427: mkdir($path,0770);
11428: }
11429: }
11430: # now the path exists for sure
11431: # get a user agent
11432: my $ua=new LWP::UserAgent;
11433: my $transferfile=$file.'.in.transfer';
11434: # FIXME: this should flock
11435: if (-e $transferfile) { return 'ok'; }
11436: my $request;
11437: $uri=~s/^\///;
11438: my $homeserver = &homeserver($cnum,$cdom);
11439: my $protocol = $protocol{$homeserver};
11440: $protocol = 'http' if ($protocol ne 'https');
11441: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11442: my $response=$ua->request($request,$transferfile);
11443: # did it work?
11444: if ($response->is_error()) {
11445: unlink($transferfile);
11446: &logthis("Userfile repcopy failed for $uri");
11447: return -1;
11448: }
11449: # worked, rename the transfer file
11450: rename($transferfile,$file);
11451: return 'ok';
11452: }
11453:
11454: sub tokenwrapper {
11455: my $uri=shift;
11456: $uri=~s|^https?\://([^/]+)||;
11457: $uri=~s|^/||;
11458: $env{'user.environment'}=~/\/([^\/]+)\.id/;
11459: my $token=$1;
11460: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11461: if ($udom && $uname && $file) {
11462: $file=~s|(\?\.*)*$||;
11463: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11464: my $homeserver = &homeserver($uname,$udom);
11465: my $protocol = $protocol{$homeserver};
11466: $protocol = 'http' if ($protocol ne 'https');
11467: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11468: (($uri=~/\?/)?'&':'?').'token='.$token.
11469: '&tokenissued='.$perlvar{'lonHostID'};
11470: } else {
11471: return '/adm/notfound.html';
11472: }
11473: }
11474:
11475: # call with reqtype HEAD: get last modification time
11476: # call with reqtype GET: get the file contents
11477: # Do not call this with reqtype GET for large files! It loads everything into memory
11478: #
11479: sub getuploaded {
11480: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11481: $uri=~s/^\///;
11482: my $homeserver = &homeserver($cnum,$cdom);
11483: my $protocol = $protocol{$homeserver};
11484: $protocol = 'http' if ($protocol ne 'https');
11485: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11486: my $ua=new LWP::UserAgent;
11487: my $request=new HTTP::Request($reqtype,$uri);
11488: my $response=$ua->request($request);
11489: $$rtncode = $response->code;
11490: if (! $response->is_success()) {
11491: return 'failed';
11492: }
11493: if ($reqtype eq 'HEAD') {
11494: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11495: } elsif ($reqtype eq 'GET') {
11496: $$info = $response->content;
11497: }
11498: return 'ok';
11499: }
11500:
11501: sub readfile {
11502: my $file = shift;
11503: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11504: my $fh;
11505: open($fh,"<$file");
11506: my $a='';
11507: while (my $line = <$fh>) { $a .= $line; }
11508: return $a;
11509: }
11510:
11511: sub filelocation {
11512: my ($dir,$file) = @_;
11513: my $location;
11514: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11515:
11516: if ($file =~ m-^/adm/-) {
11517: $file=~s-^/adm/wrapper/-/-;
11518: $file=~s-^/adm/coursedocs/showdoc/-/-;
11519: }
11520:
11521: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11522: $location = $file;
11523: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11524: my ($udom,$uname,$filename)=
11525: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11526: my $home=&homeserver($uname,$udom);
11527: my $is_me=0;
11528: my @ids=¤t_machine_ids();
11529: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11530: if ($is_me) {
11531: $location=propath($udom,$uname).'/userfiles/'.$filename;
11532: } else {
11533: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11534: $udom.'/'.$uname.'/'.$filename;
11535: }
11536: } elsif ($file =~ m-^/adm/-) {
11537: $location = $perlvar{'lonDocRoot'}.'/'.$file;
11538: } else {
11539: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11540: $file=~s:^/(res|priv)/:/:;
11541: my $space=$1;
11542: if ( !( $file =~ m:^/:) ) {
11543: $location = $dir. '/'.$file;
11544: } else {
11545: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11546: }
11547: }
11548: $location=~s://+:/:g; # remove duplicate /
11549: while ($location=~m{/\.\./}) {
11550: if ($location =~ m{/[^/]+/\.\./}) {
11551: $location=~ s{/[^/]+/\.\./}{/}g;
11552: } else {
11553: $location=~ s{/\.\./}{/}g;
11554: }
11555: } #remove dir/..
11556: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11557: return $location;
11558: }
11559:
11560: sub hreflocation {
11561: my ($dir,$file)=@_;
11562: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11563: $file=filelocation($dir,$file);
11564: } elsif ($file=~m-^/adm/-) {
11565: $file=~s-^/adm/wrapper/-/-;
11566: $file=~s-^/adm/coursedocs/showdoc/-/-;
11567: }
11568: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11569: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11570: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11571: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11572: {/uploaded/$1/$2/}x;
11573: }
11574: if ($file=~ m{^/userfiles/}) {
11575: $file =~ s{^/userfiles/}{/uploaded/};
11576: }
11577: return $file;
11578: }
11579:
11580:
11581:
11582:
11583:
11584: sub current_machine_domains {
11585: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11586: }
11587:
11588: sub machine_domains {
11589: my ($hostname) = @_;
11590: my @domains;
11591: my %hostname = &all_hostnames();
11592: while( my($id, $name) = each(%hostname)) {
11593: # &logthis("-$id-$name-$hostname-");
11594: if ($hostname eq $name) {
11595: push(@domains,&host_domain($id));
11596: }
11597: }
11598: return @domains;
11599: }
11600:
11601: sub current_machine_ids {
11602: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11603: }
11604:
11605: sub machine_ids {
11606: my ($hostname) = @_;
11607: $hostname ||= &hostname($perlvar{'lonHostID'});
11608: my @ids;
11609: my %name_to_host = &all_names();
11610: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11611: return @{ $name_to_host{$hostname} };
11612: }
11613: return;
11614: }
11615:
11616: sub additional_machine_domains {
11617: my @domains;
11618: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11619: while( my $line = <$fh>) {
11620: $line =~ s/\s//g;
11621: push(@domains,$line);
11622: }
11623: return @domains;
11624: }
11625:
11626: sub default_login_domain {
11627: my $domain = $perlvar{'lonDefDomain'};
11628: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11629: foreach my $posdom (¤t_machine_domains(),
11630: &additional_machine_domains()) {
11631: if (lc($posdom) eq lc($testdomain)) {
11632: $domain=$posdom;
11633: last;
11634: }
11635: }
11636: return $domain;
11637: }
11638:
11639: # ------------------------------------------------------------- Declutters URLs
11640:
11641: sub declutter {
11642: my $thisfn=shift;
11643: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11644: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11645: $thisfn=~s/^\///;
11646: $thisfn=~s|^adm/wrapper/||;
11647: $thisfn=~s|^adm/coursedocs/showdoc/||;
11648: $thisfn=~s/^res\///;
11649: $thisfn=~s/^priv\///;
11650: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11651: $thisfn=~s/\?.+$//;
11652: }
11653: return $thisfn;
11654: }
11655:
11656: # ------------------------------------------------------------- Clutter up URLs
11657:
11658: sub clutter {
11659: my $thisfn='/'.&declutter(shift);
11660: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11661: || $thisfn =~ m{^/adm/(includes|pages)} ) {
11662: $thisfn='/res'.$thisfn;
11663: }
11664: if ($thisfn !~m|^/adm|) {
11665: if ($thisfn =~ m|^/ext/|) {
11666: $thisfn='/adm/wrapper'.$thisfn;
11667: } else {
11668: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11669: my $embstyle=&Apache::loncommon::fileembstyle($ext);
11670: if ($embstyle eq 'ssi'
11671: || ($embstyle eq 'hdn')
11672: || ($embstyle eq 'rat')
11673: || ($embstyle eq 'prv')
11674: || ($embstyle eq 'ign')) {
11675: #do nothing with these
11676: } elsif (($embstyle eq 'img')
11677: || ($embstyle eq 'emb')
11678: || ($embstyle eq 'wrp')) {
11679: $thisfn='/adm/wrapper'.$thisfn;
11680: } elsif ($embstyle eq 'unk'
11681: && $thisfn!~/\.(sequence|page)$/) {
11682: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
11683: } else {
11684: # &logthis("Got a blank emb style");
11685: }
11686: }
11687: }
11688: return $thisfn;
11689: }
11690:
11691: sub clutter_with_no_wrapper {
11692: my $uri = &clutter(shift);
11693: if ($uri =~ m-^/adm/-) {
11694: $uri =~ s-^/adm/wrapper/-/-;
11695: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11696: }
11697: return $uri;
11698: }
11699:
11700: sub freeze_escape {
11701: my ($value)=@_;
11702: if (ref($value)) {
11703: $value=&nfreeze($value);
11704: return '__FROZEN__'.&escape($value);
11705: }
11706: return &escape($value);
11707: }
11708:
11709:
11710: sub thaw_unescape {
11711: my ($value)=@_;
11712: if ($value =~ /^__FROZEN__/) {
11713: substr($value,0,10,undef);
11714: $value=&unescape($value);
11715: return &thaw($value);
11716: }
11717: return &unescape($value);
11718: }
11719:
11720: sub correct_line_ends {
11721: my ($result)=@_;
11722: $$result =~s/\r\n/\n/mg;
11723: $$result =~s/\r/\n/mg;
11724: }
11725: # ================================================================ Main Program
11726:
11727: sub goodbye {
11728: &logthis("Starting Shut down");
11729: #not converted to using infrastruture and probably shouldn't be
11730: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11731: #converted
11732: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11733: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11734: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11735: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11736: #1.1 only
11737: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11738: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11739: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11740: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11741: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11742: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11743: &logthis(sprintf("%-20s is %s",'hits',$hits));
11744: &flushcourselogs();
11745: &logthis("Shutting down");
11746: }
11747:
11748: sub get_dns {
11749: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
11750: if (!$ignore_cache) {
11751: my ($content,$cached)=
11752: &Apache::lonnet::is_cached_new('dns',$url);
11753: if ($cached) {
11754: &$func($content,$hashref);
11755: return;
11756: }
11757: }
11758:
11759: my %alldns;
11760: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11761: foreach my $dns (<$config>) {
11762: next if ($dns !~ /^\^(\S*)/x);
11763: my $line = $1;
11764: my ($host,$protocol) = split(/:/,$line);
11765: if ($protocol ne 'https') {
11766: $protocol = 'http';
11767: }
11768: $alldns{$host} = $protocol;
11769: }
11770: while (%alldns) {
11771: my ($dns) = keys(%alldns);
11772: my $ua=new LWP::UserAgent;
11773: $ua->timeout(30);
11774: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11775: my $response=$ua->request($request);
11776: delete($alldns{$dns});
11777: next if ($response->is_error());
11778: my @content = split("\n",$response->content);
11779: unless ($nocache) {
11780: &do_cache_new('dns',$url,\@content,30*24*60*60);
11781: }
11782: &$func(\@content,$hashref);
11783: return;
11784: }
11785: close($config);
11786: my $which = (split('/',$url))[3];
11787: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11788: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11789: my @content = <$config>;
11790: &$func(\@content,$hashref);
11791: return;
11792: }
11793:
11794: # ------------------------------------------------------Get DNS checksums file
11795: sub parse_dns_checksums_tab {
11796: my ($lines,$hashref) = @_;
11797: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11798: my $loncaparev = &get_server_loncaparev($machine_dom);
11799: my ($release,$timestamp) = split(/\-/,$loncaparev);
11800: my (%chksum,%revnum);
11801: if (ref($lines) eq 'ARRAY') {
11802: chomp(@{$lines});
11803: my $version = shift(@{$lines});
11804: if ($version eq $release) {
11805: foreach my $line (@{$lines}) {
11806: my ($file,$version,$shasum) = split(/,/,$line);
11807: $chksum{$file} = $shasum;
11808: $revnum{$file} = $version;
11809: }
11810: if (ref($hashref) eq 'HASH') {
11811: %{$hashref} = (
11812: sums => \%chksum,
11813: versions => \%revnum,
11814: );
11815: }
11816: }
11817: }
11818: return;
11819: }
11820:
11821: sub fetch_dns_checksums {
11822: my %checksums;
11823: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11824: my $loncaparev = &get_server_loncaparev($machine_dom);
11825: my ($release,$timestamp) = split(/\-/,$loncaparev);
11826: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
11827: \%checksums);
11828: return \%checksums;
11829: }
11830:
11831: # ------------------------------------------------------------ Read domain file
11832: {
11833: my $loaded;
11834: my %domain;
11835:
11836: sub parse_domain_tab {
11837: my ($lines) = @_;
11838: foreach my $line (@$lines) {
11839: next if ($line =~ /^(\#|\s*$ )/x);
11840:
11841: chomp($line);
11842: my ($name,@elements) = split(/:/,$line,9);
11843: my %this_domain;
11844: foreach my $field ('description', 'auth_def', 'auth_arg_def',
11845: 'lang_def', 'city', 'longi', 'lati',
11846: 'primary') {
11847: $this_domain{$field} = shift(@elements);
11848: }
11849: $domain{$name} = \%this_domain;
11850: }
11851: }
11852:
11853: sub reset_domain_info {
11854: undef($loaded);
11855: undef(%domain);
11856: }
11857:
11858: sub load_domain_tab {
11859: my ($ignore_cache) = @_;
11860: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11861: my $fh;
11862: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11863: my @lines = <$fh>;
11864: &parse_domain_tab(\@lines);
11865: }
11866: close($fh);
11867: $loaded = 1;
11868: }
11869:
11870: sub domain {
11871: &load_domain_tab() if (!$loaded);
11872:
11873: my ($name,$what) = @_;
11874: return if ( !exists($domain{$name}) );
11875:
11876: if (!$what) {
11877: return $domain{$name}{'description'};
11878: }
11879: return $domain{$name}{$what};
11880: }
11881:
11882: sub domain_info {
11883: &load_domain_tab() if (!$loaded);
11884: return %domain;
11885: }
11886:
11887: }
11888:
11889:
11890: # ------------------------------------------------------------- Read hosts file
11891: {
11892: my %hostname;
11893: my %hostdom;
11894: my %libserv;
11895: my $loaded;
11896: my %name_to_host;
11897: my %internetdom;
11898: my %LC_dns_serv;
11899:
11900: sub parse_hosts_tab {
11901: my ($file) = @_;
11902: foreach my $configline (@$file) {
11903: next if ($configline =~ /^(\#|\s*$ )/x);
11904: chomp($configline);
11905: if ($configline =~ /^\^/) {
11906: if ($configline =~ /^\^([\w.\-]+)/) {
11907: $LC_dns_serv{$1} = 1;
11908: }
11909: next;
11910: }
11911: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11912: $name=~s/\s//g;
11913: if ($id && $domain && $role && $name) {
11914: $hostname{$id}=$name;
11915: push(@{$name_to_host{$name}}, $id);
11916: $hostdom{$id}=$domain;
11917: if ($role eq 'library') { $libserv{$id}=$name; }
11918: if (defined($protocol)) {
11919: if ($protocol eq 'https') {
11920: $protocol{$id} = $protocol;
11921: } else {
11922: $protocol{$id} = 'http';
11923: }
11924: } else {
11925: $protocol{$id} = 'http';
11926: }
11927: if (defined($intdom)) {
11928: $internetdom{$id} = $intdom;
11929: }
11930: }
11931: }
11932: }
11933:
11934: sub reset_hosts_info {
11935: &purge_remembered();
11936: &reset_domain_info();
11937: &reset_hosts_ip_info();
11938: undef(%name_to_host);
11939: undef(%hostname);
11940: undef(%hostdom);
11941: undef(%libserv);
11942: undef($loaded);
11943: }
11944:
11945: sub load_hosts_tab {
11946: my ($ignore_cache) = @_;
11947: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11948: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11949: my @config = <$config>;
11950: &parse_hosts_tab(\@config);
11951: close($config);
11952: $loaded=1;
11953: }
11954:
11955: sub hostname {
11956: &load_hosts_tab() if (!$loaded);
11957:
11958: my ($lonid) = @_;
11959: return $hostname{$lonid};
11960: }
11961:
11962: sub all_hostnames {
11963: &load_hosts_tab() if (!$loaded);
11964:
11965: return %hostname;
11966: }
11967:
11968: sub all_names {
11969: &load_hosts_tab() if (!$loaded);
11970:
11971: return %name_to_host;
11972: }
11973:
11974: sub all_host_domain {
11975: &load_hosts_tab() if (!$loaded);
11976: return %hostdom;
11977: }
11978:
11979: sub is_library {
11980: &load_hosts_tab() if (!$loaded);
11981:
11982: return exists($libserv{$_[0]});
11983: }
11984:
11985: sub all_library {
11986: &load_hosts_tab() if (!$loaded);
11987:
11988: return %libserv;
11989: }
11990:
11991: sub unique_library {
11992: #2x reverse removes all hostnames that appear more than once
11993: my %unique = reverse &all_library();
11994: return reverse %unique;
11995: }
11996:
11997: sub get_servers {
11998: &load_hosts_tab() if (!$loaded);
11999:
12000: my ($domain,$type) = @_;
12001: my %possible_hosts = ($type eq 'library') ? %libserv
12002: : %hostname;
12003: my %result;
12004: if (ref($domain) eq 'ARRAY') {
12005: while ( my ($host,$hostname) = each(%possible_hosts)) {
12006: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
12007: $result{$host} = $hostname;
12008: }
12009: }
12010: } else {
12011: while ( my ($host,$hostname) = each(%possible_hosts)) {
12012: if ($hostdom{$host} eq $domain) {
12013: $result{$host} = $hostname;
12014: }
12015: }
12016: }
12017: return %result;
12018: }
12019:
12020: sub get_unique_servers {
12021: my %unique = reverse &get_servers(@_);
12022: return reverse %unique;
12023: }
12024:
12025: sub host_domain {
12026: &load_hosts_tab() if (!$loaded);
12027:
12028: my ($lonid) = @_;
12029: return $hostdom{$lonid};
12030: }
12031:
12032: sub all_domains {
12033: &load_hosts_tab() if (!$loaded);
12034:
12035: my %seen;
12036: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12037: return @uniq;
12038: }
12039:
12040: sub internet_dom {
12041: &load_hosts_tab() if (!$loaded);
12042:
12043: my ($lonid) = @_;
12044: return $internetdom{$lonid};
12045: }
12046:
12047: sub is_LC_dns {
12048: &load_hosts_tab() if (!$loaded);
12049:
12050: my ($hostname) = @_;
12051: return exists($LC_dns_serv{$hostname});
12052: }
12053:
12054: }
12055:
12056: {
12057: my %iphost;
12058: my %name_to_ip;
12059: my %lonid_to_ip;
12060:
12061: sub get_hosts_from_ip {
12062: my ($ip) = @_;
12063: my %iphosts = &get_iphost();
12064: if (ref($iphosts{$ip})) {
12065: return @{$iphosts{$ip}};
12066: }
12067: return;
12068: }
12069:
12070: sub reset_hosts_ip_info {
12071: undef(%iphost);
12072: undef(%name_to_ip);
12073: undef(%lonid_to_ip);
12074: }
12075:
12076: sub get_host_ip {
12077: my ($lonid) = @_;
12078: if (exists($lonid_to_ip{$lonid})) {
12079: return $lonid_to_ip{$lonid};
12080: }
12081: my $name=&hostname($lonid);
12082: my $ip = gethostbyname($name);
12083: return if (!$ip || length($ip) ne 4);
12084: $ip=inet_ntoa($ip);
12085: $name_to_ip{$name} = $ip;
12086: $lonid_to_ip{$lonid} = $ip;
12087: return $ip;
12088: }
12089:
12090: sub get_iphost {
12091: my ($ignore_cache) = @_;
12092:
12093: if (!$ignore_cache) {
12094: if (%iphost) {
12095: return %iphost;
12096: }
12097: my ($ip_info,$cached)=
12098: &Apache::lonnet::is_cached_new('iphost','iphost');
12099: if ($cached) {
12100: %iphost = %{$ip_info->[0]};
12101: %name_to_ip = %{$ip_info->[1]};
12102: %lonid_to_ip = %{$ip_info->[2]};
12103: return %iphost;
12104: }
12105: }
12106:
12107: # get yesterday's info for fallback
12108: my %old_name_to_ip;
12109: my ($ip_info,$cached)=
12110: &Apache::lonnet::is_cached_new('iphost','iphost');
12111: if ($cached) {
12112: %old_name_to_ip = %{$ip_info->[1]};
12113: }
12114:
12115: my %name_to_host = &all_names();
12116: foreach my $name (keys(%name_to_host)) {
12117: my $ip;
12118: if (!exists($name_to_ip{$name})) {
12119: $ip = gethostbyname($name);
12120: if (!$ip || length($ip) ne 4) {
12121: if (defined($old_name_to_ip{$name})) {
12122: $ip = $old_name_to_ip{$name};
12123: &logthis("Can't find $name defaulting to old $ip");
12124: } else {
12125: &logthis("Name $name no IP found");
12126: next;
12127: }
12128: } else {
12129: $ip=inet_ntoa($ip);
12130: }
12131: $name_to_ip{$name} = $ip;
12132: } else {
12133: $ip = $name_to_ip{$name};
12134: }
12135: foreach my $id (@{ $name_to_host{$name} }) {
12136: $lonid_to_ip{$id} = $ip;
12137: }
12138: push(@{$iphost{$ip}},@{$name_to_host{$name}});
12139: }
12140: &do_cache_new('iphost','iphost',
12141: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12142: 48*60*60);
12143:
12144: return %iphost;
12145: }
12146:
12147: #
12148: # Given a DNS returns the loncapa host name for that DNS
12149: #
12150: sub host_from_dns {
12151: my ($dns) = @_;
12152: my @hosts;
12153: my $ip;
12154:
12155: if (exists($name_to_ip{$dns})) {
12156: $ip = $name_to_ip{$dns};
12157: }
12158: if (!$ip) {
12159: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12160: if (length($ip) == 4) {
12161: $ip = &IO::Socket::inet_ntoa($ip);
12162: }
12163: }
12164: if ($ip) {
12165: @hosts = get_hosts_from_ip($ip);
12166: return $hosts[0];
12167: }
12168: return undef;
12169: }
12170:
12171: sub get_internet_names {
12172: my ($lonid) = @_;
12173: return if ($lonid eq '');
12174: my ($idnref,$cached)=
12175: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12176: if ($cached) {
12177: return $idnref;
12178: }
12179: my $ip = &get_host_ip($lonid);
12180: my @hosts = &get_hosts_from_ip($ip);
12181: my %iphost = &get_iphost();
12182: my (@idns,%seen);
12183: foreach my $id (@hosts) {
12184: my $dom = &host_domain($id);
12185: my $prim_id = &domain($dom,'primary');
12186: my $prim_ip = &get_host_ip($prim_id);
12187: next if ($seen{$prim_ip});
12188: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12189: foreach my $id (@{$iphost{$prim_ip}}) {
12190: my $intdom = &internet_dom($id);
12191: unless (grep(/^\Q$intdom\E$/,@idns)) {
12192: push(@idns,$intdom);
12193: }
12194: }
12195: }
12196: $seen{$prim_ip} = 1;
12197: }
12198: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12199: }
12200:
12201: }
12202:
12203: sub all_loncaparevs {
12204: return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10 2.11);
12205: }
12206:
12207: # ---------------------------------------------------------- Read loncaparev table
12208: {
12209: sub load_loncaparevs {
12210: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12211: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12212: while (my $configline=<$config>) {
12213: chomp($configline);
12214: my ($hostid,$loncaparev)=split(/:/,$configline);
12215: $loncaparevs{$hostid}=$loncaparev;
12216: }
12217: close($config);
12218: }
12219: }
12220: }
12221: }
12222:
12223: # ---------------------------------------------------------- Read serverhostID table
12224: {
12225: sub load_serverhomeIDs {
12226: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12227: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12228: while (my $configline=<$config>) {
12229: chomp($configline);
12230: my ($name,$id)=split(/:/,$configline);
12231: $serverhomeIDs{$name}=$id;
12232: }
12233: close($config);
12234: }
12235: }
12236: }
12237: }
12238:
12239:
12240: BEGIN {
12241:
12242: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12243: unless ($readit) {
12244: {
12245: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12246: %perlvar = (%perlvar,%{$configvars});
12247: }
12248:
12249:
12250: # ------------------------------------------------------ Read spare server file
12251: {
12252: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12253:
12254: while (my $configline=<$config>) {
12255: chomp($configline);
12256: if ($configline) {
12257: my ($host,$type) = split(':',$configline,2);
12258: if (!defined($type) || $type eq '') { $type = 'default' };
12259: push(@{ $spareid{$type} }, $host);
12260: }
12261: }
12262: close($config);
12263: }
12264: # ------------------------------------------------------------ Read permissions
12265: {
12266: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12267:
12268: while (my $configline=<$config>) {
12269: chomp($configline);
12270: if ($configline) {
12271: my ($role,$perm)=split(/ /,$configline);
12272: if ($perm ne '') { $pr{$role}=$perm; }
12273: }
12274: }
12275: close($config);
12276: }
12277:
12278: # -------------------------------------------- Read plain texts for permissions
12279: {
12280: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12281:
12282: while (my $configline=<$config>) {
12283: chomp($configline);
12284: if ($configline) {
12285: my ($short,@plain)=split(/:/,$configline);
12286: %{$prp{$short}} = ();
12287: if (@plain > 0) {
12288: $prp{$short}{'std'} = $plain[0];
12289: for (my $i=1; $i<@plain; $i++) {
12290: $prp{$short}{'alt'.$i} = $plain[$i];
12291: }
12292: }
12293: }
12294: }
12295: close($config);
12296: }
12297:
12298: # ---------------------------------------------------------- Read package table
12299: {
12300: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12301:
12302: while (my $configline=<$config>) {
12303: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12304: chomp($configline);
12305: my ($short,$plain)=split(/:/,$configline);
12306: my ($pack,$name)=split(/\&/,$short);
12307: if ($plain ne '') {
12308: $packagetab{$pack.'&'.$name.'&name'}=$name;
12309: $packagetab{$short}=$plain;
12310: }
12311: }
12312: close($config);
12313: }
12314:
12315: # ---------------------------------------------------------- Read loncaparev table
12316:
12317: &load_loncaparevs();
12318:
12319: # ---------------------------------------------------------- Read serverhostID table
12320:
12321: &load_serverhomeIDs();
12322:
12323: # ---------------------------------------------------------- Read releaseslist XML
12324: {
12325: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12326: if (-e $file) {
12327: my $parser = HTML::LCParser->new($file);
12328: while (my $token = $parser->get_token()) {
12329: if ($token->[0] eq 'S') {
12330: my $item = $token->[1];
12331: my $name = $token->[2]{'name'};
12332: my $value = $token->[2]{'value'};
12333: if ($item ne '' && $name ne '' && $value ne '') {
12334: my $release = $parser->get_text();
12335: $release =~ s/(^\s*|\s*$ )//gx;
12336: $needsrelease{$item.':'.$name.':'.$value} = $release;
12337: }
12338: }
12339: }
12340: }
12341: }
12342:
12343: # ---------------------------------------------------------- Read managers table
12344: {
12345: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12346: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12347: while (my $configline=<$config>) {
12348: chomp($configline);
12349: next if ($configline =~ /^\#/);
12350: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12351: $managerstab{$configline} = 1;
12352: }
12353: }
12354: close($config);
12355: }
12356: }
12357: }
12358:
12359: # ------------- set up temporary directory
12360: {
12361: $tmpdir = LONCAPA::tempdir();
12362:
12363: }
12364:
12365: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12366: 'compress_threshold'=> 20_000,
12367: });
12368:
12369: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12370: $dumpcount=0;
12371: $locknum=0;
12372:
12373: &logtouch();
12374: &logthis('<font color="yellow">INFO: Read configuration</font>');
12375: $readit=1;
12376: {
12377: use integer;
12378: my $test=(2**32)+1;
12379: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12380: &logthis(" Detected 64bit platform ($_64bit)");
12381: }
12382: }
12383: }
12384:
12385: 1;
12386: __END__
12387:
12388: =pod
12389:
12390: =head1 NAME
12391:
12392: Apache::lonnet - Subroutines to ask questions about things in the network.
12393:
12394: =head1 SYNOPSIS
12395:
12396: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12397:
12398: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12399:
12400: Common parameters:
12401:
12402: =over 4
12403:
12404: =item *
12405:
12406: $uname : an internal username (if $cname expecting a course Id specifically)
12407:
12408: =item *
12409:
12410: $udom : a domain (if $cdom expecting a course's domain specifically)
12411:
12412: =item *
12413:
12414: $symb : a resource instance identifier
12415:
12416: =item *
12417:
12418: $namespace : the name of a .db file that contains the data needed or
12419: being set.
12420:
12421: =back
12422:
12423: =head1 OVERVIEW
12424:
12425: lonnet provides subroutines which interact with the
12426: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12427: about classes, users, and resources.
12428:
12429: For many of these objects you can also use this to store data about
12430: them or modify them in various ways.
12431:
12432: =head2 Symbs
12433:
12434: To identify a specific instance of a resource, LON-CAPA uses symbols
12435: or "symbs"X<symb>. These identifiers are built from the URL of the
12436: map, the resource number of the resource in the map, and the URL of
12437: the resource itself. The latter is somewhat redundant, but might help
12438: if maps change.
12439:
12440: An example is
12441:
12442: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12443:
12444: The respective map entry is
12445:
12446: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12447: title="Problem 2">
12448: </resource>
12449:
12450: Symbs are used by the random number generator, as well as to store and
12451: restore data specific to a certain instance of for example a problem.
12452:
12453: =head2 Storing And Retrieving Data
12454:
12455: X<store()>X<cstore()>X<restore()>Three of the most important functions
12456: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12457: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12458: is is the non-critical message twin of cstore. These functions are for
12459: handlers to store a perl hash to a user's permanent data space in an
12460: easy manner, and to retrieve it again on another call. It is expected
12461: that a handler would use this once at the beginning to retrieve data,
12462: and then again once at the end to send only the new data back.
12463:
12464: The data is stored in the user's data directory on the user's
12465: homeserver under the ID of the course.
12466:
12467: The hash that is returned by restore will have all of the previous
12468: value for all of the elements of the hash.
12469:
12470: Example:
12471:
12472: #creating a hash
12473: my %hash;
12474: $hash{'foo'}='bar';
12475:
12476: #storing it
12477: &Apache::lonnet::cstore(\%hash);
12478:
12479: #changing a value
12480: $hash{'foo'}='notbar';
12481:
12482: #adding a new value
12483: $hash{'bar'}='foo';
12484: &Apache::lonnet::cstore(\%hash);
12485:
12486: #retrieving the hash
12487: my %history=&Apache::lonnet::restore();
12488:
12489: #print the hash
12490: foreach my $key (sort(keys(%history))) {
12491: print("\%history{$key} = $history{$key}");
12492: }
12493:
12494: Will print out:
12495:
12496: %history{1:foo} = bar
12497: %history{1:keys} = foo:timestamp
12498: %history{1:timestamp} = 990455579
12499: %history{2:bar} = foo
12500: %history{2:foo} = notbar
12501: %history{2:keys} = foo:bar:timestamp
12502: %history{2:timestamp} = 990455580
12503: %history{bar} = foo
12504: %history{foo} = notbar
12505: %history{timestamp} = 990455580
12506: %history{version} = 2
12507:
12508: Note that the special hash entries C<keys>, C<version> and
12509: C<timestamp> were added to the hash. C<version> will be equal to the
12510: total number of versions of the data that have been stored. The
12511: C<timestamp> attribute will be the UNIX time the hash was
12512: stored. C<keys> is available in every historical section to list which
12513: keys were added or changed at a specific historical revision of a
12514: hash.
12515:
12516: B<Warning>: do not store the hash that restore returns directly. This
12517: will cause a mess since it will restore the historical keys as if the
12518: were new keys. I.E. 1:foo will become 1:1:foo etc.
12519:
12520: Calling convention:
12521:
12522: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12523: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
12524:
12525: For more detailed information, see lonnet specific documentation.
12526:
12527: =head1 RETURN MESSAGES
12528:
12529: =over 4
12530:
12531: =item * B<con_lost>: unable to contact remote host
12532:
12533: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12534: when the connection is brought back up
12535:
12536: =item * B<con_failed>: unable to contact remote host and unable to save message
12537: for later delivery
12538:
12539: =item * B<error:>: an error a occurred, a description of the error follows the :
12540:
12541: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12542: that was requested
12543:
12544: =back
12545:
12546: =head1 PUBLIC SUBROUTINES
12547:
12548: =head2 Session Environment Functions
12549:
12550: =over 4
12551:
12552: =item *
12553: X<appenv()>
12554: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12555: the user envirnoment file, and will be restored for each access this
12556: user makes during this session, also modifies the %env for the current
12557: process. Optional rolesarrayref - if defined contains a reference to an array
12558: of roles which are exempt from the restriction on modifying user.role entries
12559: in the user's environment.db and in %env.
12560:
12561: =item *
12562: X<delenv()>
12563: B<delenv($delthis,$regexp)>: removes all items from the session
12564: environment file that begin with $delthis. If the
12565: optional second arg - $regexp - is true, $delthis is treated as a
12566: regular expression, otherwise \Q$delthis\E is used.
12567: The values are also deleted from the current processes %env.
12568:
12569: =item * get_env_multiple($name)
12570:
12571: gets $name from the %env hash, it seemlessly handles the cases where multiple
12572: values may be defined and end up as an array ref.
12573:
12574: returns an array of values
12575:
12576: =back
12577:
12578: =head2 User Information
12579:
12580: =over 4
12581:
12582: =item *
12583: X<queryauthenticate()>
12584: B<queryauthenticate($uname,$udom)>: try to determine user's current
12585: authentication scheme
12586:
12587: =item *
12588: X<authenticate()>
12589: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12590: authenticate user from domain's lib servers (first use the current
12591: one). C<$upass> should be the users password.
12592: $checkdefauth is optional (value is 1 if a check should be made to
12593: authenticate user using default authentication method, and allow
12594: account creation if username does not have account in the domain).
12595: $clientcancheckhost is optional (value is 1 if checking whether the
12596: server can host will occur on the client side in lonauth.pm).
12597:
12598: =item *
12599: X<homeserver()>
12600: B<homeserver($uname,$udom)>: find the server which has
12601: the user's directory and files (there must be only one), this caches
12602: the answer, and also caches if there is a borken connection.
12603:
12604: =item *
12605: X<idget()>
12606: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12607: (IDs are a unique resource in a domain, there must be only 1 ID per
12608: username, and only 1 username per ID in a specific domain) (returns
12609: hash: id=>name,id=>name)
12610:
12611: =item *
12612: X<idrget()>
12613: B<idrget($udom,@unames)>: find the IDs behind a list of
12614: usernames (returns hash: name=>id,name=>id)
12615:
12616: =item *
12617: X<idput()>
12618: B<idput($udom,%ids)>: store away a list of names and associated IDs
12619:
12620: =item *
12621: X<rolesinit()>
12622: B<rolesinit($udom,$username)>: get user privileges.
12623: returns user role, first access and timer interval hashes
12624:
12625: =item *
12626: X<privileged()>
12627: B<privileged($username,$domain)>: returns a true if user has a
12628: privileged and active role (i.e. su or dc), false otherwise.
12629:
12630: =item *
12631: X<getsection()>
12632: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12633: course $cname, return section name/number or '' for "not in course"
12634: and '-1' for "no section"
12635:
12636: =item *
12637: X<userenvironment()>
12638: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12639: passed in @what from the requested user's environment, returns a hash
12640:
12641: =item *
12642: X<userlog_query()>
12643: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12644: activity.log file. %filters defines filters applied when parsing the
12645: log file. These can be start or end timestamps, or the type of action
12646: - log to look for Login or Logout events, check for Checkin or
12647: Checkout, role for role selection. The response is in the form
12648: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12649: escaped strings of the action recorded in the activity.log file.
12650:
12651: =back
12652:
12653: =head2 User Roles
12654:
12655: =over 4
12656:
12657: =item *
12658:
12659: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12660: F: full access
12661: U,I,K: authentication modes (cxx only)
12662: '': forbidden
12663: 1: user needs to choose course
12664: 2: browse allowed
12665: A: passphrase authentication needed
12666:
12667: =item *
12668:
12669: constructaccess($url,$setpriv) : check for access to construction space URL
12670:
12671: See if the owner domain and name in the URL match those in the
12672: expected environment. If so, return three element list
12673: ($ownername,$ownerdomain,$ownerhome).
12674:
12675: Otherwise return the null string.
12676:
12677: If second argument 'setpriv' is true, it assigns the privileges,
12678: and returns the same three element list, unless the owner has
12679: blocked "ad hoc" Domain Coordinator access to the Author Space,
12680: in which case the null string is returned.
12681:
12682: =item *
12683:
12684: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12685: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12686: and course level
12687:
12688: =item *
12689:
12690: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12691: (rolesplain.tab); plain text explanation of a user role term.
12692: $type is Course (default) or Community.
12693: If $forcedefault evaluates to true, text returned will be default
12694: text for $type. Otherwise, if this is a course, the text returned
12695: will be a custom name for the role (if defined in the course's
12696: environment). If no custom name is defined the default is returned.
12697:
12698: =item *
12699:
12700: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
12701: All arguments are optional. Returns a hash of a roles, either for
12702: co-author/assistant author roles for a user's Construction Space
12703: (default), or if $context is 'userroles', roles for the user himself,
12704: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12705: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12706: For each key, value is set to colon-separated start and end times for
12707: the role. If no username and domain are specified, will default to
12708: current user/domain. Types, roles, and roledoms are references to arrays
12709: of role statuses (active, future or previous), roles
12710: (e.g., cc,in, st etc.) and domains of the roles which can be used
12711: to restrict the list of roles reported. If no array ref is
12712: provided for types, will default to return only active roles.
12713:
12714: =item *
12715:
12716: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12717: user: $uname:$udom has a role in the course: $cdom_$cnum.
12718:
12719: Additional optional arguments are: $type (if role checking is to be restricted
12720: to certain user status types -- previous (expired roles), active (currently
12721: available roles) or future (roles available in the future), and
12722: $hideprivileged -- if true will not report course roles for users who
12723: have active Domain Coordinator role in course's domain or in additional
12724: domains (specified in 'Domains to check for privileged users' in course
12725: environment -- set via: Course Settings -> Classlists and staff listing).
12726:
12727: =item *
12728:
12729: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12730: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12731: $possdomains and $possroles are optional array refs -- to domains to check and
12732: roles to check. If $possdomains is not specified, a dump will be done of the
12733: users' roles.db to check for a dc or su role in any domain. This can be
12734: time consuming if &privileged is called repeatedly (e.g., when displaying a
12735: classlist), so in such cases, supplying a $possdomains array is preferred, as
12736: this then allows &privileged_by_domain() to be used, which caches the identity
12737: of privileged users, eliminating the need for repeated calls to &dump().
12738:
12739: =item *
12740:
12741: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12742: where the outer hash keys are domains specified in the $possdomains array ref,
12743: next inner hash keys are privileged roles specified in the $roles array ref,
12744: and the innermost hash contains key = value pairs for username:domain = end:start
12745: for active or future "privileged" users with that role in that domain. To avoid
12746: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12747: innerhash are cached using priv_$role and $dom as the identifiers.
12748:
12749: =back
12750:
12751: =head2 User Modification
12752:
12753: =over 4
12754:
12755: =item *
12756:
12757: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
12758: user for the level given by URL. Optional start and end dates (leave empty
12759: string or zero for "no date")
12760:
12761: =item *
12762:
12763: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12764: change a users, password, possible return values are: ok,
12765: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12766: refused
12767:
12768: =item *
12769:
12770: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
12771:
12772: =item *
12773:
12774: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12775: $forceid,$desiredhome,$email,$inststatus,$candelete) :
12776:
12777: will update user information (firstname,middlename,lastname,generation,
12778: permanentemail), and if forceid is true, student/employee ID also.
12779: A user's institutional affiliation(s) can also be updated.
12780: User information fields will not be overwritten with empty entries
12781: unless the field is included in the $candelete array reference.
12782: This array is included when a single user is modified via "Manage Users",
12783: or when Autoupdate.pl is run by cron in a domain.
12784:
12785: =item *
12786:
12787: modifystudent
12788:
12789: modify a student's enrollment and identification information.
12790: The course id is resolved based on the current user's environment.
12791: This means the invoking user must be a course coordinator or otherwise
12792: associated with a course.
12793:
12794: This call is essentially a wrapper for lonnet::modifyuser and
12795: lonnet::modify_student_enrollment
12796:
12797: Inputs:
12798:
12799: =over 4
12800:
12801: =item B<$udom> Student's loncapa domain
12802:
12803: =item B<$uname> Student's loncapa login name
12804:
12805: =item B<$uid> Student/Employee ID
12806:
12807: =item B<$umode> Student's authentication mode
12808:
12809: =item B<$upass> Student's password
12810:
12811: =item B<$first> Student's first name
12812:
12813: =item B<$middle> Student's middle name
12814:
12815: =item B<$last> Student's last name
12816:
12817: =item B<$gene> Student's generation
12818:
12819: =item B<$usec> Student's section in course
12820:
12821: =item B<$end> Unix time of the roles expiration
12822:
12823: =item B<$start> Unix time of the roles start date
12824:
12825: =item B<$forceid> If defined, allow $uid to be changed
12826:
12827: =item B<$desiredhome> server to use as home server for student
12828:
12829: =item B<$email> Student's permanent e-mail address
12830:
12831: =item B<$type> Type of enrollment (auto or manual)
12832:
12833: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
12834:
12835: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
12836:
12837: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
12838:
12839: =item B<$context> role change context (shown in User Management Logs display in a course)
12840:
12841: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12842:
12843: =item B<$credits> Number of credits student will earn from this class - only needs to be supplied if value needs to be different from default credits for class.
12844:
12845: =back
12846:
12847: =item *
12848:
12849: modify_student_enrollment
12850:
12851: Change a student's enrollment status in a class. The environment variable
12852: 'role.request.course' must be defined for this function to proceed.
12853:
12854: Inputs:
12855:
12856: =over 4
12857:
12858: =item $udom, student's domain
12859:
12860: =item $uname, student's name
12861:
12862: =item $uid, student's user id
12863:
12864: =item $first, student's first name
12865:
12866: =item $middle
12867:
12868: =item $last
12869:
12870: =item $gene
12871:
12872: =item $usec
12873:
12874: =item $end
12875:
12876: =item $start
12877:
12878: =item $type
12879:
12880: =item $locktype
12881:
12882: =item $cid
12883:
12884: =item $selfenroll
12885:
12886: =item $context
12887:
12888: =item $credits, number of credits student will earn from this class
12889:
12890: =back
12891:
12892:
12893: =item *
12894:
12895: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12896: custom role; give a custom role to a user for the level given by URL. Specify
12897: name and domain of role author, and role name
12898:
12899: =item *
12900:
12901: revokerole($udom,$uname,$url,$role) : revoke a role for url
12902:
12903: =item *
12904:
12905: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12906:
12907: =back
12908:
12909: =head2 Course Infomation
12910:
12911: =over 4
12912:
12913: =item *
12914:
12915: coursedescription($courseid,$options) : returns a hash of information about the
12916: specified course id, including all environment settings for the
12917: course, the description of the course will be in the hash under the
12918: key 'description'
12919:
12920: $options is an optional parameter that if supplied is a hash reference that controls
12921: what how this function works. It has the following key/values:
12922:
12923: =over 4
12924:
12925: =item freshen_cache
12926:
12927: If defined, and the environment cache for the course is valid, it is
12928: returned in the returned hash.
12929:
12930: =item one_time
12931:
12932: If defined, the last cache time is set to _now_
12933:
12934: =item user
12935:
12936: If defined, the supplied username is used instead of the current user.
12937:
12938:
12939: =back
12940:
12941: =item *
12942:
12943: resdata($name,$domain,$type,@which) : request for current parameter
12944: setting for a specific $type, where $type is either 'course' or 'user',
12945: @what should be a list of parameters to ask about. This routine caches
12946: answers for 10 minutes.
12947:
12948: =item *
12949:
12950: get_courseresdata($courseid, $domain) : dump the entire course resource
12951: data base, returning a hash that is keyed by the resource name and has
12952: values that are the resource value. I believe that the timestamps and
12953: versions are also returned.
12954:
12955: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
12956: supplemental content area. This routine caches the number of files for
12957: 10 minutes.
12958:
12959: =back
12960:
12961: =head2 Course Modification
12962:
12963: =over 4
12964:
12965: =item *
12966:
12967: writecoursepref($courseid,%prefs) : write preferences (environment
12968: database) for a course
12969:
12970: =item *
12971:
12972: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12973:
12974: =item *
12975:
12976: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
12977:
12978: =item *
12979:
12980: is_course($courseid), is_course($cdom, $cnum)
12981:
12982: Accepts either a combined $courseid (in the form of domain_courseid) or the
12983: two component version $cdom, $cnum. It checks if the specified course exists.
12984:
12985: Returns:
12986: undef if the course doesn't exist, otherwise
12987: in scalar context the combined courseid.
12988: in list context the two components of the course identifier, domain and
12989: courseid.
12990:
12991: =back
12992:
12993: =head2 Resource Subroutines
12994:
12995: =over 4
12996:
12997: =item *
12998:
12999: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
13000:
13001: =item *
13002:
13003: repcopy($filename) : subscribes to the requested file, and attempts to
13004: replicate from the owning library server, Might return
13005: 'unavailable', 'not_found', 'forbidden', 'ok', or
13006: 'bad_request', also attempts to grab the metadata for the
13007: resource. Expects the local filesystem pathname
13008: (/home/httpd/html/res/....)
13009:
13010: =back
13011:
13012: =head2 Resource Information
13013:
13014: =over 4
13015:
13016: =item *
13017:
13018: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13019: and returns the value of a variety of different possible values,
13020: $varname should be a request string, and the other parameters can be
13021: used to specify who and what one is asking about. Ordinarily, $cid
13022: does not need to be specified, as it is retrived from
13023: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13024: within lonuserstate::loadmap() when initializing a course, before
13025: $env{'request.course.id'} has been set, so it needs to be provided
13026: in that one case.
13027:
13028: Possible values for $varname are environment.lastname (or other item
13029: from the envirnment hash), user.name (or someother aspect about the
13030: user), resource.0.maxtries (or some other part and parameter of a
13031: resource)
13032:
13033: =item *
13034:
13035: directcondval($number) : get current value of a condition; reads from a state
13036: string
13037:
13038: =item *
13039:
13040: condval($condidx) : value of condition index based on state
13041:
13042: =item *
13043:
13044: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13045: resource's metadata, $what should be either a specific key, or either
13046: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13047: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13048:
13049: this function automatically caches all requests
13050:
13051: =item *
13052:
13053: metadata_query($query,$custom,$customshow) : make a metadata query against the
13054: network of library servers; returns file handle of where SQL and regex results
13055: will be stored for query
13056:
13057: =item *
13058:
13059: symbread($filename) : return symbolic list entry (filename argument optional);
13060: returns the data handle
13061:
13062: =item *
13063:
13064: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13065: and is a possible symb for the URL in $thisfn, and if is an encrypted
13066: resource that the user accessed using /enc/ returns a 1 on success, 0
13067: on failure, user must be in a course, as it assumes the existence of
13068: the course initial hash, and uses $env('request.course.id'}. The third
13069: arg is an optional reference to a scalar. If this arg is passed in the
13070: call to symbverify, it will be set to 1 if the symb has been set to be
13071: encrypted; otherwise it will be null.
13072:
13073: =item *
13074:
13075: symbclean($symb) : removes versions numbers from a symb, returns the
13076: cleaned symb
13077:
13078: =item *
13079:
13080: is_on_map($uri) : checks if the $uri is somewhere on the current
13081: course map, user must be in a course for it to work.
13082:
13083: =item *
13084:
13085: numval($salt) : return random seed value (addend for rndseed)
13086:
13087: =item *
13088:
13089: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13090: a random seed, all arguments are optional, if they aren't sent it uses the
13091: environment to derive them. Note: if symb isn't sent and it can't get one
13092: from &symbread it will use the current time as its return value
13093:
13094: =item *
13095:
13096: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13097: unfakeable, receipt
13098:
13099: =item *
13100:
13101: receipt() : API to ireceipt working off of env values; given out to users
13102:
13103: =item *
13104:
13105: countacc($url) : count the number of accesses to a given URL
13106:
13107: =item *
13108:
13109: 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
13110:
13111: =item *
13112:
13113: 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)
13114:
13115: =item *
13116:
13117: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
13118:
13119: =item *
13120:
13121: devalidate($symb) : devalidate temporary spreadsheet calculations,
13122: forcing spreadsheet to reevaluate the resource scores next time.
13123:
13124: =item *
13125:
13126: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13127: when viewing in course context.
13128:
13129: input: six args -- filename (decluttered), course number, course domain,
13130: url, symb (if registered) and group (if this is a
13131: group item -- e.g., bulletin board, group page etc.).
13132:
13133: output: array of five scalars --
13134: $cfile -- url for file editing if editable on current server
13135: $home -- homeserver of resource (i.e., for author if published,
13136: or course if uploaded.).
13137: $switchserver -- 1 if server switch will be needed.
13138: $forceedit -- 1 if icon/link should be to go to edit mode
13139: $forceview -- 1 if icon/link should be to go to view mode
13140:
13141: =item *
13142:
13143: is_course_upload($file,$cnum,$cdom)
13144:
13145: Used in course context to determine if current file was uploaded to
13146: the course (i.e., would be found in /userfiles/docs on the course's
13147: homeserver.
13148:
13149: input: 3 args -- filename (decluttered), course number and course domain.
13150: output: boolean -- 1 if file was uploaded.
13151:
13152: =back
13153:
13154: =head2 Storing/Retreiving Data
13155:
13156: =over 4
13157:
13158: =item *
13159:
13160: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13161: for this url; hashref needs to be given and should be a \%hashname; the
13162: remaining args aren't required and if they aren't passed or are '' they will
13163: be derived from the env
13164:
13165: =item *
13166:
13167: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13168: uses critical subroutine
13169:
13170: =item *
13171:
13172: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13173: all args are optional
13174:
13175: =item *
13176:
13177: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13178: dumps the complete (or key matching regexp) namespace into a hash
13179: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13180: normally &store()ed into
13181:
13182: $range should be either an integer '100' (give me the first 100
13183: matching records)
13184: or be two integers sperated by a - with no spaces
13185: '30-50' (give me the 30th through the 50th matching
13186: records)
13187:
13188:
13189: =item *
13190:
13191: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13192: replaces a &store() version of data with a replacement set of data
13193: for a particular resource in a namespace passed in the $storehash hash
13194: reference
13195:
13196: =item *
13197:
13198: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13199: works very similar to store/cstore, but all data is stored in a
13200: temporary location and can be reset using tmpreset, $storehash should
13201: be a hash reference, returns nothing on success
13202:
13203: =item *
13204:
13205: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13206: similar to restore, but all data is stored in a temporary location and
13207: can be reset using tmpreset. Returns a hash of values on success,
13208: error string otherwise.
13209:
13210: =item *
13211:
13212: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13213: deltes all keys for $symb form the temporary storage hash.
13214:
13215: =item *
13216:
13217: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13218: reference filled in from namesp ($udom and $uname are optional)
13219:
13220: =item *
13221:
13222: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13223: namesp ($udom and $uname are optional)
13224:
13225: =item *
13226:
13227: dump($namespace,$udom,$uname,$regexp,$range) :
13228: dumps the complete (or key matching regexp) namespace into a hash
13229: ($udom, $uname, $regexp, $range are optional)
13230:
13231: $range should be either an integer '100' (give me the first 100
13232: matching records)
13233: or be two integers sperated by a - with no spaces
13234: '30-50' (give me the 30th through the 50th matching
13235: records)
13236: =item *
13237:
13238: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13239: $store can be a scalar, an array reference, or if the amount to be
13240: incremented is > 1, a hash reference.
13241:
13242: ($udom and $uname are optional)
13243:
13244: =item *
13245:
13246: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13247: ($udom and $uname are optional)
13248:
13249: =item *
13250:
13251: cput($namespace,$storehash,$udom,$uname) : critical put
13252: ($udom and $uname are optional)
13253:
13254: =item *
13255:
13256: newput($namespace,$storehash,$udom,$uname) :
13257:
13258: Attempts to store the items in the $storehash, but only if they don't
13259: currently exist, if this succeeds you can be certain that you have
13260: successfully created a new key value pair in the $namespace db.
13261:
13262:
13263: Args:
13264: $namespace: name of database to store values to
13265: $storehash: hashref to store to the db
13266: $udom: (optional) domain of user containing the db
13267: $uname: (optional) name of user caontaining the db
13268:
13269: Returns:
13270: 'ok' -> succeeded in storing all keys of $storehash
13271: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13272: least <key> already existed in the db (other
13273: requested keys may also already exist)
13274: 'error: <msg>' -> unable to tie the DB or other error occurred
13275: 'con_lost' -> unable to contact request server
13276: 'refused' -> action was not allowed by remote machine
13277:
13278:
13279: =item *
13280:
13281: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13282: reference filled in from namesp (encrypts the return communication)
13283: ($udom and $uname are optional)
13284:
13285: =item *
13286:
13287: log($udom,$name,$home,$message) : write to permanent log for user; use
13288: critical subroutine
13289:
13290: =item *
13291:
13292: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13293: array reference filled in from namespace found in domain level on either
13294: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13295:
13296: =item *
13297:
13298: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13299: domain level either on specified domain server ($uhome) or primary domain
13300: server ($udom and $uhome are optional)
13301:
13302: =item *
13303:
13304: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13305: for: authentication, language, quotas, timezone, date locale, and portal URL in
13306: the target domain.
13307:
13308: May also include additional key => value pairs for the following groups:
13309:
13310: =over
13311:
13312: =item
13313: disk quotas (MB allocated by default to portfolios and authoring spaces).
13314:
13315: =over
13316:
13317: =item defaultquota, authorquota
13318:
13319: =back
13320:
13321: =item
13322: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13323: portfolio for users).
13324:
13325: =over
13326:
13327: =item
13328: aboutme, blog, webdav, portfolio
13329:
13330: =back
13331:
13332: =item
13333: requestcourses: ability to request courses, and how requests are processed.
13334:
13335: =over
13336:
13337: =item
13338: official, unofficial, community, textbook
13339:
13340: =back
13341:
13342: =item
13343: inststatus: types of institutional affiliation, and order in which they are displayed.
13344:
13345: =over
13346:
13347: =item
13348: inststatustypes, inststatusorder
13349:
13350: =back
13351:
13352: =item
13353: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13354: for course's uploaded content.
13355:
13356: =over
13357:
13358: =item
13359: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
13360: communityquota, textbookquota
13361:
13362: =back
13363:
13364: =item
13365: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13366: on your servers.
13367:
13368: =over
13369:
13370: =item
13371: remotesessions, hostedsessions
13372:
13373: =back
13374:
13375: =back
13376:
13377: In cases where a domain coordinator has never used the "Set Domain Configuration"
13378: utility to create a configuration.db file on a domain's primary library server
13379: only the following domain defaults: auth_def, auth_arg_def, lang_def
13380: -- corresponding values are authentication type (internal, krb4, krb5,
13381: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13382: will be available. Values are retrieved from cache (if current), unless the
13383: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13384: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13385:
13386: Typical usage:
13387:
13388: %domdefaults = &get_domain_defaults($target_domain);
13389:
13390: =back
13391:
13392: =head2 Network Status Functions
13393:
13394: =over 4
13395:
13396: =item *
13397:
13398: dirlist() : return directory list based on URI (first arg).
13399:
13400: Inputs: 1 required, 5 optional.
13401:
13402: =over
13403:
13404: =item
13405: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13406:
13407: =item
13408: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13409:
13410: =item
13411: $username - username of user/course to be listed. Extracted from $uri if absent.
13412:
13413: =item
13414: $getpropath - boolean: 1 if prepend path using &propath().
13415:
13416: =item
13417: $getuserdir - boolean: 1 if prepend path for "userfiles".
13418:
13419: =item
13420: $alternateRoot - path to prepend in place of path from $uri.
13421:
13422: =back
13423:
13424: Returns: Array of up to two items.
13425:
13426: =over
13427:
13428: a reference to an array of files/subdirectories
13429:
13430: =over
13431:
13432: Each element in the array of files/subdirectories is a & separated list of
13433: item name and the result of running stat on the item. If dirlist was requested
13434: for a file instead of a directory, the item name will be ''. For a directory
13435: listing, if the item is a metadata file, the element will end &N&M
13436: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13437: default copyright set (1).
13438:
13439: =back
13440:
13441: a scalar containing error condition (if encountered).
13442:
13443: =over
13444:
13445: =item
13446: no_host (no homeserver identified for $username:$domain).
13447:
13448: =item
13449: no_such_host (server contacted for listing not identified as valid host).
13450:
13451: =item
13452: con_lost (connection to remote server failed).
13453:
13454: =item
13455: refused (invalid $username:$domain received on lond side).
13456:
13457: =item
13458: no_such_dir (directory at specified path on lond side does not exist).
13459:
13460: =item
13461: empty (directory at specified path on lond side is empty).
13462:
13463: =over
13464:
13465: This is currently not encountered because the &ls3, &ls2,
13466: &ls (_handler) routines on the lond side do not filter out
13467: . and .. from a directory listing.
13468:
13469: =back
13470:
13471: =back
13472:
13473: =back
13474:
13475: =item *
13476:
13477: spareserver() : find server with least workload from spare.tab
13478:
13479:
13480: =item *
13481:
13482: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13483: if there is no corresponding loncapa host.
13484:
13485: =back
13486:
13487:
13488: =head2 Apache Request
13489:
13490: =over 4
13491:
13492: =item *
13493:
13494: ssi($url,%hash) : server side include, does a complete request cycle on url to
13495: localhost, posts hash
13496:
13497: =back
13498:
13499: =head2 Data to String to Data
13500:
13501: =over 4
13502:
13503: =item *
13504:
13505: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13506: and '&' separators, supports elements that are arrayrefs and hashrefs
13507:
13508: =item *
13509:
13510: hashref2str($hashref) : convert a hashref into a string complete with
13511: escaping and '=' and '&' separators, supports elements that are
13512: arrayrefs and hashrefs
13513:
13514: =item *
13515:
13516: arrayref2str($arrayref) : convert an arrayref into a string complete
13517: with escaping and '&' separators, supports elements that are arrayrefs
13518: and hashrefs
13519:
13520: =item *
13521:
13522: str2hash($string) : convert string to hash using unescaping and
13523: splitting on '=' and '&', supports elements that are arrayrefs and
13524: hashrefs
13525:
13526: =item *
13527:
13528: str2array($string) : convert string to hash using unescaping and
13529: splitting on '&', supports elements that are arrayrefs and hashrefs
13530:
13531: =back
13532:
13533: =head2 Logging Routines
13534:
13535:
13536: These routines allow one to make log messages in the lonnet.log and
13537: lonnet.perm logfiles.
13538:
13539: =over 4
13540:
13541: =item *
13542:
13543: logtouch() : make sure the logfile, lonnet.log, exists
13544:
13545: =item *
13546:
13547: logthis() : append message to the normal lonnet.log file, it gets
13548: preiodically rolled over and deleted.
13549:
13550: =item *
13551:
13552: logperm() : append a permanent message to lonnet.perm.log, this log
13553: file never gets deleted by any automated portion of the system, only
13554: messages of critical importance should go in here.
13555:
13556:
13557: =back
13558:
13559: =head2 General File Helper Routines
13560:
13561: =over 4
13562:
13563: =item *
13564:
13565: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13566: (a) files in /uploaded
13567: (i) If a local copy of the file exists -
13568: compares modification date of local copy with last-modified date for
13569: definitive version stored on home server for course. If local copy is
13570: stale, requests a new version from the home server and stores it.
13571: If the original has been removed from the home server, then local copy
13572: is unlinked.
13573: (ii) If local copy does not exist -
13574: requests the file from the home server and stores it.
13575:
13576: If $caller is 'uploadrep':
13577: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13578: for request for files originally uploaded via DOCS.
13579: - returns 'ok' if fresh local copy now available, -1 otherwise.
13580:
13581: Otherwise:
13582: This indicates a call from the content generation phase of the request.
13583: - returns the entire contents of the file or -1.
13584:
13585: (b) files in /res
13586: - returns the entire contents of a file or -1;
13587: it properly subscribes to and replicates the file if neccessary.
13588:
13589:
13590: =item *
13591:
13592: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13593: reference
13594:
13595: returns either a stat() list of data about the file or an empty list
13596: if the file doesn't exist or couldn't find out about it (connection
13597: problems or user unknown)
13598:
13599: =item *
13600:
13601: filelocation($dir,$file) : returns file system location of a file
13602: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13603: directory that relative $file lookups are to looked in ($dir of /a/dir
13604: and a file of ../bob will become /a/bob)
13605:
13606: =item *
13607:
13608: hreflocation($dir,$file) : returns file system location or a URL; same as
13609: filelocation except for hrefs
13610:
13611: =item *
13612:
13613: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13614:
13615: =back
13616:
13617: =head2 Usererfile file routines (/uploaded*)
13618:
13619: =over 4
13620:
13621: =item *
13622:
13623: userfileupload(): main rotine for putting a file in a user or course's
13624: filespace, arguments are,
13625:
13626: formname - required - this is the name of the element in $env where the
13627: filename, and the contents of the file to create/modifed exist
13628: the filename is in $env{'form.'.$formname.'.filename'} and the
13629: contents of the file is located in $env{'form.'.$formname}
13630: context - if coursedoc, store the file in the course of the active role
13631: of the current user;
13632: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13633: if 'canceloverwrite': delete file in tmp/overwrites directory
13634: subdir - required - subdirectory to put the file in under ../userfiles/
13635: if undefined, it will be placed in "unknown"
13636:
13637: (This routine calls clean_filename() to remove any dangerous
13638: characters from the filename, and then calls finuserfileupload() to
13639: complete the transaction)
13640:
13641: returns either the url of the uploaded file (/uploaded/....) if successful
13642: and /adm/notfound.html if unsuccessful
13643:
13644: =item *
13645:
13646: clean_filename(): routine for cleaing a filename up for storage in
13647: userfile space, argument is:
13648:
13649: filename - proposed filename
13650:
13651: returns: the new clean filename
13652:
13653: =item *
13654:
13655: finishuserfileupload(): routine that creates and sends the file to
13656: userspace, probably shouldn't be called directly
13657:
13658: docuname: username or courseid of destination for the file
13659: docudom: domain of user/course of destination for the file
13660: formname: same as for userfileupload()
13661: fname: filename (including subdirectories) for the file
13662: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13663: allfiles: reference to hash used to store objects found by parser
13664: codebase: reference to hash used for codebases of java objects found by parser
13665: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13666: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13667: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13668: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13669: context: if 'overwrite', will move the uploaded file from its temporary location to
13670: userfiles to facilitate overwriting a previously uploaded file with same name.
13671: mimetype: reference to scalar to accommodate mime type determined
13672: from File::MMagic if $parser = parse.
13673:
13674: returns either the url of the uploaded file (/uploaded/....) if successful
13675: and /adm/notfound.html if unsuccessful (or an error message if context
13676: was 'overwrite').
13677:
13678:
13679: =item *
13680:
13681: renameuserfile(): renames an existing userfile to a new name
13682:
13683: Args:
13684: docuname: username or courseid of destination for the file
13685: docudom: domain of user/course of destination for the file
13686: old: current file name (including any subdirs under userfiles)
13687: new: desired file name (including any subdirs under userfiles)
13688:
13689: =item *
13690:
13691: mkdiruserfile(): creates a directory is a userfiles dir
13692:
13693: Args:
13694: docuname: username or courseid of destination for the file
13695: docudom: domain of user/course of destination for the file
13696: dir: dir to create (including any subdirs under userfiles)
13697:
13698: =item *
13699:
13700: removeuserfile(): removes a file that exists in userfiles
13701:
13702: Args:
13703: docuname: username or courseid of destination for the file
13704: docudom: domain of user/course of destination for the file
13705: fname: filname to delete (including any subdirs under userfiles)
13706:
13707: =item *
13708:
13709: removeuploadedurl(): convience function for removeuserfile()
13710:
13711: Args:
13712: url: a full /uploaded/... url to delete
13713:
13714: =item *
13715:
13716: get_portfile_permissions():
13717: Args:
13718: domain: domain of user or course contain the portfolio files
13719: user: name of user or num of course contain the portfolio files
13720: Returns:
13721: hashref of a dump of the proper file_permissions.db
13722:
13723:
13724: =item *
13725:
13726: get_access_controls():
13727:
13728: Args:
13729: current_permissions: the hash ref returned from get_portfile_permissions()
13730: group: (optional) the group you want the files associated with
13731: file: (optional) the file you want access info on
13732:
13733: Returns:
13734: a hash (keys are file names) of hashes containing
13735: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13736: values are XML containing access control settings (see below)
13737:
13738: Internal notes:
13739:
13740: access controls are stored in file_permissions.db as key=value pairs.
13741: key -> path to file/file_name\0uniqueID:scope_end_start
13742: where scope -> public,guest,course,group,domains or users.
13743: end -> UNIX time for end of access (0 -> no end date)
13744: start -> UNIX time for start of access
13745:
13746: value -> XML description of access control
13747: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13748: <start></start>
13749: <end></end>
13750:
13751: <password></password> for scope type = guest
13752:
13753: <domain></domain> for scope type = course or group
13754: <number></number>
13755: <roles id="">
13756: <role></role>
13757: <access></access>
13758: <section></section>
13759: <group></group>
13760: </roles>
13761:
13762: <dom></dom> for scope type = domains
13763:
13764: <users> for scope type = users
13765: <user>
13766: <uname></uname>
13767: <udom></udom>
13768: </user>
13769: </users>
13770: </scope>
13771:
13772: Access data is also aggregated for each file in an additional key=value pair:
13773: key -> path to file/file_name\0accesscontrol
13774: value -> reference to hash
13775: hash contains key = value pairs
13776: where key = uniqueID:scope_end_start
13777: value = UNIX time record was last updated
13778:
13779: Used to improve speed of look-ups of access controls for each file.
13780:
13781: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13782:
13783: =item *
13784:
13785: modify_access_controls():
13786:
13787: Modifies access controls for a portfolio file
13788: Args
13789: 1. file name
13790: 2. reference to hash of required changes,
13791: 3. domain
13792: 4. username
13793: where domain,username are the domain of the portfolio owner
13794: (either a user or a course)
13795:
13796: Returns:
13797: 1. result of additions or updates ('ok' or 'error', with error message).
13798: 2. result of deletions ('ok' or 'error', with error message).
13799: 3. reference to hash of any new or updated access controls.
13800: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13801: key = integer (inbound ID)
13802: value = uniqueID
13803:
13804: =item *
13805:
13806: get_timebased_id():
13807:
13808: Attempts to get a unique timestamp-based suffix for use with items added to a
13809: course via the Course Editor (e.g., folders, composite pages,
13810: group bulletin boards).
13811:
13812: Args: (first three required; six others optional)
13813:
13814: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13815: docssequence, or name of group
13816:
13817: 2. keyid (alphanumeric): name of temporary locking key in hash,
13818: e.g., num, boardids
13819:
13820: 3. namespace: name of gdbm file used to store suffixes already assigned;
13821: file will be named nohist_namespace.db
13822:
13823: 4. cdom: domain of course; default is current course domain from %env
13824:
13825: 5. cnum: course number; default is current course number from %env
13826:
13827: 6. idtype: set to concat if an additional digit is to be appended to the
13828: unix timestamp to form the suffix, if the plain timestamp is already
13829: in use. Default is to not do this, but simply increment the unix
13830: timestamp by 1 until a unique key is obtained.
13831:
13832: 7. who: holder of locking key; defaults to user:domain for user.
13833:
13834: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
13835: retrying); default is 3.
13836:
13837: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
13838:
13839: Returns:
13840:
13841: 1. suffix obtained (numeric)
13842:
13843: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13844:
13845: 3. error: contains (localized) error message if an error occurred.
13846:
13847:
13848: =back
13849:
13850: =head2 HTTP Helper Routines
13851:
13852: =over 4
13853:
13854: =item *
13855:
13856: escape() : unpack non-word characters into CGI-compatible hex codes
13857:
13858: =item *
13859:
13860: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13861:
13862: =back
13863:
13864: =head1 PRIVATE SUBROUTINES
13865:
13866: =head2 Underlying communication routines (Shouldn't call)
13867:
13868: =over 4
13869:
13870: =item *
13871:
13872: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13873:
13874: =item *
13875:
13876: reply() : uses subreply to send a message to remote machine, logs all failures
13877:
13878: =item *
13879:
13880: critical() : passes a critical message to another server; if cannot
13881: get through then place message in connection buffer directory and
13882: returns con_delayed, if incapable of saving message, returns
13883: con_failed
13884:
13885: =item *
13886:
13887: reconlonc() : tries to reconnect lonc client processes.
13888:
13889: =back
13890:
13891: =head2 Resource Access Logging
13892:
13893: =over 4
13894:
13895: =item *
13896:
13897: flushcourselogs() : flush (save) buffer logs and access logs
13898:
13899: =item *
13900:
13901: courselog($what) : save message for course in hash
13902:
13903: =item *
13904:
13905: courseacclog($what) : save message for course using &courselog(). Perform
13906: special processing for specific resource types (problems, exams, quizzes, etc).
13907:
13908: =item *
13909:
13910: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13911: as a PerlChildExitHandler
13912:
13913: =back
13914:
13915: =head2 Other
13916:
13917: =over 4
13918:
13919: =item *
13920:
13921: symblist($mapname,%newhash) : update symbolic storage links
13922:
13923: =back
13924:
13925: =cut
13926:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>