1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.1175 2012/05/30 16:29:25 raeburn Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28: ###
29:
30: =pod
31:
32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
71: package Apache::lonnet;
72:
73: use strict;
74: use LWP::UserAgent();
75: use HTTP::Date;
76: use Image::Magick;
77:
78: use Encode;
79:
80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
81: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
82: %managerstab);
83:
84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
85: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
86: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
87: %courseownerbuf, %coursetypebuf,$locknum);
88:
89: use IO::Socket;
90: use GDBM_File;
91: use HTML::LCParser;
92: use Fcntl qw(:flock);
93: use Storable qw(thaw nfreeze);
94: use Time::HiRes qw( gettimeofday tv_interval );
95: use Cache::Memcached;
96: use Digest::MD5;
97: use Math::Random;
98: use File::MMagic;
99: use LONCAPA qw(:DEFAULT :match);
100: use LONCAPA::Configuration;
101: use LONCAPA::lonmetadata;
102: use LONCAPA::Lond;
103:
104: use File::Copy;
105:
106: my $readit;
107: my $max_connection_retries = 10; # Or some such value.
108:
109: require Exporter;
110:
111: our @ISA = qw (Exporter);
112: our @EXPORT = qw(%env);
113:
114:
115: # --------------------------------------------------------------------- Logging
116: {
117: my $logid;
118: sub instructor_log {
119: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
120: if (($cnum eq '') || ($cdom eq '')) {
121: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
122: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
123: }
124: $logid++;
125: my $now = time();
126: my $id=$now.'00000'.$$.'00000'.$logid;
127: return &Apache::lonnet::put('nohist_'.$hash_name,
128: { $id => {
129: 'exe_uname' => $env{'user.name'},
130: 'exe_udom' => $env{'user.domain'},
131: 'exe_time' => $now,
132: 'exe_ip' => $ENV{'REMOTE_ADDR'},
133: 'delflag' => $delflag,
134: 'logentry' => $storehash,
135: 'uname' => $uname,
136: 'udom' => $udom,
137: }
138: },$cdom,$cnum);
139: }
140: }
141:
142: sub logtouch {
143: my $execdir=$perlvar{'lonDaemons'};
144: unless (-e "$execdir/logs/lonnet.log") {
145: open(my $fh,">>$execdir/logs/lonnet.log");
146: close $fh;
147: }
148: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
149: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
150: }
151:
152: sub logthis {
153: my $message=shift;
154: my $execdir=$perlvar{'lonDaemons'};
155: my $now=time;
156: my $local=localtime($now);
157: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
158: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
159: print $fh $logstring;
160: close($fh);
161: }
162: return 1;
163: }
164:
165: sub logperm {
166: my $message=shift;
167: my $execdir=$perlvar{'lonDaemons'};
168: my $now=time;
169: my $local=localtime($now);
170: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
171: print $fh "$now:$message:$local\n";
172: close($fh);
173: }
174: return 1;
175: }
176:
177: sub create_connection {
178: my ($hostname,$lonid) = @_;
179: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
180: Type => SOCK_STREAM,
181: Timeout => 10);
182: return 0 if (!$client);
183: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
184: my $result = <$client>;
185: chomp($result);
186: return 1 if ($result eq 'done');
187: return 0;
188: }
189:
190: sub get_server_timezone {
191: my ($cnum,$cdom) = @_;
192: my $home=&homeserver($cnum,$cdom);
193: if ($home ne 'no_host') {
194: my $cachetime = 24*3600;
195: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
196: if (defined($cached)) {
197: return $timezone;
198: } else {
199: my $timezone = &reply('servertimezone',$home);
200: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
201: }
202: }
203: }
204:
205: sub get_server_distarch {
206: my ($lonhost,$ignore_cache) = @_;
207: if (defined($lonhost)) {
208: if (!defined(&hostname($lonhost))) {
209: return;
210: }
211: my $cachetime = 12*3600;
212: if (!$ignore_cache) {
213: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
214: if (defined($cached)) {
215: return $distarch;
216: }
217: }
218: my $rep = &reply('serverdistarch',$lonhost);
219: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
220: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
221: $rep eq '') {
222: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
223: }
224: }
225: return;
226: }
227:
228: sub get_server_loncaparev {
229: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
230: if (defined($lonhost)) {
231: if (!defined(&hostname($lonhost))) {
232: undef($lonhost);
233: }
234: }
235: if (!defined($lonhost)) {
236: if (defined(&domain($dom,'primary'))) {
237: $lonhost=&domain($dom,'primary');
238: if ($lonhost eq 'no_host') {
239: undef($lonhost);
240: }
241: }
242: }
243: if (defined($lonhost)) {
244: my $cachetime = 12*3600;
245: if (!$ignore_cache) {
246: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
247: if (defined($cached)) {
248: return $loncaparev;
249: }
250: }
251: my ($answer,$loncaparev);
252: my @ids=¤t_machine_ids();
253: if (grep(/^\Q$lonhost\E$/,@ids)) {
254: $answer = $perlvar{'lonVersion'};
255: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
256: $loncaparev = $1;
257: }
258: } else {
259: $answer = &reply('serverloncaparev',$lonhost);
260: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
261: if ($caller eq 'loncron') {
262: my $ua=new LWP::UserAgent;
263: $ua->timeout(4);
264: my $protocol = $protocol{$lonhost};
265: $protocol = 'http' if ($protocol ne 'https');
266: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
267: my $request=new HTTP::Request('GET',$url);
268: my $response=$ua->request($request);
269: unless ($response->is_error()) {
270: my $content = $response->content;
271: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
272: $loncaparev = $1;
273: }
274: }
275: } else {
276: $loncaparev = $loncaparevs{$lonhost};
277: }
278: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
279: $loncaparev = $1;
280: }
281: }
282: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
283: }
284: }
285:
286: sub get_server_homeID {
287: my ($hostname,$ignore_cache,$caller) = @_;
288: unless ($ignore_cache) {
289: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
290: if (defined($cached)) {
291: return $serverhomeID;
292: }
293: }
294: my $cachetime = 12*3600;
295: my $serverhomeID;
296: if ($caller eq 'loncron') {
297: my @machine_ids = &machine_ids($hostname);
298: foreach my $id (@machine_ids) {
299: my $response = &reply('serverhomeID',$id);
300: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
301: $serverhomeID = $response;
302: last;
303: }
304: }
305: if ($serverhomeID eq '') {
306: $serverhomeID = $machine_ids[-1];
307: }
308: } else {
309: $serverhomeID = $serverhomeIDs{$hostname};
310: }
311: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
312: }
313:
314: sub get_remote_globals {
315: my ($lonhost,$whathash,$ignore_cache) = @_;
316: my ($result,%returnhash,%whatneeded);
317: if (ref($whathash) eq 'HASH') {
318: foreach my $what (sort(keys(%{$whathash}))) {
319: my $hashid = $lonhost.'-'.$what;
320: my ($response,$cached);
321: unless ($ignore_cache) {
322: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
323: }
324: if (defined($cached)) {
325: $returnhash{$what} = $response;
326: } else {
327: $whatneeded{$what} = 1;
328: }
329: }
330: if (keys(%whatneeded) == 0) {
331: $result = 'ok';
332: } else {
333: my $requested = &freeze_escape(\%whatneeded);
334: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
335: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
336: ($rep eq 'unknown_cmd')) {
337: $result = $rep;
338: } else {
339: $result = 'ok';
340: my @pairs=split(/\&/,$rep);
341: foreach my $item (@pairs) {
342: my ($key,$value)=split(/=/,$item,2);
343: my $what = &unescape($key);
344: my $hashid = $lonhost.'-'.$what;
345: $returnhash{$what}=&thaw_unescape($value);
346: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
347: }
348: }
349: }
350: }
351: return ($result,\%returnhash);
352: }
353:
354: sub remote_devalidate_cache {
355: my ($lonhost,$name,$id) = @_;
356: my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
357: return $response;
358: }
359:
360: # -------------------------------------------------- Non-critical communication
361: sub subreply {
362: my ($cmd,$server)=@_;
363: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
364: #
365: # With loncnew process trimming, there's a timing hole between lonc server
366: # process exit and the master server picking up the listen on the AF_UNIX
367: # socket. In that time interval, a lock file will exist:
368:
369: my $lockfile=$peerfile.".lock";
370: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
371: sleep(1);
372: }
373: # At this point, either a loncnew parent is listening or an old lonc
374: # or loncnew child is listening so we can connect or everything's dead.
375: #
376: # We'll give the connection a few tries before abandoning it. If
377: # connection is not possible, we'll con_lost back to the client.
378: #
379: my $client;
380: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
381: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
382: Type => SOCK_STREAM,
383: Timeout => 10);
384: if ($client) {
385: last; # Connected!
386: } else {
387: &create_connection(&hostname($server),$server);
388: }
389: sleep(1); # Try again later if failed connection.
390: }
391: my $answer;
392: if ($client) {
393: print $client "sethost:$server:$cmd\n";
394: $answer=<$client>;
395: if (!$answer) { $answer="con_lost"; }
396: chomp($answer);
397: } else {
398: $answer = 'con_lost'; # Failed connection.
399: }
400: return $answer;
401: }
402:
403: sub reply {
404: my ($cmd,$server)=@_;
405: unless (defined(&hostname($server))) { return 'no_such_host'; }
406: my $answer=subreply($cmd,$server);
407: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
408: &logthis("<font color=\"blue\">WARNING:".
409: " $cmd to $server returned $answer</font>");
410: }
411: return $answer;
412: }
413:
414: # ----------------------------------------------------------- Send USR1 to lonc
415:
416: sub reconlonc {
417: my ($lonid) = @_;
418: my $hostname = &hostname($lonid);
419: if ($lonid) {
420: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
421: if ($hostname && -e $peerfile) {
422: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
423: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
424: Type => SOCK_STREAM,
425: Timeout => 10);
426: if ($client) {
427: print $client ("reset_retries\n");
428: my $answer=<$client>;
429: #reset just this one.
430: }
431: }
432: return;
433: }
434:
435: &logthis("Trying to reconnect lonc");
436: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
437: if (open(my $fh,"<$loncfile")) {
438: my $loncpid=<$fh>;
439: chomp($loncpid);
440: if (kill 0 => $loncpid) {
441: &logthis("lonc at pid $loncpid responding, sending USR1");
442: kill USR1 => $loncpid;
443: sleep 1;
444: } else {
445: &logthis(
446: "<font color=\"blue\">WARNING:".
447: " lonc at pid $loncpid not responding, giving up</font>");
448: }
449: } else {
450: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
451: }
452: }
453:
454: # ------------------------------------------------------ Critical communication
455:
456: sub critical {
457: my ($cmd,$server)=@_;
458: unless (&hostname($server)) {
459: &logthis("<font color=\"blue\">WARNING:".
460: " Critical message to unknown server ($server)</font>");
461: return 'no_such_host';
462: }
463: my $answer=reply($cmd,$server);
464: if ($answer eq 'con_lost') {
465: &reconlonc("$perlvar{'lonSockDir'}/$server");
466: my $answer=reply($cmd,$server);
467: if ($answer eq 'con_lost') {
468: my $now=time;
469: my $middlename=$cmd;
470: $middlename=substr($middlename,0,16);
471: $middlename=~s/\W//g;
472: my $dfilename=
473: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
474: $dumpcount++;
475: {
476: my $dfh;
477: if (open($dfh,">$dfilename")) {
478: print $dfh "$cmd\n";
479: close($dfh);
480: }
481: }
482: sleep 2;
483: my $wcmd='';
484: {
485: my $dfh;
486: if (open($dfh,"<$dfilename")) {
487: $wcmd=<$dfh>;
488: close($dfh);
489: }
490: }
491: chomp($wcmd);
492: if ($wcmd eq $cmd) {
493: &logthis("<font color=\"blue\">WARNING: ".
494: "Connection buffer $dfilename: $cmd</font>");
495: &logperm("D:$server:$cmd");
496: return 'con_delayed';
497: } else {
498: &logthis("<font color=\"red\">CRITICAL:"
499: ." Critical connection failed: $server $cmd</font>");
500: &logperm("F:$server:$cmd");
501: return 'con_failed';
502: }
503: }
504: }
505: return $answer;
506: }
507:
508: # ------------------------------------------- check if return value is an error
509:
510: sub error {
511: my ($result) = @_;
512: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
513: if ($2 == 2) { return undef; }
514: return $1;
515: }
516: return undef;
517: }
518:
519: sub convert_and_load_session_env {
520: my ($lonidsdir,$handle)=@_;
521: my @profile;
522: {
523: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
524: if (!$opened) {
525: return 0;
526: }
527: flock($idf,LOCK_SH);
528: @profile=<$idf>;
529: close($idf);
530: }
531: my %temp_env;
532: foreach my $line (@profile) {
533: if ($line !~ m/=/) {
534: return 0;
535: }
536: chomp($line);
537: my ($envname,$envvalue)=split(/=/,$line,2);
538: $temp_env{&unescape($envname)} = &unescape($envvalue);
539: }
540: unlink("$lonidsdir/$handle.id");
541: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
542: 0640)) {
543: %disk_env = %temp_env;
544: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
545: untie(%disk_env);
546: }
547: return 1;
548: }
549:
550: # ------------------------------------------- Transfer profile into environment
551: my $env_loaded;
552: sub transfer_profile_to_env {
553: my ($lonidsdir,$handle,$force_transfer) = @_;
554: if (!$force_transfer && $env_loaded) { return; }
555:
556: if (!defined($lonidsdir)) {
557: $lonidsdir = $perlvar{'lonIDsDir'};
558: }
559: if (!defined($handle)) {
560: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
561: }
562:
563: my $convert;
564: {
565: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
566: if (!$opened) {
567: return;
568: }
569: flock($idf,LOCK_SH);
570: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
571: &GDBM_READER(),0640)) {
572: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
573: untie(%disk_env);
574: } else {
575: $convert = 1;
576: }
577: }
578: if ($convert) {
579: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
580: &logthis("Failed to load session, or convert session.");
581: }
582: }
583:
584: my %remove;
585: while ( my $envname = each(%env) ) {
586: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
587: if ($time < time-300) {
588: $remove{$key}++;
589: }
590: }
591: }
592:
593: $env{'user.environment'} = "$lonidsdir/$handle.id";
594: $env_loaded=1;
595: foreach my $expired_key (keys(%remove)) {
596: &delenv($expired_key);
597: }
598: }
599:
600: # ---------------------------------------------------- Check for valid session
601: sub check_for_valid_session {
602: my ($r,$name) = @_;
603: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
604: if ($name eq '') {
605: $name = 'lonID';
606: }
607: my $lonid=$cookies{$name};
608: return undef if (!$lonid);
609:
610: my $handle=&LONCAPA::clean_handle($lonid->value);
611: my $lonidsdir;
612: if ($name eq 'lonDAV') {
613: $lonidsdir=$r->dir_config('lonDAVsessDir');
614: } else {
615: $lonidsdir=$r->dir_config('lonIDsDir');
616: }
617: return undef if (!-e "$lonidsdir/$handle.id");
618:
619: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
620: return undef if (!$opened);
621:
622: flock($idf,LOCK_SH);
623: my %disk_env;
624: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
625: &GDBM_READER(),0640)) {
626: return undef;
627: }
628:
629: if (!defined($disk_env{'user.name'})
630: || !defined($disk_env{'user.domain'})) {
631: return undef;
632: }
633: return $handle;
634: }
635:
636: sub timed_flock {
637: my ($file,$lock_type) = @_;
638: my $failed=0;
639: eval {
640: local $SIG{__DIE__}='DEFAULT';
641: local $SIG{ALRM}=sub {
642: $failed=1;
643: die("failed lock");
644: };
645: alarm(13);
646: flock($file,$lock_type);
647: alarm(0);
648: };
649: if ($failed) {
650: return undef;
651: } else {
652: return 1;
653: }
654: }
655:
656: # ---------------------------------------------------------- Append Environment
657:
658: sub appenv {
659: my ($newenv,$roles) = @_;
660: if (ref($newenv) eq 'HASH') {
661: foreach my $key (keys(%{$newenv})) {
662: my $refused = 0;
663: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
664: $refused = 1;
665: if (ref($roles) eq 'ARRAY') {
666: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
667: if (grep(/^\Q$role\E$/,@{$roles})) {
668: $refused = 0;
669: }
670: }
671: }
672: if ($refused) {
673: &logthis("<font color=\"blue\">WARNING: ".
674: "Attempt to modify environment ".$key." to ".$newenv->{$key}
675: .'</font>');
676: delete($newenv->{$key});
677: } else {
678: $env{$key}=$newenv->{$key};
679: }
680: }
681: my $opened = open(my $env_file,'+<',$env{'user.environment'});
682: if ($opened
683: && &timed_flock($env_file,LOCK_EX)
684: &&
685: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
686: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
687: while (my ($key,$value) = each(%{$newenv})) {
688: $disk_env{$key} = $value;
689: }
690: untie(%disk_env);
691: }
692: }
693: return 'ok';
694: }
695: # ----------------------------------------------------- Delete from Environment
696:
697: sub delenv {
698: my ($delthis,$regexp,$roles) = @_;
699: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
700: my $refused = 1;
701: if (ref($roles) eq 'ARRAY') {
702: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
703: if (grep(/^\Q$role\E$/,@{$roles})) {
704: $refused = 0;
705: }
706: }
707: if ($refused) {
708: &logthis("<font color=\"blue\">WARNING: ".
709: "Attempt to delete from environment ".$delthis);
710: return 'error';
711: }
712: }
713: my $opened = open(my $env_file,'+<',$env{'user.environment'});
714: if ($opened
715: && &timed_flock($env_file,LOCK_EX)
716: &&
717: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
718: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
719: foreach my $key (keys(%disk_env)) {
720: if ($regexp) {
721: if ($key=~/^$delthis/) {
722: delete($env{$key});
723: delete($disk_env{$key});
724: }
725: } else {
726: if ($key=~/^\Q$delthis\E/) {
727: delete($env{$key});
728: delete($disk_env{$key});
729: }
730: }
731: }
732: untie(%disk_env);
733: }
734: return 'ok';
735: }
736:
737: sub get_env_multiple {
738: my ($name) = @_;
739: my @values;
740: if (defined($env{$name})) {
741: # exists is it an array
742: if (ref($env{$name})) {
743: @values=@{ $env{$name} };
744: } else {
745: $values[0]=$env{$name};
746: }
747: }
748: return(@values);
749: }
750:
751: # ------------------------------------------------------------------- Locking
752:
753: sub set_lock {
754: my ($text)=@_;
755: $locknum++;
756: my $id=$$.'-'.$locknum;
757: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
758: 'session.lock.'.$id => $text});
759: return $id;
760: }
761:
762: sub get_locks {
763: my $num=0;
764: my %texts=();
765: foreach my $lock (split(/\,/,$env{'session.locks'})) {
766: if ($lock=~/\w/) {
767: $num++;
768: $texts{$lock}=$env{'session.lock.'.$lock};
769: }
770: }
771: return ($num,%texts);
772: }
773:
774: sub remove_lock {
775: my ($id)=@_;
776: my $newlocks='';
777: foreach my $lock (split(/\,/,$env{'session.locks'})) {
778: if (($lock=~/\w/) && ($lock ne $id)) {
779: $newlocks.=','.$lock;
780: }
781: }
782: &appenv({'session.locks' => $newlocks});
783: &delenv('session.lock.'.$id);
784: }
785:
786: sub remove_all_locks {
787: my $activelocks=$env{'session.locks'};
788: foreach my $lock (split(/\,/,$env{'session.locks'})) {
789: if ($lock=~/\w/) {
790: &remove_lock($lock);
791: }
792: }
793: }
794:
795:
796: # ------------------------------------------ Find out current server userload
797: sub userload {
798: my $numusers=0;
799: {
800: opendir(LONIDS,$perlvar{'lonIDsDir'});
801: my $filename;
802: my $curtime=time;
803: while ($filename=readdir(LONIDS)) {
804: next if ($filename eq '.' || $filename eq '..');
805: next if ($filename =~ /publicuser_\d+\.id/);
806: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
807: if ($curtime-$mtime < 1800) { $numusers++; }
808: }
809: closedir(LONIDS);
810: }
811: my $userloadpercent=0;
812: my $maxuserload=$perlvar{'lonUserLoadLim'};
813: if ($maxuserload) {
814: $userloadpercent=100*$numusers/$maxuserload;
815: }
816: $userloadpercent=sprintf("%.2f",$userloadpercent);
817: return $userloadpercent;
818: }
819:
820: # ------------------------------ Find server with least workload from spare.tab
821:
822: sub spareserver {
823: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
824: my $spare_server;
825: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
826: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
827: : $userloadpercent;
828: my ($uint_dom,$remotesessions);
829: if (($udom ne '') && (&domain($udom) ne '')) {
830: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
831: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
832: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
833: $remotesessions = $udomdefaults{'remotesessions'};
834: }
835: my $spareshash = &this_host_spares($udom);
836: if (ref($spareshash) eq 'HASH') {
837: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
838: foreach my $try_server (@{ $spareshash->{'primary'} }) {
839: if ($uint_dom) {
840: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
841: $try_server));
842: }
843: ($spare_server, $lowest_load) =
844: &compare_server_load($try_server, $spare_server, $lowest_load);
845: }
846: }
847:
848: my $found_server = ($spare_server ne '' && $lowest_load < 100);
849:
850: if (!$found_server) {
851: if (ref($spareshash->{'default'}) eq 'ARRAY') {
852: foreach my $try_server (@{ $spareshash->{'default'} }) {
853: if ($uint_dom) {
854: next unless (&spare_can_host($udom,$uint_dom,
855: $remotesessions,$try_server));
856: }
857: ($spare_server, $lowest_load) =
858: &compare_server_load($try_server, $spare_server, $lowest_load);
859: }
860: }
861: }
862: }
863:
864: if (!$want_server_name) {
865: my $protocol = 'http';
866: if ($protocol{$spare_server} eq 'https') {
867: $protocol = $protocol{$spare_server};
868: }
869: if (defined($spare_server)) {
870: my $hostname = &hostname($spare_server);
871: if (defined($hostname)) {
872: $spare_server = $protocol.'://'.$hostname;
873: }
874: }
875: }
876: return $spare_server;
877: }
878:
879: sub compare_server_load {
880: my ($try_server, $spare_server, $lowest_load) = @_;
881:
882: my $loadans = &reply('load', $try_server);
883: my $userloadans = &reply('userload',$try_server);
884:
885: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
886: return ($spare_server, $lowest_load); #didn't get a number from the server
887: }
888:
889: my $load;
890: if ($loadans =~ /\d/) {
891: if ($userloadans =~ /\d/) {
892: #both are numbers, pick the bigger one
893: $load = ($loadans > $userloadans) ? $loadans
894: : $userloadans;
895: } else {
896: $load = $loadans;
897: }
898: } else {
899: $load = $userloadans;
900: }
901:
902: if (($load =~ /\d/) && ($load < $lowest_load)) {
903: $spare_server = $try_server;
904: $lowest_load = $load;
905: }
906: return ($spare_server,$lowest_load);
907: }
908:
909: # --------------------------- ask offload servers if user already has a session
910: sub find_existing_session {
911: my ($udom,$uname) = @_;
912: my $spareshash = &this_host_spares($udom);
913: if (ref($spareshash) eq 'HASH') {
914: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
915: foreach my $try_server (@{ $spareshash->{'primary'} }) {
916: return $try_server if (&has_user_session($try_server, $udom, $uname));
917: }
918: }
919: if (ref($spareshash->{'default'}) eq 'ARRAY') {
920: foreach my $try_server (@{ $spareshash->{'default'} }) {
921: return $try_server if (&has_user_session($try_server, $udom, $uname));
922: }
923: }
924: }
925: return;
926: }
927:
928: # -------------------------------- ask if server already has a session for user
929: sub has_user_session {
930: my ($lonid,$udom,$uname) = @_;
931: my $result = &reply(join(':','userhassession',
932: map {&escape($_)} ($udom,$uname)),$lonid);
933: return 1 if ($result eq 'ok');
934:
935: return 0;
936: }
937:
938: # --------- determine least loaded server in a user's domain which allows login
939:
940: sub choose_server {
941: my ($udom,$checkloginvia) = @_;
942: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
943: my %servers = &get_servers($udom);
944: my $lowest_load = 30000;
945: my ($login_host,$hostname,$portal_path,$isredirect);
946: foreach my $lonhost (keys(%servers)) {
947: my $loginvia;
948: if ($checkloginvia) {
949: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
950: if ($loginvia) {
951: my ($server,$path) = split(/:/,$loginvia);
952: ($login_host, $lowest_load) =
953: &compare_server_load($server, $login_host, $lowest_load);
954: if ($login_host eq $server) {
955: $portal_path = $path;
956: $isredirect = 1;
957: }
958: } else {
959: ($login_host, $lowest_load) =
960: &compare_server_load($lonhost, $login_host, $lowest_load);
961: if ($login_host eq $lonhost) {
962: $portal_path = '';
963: $isredirect = '';
964: }
965: }
966: } else {
967: ($login_host, $lowest_load) =
968: &compare_server_load($lonhost, $login_host, $lowest_load);
969: }
970: }
971: if ($login_host ne '') {
972: $hostname = &hostname($login_host);
973: }
974: return ($login_host,$hostname,$portal_path,$isredirect);
975: }
976:
977: # --------------------------------------------- Try to change a user's password
978:
979: sub changepass {
980: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
981: $currentpass = &escape($currentpass);
982: $newpass = &escape($newpass);
983: my $lonhost = $perlvar{'lonHostID'};
984: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
985: $server);
986: if (! $answer) {
987: &logthis("No reply on password change request to $server ".
988: "by $uname in domain $udom.");
989: } elsif ($answer =~ "^ok") {
990: &logthis("$uname in $udom successfully changed their password ".
991: "on $server.");
992: } elsif ($answer =~ "^pwchange_failure") {
993: &logthis("$uname in $udom was unable to change their password ".
994: "on $server. The action was blocked by either lcpasswd ".
995: "or pwchange");
996: } elsif ($answer =~ "^non_authorized") {
997: &logthis("$uname in $udom did not get their password correct when ".
998: "attempting to change it on $server.");
999: } elsif ($answer =~ "^auth_mode_error") {
1000: &logthis("$uname in $udom attempted to change their password despite ".
1001: "not being locally or internally authenticated on $server.");
1002: } elsif ($answer =~ "^unknown_user") {
1003: &logthis("$uname in $udom attempted to change their password ".
1004: "on $server but were unable to because $server is not ".
1005: "their home server.");
1006: } elsif ($answer =~ "^refused") {
1007: &logthis("$server refused to change $uname in $udom password because ".
1008: "it was sent an unencrypted request to change the password.");
1009: } elsif ($answer =~ "invalid_client") {
1010: &logthis("$server refused to change $uname in $udom password because ".
1011: "it was a reset by e-mail originating from an invalid server.");
1012: }
1013: return $answer;
1014: }
1015:
1016: # ----------------------- Try to determine user's current authentication scheme
1017:
1018: sub queryauthenticate {
1019: my ($uname,$udom)=@_;
1020: my $uhome=&homeserver($uname,$udom);
1021: if (!$uhome) {
1022: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1023: return 'no_host';
1024: }
1025: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1026: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1027: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1028: }
1029: return $answer;
1030: }
1031:
1032: # --------- Try to authenticate user from domain's lib servers (first this one)
1033:
1034: sub authenticate {
1035: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1036: $upass=&escape($upass);
1037: $uname= &LONCAPA::clean_username($uname);
1038: my $uhome=&homeserver($uname,$udom,1);
1039: my $newhome;
1040: if ((!$uhome) || ($uhome eq 'no_host')) {
1041: # Maybe the machine was offline and only re-appeared again recently?
1042: &reconlonc();
1043: # One more
1044: $uhome=&homeserver($uname,$udom,1);
1045: if (($uhome eq 'no_host') && $checkdefauth) {
1046: if (defined(&domain($udom,'primary'))) {
1047: $newhome=&domain($udom,'primary');
1048: }
1049: if ($newhome ne '') {
1050: $uhome = $newhome;
1051: }
1052: }
1053: if ((!$uhome) || ($uhome eq 'no_host')) {
1054: &logthis("User $uname at $udom is unknown in authenticate");
1055: return 'no_host';
1056: }
1057: }
1058: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1059: if ($answer eq 'authorized') {
1060: if ($newhome) {
1061: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1062: return 'no_account_on_host';
1063: } else {
1064: &logthis("User $uname at $udom authorized by $uhome");
1065: return $uhome;
1066: }
1067: }
1068: if ($answer eq 'non_authorized') {
1069: &logthis("User $uname at $udom rejected by $uhome");
1070: return 'no_host';
1071: }
1072: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1073: return 'no_host';
1074: }
1075:
1076: sub can_host_session {
1077: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1078: my $canhost = 1;
1079: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1080: if (ref($remotesessions) eq 'HASH') {
1081: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1082: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1083: $canhost = 0;
1084: } else {
1085: $canhost = 1;
1086: }
1087: }
1088: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1089: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1090: $canhost = 1;
1091: } else {
1092: $canhost = 0;
1093: }
1094: }
1095: if ($canhost) {
1096: if ($remotesessions->{'version'} ne '') {
1097: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1098: if ($reqmajor ne '' && $reqminor ne '') {
1099: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1100: my $major = $1;
1101: my $minor = $2;
1102: if (($major < $reqmajor ) ||
1103: (($major == $reqmajor) && ($minor < $reqminor))) {
1104: $canhost = 0;
1105: }
1106: } else {
1107: $canhost = 0;
1108: }
1109: }
1110: }
1111: }
1112: }
1113: if ($canhost) {
1114: if (ref($hostedsessions) eq 'HASH') {
1115: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1116: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1117: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1118: if (($uint_dom ne '') &&
1119: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1120: $canhost = 0;
1121: } else {
1122: $canhost = 1;
1123: }
1124: }
1125: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1126: if (($uint_dom ne '') &&
1127: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1128: $canhost = 1;
1129: } else {
1130: $canhost = 0;
1131: }
1132: }
1133: }
1134: }
1135: return $canhost;
1136: }
1137:
1138: sub spare_can_host {
1139: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1140: my $canhost=1;
1141: my @intdoms;
1142: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1143: if (ref($internet_names) eq 'ARRAY') {
1144: @intdoms = @{$internet_names};
1145: }
1146: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1147: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1148: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1149: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1150: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1151: $canhost = &can_host_session($udom,$try_server,$remoterev,
1152: $remotesessions,
1153: $defdomdefaults{'hostedsessions'});
1154: }
1155: return $canhost;
1156: }
1157:
1158: sub this_host_spares {
1159: my ($dom) = @_;
1160: my ($dom_in_use,$lonhost_in_use,$result);
1161: my @hosts = ¤t_machine_ids();
1162: foreach my $lonhost (@hosts) {
1163: if (&host_domain($lonhost) eq $dom) {
1164: $dom_in_use = $dom;
1165: $lonhost_in_use = $lonhost;
1166: last;
1167: }
1168: }
1169: if ($dom_in_use ne '') {
1170: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1171: }
1172: if (ref($result) ne 'HASH') {
1173: $lonhost_in_use = $perlvar{'lonHostID'};
1174: $dom_in_use = &host_domain($lonhost_in_use);
1175: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1176: if (ref($result) ne 'HASH') {
1177: $result = \%spareid;
1178: }
1179: }
1180: return $result;
1181: }
1182:
1183: sub spares_for_offload {
1184: my ($dom_in_use,$lonhost_in_use) = @_;
1185: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1186: if (defined($cached)) {
1187: return $result;
1188: } else {
1189: my $cachetime = 60*60*24;
1190: my %domconfig =
1191: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1192: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1193: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1194: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1195: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1196: }
1197: }
1198: }
1199: }
1200: return;
1201: }
1202:
1203: sub get_lonbalancer_config {
1204: my ($servers) = @_;
1205: my ($currbalancer,$currtargets);
1206: if (ref($servers) eq 'HASH') {
1207: foreach my $server (keys(%{$servers})) {
1208: my %what = (
1209: spareid => 1,
1210: perlvar => 1,
1211: );
1212: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1213: if ($result eq 'ok') {
1214: if (ref($returnhash) eq 'HASH') {
1215: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1216: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1217: $currbalancer = $server;
1218: $currtargets = {};
1219: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1220: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1221: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1222: }
1223: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1224: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1225: }
1226: }
1227: last;
1228: }
1229: }
1230: }
1231: }
1232: }
1233: }
1234: return ($currbalancer,$currtargets);
1235: }
1236:
1237: sub check_loadbalancing {
1238: my ($uname,$udom) = @_;
1239: my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
1240: $offloadto,$otherserver);
1241: my $lonhost = $perlvar{'lonHostID'};
1242: my @hosts = ¤t_machine_ids();
1243: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1244: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1245: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1246: my $serverhomedom = &host_domain($lonhost);
1247:
1248: my $cachetime = 60*60*24;
1249:
1250: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1251: $dom_in_use = $udom;
1252: $homeintdom = 1;
1253: } else {
1254: $dom_in_use = $serverhomedom;
1255: }
1256: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1257: unless (defined($cached)) {
1258: my %domconfig =
1259: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1260: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1261: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1262: }
1263: }
1264: if (ref($result) eq 'HASH') {
1265: my $currbalancer = $result->{'lonhost'};
1266: my $currtargets = $result->{'targets'};
1267: my $currrules = $result->{'rules'};
1268: if ($currbalancer ne '') {
1269: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1270: $is_balancer = 1;
1271: }
1272: }
1273: if ($is_balancer) {
1274: if (ref($currrules) eq 'HASH') {
1275: if ($homeintdom) {
1276: if ($uname ne '') {
1277: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1278: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1279: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1280: $rule_in_effect = $currrules->{'_LC_author'};
1281: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1282: $rule_in_effect = $currrules->{'_LC_adv'}
1283: }
1284: }
1285: if ($rule_in_effect eq '') {
1286: my %userenv = &userenvironment($udom,$uname,'inststatus');
1287: if ($userenv{'inststatus'} ne '') {
1288: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1289: my ($othertitle,$usertypes,$types) =
1290: &Apache::loncommon::sorted_inst_types($udom);
1291: if (ref($types) eq 'ARRAY') {
1292: foreach my $type (@{$types}) {
1293: if (grep(/^\Q$type\E$/,@statuses)) {
1294: if (exists($currrules->{$type})) {
1295: $rule_in_effect = $currrules->{$type};
1296: }
1297: }
1298: }
1299: }
1300: } else {
1301: if (exists($currrules->{'default'})) {
1302: $rule_in_effect = $currrules->{'default'};
1303: }
1304: }
1305: }
1306: } else {
1307: if (exists($currrules->{'default'})) {
1308: $rule_in_effect = $currrules->{'default'};
1309: }
1310: }
1311: } else {
1312: if ($currrules->{'_LC_external'} ne '') {
1313: $rule_in_effect = $currrules->{'_LC_external'};
1314: }
1315: }
1316: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1317: $uname,$udom);
1318: }
1319: }
1320: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1321: my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1322: unless (defined($cached)) {
1323: my %domconfig =
1324: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1325: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1326: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1327: }
1328: }
1329: if (ref($result) eq 'HASH') {
1330: my $currbalancer = $result->{'lonhost'};
1331: my $currtargets = $result->{'targets'};
1332: my $currrules = $result->{'rules'};
1333:
1334: if ($currbalancer eq $lonhost) {
1335: $is_balancer = 1;
1336: if (ref($currrules) eq 'HASH') {
1337: if ($currrules->{'_LC_internetdom'} ne '') {
1338: $rule_in_effect = $currrules->{'_LC_internetdom'};
1339: }
1340: }
1341: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1342: $uname,$udom);
1343: }
1344: } else {
1345: if ($perlvar{'lonBalancer'} eq 'yes') {
1346: $is_balancer = 1;
1347: $offloadto = &this_host_spares($dom_in_use);
1348: }
1349: }
1350: } else {
1351: if ($perlvar{'lonBalancer'} eq 'yes') {
1352: $is_balancer = 1;
1353: $offloadto = &this_host_spares($dom_in_use);
1354: }
1355: }
1356: my $lowest_load = 30000;
1357: if (ref($offloadto) eq 'HASH') {
1358: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1359: foreach my $try_server (@{$offloadto->{'primary'}}) {
1360: ($otherserver,$lowest_load) =
1361: &compare_server_load($try_server,$otherserver,$lowest_load);
1362: }
1363: }
1364: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1365:
1366: if (!$found_server) {
1367: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1368: foreach my $try_server (@{$offloadto->{'default'}}) {
1369: ($otherserver,$lowest_load) =
1370: &compare_server_load($try_server,$otherserver,$lowest_load);
1371: }
1372: }
1373: }
1374: } elsif (ref($offloadto) eq 'ARRAY') {
1375: if (@{$offloadto} == 1) {
1376: $otherserver = $offloadto->[0];
1377: } elsif (@{$offloadto} > 1) {
1378: foreach my $try_server (@{$offloadto}) {
1379: ($otherserver,$lowest_load) =
1380: &compare_server_load($try_server,$otherserver,$lowest_load);
1381: }
1382: }
1383: }
1384: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1385: $is_balancer = 0;
1386: }
1387: return ($is_balancer,$otherserver);
1388: }
1389:
1390: sub get_loadbalancer_targets {
1391: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1392: my $offloadto;
1393: if ($rule_in_effect eq 'none') {
1394: return [$perlvar{'lonHostID'}];
1395: } elsif ($rule_in_effect eq '') {
1396: $offloadto = $currtargets;
1397: } else {
1398: if ($rule_in_effect eq 'homeserver') {
1399: my $homeserver = &homeserver($uname,$udom);
1400: if ($homeserver ne 'no_host') {
1401: $offloadto = [$homeserver];
1402: }
1403: } elsif ($rule_in_effect eq 'externalbalancer') {
1404: my %domconfig =
1405: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1406: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1407: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1408: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1409: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1410: }
1411: }
1412: } else {
1413: my %servers = &dom_servers($udom);
1414: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1415: if (&hostname($remotebalancer) ne '') {
1416: $offloadto = [$remotebalancer];
1417: }
1418: }
1419: } elsif (&hostname($rule_in_effect) ne '') {
1420: $offloadto = [$rule_in_effect];
1421: }
1422: }
1423: return $offloadto;
1424: }
1425:
1426: sub internet_dom_servers {
1427: my ($dom) = @_;
1428: my (%uniqservers,%servers);
1429: my $primaryserver = &hostname(&domain($dom,'primary'));
1430: my @machinedoms = &machine_domains($primaryserver);
1431: foreach my $mdom (@machinedoms) {
1432: my %currservers = %servers;
1433: my %server = &get_servers($mdom);
1434: %servers = (%currservers,%server);
1435: }
1436: my %by_hostname;
1437: foreach my $id (keys(%servers)) {
1438: push(@{$by_hostname{$servers{$id}}},$id);
1439: }
1440: foreach my $hostname (sort(keys(%by_hostname))) {
1441: if (@{$by_hostname{$hostname}} > 1) {
1442: my $match = 0;
1443: foreach my $id (@{$by_hostname{$hostname}}) {
1444: if (&host_domain($id) eq $dom) {
1445: $uniqservers{$id} = $hostname;
1446: $match = 1;
1447: }
1448: }
1449: unless ($match) {
1450: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1451: }
1452: } else {
1453: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1454: }
1455: }
1456: return %uniqservers;
1457: }
1458:
1459: # ---------------------- Find the homebase for a user from domain's lib servers
1460:
1461: my %homecache;
1462: sub homeserver {
1463: my ($uname,$udom,$ignoreBadCache)=@_;
1464: my $index="$uname:$udom";
1465:
1466: if (exists($homecache{$index})) { return $homecache{$index}; }
1467:
1468: my %servers = &get_servers($udom,'library');
1469: foreach my $tryserver (keys(%servers)) {
1470: next if ($ignoreBadCache ne 'true' &&
1471: exists($badServerCache{$tryserver}));
1472:
1473: my $answer=reply("home:$udom:$uname",$tryserver);
1474: if ($answer eq 'found') {
1475: delete($badServerCache{$tryserver});
1476: return $homecache{$index}=$tryserver;
1477: } elsif ($answer eq 'no_host') {
1478: $badServerCache{$tryserver}=1;
1479: }
1480: }
1481: return 'no_host';
1482: }
1483:
1484: # ------------------------------------- Find the usernames behind a list of IDs
1485:
1486: sub idget {
1487: my ($udom,@ids)=@_;
1488: my %returnhash=();
1489:
1490: my %servers = &get_servers($udom,'library');
1491: foreach my $tryserver (keys(%servers)) {
1492: my $idlist=join('&',@ids);
1493: $idlist=~tr/A-Z/a-z/;
1494: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1495: my @answer=();
1496: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1497: @answer=split(/\&/,$reply);
1498: } ;
1499: my $i;
1500: for ($i=0;$i<=$#ids;$i++) {
1501: if ($answer[$i]) {
1502: $returnhash{$ids[$i]}=$answer[$i];
1503: }
1504: }
1505: }
1506: return %returnhash;
1507: }
1508:
1509: # ------------------------------------- Find the IDs behind a list of usernames
1510:
1511: sub idrget {
1512: my ($udom,@unames)=@_;
1513: my %returnhash=();
1514: foreach my $uname (@unames) {
1515: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1516: }
1517: return %returnhash;
1518: }
1519:
1520: # ------------------------------- Store away a list of names and associated IDs
1521:
1522: sub idput {
1523: my ($udom,%ids)=@_;
1524: my %servers=();
1525: foreach my $uname (keys(%ids)) {
1526: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1527: my $uhom=&homeserver($uname,$udom);
1528: if ($uhom ne 'no_host') {
1529: my $id=&escape($ids{$uname});
1530: $id=~tr/A-Z/a-z/;
1531: my $esc_unam=&escape($uname);
1532: if ($servers{$uhom}) {
1533: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1534: } else {
1535: $servers{$uhom}=$id.'='.$esc_unam;
1536: }
1537: }
1538: }
1539: foreach my $server (keys(%servers)) {
1540: &critical('idput:'.$udom.':'.$servers{$server},$server);
1541: }
1542: }
1543:
1544: # ------------------------------dump from db file owned by domainconfig user
1545: sub dump_dom {
1546: my ($namespace, $udom, $regexp) = @_;
1547:
1548: $udom ||= $env{'user.domain'};
1549:
1550: return () unless $udom;
1551:
1552: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1553: }
1554:
1555: # ------------------------------------------ get items from domain db files
1556:
1557: sub get_dom {
1558: my ($namespace,$storearr,$udom,$uhome)=@_;
1559: my $items='';
1560: foreach my $item (@$storearr) {
1561: $items.=&escape($item).'&';
1562: }
1563: $items=~s/\&$//;
1564: if (!$udom) {
1565: $udom=$env{'user.domain'};
1566: if (defined(&domain($udom,'primary'))) {
1567: $uhome=&domain($udom,'primary');
1568: } else {
1569: undef($uhome);
1570: }
1571: } else {
1572: if (!$uhome) {
1573: if (defined(&domain($udom,'primary'))) {
1574: $uhome=&domain($udom,'primary');
1575: }
1576: }
1577: }
1578: if ($udom && $uhome && ($uhome ne 'no_host')) {
1579: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1580: my %returnhash;
1581: if ($rep eq '' || $rep =~ /^error: 2 /) {
1582: return %returnhash;
1583: }
1584: my @pairs=split(/\&/,$rep);
1585: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1586: return @pairs;
1587: }
1588: my $i=0;
1589: foreach my $item (@$storearr) {
1590: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1591: $i++;
1592: }
1593: return %returnhash;
1594: } else {
1595: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1596: }
1597: }
1598:
1599: # -------------------------------------------- put items in domain db files
1600:
1601: sub put_dom {
1602: my ($namespace,$storehash,$udom,$uhome)=@_;
1603: if (!$udom) {
1604: $udom=$env{'user.domain'};
1605: if (defined(&domain($udom,'primary'))) {
1606: $uhome=&domain($udom,'primary');
1607: } else {
1608: undef($uhome);
1609: }
1610: } else {
1611: if (!$uhome) {
1612: if (defined(&domain($udom,'primary'))) {
1613: $uhome=&domain($udom,'primary');
1614: }
1615: }
1616: }
1617: if ($udom && $uhome && ($uhome ne 'no_host')) {
1618: my $items='';
1619: foreach my $item (keys(%$storehash)) {
1620: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1621: }
1622: $items=~s/\&$//;
1623: return &reply("putdom:$udom:$namespace:$items",$uhome);
1624: } else {
1625: &logthis("put_dom failed - no homeserver and/or domain");
1626: }
1627: }
1628:
1629: # --------------------- newput for items in db file owned by domainconfig user
1630: sub newput_dom {
1631: my ($namespace,$storehash,$udom) = @_;
1632: my $result;
1633: if (!$udom) {
1634: $udom=$env{'user.domain'};
1635: }
1636: if ($udom) {
1637: my $uname = &get_domainconfiguser($udom);
1638: $result = &newput($namespace,$storehash,$udom,$uname);
1639: }
1640: return $result;
1641: }
1642:
1643: # --------------------- delete for items in db file owned by domainconfig user
1644: sub del_dom {
1645: my ($namespace,$storearr,$udom)=@_;
1646: if (ref($storearr) eq 'ARRAY') {
1647: if (!$udom) {
1648: $udom=$env{'user.domain'};
1649: }
1650: if ($udom) {
1651: my $uname = &get_domainconfiguser($udom);
1652: return &del($namespace,$storearr,$udom,$uname);
1653: }
1654: }
1655: }
1656:
1657: # ----------------------------------construct domainconfig user for a domain
1658: sub get_domainconfiguser {
1659: my ($udom) = @_;
1660: return $udom.'-domainconfig';
1661: }
1662:
1663: sub retrieve_inst_usertypes {
1664: my ($udom) = @_;
1665: my (%returnhash,@order);
1666: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1667: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1668: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1669: %returnhash = %{$domdefs{'inststatustypes'}};
1670: @order = @{$domdefs{'inststatusorder'}};
1671: } else {
1672: if (defined(&domain($udom,'primary'))) {
1673: my $uhome=&domain($udom,'primary');
1674: my $rep=&reply("inst_usertypes:$udom",$uhome);
1675: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1676: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1677: return (\%returnhash,\@order);
1678: }
1679: my ($hashitems,$orderitems) = split(/:/,$rep);
1680: my @pairs=split(/\&/,$hashitems);
1681: foreach my $item (@pairs) {
1682: my ($key,$value)=split(/=/,$item,2);
1683: $key = &unescape($key);
1684: next if ($key =~ /^error: 2 /);
1685: $returnhash{$key}=&thaw_unescape($value);
1686: }
1687: my @esc_order = split(/\&/,$orderitems);
1688: foreach my $item (@esc_order) {
1689: push(@order,&unescape($item));
1690: }
1691: } else {
1692: &logthis("get_dom failed - no primary domain server for $udom");
1693: }
1694: }
1695: return (\%returnhash,\@order);
1696: }
1697:
1698: sub is_domainimage {
1699: my ($url) = @_;
1700: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1701: if (&domain($1) ne '') {
1702: return '1';
1703: }
1704: }
1705: return;
1706: }
1707:
1708: sub inst_directory_query {
1709: my ($srch) = @_;
1710: my $udom = $srch->{'srchdomain'};
1711: my %results;
1712: my $homeserver = &domain($udom,'primary');
1713: my $outcome;
1714: if ($homeserver ne '') {
1715: my $queryid=&reply("querysend:instdirsearch:".
1716: &escape($srch->{'srchby'}).':'.
1717: &escape($srch->{'srchterm'}).':'.
1718: &escape($srch->{'srchtype'}),$homeserver);
1719: my $host=&hostname($homeserver);
1720: if ($queryid !~/^\Q$host\E\_/) {
1721: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1722: return;
1723: }
1724: my $response = &get_query_reply($queryid);
1725: my $maxtries = 5;
1726: my $tries = 1;
1727: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1728: $response = &get_query_reply($queryid);
1729: $tries ++;
1730: }
1731:
1732: if (!&error($response) && $response ne 'refused') {
1733: if ($response eq 'unavailable') {
1734: $outcome = $response;
1735: } else {
1736: $outcome = 'ok';
1737: my @matches = split(/\n/,$response);
1738: foreach my $match (@matches) {
1739: my ($key,$value) = split(/=/,$match);
1740: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1741: }
1742: }
1743: }
1744: }
1745: return ($outcome,%results);
1746: }
1747:
1748: sub usersearch {
1749: my ($srch) = @_;
1750: my $dom = $srch->{'srchdomain'};
1751: my %results;
1752: my %libserv = &all_library();
1753: my $query = 'usersearch';
1754: foreach my $tryserver (keys(%libserv)) {
1755: if (&host_domain($tryserver) eq $dom) {
1756: my $host=&hostname($tryserver);
1757: my $queryid=
1758: &reply("querysend:".&escape($query).':'.
1759: &escape($srch->{'srchby'}).':'.
1760: &escape($srch->{'srchtype'}).':'.
1761: &escape($srch->{'srchterm'}),$tryserver);
1762: if ($queryid !~/^\Q$host\E\_/) {
1763: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1764: next;
1765: }
1766: my $reply = &get_query_reply($queryid);
1767: my $maxtries = 1;
1768: my $tries = 1;
1769: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1770: $reply = &get_query_reply($queryid);
1771: $tries ++;
1772: }
1773: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1774: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1775: } else {
1776: my @matches;
1777: if ($reply =~ /\n/) {
1778: @matches = split(/\n/,$reply);
1779: } else {
1780: @matches = split(/\&/,$reply);
1781: }
1782: foreach my $match (@matches) {
1783: my ($uname,$udom,%userhash);
1784: foreach my $entry (split(/:/,$match)) {
1785: my ($key,$value) =
1786: map {&unescape($_);} split(/=/,$entry);
1787: $userhash{$key} = $value;
1788: if ($key eq 'username') {
1789: $uname = $value;
1790: } elsif ($key eq 'domain') {
1791: $udom = $value;
1792: }
1793: }
1794: $results{$uname.':'.$udom} = \%userhash;
1795: }
1796: }
1797: }
1798: }
1799: return %results;
1800: }
1801:
1802: sub get_instuser {
1803: my ($udom,$uname,$id) = @_;
1804: my $homeserver = &domain($udom,'primary');
1805: my ($outcome,%results);
1806: if ($homeserver ne '') {
1807: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1808: &escape($id).':'.&escape($udom),$homeserver);
1809: my $host=&hostname($homeserver);
1810: if ($queryid !~/^\Q$host\E\_/) {
1811: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1812: return;
1813: }
1814: my $response = &get_query_reply($queryid);
1815: my $maxtries = 5;
1816: my $tries = 1;
1817: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1818: $response = &get_query_reply($queryid);
1819: $tries ++;
1820: }
1821: if (!&error($response) && $response ne 'refused') {
1822: if ($response eq 'unavailable') {
1823: $outcome = $response;
1824: } else {
1825: $outcome = 'ok';
1826: my @matches = split(/\n/,$response);
1827: foreach my $match (@matches) {
1828: my ($key,$value) = split(/=/,$match);
1829: $results{&unescape($key)} = &thaw_unescape($value);
1830: }
1831: }
1832: }
1833: }
1834: my %userinfo;
1835: if (ref($results{$uname}) eq 'HASH') {
1836: %userinfo = %{$results{$uname}};
1837: }
1838: return ($outcome,%userinfo);
1839: }
1840:
1841: sub inst_rulecheck {
1842: my ($udom,$uname,$id,$item,$rules) = @_;
1843: my %returnhash;
1844: if ($udom ne '') {
1845: if (ref($rules) eq 'ARRAY') {
1846: @{$rules} = map {&escape($_);} (@{$rules});
1847: my $rulestr = join(':',@{$rules});
1848: my $homeserver=&domain($udom,'primary');
1849: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1850: my $response;
1851: if ($item eq 'username') {
1852: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1853: ':'.&escape($uname).':'.$rulestr,
1854: $homeserver));
1855: } elsif ($item eq 'id') {
1856: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1857: ':'.&escape($id).':'.$rulestr,
1858: $homeserver));
1859: } elsif ($item eq 'selfcreate') {
1860: $response=&unescape(&reply('instselfcreatecheck:'.
1861: &escape($udom).':'.&escape($uname).
1862: ':'.$rulestr,$homeserver));
1863: }
1864: if ($response ne 'refused') {
1865: my @pairs=split(/\&/,$response);
1866: foreach my $item (@pairs) {
1867: my ($key,$value)=split(/=/,$item,2);
1868: $key = &unescape($key);
1869: next if ($key =~ /^error: 2 /);
1870: $returnhash{$key}=&thaw_unescape($value);
1871: }
1872: }
1873: }
1874: }
1875: }
1876: return %returnhash;
1877: }
1878:
1879: sub inst_userrules {
1880: my ($udom,$check) = @_;
1881: my (%ruleshash,@ruleorder);
1882: if ($udom ne '') {
1883: my $homeserver=&domain($udom,'primary');
1884: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1885: my $response;
1886: if ($check eq 'id') {
1887: $response=&reply('instidrules:'.&escape($udom),
1888: $homeserver);
1889: } elsif ($check eq 'email') {
1890: $response=&reply('instemailrules:'.&escape($udom),
1891: $homeserver);
1892: } else {
1893: $response=&reply('instuserrules:'.&escape($udom),
1894: $homeserver);
1895: }
1896: if (($response ne 'refused') && ($response ne 'error') &&
1897: ($response ne 'unknown_cmd') &&
1898: ($response ne 'no_such_host')) {
1899: my ($hashitems,$orderitems) = split(/:/,$response);
1900: my @pairs=split(/\&/,$hashitems);
1901: foreach my $item (@pairs) {
1902: my ($key,$value)=split(/=/,$item,2);
1903: $key = &unescape($key);
1904: next if ($key =~ /^error: 2 /);
1905: $ruleshash{$key}=&thaw_unescape($value);
1906: }
1907: my @esc_order = split(/\&/,$orderitems);
1908: foreach my $item (@esc_order) {
1909: push(@ruleorder,&unescape($item));
1910: }
1911: }
1912: }
1913: }
1914: return (\%ruleshash,\@ruleorder);
1915: }
1916:
1917: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1918:
1919: sub get_domain_defaults {
1920: my ($domain) = @_;
1921: my $cachetime = 60*60*24;
1922: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1923: if (defined($cached)) {
1924: if (ref($result) eq 'HASH') {
1925: return %{$result};
1926: }
1927: }
1928: my %domdefaults;
1929: my %domconfig =
1930: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1931: 'requestcourses','inststatus',
1932: 'coursedefaults','usersessions'],$domain);
1933: if (ref($domconfig{'defaults'}) eq 'HASH') {
1934: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1935: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1936: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1937: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1938: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1939: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1940: } else {
1941: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1942: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1943: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1944: }
1945: if (ref($domconfig{'quotas'}) eq 'HASH') {
1946: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1947: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1948: } else {
1949: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1950: }
1951: my @usertools = ('aboutme','blog','portfolio');
1952: foreach my $item (@usertools) {
1953: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1954: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1955: }
1956: }
1957: }
1958: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1959: foreach my $item ('official','unofficial','community') {
1960: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1961: }
1962: }
1963: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1964: foreach my $item ('inststatustypes','inststatusorder') {
1965: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1966: }
1967: }
1968: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1969: foreach my $item ('canuse_pdfforms') {
1970: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1971: }
1972: }
1973: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1974: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1975: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1976: }
1977: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1978: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1979: }
1980: }
1981: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1982: $cachetime);
1983: return %domdefaults;
1984: }
1985:
1986: # --------------------------------------------------- Assign a key to a student
1987:
1988: sub assign_access_key {
1989: #
1990: # a valid key looks like uname:udom#comments
1991: # comments are being appended
1992: #
1993: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1994: $kdom=
1995: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1996: $knum=
1997: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1998: $cdom=
1999: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2000: $cnum=
2001: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2002: $udom=$env{'user.name'} unless (defined($udom));
2003: $uname=$env{'user.domain'} unless (defined($uname));
2004: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
2005: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
2006: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
2007: # assigned to this person
2008: # - this should not happen,
2009: # unless something went wrong
2010: # the first time around
2011: # ready to assign
2012: $logentry=$1.'; '.$logentry;
2013: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
2014: $kdom,$knum) eq 'ok') {
2015: # key now belongs to user
2016: my $envkey='key.'.$cdom.'_'.$cnum;
2017: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
2018: &appenv({'environment.'.$envkey => $ckey});
2019: return 'ok';
2020: } else {
2021: return
2022: 'error: Count not permanently assign key, will need to be re-entered later.';
2023: }
2024: } else {
2025: return 'error: Could not assign key, try again later.';
2026: }
2027: } elsif (!$existing{$ckey}) {
2028: # the key does not exist
2029: return 'error: The key does not exist';
2030: } else {
2031: # the key is somebody else's
2032: return 'error: The key is already in use';
2033: }
2034: }
2035:
2036: # ------------------------------------------ put an additional comment on a key
2037:
2038: sub comment_access_key {
2039: #
2040: # a valid key looks like uname:udom#comments
2041: # comments are being appended
2042: #
2043: my ($ckey,$cdom,$cnum,$logentry)=@_;
2044: $cdom=
2045: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2046: $cnum=
2047: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2048: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2049: if ($existing{$ckey}) {
2050: $existing{$ckey}.='; '.$logentry;
2051: # ready to assign
2052: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
2053: $cdom,$cnum) eq 'ok') {
2054: return 'ok';
2055: } else {
2056: return 'error: Count not store comment.';
2057: }
2058: } else {
2059: # the key does not exist
2060: return 'error: The key does not exist';
2061: }
2062: }
2063:
2064: # ------------------------------------------------------ Generate a set of keys
2065:
2066: sub generate_access_keys {
2067: my ($number,$cdom,$cnum,$logentry)=@_;
2068: $cdom=
2069: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2070: $cnum=
2071: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2072: unless (&allowed('mky',$cdom)) { return 0; }
2073: unless (($cdom) && ($cnum)) { return 0; }
2074: if ($number>10000) { return 0; }
2075: sleep(2); # make sure don't get same seed twice
2076: srand(time()^($$+($$<<15))); # from "Programming Perl"
2077: my $total=0;
2078: for (my $i=1;$i<=$number;$i++) {
2079: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2080: sprintf("%lx",int(100000*rand)).'-'.
2081: sprintf("%lx",int(100000*rand));
2082: $newkey=~s/1/g/g; # folks mix up 1 and l
2083: $newkey=~s/0/h/g; # and also 0 and O
2084: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2085: if ($existing{$newkey}) {
2086: $i--;
2087: } else {
2088: if (&put('accesskeys',
2089: { $newkey => '# generated '.localtime().
2090: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
2091: '; '.$logentry },
2092: $cdom,$cnum) eq 'ok') {
2093: $total++;
2094: }
2095: }
2096: }
2097: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
2098: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2099: return $total;
2100: }
2101:
2102: # ------------------------------------------------------- Validate an accesskey
2103:
2104: sub validate_access_key {
2105: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2106: $cdom=
2107: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2108: $cnum=
2109: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2110: $udom=$env{'user.domain'} unless (defined($udom));
2111: $uname=$env{'user.name'} unless (defined($uname));
2112: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2113: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
2114: }
2115:
2116: # ------------------------------------- Find the section of student in a course
2117: sub devalidate_getsection_cache {
2118: my ($udom,$unam,$courseid)=@_;
2119: my $hashid="$udom:$unam:$courseid";
2120: &devalidate_cache_new('getsection',$hashid);
2121: }
2122:
2123: sub courseid_to_courseurl {
2124: my ($courseid) = @_;
2125: #already url style courseid
2126: return $courseid if ($courseid =~ m{^/});
2127:
2128: if (exists($env{'course.'.$courseid.'.num'})) {
2129: my $cnum = $env{'course.'.$courseid.'.num'};
2130: my $cdom = $env{'course.'.$courseid.'.domain'};
2131: return "/$cdom/$cnum";
2132: }
2133:
2134: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2135: if (exists($courseinfo{'num'})) {
2136: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2137: }
2138:
2139: return undef;
2140: }
2141:
2142: sub getsection {
2143: my ($udom,$unam,$courseid)=@_;
2144: my $cachetime=1800;
2145:
2146: my $hashid="$udom:$unam:$courseid";
2147: my ($result,$cached)=&is_cached_new('getsection',$hashid);
2148: if (defined($cached)) { return $result; }
2149:
2150: my %Pending;
2151: my %Expired;
2152: #
2153: # Each role can either have not started yet (pending), be active,
2154: # or have expired.
2155: #
2156: # If there is an active role, we are done.
2157: #
2158: # If there is more than one role which has not started yet,
2159: # choose the one which will start sooner
2160: # If there is one role which has not started yet, return it.
2161: #
2162: # If there is more than one expired role, choose the one which ended last.
2163: # If there is a role which has expired, return it.
2164: #
2165: $courseid = &courseid_to_courseurl($courseid);
2166: my %roleshash = &dump('roles',$udom,$unam,$courseid);
2167: foreach my $key (keys(%roleshash)) {
2168: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
2169: my $section=$1;
2170: if ($key eq $courseid.'_st') { $section=''; }
2171: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
2172: my $now=time;
2173: if (defined($end) && $end && ($now > $end)) {
2174: $Expired{$end}=$section;
2175: next;
2176: }
2177: if (defined($start) && $start && ($now < $start)) {
2178: $Pending{$start}=$section;
2179: next;
2180: }
2181: return &do_cache_new('getsection',$hashid,$section,$cachetime);
2182: }
2183: #
2184: # Presumedly there will be few matching roles from the above
2185: # loop and the sorting time will be negligible.
2186: if (scalar(keys(%Pending))) {
2187: my ($time) = sort {$a <=> $b} keys(%Pending);
2188: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
2189: }
2190: if (scalar(keys(%Expired))) {
2191: my @sorted = sort {$a <=> $b} keys(%Expired);
2192: my $time = pop(@sorted);
2193: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
2194: }
2195: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
2196: }
2197:
2198: sub save_cache {
2199: &purge_remembered();
2200: #&Apache::loncommon::validate_page();
2201: undef(%env);
2202: undef($env_loaded);
2203: }
2204:
2205: my $to_remember=-1;
2206: my %remembered;
2207: my %accessed;
2208: my $kicks=0;
2209: my $hits=0;
2210: sub make_key {
2211: my ($name,$id) = @_;
2212: if (length($id) > 65
2213: && length(&escape($id)) > 200) {
2214: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2215: }
2216: return &escape($name.':'.$id);
2217: }
2218:
2219: sub devalidate_cache_new {
2220: my ($name,$id,$debug) = @_;
2221: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
2222: $id=&make_key($name,$id);
2223: $memcache->delete($id);
2224: delete($remembered{$id});
2225: delete($accessed{$id});
2226: }
2227:
2228: sub is_cached_new {
2229: my ($name,$id,$debug) = @_;
2230: $id=&make_key($name,$id);
2231: if (exists($remembered{$id})) {
2232: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
2233: $accessed{$id}=[&gettimeofday()];
2234: $hits++;
2235: return ($remembered{$id},1);
2236: }
2237: my $value = $memcache->get($id);
2238: if (!(defined($value))) {
2239: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
2240: return (undef,undef);
2241: }
2242: if ($value eq '__undef__') {
2243: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2244: $value=undef;
2245: }
2246: &make_room($id,$value,$debug);
2247: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2248: return ($value,1);
2249: }
2250:
2251: sub do_cache_new {
2252: my ($name,$id,$value,$time,$debug) = @_;
2253: $id=&make_key($name,$id);
2254: my $setvalue=$value;
2255: if (!defined($setvalue)) {
2256: $setvalue='__undef__';
2257: }
2258: if (!defined($time) ) {
2259: $time=600;
2260: }
2261: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
2262: my $result = $memcache->set($id,$setvalue,$time);
2263: if (! $result) {
2264: &logthis("caching of id -> $id failed");
2265: $memcache->disconnect_all();
2266: }
2267: # need to make a copy of $value
2268: &make_room($id,$value,$debug);
2269: return $value;
2270: }
2271:
2272: sub make_room {
2273: my ($id,$value,$debug)=@_;
2274:
2275: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2276: : $value;
2277: if ($to_remember<0) { return; }
2278: $accessed{$id}=[&gettimeofday()];
2279: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2280: my $to_kick;
2281: my $max_time=0;
2282: foreach my $other (keys(%accessed)) {
2283: if (&tv_interval($accessed{$other}) > $max_time) {
2284: $to_kick=$other;
2285: $max_time=&tv_interval($accessed{$other});
2286: }
2287: }
2288: delete($remembered{$to_kick});
2289: delete($accessed{$to_kick});
2290: $kicks++;
2291: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
2292: return;
2293: }
2294:
2295: sub purge_remembered {
2296: #&logthis("Tossing ".scalar(keys(%remembered)));
2297: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
2298: undef(%remembered);
2299: undef(%accessed);
2300: }
2301: # ------------------------------------- Read an entry from a user's environment
2302:
2303: sub userenvironment {
2304: my ($udom,$unam,@what)=@_;
2305: my $items;
2306: foreach my $item (@what) {
2307: $items.=&escape($item).'&';
2308: }
2309: $items=~s/\&$//;
2310: my %returnhash=();
2311: my $uhome = &homeserver($unam,$udom);
2312: unless ($uhome eq 'no_host') {
2313: my @answer=split(/\&/,
2314: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
2315: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2316: return %returnhash;
2317: }
2318: my $i;
2319: for ($i=0;$i<=$#what;$i++) {
2320: $returnhash{$what[$i]}=&unescape($answer[$i]);
2321: }
2322: }
2323: return %returnhash;
2324: }
2325:
2326: # ---------------------------------------------------------- Get a studentphoto
2327: sub studentphoto {
2328: my ($udom,$unam,$ext) = @_;
2329: my $home=&Apache::lonnet::homeserver($unam,$udom);
2330: if (defined($env{'request.course.id'})) {
2331: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
2332: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2333: return(&retrievestudentphoto($udom,$unam,$ext));
2334: } else {
2335: my ($result,$perm_reqd)=
2336: &Apache::lonnet::auto_photo_permission($unam,$udom);
2337: if ($result eq 'ok') {
2338: if (!($perm_reqd eq 'yes')) {
2339: return(&retrievestudentphoto($udom,$unam,$ext));
2340: }
2341: }
2342: }
2343: }
2344: } else {
2345: my ($result,$perm_reqd) =
2346: &Apache::lonnet::auto_photo_permission($unam,$udom);
2347: if ($result eq 'ok') {
2348: if (!($perm_reqd eq 'yes')) {
2349: return(&retrievestudentphoto($udom,$unam,$ext));
2350: }
2351: }
2352: }
2353: return '/adm/lonKaputt/lonlogo_broken.gif';
2354: }
2355:
2356: sub retrievestudentphoto {
2357: my ($udom,$unam,$ext,$type) = @_;
2358: my $home=&Apache::lonnet::homeserver($unam,$udom);
2359: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2360: if ($ret eq 'ok') {
2361: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2362: if ($type eq 'thumbnail') {
2363: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2364: }
2365: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2366: return $tokenurl;
2367: } else {
2368: if ($type eq 'thumbnail') {
2369: return '/adm/lonKaputt/genericstudent_tn.gif';
2370: } else {
2371: return '/adm/lonKaputt/lonlogo_broken.gif';
2372: }
2373: }
2374: }
2375:
2376: # -------------------------------------------------------------------- New chat
2377:
2378: sub chatsend {
2379: my ($newentry,$anon,$group)=@_;
2380: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2381: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2382: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
2383: &reply('chatsend:'.$cdom.':'.$cnum.':'.
2384: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
2385: &escape($newentry)).':'.$group,$chome);
2386: }
2387:
2388: # ------------------------------------------ Find current version of a resource
2389:
2390: sub getversion {
2391: my $fname=&clutter(shift);
2392: unless ($fname=~/^\/res\//) { return -1; }
2393: return ¤tversion(&filelocation('',$fname));
2394: }
2395:
2396: sub currentversion {
2397: my $fname=shift;
2398: my $author=$fname;
2399: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2400: my ($udom,$uname)=split(/\//,$author);
2401: my $home=&homeserver($uname,$udom);
2402: if ($home eq 'no_host') {
2403: return -1;
2404: }
2405: my $answer=&reply("currentversion:$fname",$home);
2406: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2407: return -1;
2408: }
2409: return $answer;
2410: }
2411:
2412: #
2413: # Return special version number of resource if set by override, empty otherwise
2414: #
2415: sub usedversion {
2416: my $fname=shift;
2417: unless ($fname) { $fname=$env{'request.uri'}; }
2418: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2419: if ($urlversion) { return $urlversion; }
2420: return '';
2421: }
2422:
2423: # ----------------------------- Subscribe to a resource, return URL if possible
2424:
2425: sub subscribe {
2426: my $fname=shift;
2427: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
2428: $fname=~s/[\n\r]//g;
2429: my $author=$fname;
2430: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2431: my ($udom,$uname)=split(/\//,$author);
2432: my $home=homeserver($uname,$udom);
2433: if ($home eq 'no_host') {
2434: return 'not_found';
2435: }
2436: my $answer=reply("sub:$fname",$home);
2437: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2438: $answer.=' by '.$home;
2439: }
2440: return $answer;
2441: }
2442:
2443: # -------------------------------------------------------------- Replicate file
2444:
2445: sub repcopy {
2446: my $filename=shift;
2447: $filename=~s/\/+/\//g;
2448: my $londocroot = $perlvar{'lonDocRoot'};
2449: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
2450: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
2451: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2452: $filename=~m{^/*(uploaded|editupload)/}) {
2453: return &repcopy_userfile($filename);
2454: }
2455: $filename=~s/[\n\r]//g;
2456: my $transname="$filename.in.transfer";
2457: # FIXME: this should flock
2458: if ((-e $filename) || (-e $transname)) { return 'ok'; }
2459: my $remoteurl=subscribe($filename);
2460: if ($remoteurl =~ /^con_lost by/) {
2461: &logthis("Subscribe returned $remoteurl: $filename");
2462: return 'unavailable';
2463: } elsif ($remoteurl eq 'not_found') {
2464: #&logthis("Subscribe returned not_found: $filename");
2465: return 'not_found';
2466: } elsif ($remoteurl =~ /^rejected by/) {
2467: &logthis("Subscribe returned $remoteurl: $filename");
2468: return 'forbidden';
2469: } elsif ($remoteurl eq 'directory') {
2470: return 'ok';
2471: } else {
2472: my $author=$filename;
2473: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2474: my ($udom,$uname)=split(/\//,$author);
2475: my $home=homeserver($uname,$udom);
2476: unless ($home eq $perlvar{'lonHostID'}) {
2477: my @parts=split(/\//,$filename);
2478: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2479: if ($path ne "$londocroot/res") {
2480: &logthis("Malconfiguration for replication: $filename");
2481: return 'bad_request';
2482: }
2483: my $count;
2484: for ($count=5;$count<$#parts;$count++) {
2485: $path.="/$parts[$count]";
2486: if ((-e $path)!=1) {
2487: mkdir($path,0777);
2488: }
2489: }
2490: my $ua=new LWP::UserAgent;
2491: my $request=new HTTP::Request('GET',"$remoteurl");
2492: my $response=$ua->request($request,$transname);
2493: if ($response->is_error()) {
2494: unlink($transname);
2495: my $message=$response->status_line;
2496: &logthis("<font color=\"blue\">WARNING:"
2497: ." LWP get: $message: $filename</font>");
2498: return 'unavailable';
2499: } else {
2500: if ($remoteurl!~/\.meta$/) {
2501: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2502: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2503: if ($mresponse->is_error()) {
2504: unlink($filename.'.meta');
2505: &logthis(
2506: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
2507: }
2508: }
2509: rename($transname,$filename);
2510: return 'ok';
2511: }
2512: }
2513: }
2514: }
2515:
2516: # ------------------------------------------------ Get server side include body
2517: sub ssi_body {
2518: my ($filelink,%form)=@_;
2519: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2520: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2521: }
2522: my $output='';
2523: my $response;
2524: if ($filelink=~/^https?\:/) {
2525: ($output,$response)=&externalssi($filelink);
2526: } else {
2527: $filelink .= $filelink=~/\?/ ? '&' : '?';
2528: $filelink .= 'inhibitmenu=yes';
2529: ($output,$response)=&ssi($filelink,%form);
2530: }
2531: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
2532: $output=~s/^.*?\<body[^\>]*\>//si;
2533: $output=~s/\<\/body\s*\>.*?$//si;
2534: if (wantarray) {
2535: return ($output, $response);
2536: } else {
2537: return $output;
2538: }
2539: }
2540:
2541: # --------------------------------------------------------- Server Side Include
2542:
2543: sub absolute_url {
2544: my ($host_name) = @_;
2545: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2546: if ($host_name eq '') {
2547: $host_name = $ENV{'SERVER_NAME'};
2548: }
2549: return $protocol.$host_name;
2550: }
2551:
2552: #
2553: # Server side include.
2554: # Parameters:
2555: # fn Possibly encrypted resource name/id.
2556: # form Hash that describes how the rendering should be done
2557: # and other things.
2558: # Returns:
2559: # Scalar context: The content of the response.
2560: # Array context: 2 element list of the content and the full response object.
2561: #
2562: sub ssi {
2563:
2564: my ($fn,%form)=@_;
2565: my $ua=new LWP::UserAgent;
2566: my $request;
2567:
2568: $form{'no_update_last_known'}=1;
2569: &Apache::lonenc::check_encrypt(\$fn);
2570: if (%form) {
2571: $request=new HTTP::Request('POST',&absolute_url().$fn);
2572: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
2573: } else {
2574: $request=new HTTP::Request('GET',&absolute_url().$fn);
2575: }
2576:
2577: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2578: my $response= $ua->request($request);
2579: my $content = Encode::decode_utf8($response->content);
2580: if (wantarray) {
2581: return ($content, $response);
2582: } else {
2583: return $content;
2584: }
2585: }
2586:
2587: sub externalssi {
2588: my ($url)=@_;
2589: my $ua=new LWP::UserAgent;
2590: my $request=new HTTP::Request('GET',$url);
2591: my $response=$ua->request($request);
2592: if (wantarray) {
2593: return ($response->content, $response);
2594: } else {
2595: return $response->content;
2596: }
2597: }
2598:
2599: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2600:
2601: sub allowuploaded {
2602: my ($srcurl,$url)=@_;
2603: $url=&clutter(&declutter($url));
2604: my $dir=$url;
2605: $dir=~s/\/[^\/]+$//;
2606: my %httpref=();
2607: my $httpurl=&hreflocation('',$url);
2608: $httpref{'httpref.'.$httpurl}=$srcurl;
2609: &Apache::lonnet::appenv(\%httpref);
2610: }
2611:
2612: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
2613: # input: action, courseID, current domain, intended
2614: # path to file, source of file, instruction to parse file for objects,
2615: # ref to hash for embedded objects,
2616: # ref to hash for codebase of java objects.
2617: # reference to scalar to accommodate mime type determined
2618: # from File::MMagic if $parser = parse.
2619: #
2620: # output: url to file (if action was uploaddoc),
2621: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
2622: #
2623: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2624: # course.
2625: #
2626: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2627: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2628: # course's home server.
2629: #
2630: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2631: # be copied from $source (current location) to
2632: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2633: # and will then be copied to
2634: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2635: # course's home server.
2636: #
2637: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2638: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
2639: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2640: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2641: # in course's home server.
2642: #
2643:
2644: sub process_coursefile {
2645: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2646: $mimetype)=@_;
2647: my $fetchresult;
2648: my $home=&homeserver($docuname,$docudom);
2649: if ($action eq 'propagate') {
2650: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2651: $home);
2652: } else {
2653: my $fpath = '';
2654: my $fname = $file;
2655: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2656: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2657: my $filepath = &build_filepath($fpath);
2658: if ($action eq 'copy') {
2659: if ($source eq '') {
2660: $fetchresult = 'no source file';
2661: return $fetchresult;
2662: } else {
2663: my $destination = $filepath.'/'.$fname;
2664: rename($source,$destination);
2665: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2666: $home);
2667: }
2668: } elsif ($action eq 'uploaddoc') {
2669: open(my $fh,'>'.$filepath.'/'.$fname);
2670: print $fh $env{'form.'.$source};
2671: close($fh);
2672: if ($parser eq 'parse') {
2673: my $mm = new File::MMagic;
2674: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2675: if ($type eq 'text/html') {
2676: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2677: unless ($parse_result eq 'ok') {
2678: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2679: }
2680: }
2681: if (ref($mimetype)) {
2682: $$mimetype = $type;
2683: }
2684: }
2685: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2686: $home);
2687: if ($fetchresult eq 'ok') {
2688: return '/uploaded/'.$fpath.'/'.$fname;
2689: } else {
2690: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2691: ' to host '.$home.': '.$fetchresult);
2692: return '/adm/notfound.html';
2693: }
2694: }
2695: }
2696: unless ( $fetchresult eq 'ok') {
2697: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2698: ' to host '.$home.': '.$fetchresult);
2699: }
2700: return $fetchresult;
2701: }
2702:
2703: sub build_filepath {
2704: my ($fpath) = @_;
2705: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2706: unless ($fpath eq '') {
2707: my @parts=split('/',$fpath);
2708: foreach my $part (@parts) {
2709: $filepath.= '/'.$part;
2710: if ((-e $filepath)!=1) {
2711: mkdir($filepath,0777);
2712: }
2713: }
2714: }
2715: return $filepath;
2716: }
2717:
2718: sub store_edited_file {
2719: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
2720: my $file = $primary_url;
2721: $file =~ s#^/uploaded/$docudom/$docuname/##;
2722: my $fpath = '';
2723: my $fname = $file;
2724: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2725: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2726: my $filepath = &build_filepath($fpath);
2727: open(my $fh,'>'.$filepath.'/'.$fname);
2728: print $fh $content;
2729: close($fh);
2730: my $home=&homeserver($docuname,$docudom);
2731: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2732: $home);
2733: if ($$fetchresult eq 'ok') {
2734: return '/uploaded/'.$fpath.'/'.$fname;
2735: } else {
2736: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2737: ' to host '.$home.': '.$$fetchresult);
2738: return '/adm/notfound.html';
2739: }
2740: }
2741:
2742: sub clean_filename {
2743: my ($fname,$args)=@_;
2744: # Replace Windows backslashes by forward slashes
2745: $fname=~s/\\/\//g;
2746: if (!$args->{'keep_path'}) {
2747: # Get rid of everything but the actual filename
2748: $fname=~s/^.*\/([^\/]+)$/$1/;
2749: }
2750: # Replace spaces by underscores
2751: $fname=~s/\s+/\_/g;
2752: # Replace all other weird characters by nothing
2753: $fname=~s{[^/\w\.\-]}{}g;
2754: # Replace all .\d. sequences with _\d. so they no longer look like version
2755: # numbers
2756: $fname=~s/\.(\d+)(?=\.)/_$1/g;
2757: return $fname;
2758: }
2759: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2760: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2761: # image with the same aspect ratio as the original, but with dimensions which do
2762: # not exceed $resizewidth and $resizeheight.
2763:
2764: sub resizeImage {
2765: my ($img_path,$resizewidth,$resizeheight) = @_;
2766: my $ima = Image::Magick->new;
2767: my $resized;
2768: if (-e $img_path) {
2769: $ima->Read($img_path);
2770: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2771: my $width = $ima->Get('width');
2772: my $height = $ima->Get('height');
2773: if ($width > $resizewidth) {
2774: my $factor = $width/$resizewidth;
2775: my $newheight = $height/$factor;
2776: $ima->Scale(width=>$resizewidth,height=>$newheight);
2777: $resized = 1;
2778: }
2779: }
2780: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2781: my $width = $ima->Get('width');
2782: my $height = $ima->Get('height');
2783: if ($height > $resizeheight) {
2784: my $factor = $height/$resizeheight;
2785: my $newwidth = $width/$factor;
2786: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2787: $resized = 1;
2788: }
2789: }
2790: if ($resized) {
2791: $ima->Write($img_path);
2792: }
2793: }
2794: return;
2795: }
2796:
2797: # --------------- Take an uploaded file and put it into the userfiles directory
2798: # input: $formname - the contents of the file are in $env{"form.$formname"}
2799: # the desired filename is in $env{"form.$formname.filename"}
2800: # $context - possible values: coursedoc, existingfile, overwrite,
2801: # canceloverwrite, or ''.
2802: # if 'coursedoc': upload to the current course
2803: # if 'existingfile': write file to tmp/overwrites directory
2804: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2805: # $context is passed as argument to &finishuserfileupload
2806: # $subdir - directory in userfile to store the file into
2807: # $parser - instruction to parse file for objects ($parser = parse)
2808: # $allfiles - reference to hash for embedded objects
2809: # $codebase - reference to hash for codebase of java objects
2810: # $desuname - username for permanent storage of uploaded file
2811: # $dsetudom - domain for permanaent storage of uploaded file
2812: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2813: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
2814: # $resizewidth - width (pixels) to which to resize uploaded image
2815: # $resizeheight - height (pixels) to which to resize uploaded image
2816: # $mimetype - reference to scalar to accommodate mime type determined
2817: # from File::MMagic.
2818: #
2819: # output: url of file in userspace, or error: <message>
2820: # or /adm/notfound.html if failure to upload occurse
2821:
2822: sub userfileupload {
2823: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
2824: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
2825: if (!defined($subdir)) { $subdir='unknown'; }
2826: my $fname=$env{'form.'.$formname.'.filename'};
2827: $fname=&clean_filename($fname);
2828: # See if there is anything left
2829: unless ($fname) { return 'error: no uploaded file'; }
2830: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2831: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2832: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2833: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2834: my $now = time;
2835: my $filepath;
2836: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
2837: $filepath = 'tmp/helprequests/'.$now;
2838: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2839: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2840: '_'.$env{'user.domain'}.'/pending';
2841: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2842: my ($docuname,$docudom);
2843: if ($destudom) {
2844: $docudom = $destudom;
2845: } else {
2846: $docudom = $env{'user.domain'};
2847: }
2848: if ($destuname) {
2849: $docuname = $destuname;
2850: } else {
2851: $docuname = $env{'user.name'};
2852: }
2853: if (exists($env{'form.group'})) {
2854: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2855: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2856: }
2857: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2858: if ($context eq 'canceloverwrite') {
2859: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2860: if (-e $tempfile) {
2861: my @info = stat($tempfile);
2862: if ($info[9] eq $env{'form.timestamp'}) {
2863: unlink($tempfile);
2864: }
2865: }
2866: return;
2867: }
2868: }
2869: # Create the directory if not present
2870: my @parts=split(/\//,$filepath);
2871: my $fullpath = $perlvar{'lonDaemons'};
2872: for (my $i=0;$i<@parts;$i++) {
2873: $fullpath .= '/'.$parts[$i];
2874: if ((-e $fullpath)!=1) {
2875: mkdir($fullpath,0777);
2876: }
2877: }
2878: open(my $fh,'>'.$fullpath.'/'.$fname);
2879: print $fh $env{'form.'.$formname};
2880: close($fh);
2881: if ($context eq 'existingfile') {
2882: my @info = stat($fullpath.'/'.$fname);
2883: return ($fullpath.'/'.$fname,$info[9]);
2884: } else {
2885: return $fullpath.'/'.$fname;
2886: }
2887: }
2888: if ($subdir eq 'scantron') {
2889: $fname = 'scantron_orig_'.$fname;
2890: } else {
2891: $fname="$subdir/$fname";
2892: }
2893: if ($context eq 'coursedoc') {
2894: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2895: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2896: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
2897: return &finishuserfileupload($docuname,$docudom,
2898: $formname,$fname,$parser,$allfiles,
2899: $codebase,$thumbwidth,$thumbheight,
2900: $resizewidth,$resizeheight,$context,$mimetype);
2901: } else {
2902: $fname=$env{'form.folder'}.'/'.$fname;
2903: return &process_coursefile('uploaddoc',$docuname,$docudom,
2904: $fname,$formname,$parser,
2905: $allfiles,$codebase,$mimetype);
2906: }
2907: } elsif (defined($destuname)) {
2908: my $docuname=$destuname;
2909: my $docudom=$destudom;
2910: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2911: $parser,$allfiles,$codebase,
2912: $thumbwidth,$thumbheight,
2913: $resizewidth,$resizeheight,$context,$mimetype);
2914: } else {
2915: my $docuname=$env{'user.name'};
2916: my $docudom=$env{'user.domain'};
2917: if (exists($env{'form.group'})) {
2918: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2919: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2920: }
2921: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2922: $parser,$allfiles,$codebase,
2923: $thumbwidth,$thumbheight,
2924: $resizewidth,$resizeheight,$context,$mimetype);
2925: }
2926: }
2927:
2928: sub finishuserfileupload {
2929: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
2930: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
2931: my $path=$docudom.'/'.$docuname.'/';
2932: my $filepath=$perlvar{'lonDocRoot'};
2933:
2934: my ($fnamepath,$file,$fetchthumb);
2935: $file=$fname;
2936: if ($fname=~m|/|) {
2937: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2938: $path.=$fnamepath.'/';
2939: }
2940: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
2941: my $count;
2942: for ($count=4;$count<=$#parts;$count++) {
2943: $filepath.="/$parts[$count]";
2944: if ((-e $filepath)!=1) {
2945: mkdir($filepath,0777);
2946: }
2947: }
2948:
2949: # Save the file
2950: {
2951: if (!open(FH,'>'.$filepath.'/'.$file)) {
2952: &logthis('Failed to create '.$filepath.'/'.$file);
2953: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2954: return '/adm/notfound.html';
2955: }
2956: if ($context eq 'overwrite') {
2957: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
2958: my $target = $filepath.'/'.$file;
2959: if (-e $source) {
2960: my @info = stat($source);
2961: if ($info[9] eq $env{'form.timestamp'}) {
2962: unless (&File::Copy::move($source,$target)) {
2963: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2964: return "Moving from $source failed";
2965: }
2966: } else {
2967: return "Temporary file: $source had unexpected date/time for last modification";
2968: }
2969: } else {
2970: return "Temporary file: $source missing";
2971: }
2972: } elsif (!print FH ($env{'form.'.$formname})) {
2973: &logthis('Failed to write to '.$filepath.'/'.$file);
2974: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2975: return '/adm/notfound.html';
2976: }
2977: close(FH);
2978: if ($resizewidth && $resizeheight) {
2979: my $mm = new File::MMagic;
2980: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2981: if ($mime_type =~ m{^image/}) {
2982: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2983: }
2984: }
2985: }
2986: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
2987: if (ref($mimetype)) {
2988: if ($$mimetype eq '') {
2989: my $mm = new File::MMagic;
2990: my $type = $mm->checktype_filename($filepath.'/'.$file);
2991: $$mimetype = $type;
2992: }
2993: }
2994: }
2995: if ($parser eq 'parse') {
2996: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
2997: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2998: $allfiles,$codebase);
2999: unless ($parse_result eq 'ok') {
3000: &logthis('Failed to parse '.$filepath.$file.
3001: ' for embedded media: '.$parse_result);
3002: }
3003: }
3004: }
3005: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3006: my $input = $filepath.'/'.$file;
3007: my $output = $filepath.'/'.'tn-'.$file;
3008: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3009: system("convert -sample $thumbsize $input $output");
3010: if (-e $filepath.'/'.'tn-'.$file) {
3011: $fetchthumb = 1;
3012: }
3013: }
3014:
3015: # Notify homeserver to grep it
3016: #
3017: my $docuhome=&homeserver($docuname,$docudom);
3018: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
3019: if ($fetchresult eq 'ok') {
3020: if ($fetchthumb) {
3021: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3022: if ($thumbresult ne 'ok') {
3023: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3024: $docuhome.': '.$thumbresult);
3025: }
3026: }
3027: #
3028: # Return the URL to it
3029: return '/uploaded/'.$path.$file;
3030: } else {
3031: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3032: ': '.$fetchresult);
3033: return '/adm/notfound.html';
3034: }
3035: }
3036:
3037: sub extract_embedded_items {
3038: my ($fullpath,$allfiles,$codebase,$content) = @_;
3039: my @state = ();
3040: my (%lastids,%related,%shockwave,%flashvars);
3041: my %javafiles = (
3042: codebase => '',
3043: code => '',
3044: archive => ''
3045: );
3046: my %mediafiles = (
3047: src => '',
3048: movie => '',
3049: );
3050: my $p;
3051: if ($content) {
3052: $p = HTML::LCParser->new($content);
3053: } else {
3054: $p = HTML::LCParser->new($fullpath);
3055: }
3056: while (my $t=$p->get_token()) {
3057: if ($t->[0] eq 'S') {
3058: my ($tagname, $attr) = ($t->[1],$t->[2]);
3059: push(@state, $tagname);
3060: if (lc($tagname) eq 'allow') {
3061: &add_filetype($allfiles,$attr->{'src'},'src');
3062: }
3063: if (lc($tagname) eq 'img') {
3064: &add_filetype($allfiles,$attr->{'src'},'src');
3065: }
3066: if (lc($tagname) eq 'a') {
3067: &add_filetype($allfiles,$attr->{'href'},'href');
3068: }
3069: if (lc($tagname) eq 'script') {
3070: my $src;
3071: if ($attr->{'archive'} =~ /\.jar$/i) {
3072: &add_filetype($allfiles,$attr->{'archive'},'archive');
3073: } else {
3074: if ($attr->{'src'} ne '') {
3075: $src = $attr->{'src'};
3076: &add_filetype($allfiles,$src,'src');
3077: }
3078: }
3079: my $text = $p->get_trimmed_text();
3080: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3081: my @swfargs = split(/,/,$1);
3082: foreach my $item (@swfargs) {
3083: $item =~ s/["']//g;
3084: $item =~ s/^\s+//;
3085: $item =~ s/\s+$//;
3086: }
3087: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3088: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3089: push(@{$related{$swfargs[0]}},$swfargs[2]);
3090: } else {
3091: $related{$swfargs[0]} = [$swfargs[2]];
3092: }
3093: }
3094: }
3095: }
3096: if (lc($tagname) eq 'link') {
3097: if (lc($attr->{'rel'}) eq 'stylesheet') {
3098: &add_filetype($allfiles,$attr->{'href'},'href');
3099: }
3100: }
3101: if (lc($tagname) eq 'object' ||
3102: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3103: foreach my $item (keys(%javafiles)) {
3104: $javafiles{$item} = '';
3105: }
3106: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3107: $lastids{lc($tagname)} = $attr->{'id'};
3108: }
3109: }
3110: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3111: my $name = lc($attr->{'name'});
3112: foreach my $item (keys(%javafiles)) {
3113: if ($name eq $item) {
3114: $javafiles{$item} = $attr->{'value'};
3115: last;
3116: }
3117: }
3118: my $pathfrom;
3119: foreach my $item (keys(%mediafiles)) {
3120: if ($name eq $item) {
3121: $pathfrom = $attr->{'value'};
3122: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3123: &add_filetype($allfiles,$pathfrom,$name);
3124: last;
3125: }
3126: }
3127: if ($name eq 'flashvars') {
3128: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3129: }
3130: if ($pathfrom ne '') {
3131: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3132: $pathfrom);
3133: }
3134: }
3135: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3136: foreach my $item (keys(%javafiles)) {
3137: if ($attr->{$item}) {
3138: $javafiles{$item} = $attr->{$item};
3139: last;
3140: }
3141: }
3142: foreach my $item (keys(%mediafiles)) {
3143: if ($attr->{$item}) {
3144: &add_filetype($allfiles,$attr->{$item},$item);
3145: last;
3146: }
3147: }
3148: if (lc($tagname) eq 'embed') {
3149: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3150: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3151: $attr->{'src'});
3152: }
3153: }
3154: }
3155: if ($t->[4] =~ m{/>$}) {
3156: pop(@state);
3157: }
3158: } elsif ($t->[0] eq 'E') {
3159: my ($tagname) = ($t->[1]);
3160: if ($javafiles{'codebase'} ne '') {
3161: $javafiles{'codebase'} .= '/';
3162: }
3163: if (lc($tagname) eq 'applet' ||
3164: lc($tagname) eq 'object' ||
3165: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3166: ) {
3167: foreach my $item (keys(%javafiles)) {
3168: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3169: my $file=$javafiles{'codebase'}.$javafiles{$item};
3170: &add_filetype($allfiles,$file,$item);
3171: }
3172: }
3173: }
3174: pop @state;
3175: }
3176: }
3177: foreach my $id (sort(keys(%flashvars))) {
3178: if ($shockwave{$id} ne '') {
3179: my @pairs = split(/\&/,$flashvars{$id});
3180: foreach my $pair (@pairs) {
3181: my ($key,$value) = split(/\=/,$pair);
3182: if ($key eq 'thumb') {
3183: &add_filetype($allfiles,$value,$key);
3184: } elsif ($key eq 'content') {
3185: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3186: my ($ext) = ($value =~ /\.([^.]+)$/);
3187: if ($ext ne '') {
3188: &add_filetype($allfiles,$path.$value,$ext);
3189: }
3190: }
3191: }
3192: }
3193: }
3194: return 'ok';
3195: }
3196:
3197: sub add_filetype {
3198: my ($allfiles,$file,$type)=@_;
3199: if (exists($allfiles->{$file})) {
3200: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3201: push(@{$allfiles->{$file}}, &escape($type));
3202: }
3203: } else {
3204: @{$allfiles->{$file}} = (&escape($type));
3205: }
3206: }
3207:
3208: sub embedded_dependency {
3209: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3210: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3211: if (($identifier ne '') &&
3212: (ref($related->{$identifier}) eq 'ARRAY') &&
3213: ($pathfrom ne '')) {
3214: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3215: foreach my $dep (@{$related->{$identifier}}) {
3216: &add_filetype($allfiles,$path.$dep,'object');
3217: }
3218: }
3219: }
3220: return;
3221: }
3222:
3223: sub removeuploadedurl {
3224: my ($url)=@_;
3225: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
3226: return &removeuserfile($uname,$udom,$fname);
3227: }
3228:
3229: sub removeuserfile {
3230: my ($docuname,$docudom,$fname)=@_;
3231: my $home=&homeserver($docuname,$docudom);
3232: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
3233: if ($result eq 'ok') {
3234: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3235: my $metafile = $fname.'.meta';
3236: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
3237: my $url = "/uploaded/$docudom/$docuname/$fname";
3238: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
3239: my $sqlresult =
3240: &update_portfolio_table($docuname,$docudom,$file,
3241: 'portfolio_metadata',$group,
3242: 'delete');
3243: }
3244: }
3245: return $result;
3246: }
3247:
3248: sub mkdiruserfile {
3249: my ($docuname,$docudom,$dir)=@_;
3250: my $home=&homeserver($docuname,$docudom);
3251: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3252: }
3253:
3254: sub renameuserfile {
3255: my ($docuname,$docudom,$old,$new)=@_;
3256: my $home=&homeserver($docuname,$docudom);
3257: my $result = &reply("renameuserfile:$docudom:$docuname:".
3258: &escape("$old").':'.&escape("$new"),$home);
3259: if ($result eq 'ok') {
3260: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3261: my $oldmeta = $old.'.meta';
3262: my $newmeta = $new.'.meta';
3263: my $metaresult =
3264: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
3265: my $url = "/uploaded/$docudom/$docuname/$old";
3266: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
3267: my $sqlresult =
3268: &update_portfolio_table($docuname,$docudom,$file,
3269: 'portfolio_metadata',$group,
3270: 'delete');
3271: }
3272: }
3273: return $result;
3274: }
3275:
3276: # ------------------------------------------------------------------------- Log
3277:
3278: sub log {
3279: my ($dom,$nam,$hom,$what)=@_;
3280: return critical("log:$dom:$nam:$what",$hom);
3281: }
3282:
3283: # ------------------------------------------------------------------ Course Log
3284: #
3285: # This routine flushes several buffers of non-mission-critical nature
3286: #
3287:
3288: sub flushcourselogs {
3289: &logthis('Flushing log buffers');
3290: #
3291: # course logs
3292: # This is a log of all transactions in a course, which can be used
3293: # for data mining purposes
3294: #
3295: # It also collects the courseid database, which lists last transaction
3296: # times and course titles for all courseids
3297: #
3298: my %courseidbuffer=();
3299: foreach my $crsid (keys(%courselogs)) {
3300: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
3301: &escape($courselogs{$crsid}),
3302: $coursehombuf{$crsid}) eq 'ok') {
3303: delete $courselogs{$crsid};
3304: } else {
3305: &logthis('Failed to flush log buffer for '.$crsid);
3306: if (length($courselogs{$crsid})>40000) {
3307: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
3308: " exceeded maximum size, deleting.</font>");
3309: delete $courselogs{$crsid};
3310: }
3311: }
3312: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
3313: 'description' => $coursedescrbuf{$crsid},
3314: 'inst_code' => $courseinstcodebuf{$crsid},
3315: 'type' => $coursetypebuf{$crsid},
3316: 'owner' => $courseownerbuf{$crsid},
3317: };
3318: }
3319: #
3320: # Write course id database (reverse lookup) to homeserver of courses
3321: # Is used in pickcourse
3322: #
3323: foreach my $crs_home (keys(%courseidbuffer)) {
3324: my $response = &courseidput(&host_domain($crs_home),
3325: $courseidbuffer{$crs_home},
3326: $crs_home,'timeonly');
3327: }
3328: #
3329: # File accesses
3330: # Writes to the dynamic metadata of resources to get hit counts, etc.
3331: #
3332: foreach my $entry (keys(%accesshash)) {
3333: if ($entry =~ /___count$/) {
3334: my ($dom,$name);
3335: ($dom,$name,undef)=
3336: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
3337: if (! defined($dom) || $dom eq '' ||
3338: ! defined($name) || $name eq '') {
3339: my $cid = $env{'request.course.id'};
3340: $dom = $env{'request.'.$cid.'.domain'};
3341: $name = $env{'request.'.$cid.'.num'};
3342: }
3343: my $value = $accesshash{$entry};
3344: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3345: my %temphash=($url => $value);
3346: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3347: if ($result eq 'ok') {
3348: delete $accesshash{$entry};
3349: }
3350: } else {
3351: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
3352: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
3353: my %temphash=($entry => $accesshash{$entry});
3354: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3355: delete $accesshash{$entry};
3356: }
3357: }
3358: }
3359: #
3360: # Roles
3361: # Reverse lookup of user roles for course faculty/staff and co-authorship
3362: #
3363: foreach my $entry (keys(%userrolehash)) {
3364: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
3365: split(/\:/,$entry);
3366: if (&Apache::lonnet::put('nohist_userroles',
3367: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
3368: $rudom,$runame) eq 'ok') {
3369: delete $userrolehash{$entry};
3370: }
3371: }
3372: #
3373: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3374: #
3375: my %domrolebuffer = ();
3376: foreach my $entry (keys(%domainrolehash)) {
3377: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
3378: if ($domrolebuffer{$rudom}) {
3379: $domrolebuffer{$rudom}.='&'.&escape($entry).
3380: '='.&escape($domainrolehash{$entry});
3381: } else {
3382: $domrolebuffer{$rudom}.=&escape($entry).
3383: '='.&escape($domainrolehash{$entry});
3384: }
3385: delete $domainrolehash{$entry};
3386: }
3387: foreach my $dom (keys(%domrolebuffer)) {
3388: my %servers = &get_servers($dom,'library');
3389: foreach my $tryserver (keys(%servers)) {
3390: unless (&reply('domroleput:'.$dom.':'.
3391: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3392: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3393: }
3394: }
3395: }
3396: $dumpcount++;
3397: }
3398:
3399: sub courselog {
3400: my $what=shift;
3401: $what=time.':'.$what;
3402: unless ($env{'request.course.id'}) { return ''; }
3403: $coursedombuf{$env{'request.course.id'}}=
3404: $env{'course.'.$env{'request.course.id'}.'.domain'};
3405: $coursenumbuf{$env{'request.course.id'}}=
3406: $env{'course.'.$env{'request.course.id'}.'.num'};
3407: $coursehombuf{$env{'request.course.id'}}=
3408: $env{'course.'.$env{'request.course.id'}.'.home'};
3409: $coursedescrbuf{$env{'request.course.id'}}=
3410: $env{'course.'.$env{'request.course.id'}.'.description'};
3411: $courseinstcodebuf{$env{'request.course.id'}}=
3412: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3413: $courseownerbuf{$env{'request.course.id'}}=
3414: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
3415: $coursetypebuf{$env{'request.course.id'}}=
3416: $env{'course.'.$env{'request.course.id'}.'.type'};
3417: if (defined $courselogs{$env{'request.course.id'}}) {
3418: $courselogs{$env{'request.course.id'}}.='&'.$what;
3419: } else {
3420: $courselogs{$env{'request.course.id'}}.=$what;
3421: }
3422: if (length($courselogs{$env{'request.course.id'}})>4048) {
3423: &flushcourselogs();
3424: }
3425: }
3426:
3427: sub courseacclog {
3428: my $fnsymb=shift;
3429: unless ($env{'request.course.id'}) { return ''; }
3430: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
3431: if ($fnsymb=~/$LONCAPA::assess_re/) {
3432: $what.=':POST';
3433: # FIXME: Probably ought to escape things....
3434: foreach my $key (keys(%env)) {
3435: if ($key=~/^form\.(.*)/) {
3436: my $formitem = $1;
3437: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3438: $what.=':'.$formitem.'='.$env{$key};
3439: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3440: $what.=':'.$formitem.'='.$env{$key};
3441: }
3442: }
3443: }
3444: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3445: # FIXME: We should not be depending on a form parameter that someone
3446: # editing lonsearchcat.pm might change in the future.
3447: if ($env{'form.phase'} eq 'course_search') {
3448: $what.= ':POST';
3449: # FIXME: Probably ought to escape things....
3450: foreach my $element ('courseexp','crsfulltext','crsrelated',
3451: 'crsdiscuss') {
3452: $what.=':'.$element.'='.$env{'form.'.$element};
3453: }
3454: }
3455: }
3456: &courselog($what);
3457: }
3458:
3459: sub countacc {
3460: my $url=&declutter(shift);
3461: return if (! defined($url) || $url eq '');
3462: unless ($env{'request.course.id'}) { return ''; }
3463: #
3464: # Mark that this url was used in this course
3465: #
3466: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
3467: #
3468: # Increase the access count for this resource in this child process
3469: #
3470: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
3471: $accesshash{$key}++;
3472: }
3473:
3474: sub linklog {
3475: my ($from,$to)=@_;
3476: $from=&declutter($from);
3477: $to=&declutter($to);
3478: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3479: $accesshash{$to.'___'.$from.'___goto'}=1;
3480: }
3481:
3482: sub statslog {
3483: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3484: if ($users<2) { return; }
3485: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3486: 'course' => $env{'request.course.id'},
3487: 'sections' => '"all"',
3488: 'num_students' => $users,
3489: 'part' => $part,
3490: 'symb' => $symb,
3491: 'mean_tries' => $av_attempts,
3492: 'deg_of_diff' => $degdiff});
3493: foreach my $key (keys(%dynstore)) {
3494: $accesshash{$key}=$dynstore{$key};
3495: }
3496: }
3497:
3498: sub userrolelog {
3499: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
3500: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
3501: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3502: $userrolehash
3503: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3504: =$tend.':'.$tstart;
3505: }
3506: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
3507: $userrolehash
3508: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3509: =$tend.':'.$tstart;
3510: }
3511: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
3512: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3513: $domainrolehash
3514: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3515: = $tend.':'.$tstart;
3516: }
3517: }
3518:
3519: sub courserolelog {
3520: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3521: if (($trole eq 'cc') || ($trole eq 'in') ||
3522: ($trole eq 'ep') || ($trole eq 'ad') ||
3523: ($trole eq 'ta') || ($trole eq 'st') ||
3524: ($trole=~/^cr/) || ($trole eq 'gr') ||
3525: ($trole eq 'co')) {
3526: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3527: my $cdom = $1;
3528: my $cnum = $2;
3529: my $sec = $3;
3530: my $namespace = 'rolelog';
3531: my %storehash = (
3532: role => $trole,
3533: start => $tstart,
3534: end => $tend,
3535: selfenroll => $selfenroll,
3536: context => $context,
3537: );
3538: if ($trole eq 'gr') {
3539: $namespace = 'groupslog';
3540: $storehash{'group'} = $sec;
3541: } else {
3542: $storehash{'section'} = $sec;
3543: }
3544: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
3545: if (($trole ne 'st') || ($sec ne '')) {
3546: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3547: }
3548: }
3549: }
3550: return;
3551: }
3552:
3553: sub get_course_adv_roles {
3554: my ($cid,$codes) = @_;
3555: $cid=$env{'request.course.id'} unless (defined($cid));
3556: my %coursehash=&coursedescription($cid);
3557: my $crstype = &Apache::loncommon::course_type($cid);
3558: my %nothide=();
3559: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3560: if ($user !~ /:/) {
3561: $nothide{join(':',split(/[\@]/,$user))}=1;
3562: } else {
3563: $nothide{$user}=1;
3564: }
3565: }
3566: my %returnhash=();
3567: my %dumphash=
3568: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3569: my $now=time;
3570: my %privileged;
3571: foreach my $entry (keys(%dumphash)) {
3572: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3573: if (($tstart) && ($tstart<0)) { next; }
3574: if (($tend) && ($tend<$now)) { next; }
3575: if (($tstart) && ($now<$tstart)) { next; }
3576: my ($role,$username,$domain,$section)=split(/\:/,$entry);
3577: if ($username eq '' || $domain eq '') { next; }
3578: unless (ref($privileged{$domain}) eq 'HASH') {
3579: my %dompersonnel =
3580: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3581: $privileged{$domain} = {};
3582: foreach my $server (keys(%dompersonnel)) {
3583: if (ref($dompersonnel{$server}) eq 'HASH') {
3584: foreach my $user (keys(%{$dompersonnel{$server}})) {
3585: my ($trole,$uname,$udom) = split(/:/,$user);
3586: $privileged{$udom}{$uname} = 1;
3587: }
3588: }
3589: }
3590: }
3591: if ((exists($privileged{$domain}{$username})) &&
3592: (!$nothide{$username.':'.$domain})) { next; }
3593: if ($role eq 'cr') { next; }
3594: if ($codes) {
3595: if ($section) { $role .= ':'.$section; }
3596: if ($returnhash{$role}) {
3597: $returnhash{$role}.=','.$username.':'.$domain;
3598: } else {
3599: $returnhash{$role}=$username.':'.$domain;
3600: }
3601: } else {
3602: my $key=&plaintext($role,$crstype);
3603: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
3604: if ($returnhash{$key}) {
3605: $returnhash{$key}.=','.$username.':'.$domain;
3606: } else {
3607: $returnhash{$key}=$username.':'.$domain;
3608: }
3609: }
3610: }
3611: return %returnhash;
3612: }
3613:
3614: sub get_my_roles {
3615: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
3616: unless (defined($uname)) { $uname=$env{'user.name'}; }
3617: unless (defined($udom)) { $udom=$env{'user.domain'}; }
3618: my (%dumphash,%nothide);
3619: if ($context eq 'userroles') {
3620: %dumphash = &dump('roles',$udom,$uname);
3621: } else {
3622: %dumphash=
3623: &dump('nohist_userroles',$udom,$uname);
3624: if ($hidepriv) {
3625: my %coursehash=&coursedescription($udom.'_'.$uname);
3626: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3627: if ($user !~ /:/) {
3628: $nothide{join(':',split(/[\@]/,$user))} = 1;
3629: } else {
3630: $nothide{$user} = 1;
3631: }
3632: }
3633: }
3634: }
3635: my %returnhash=();
3636: my $now=time;
3637: my %privileged;
3638: foreach my $entry (keys(%dumphash)) {
3639: my ($role,$tend,$tstart);
3640: if ($context eq 'userroles') {
3641: next if ($entry =~ /^rolesdef/);
3642: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3643: } else {
3644: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3645: }
3646: if (($tstart) && ($tstart<0)) { next; }
3647: my $status = 'active';
3648: if (($tend) && ($tend<=$now)) {
3649: $status = 'previous';
3650: }
3651: if (($tstart) && ($now<$tstart)) {
3652: $status = 'future';
3653: }
3654: if (ref($types) eq 'ARRAY') {
3655: if (!grep(/^\Q$status\E$/,@{$types})) {
3656: next;
3657: }
3658: } else {
3659: if ($status ne 'active') {
3660: next;
3661: }
3662: }
3663: my ($rolecode,$username,$domain,$section,$area);
3664: if ($context eq 'userroles') {
3665: ($area,$rolecode) = split(/_/,$entry);
3666: (undef,$domain,$username,$section) = split(/\//,$area);
3667: } else {
3668: ($role,$username,$domain,$section) = split(/\:/,$entry);
3669: }
3670: if (ref($roledoms) eq 'ARRAY') {
3671: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3672: next;
3673: }
3674: }
3675: if (ref($roles) eq 'ARRAY') {
3676: if (!grep(/^\Q$role\E$/,@{$roles})) {
3677: if ($role =~ /^cr\//) {
3678: if (!grep(/^cr$/,@{$roles})) {
3679: next;
3680: }
3681: } elsif ($role =~ /^gr\//) {
3682: if (!grep(/^gr$/,@{$roles})) {
3683: next;
3684: }
3685: } else {
3686: next;
3687: }
3688: }
3689: }
3690: if ($hidepriv) {
3691: if ($context eq 'userroles') {
3692: if ((&privileged($username,$domain)) &&
3693: (!$nothide{$username.':'.$domain})) {
3694: next;
3695: }
3696: } else {
3697: unless (ref($privileged{$domain}) eq 'HASH') {
3698: my %dompersonnel =
3699: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3700: $privileged{$domain} = {};
3701: if (keys(%dompersonnel)) {
3702: foreach my $server (keys(%dompersonnel)) {
3703: if (ref($dompersonnel{$server}) eq 'HASH') {
3704: foreach my $user (keys(%{$dompersonnel{$server}})) {
3705: my ($trole,$uname,$udom) = split(/:/,$user);
3706: $privileged{$udom}{$uname} = $trole;
3707: }
3708: }
3709: }
3710: }
3711: }
3712: if (exists($privileged{$domain}{$username})) {
3713: if (!$nothide{$username.':'.$domain}) {
3714: next;
3715: }
3716: }
3717: }
3718: }
3719: if ($withsec) {
3720: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3721: $tstart.':'.$tend;
3722: } else {
3723: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3724: }
3725: }
3726: return %returnhash;
3727: }
3728:
3729: # ----------------------------------------------------- Frontpage Announcements
3730: #
3731: #
3732:
3733: sub postannounce {
3734: my ($server,$text)=@_;
3735: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
3736: unless ($text=~/\w/) { $text=''; }
3737: return &reply('setannounce:'.&escape($text),$server);
3738: }
3739:
3740: sub getannounce {
3741:
3742: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
3743: my $announcement='';
3744: while (my $line = <$fh>) { $announcement .= $line; }
3745: close($fh);
3746: if ($announcement=~/\w/) {
3747: return
3748: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
3749: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
3750: } else {
3751: return '';
3752: }
3753: } else {
3754: return '';
3755: }
3756: }
3757:
3758: # ---------------------------------------------------------- Course ID routines
3759: # Deal with domain's nohist_courseid.db files
3760: #
3761:
3762: sub courseidput {
3763: my ($domain,$storehash,$coursehome,$caller) = @_;
3764: return unless (ref($storehash) eq 'HASH');
3765: my $outcome;
3766: if ($caller eq 'timeonly') {
3767: my $cids = '';
3768: foreach my $item (keys(%$storehash)) {
3769: $cids.=&escape($item).'&';
3770: }
3771: $cids=~s/\&$//;
3772: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3773: $coursehome);
3774: } else {
3775: my $items = '';
3776: foreach my $item (keys(%$storehash)) {
3777: $items.= &escape($item).'='.
3778: &freeze_escape($$storehash{$item}).'&';
3779: }
3780: $items=~s/\&$//;
3781: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3782: $coursehome);
3783: }
3784: if ($outcome eq 'unknown_cmd') {
3785: my $what;
3786: foreach my $cid (keys(%$storehash)) {
3787: $what .= &escape($cid).'=';
3788: foreach my $item ('description','inst_code','owner','type') {
3789: $what .= &escape($storehash->{$cid}{$item}).':';
3790: }
3791: $what =~ s/\:$/&/;
3792: }
3793: $what =~ s/\&$//;
3794: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3795: } else {
3796: return $outcome;
3797: }
3798: }
3799:
3800: sub courseiddump {
3801: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
3802: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
3803: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
3804: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
3805: my $as_hash = 1;
3806: my %returnhash;
3807: if (!$domfilter) { $domfilter=''; }
3808: my %libserv = &all_library();
3809: foreach my $tryserver (keys(%libserv)) {
3810: if ( ( $hostidflag == 1
3811: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3812: || (!defined($hostidflag)) ) {
3813:
3814: if (($domfilter eq '') ||
3815: (&host_domain($tryserver) eq $domfilter)) {
3816: my $rep =
3817: &reply('courseiddump:'.&host_domain($tryserver).':'.
3818: $sincefilter.':'.&escape($descfilter).':'.
3819: &escape($instcodefilter).':'.&escape($ownerfilter).
3820: ':'.&escape($coursefilter).':'.&escape($typefilter).
3821: ':'.&escape($regexp_ok).':'.$as_hash.':'.
3822: &escape($selfenrollonly).':'.&escape($catfilter).':'.
3823: $showhidden.':'.$caller.':'.&escape($cloner).':'.
3824: &escape($cc_clone).':'.$cloneonly.':'.
3825: &escape($createdbefore).':'.&escape($createdafter).':'.
3826: &escape($creationcontext).':'.$domcloner,
3827: $tryserver);
3828: my @pairs=split(/\&/,$rep);
3829: foreach my $item (@pairs) {
3830: my ($key,$value)=split(/\=/,$item,2);
3831: $key = &unescape($key);
3832: next if ($key =~ /^error: 2 /);
3833: my $result = &thaw_unescape($value);
3834: if (ref($result) eq 'HASH') {
3835: $returnhash{$key}=$result;
3836: } else {
3837: my @responses = split(/:/,$value);
3838: my @items = ('description','inst_code','owner','type');
3839: for (my $i=0; $i<@responses; $i++) {
3840: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
3841: }
3842: }
3843: }
3844: }
3845: }
3846: }
3847: return %returnhash;
3848: }
3849:
3850: sub courselastaccess {
3851: my ($cdom,$cnum,$hostidref) = @_;
3852: my %returnhash;
3853: if ($cdom && $cnum) {
3854: my $chome = &homeserver($cnum,$cdom);
3855: if ($chome ne 'no_host') {
3856: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3857: &extract_lastaccess(\%returnhash,$rep);
3858: }
3859: } else {
3860: if (!$cdom) { $cdom=''; }
3861: my %libserv = &all_library();
3862: foreach my $tryserver (keys(%libserv)) {
3863: if (ref($hostidref) eq 'ARRAY') {
3864: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3865: }
3866: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3867: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3868: &extract_lastaccess(\%returnhash,$rep);
3869: }
3870: }
3871: }
3872: return %returnhash;
3873: }
3874:
3875: sub extract_lastaccess {
3876: my ($returnhash,$rep) = @_;
3877: if (ref($returnhash) eq 'HASH') {
3878: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3879: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3880: $rep eq '') {
3881: my @pairs=split(/\&/,$rep);
3882: foreach my $item (@pairs) {
3883: my ($key,$value)=split(/\=/,$item,2);
3884: $key = &unescape($key);
3885: next if ($key =~ /^error: 2 /);
3886: $returnhash->{$key} = &thaw_unescape($value);
3887: }
3888: }
3889: }
3890: return;
3891: }
3892:
3893: # ---------------------------------------------------------- DC e-mail
3894:
3895: sub dcmailput {
3896: my ($domain,$msgid,$message,$server)=@_;
3897: my $status = &Apache::lonnet::critical(
3898: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3899: &escape($message),$server);
3900: return $status;
3901: }
3902:
3903: sub dcmaildump {
3904: my ($dom,$startdate,$enddate,$senders) = @_;
3905: my %returnhash=();
3906:
3907: if (defined(&domain($dom,'primary'))) {
3908: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3909: &escape($enddate).':';
3910: my @esc_senders=map { &escape($_)} @$senders;
3911: $cmd.=&escape(join('&',@esc_senders));
3912: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
3913: my ($key,$value) = split(/\=/,$line,2);
3914: if (($key) && ($value)) {
3915: $returnhash{&unescape($key)} = &unescape($value);
3916: }
3917: }
3918: }
3919: return %returnhash;
3920: }
3921: # ---------------------------------------------------------- Domain roles
3922:
3923: sub get_domain_roles {
3924: my ($dom,$roles,$startdate,$enddate)=@_;
3925: if ((!defined($startdate)) || ($startdate eq '')) {
3926: $startdate = '.';
3927: }
3928: if ((!defined($enddate)) || ($enddate eq '')) {
3929: $enddate = '.';
3930: }
3931: my $rolelist;
3932: if (ref($roles) eq 'ARRAY') {
3933: $rolelist = join(':',@{$roles});
3934: }
3935: my %personnel = ();
3936:
3937: my %servers = &get_servers($dom,'library');
3938: foreach my $tryserver (keys(%servers)) {
3939: %{$personnel{$tryserver}}=();
3940: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3941: &escape($startdate).':'.
3942: &escape($enddate).':'.
3943: &escape($rolelist), $tryserver))) {
3944: my ($key,$value) = split(/\=/,$line,2);
3945: if (($key) && ($value)) {
3946: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3947: }
3948: }
3949: }
3950: return %personnel;
3951: }
3952:
3953: # ----------------------------------------------------------- Interval timing
3954:
3955: {
3956: # Caches needed for speedup of navmaps
3957: # We don't want to cache this for very long at all (5 seconds at most)
3958: #
3959: # The user for whom we cache
3960: my $cachedkey='';
3961: # The cached times for this user
3962: my %cachedtimes=();
3963: # When this was last done
3964: my $cachedtime=();
3965:
3966: sub load_all_first_access {
3967: my ($uname,$udom)=@_;
3968: if (($cachedkey eq $uname.':'.$udom) &&
3969: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
3970: return;
3971: }
3972: $cachedtime=time;
3973: $cachedkey=$uname.':'.$udom;
3974: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
3975: }
3976:
3977: sub get_first_access {
3978: my ($type,$argsymb,$argmap)=@_;
3979: my ($symb,$courseid,$udom,$uname)=&whichuser();
3980: if ($argsymb) { $symb=$argsymb; }
3981: my ($map,$id,$res)=&decode_symb($symb);
3982: if ($argmap) { $map = $argmap; }
3983: if ($type eq 'course') {
3984: $res='course';
3985: } elsif ($type eq 'map') {
3986: $res=&symbread($map);
3987: } else {
3988: $res=$symb;
3989: }
3990: &load_all_first_access($uname,$udom);
3991: return $cachedtimes{"$courseid\0$res"};
3992: }
3993:
3994: sub set_first_access {
3995: my ($type,$interval)=@_;
3996: my ($symb,$courseid,$udom,$uname)=&whichuser();
3997: my ($map,$id,$res)=&decode_symb($symb);
3998: if ($type eq 'course') {
3999: $res='course';
4000: } elsif ($type eq 'map') {
4001: $res=&symbread($map);
4002: } else {
4003: $res=$symb;
4004: }
4005: $cachedkey='';
4006: my $firstaccess=&get_first_access($type,$symb,$map);
4007: if (!$firstaccess) {
4008: my $start = time;
4009: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4010: $udom,$uname);
4011: if ($putres eq 'ok') {
4012: &put('timerinterval',{"$courseid\0$res"=>$interval},
4013: $udom,$uname);
4014: &appenv(
4015: {
4016: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4017: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4018: }
4019: );
4020: }
4021: return $putres;
4022: }
4023: return 'already_set';
4024: }
4025: }
4026: # --------------------------------------------- Set Expire Date for Spreadsheet
4027:
4028: sub expirespread {
4029: my ($uname,$udom,$stype,$usymb)=@_;
4030: my $cid=$env{'request.course.id'};
4031: if ($cid) {
4032: my $now=time;
4033: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
4034: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4035: $env{'course.'.$cid.'.num'}.
4036: ':nohist_expirationdates:'.
4037: &escape($key).'='.$now,
4038: $env{'course.'.$cid.'.home'})
4039: }
4040: return 'ok';
4041: }
4042:
4043: # ----------------------------------------------------- Devalidate Spreadsheets
4044:
4045: sub devalidate {
4046: my ($symb,$uname,$udom)=@_;
4047: my $cid=$env{'request.course.id'};
4048: if ($cid) {
4049: # delete the stored spreadsheets for
4050: # - the student level sheet of this user in course's homespace
4051: # - the assessment level sheet for this resource
4052: # for this user in user's homespace
4053: # - current conditional state info
4054: my $key=$uname.':'.$udom.':';
4055: my $status=
4056: &del('nohist_calculatedsheets',
4057: [$key.'studentcalc:'],
4058: $env{'course.'.$cid.'.domain'},
4059: $env{'course.'.$cid.'.num'})
4060: .' '.
4061: &del('nohist_calculatedsheets_'.$cid,
4062: [$key.'assesscalc:'.$symb],$udom,$uname);
4063: unless ($status eq 'ok ok') {
4064: &logthis('Could not devalidate spreadsheet '.
4065: $uname.' at '.$udom.' for '.
4066: $symb.': '.$status);
4067: }
4068: &delenv('user.state.'.$cid);
4069: }
4070: }
4071:
4072: sub get_scalar {
4073: my ($string,$end) = @_;
4074: my $value;
4075: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4076: $value = $1;
4077: } elsif ($$string =~ s/^([^&]*?)&//) {
4078: $value = $1;
4079: }
4080: return &unescape($value);
4081: }
4082:
4083: sub array2str {
4084: my (@array) = @_;
4085: my $result=&arrayref2str(\@array);
4086: $result=~s/^__ARRAY_REF__//;
4087: $result=~s/__END_ARRAY_REF__$//;
4088: return $result;
4089: }
4090:
4091: sub arrayref2str {
4092: my ($arrayref) = @_;
4093: my $result='__ARRAY_REF__';
4094: foreach my $elem (@$arrayref) {
4095: if(ref($elem) eq 'ARRAY') {
4096: $result.=&arrayref2str($elem).'&';
4097: } elsif(ref($elem) eq 'HASH') {
4098: $result.=&hashref2str($elem).'&';
4099: } elsif(ref($elem)) {
4100: #print("Got a ref of ".(ref($elem))." skipping.");
4101: } else {
4102: $result.=&escape($elem).'&';
4103: }
4104: }
4105: $result=~s/\&$//;
4106: $result .= '__END_ARRAY_REF__';
4107: return $result;
4108: }
4109:
4110: sub hash2str {
4111: my (%hash) = @_;
4112: my $result=&hashref2str(\%hash);
4113: $result=~s/^__HASH_REF__//;
4114: $result=~s/__END_HASH_REF__$//;
4115: return $result;
4116: }
4117:
4118: sub hashref2str {
4119: my ($hashref)=@_;
4120: my $result='__HASH_REF__';
4121: foreach my $key (sort(keys(%$hashref))) {
4122: if (ref($key) eq 'ARRAY') {
4123: $result.=&arrayref2str($key).'=';
4124: } elsif (ref($key) eq 'HASH') {
4125: $result.=&hashref2str($key).'=';
4126: } elsif (ref($key)) {
4127: $result.='=';
4128: #print("Got a ref of ".(ref($key))." skipping.");
4129: } else {
4130: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
4131: }
4132:
4133: if(ref($hashref->{$key}) eq 'ARRAY') {
4134: $result.=&arrayref2str($hashref->{$key}).'&';
4135: } elsif(ref($hashref->{$key}) eq 'HASH') {
4136: $result.=&hashref2str($hashref->{$key}).'&';
4137: } elsif(ref($hashref->{$key})) {
4138: $result.='&';
4139: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
4140: } else {
4141: $result.=&escape($hashref->{$key}).'&';
4142: }
4143: }
4144: $result=~s/\&$//;
4145: $result .= '__END_HASH_REF__';
4146: return $result;
4147: }
4148:
4149: sub str2hash {
4150: my ($string)=@_;
4151: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4152: return %$hash;
4153: }
4154:
4155: sub str2hashref {
4156: my ($string) = @_;
4157:
4158: my %hash;
4159:
4160: if($string !~ /^__HASH_REF__/) {
4161: if (! ($string eq '' || !defined($string))) {
4162: $hash{'error'}='Not hash reference';
4163: }
4164: return (\%hash, $string);
4165: }
4166:
4167: $string =~ s/^__HASH_REF__//;
4168:
4169: while($string !~ /^__END_HASH_REF__/) {
4170: #key
4171: my $key='';
4172: if($string =~ /^__HASH_REF__/) {
4173: ($key, $string)=&str2hashref($string);
4174: if(defined($key->{'error'})) {
4175: $hash{'error'}='Bad data';
4176: return (\%hash, $string);
4177: }
4178: } elsif($string =~ /^__ARRAY_REF__/) {
4179: ($key, $string)=&str2arrayref($string);
4180: if($key->[0] eq 'Array reference error') {
4181: $hash{'error'}='Bad data';
4182: return (\%hash, $string);
4183: }
4184: } else {
4185: $string =~ s/^(.*?)=//;
4186: $key=&unescape($1);
4187: }
4188: $string =~ s/^=//;
4189:
4190: #value
4191: my $value='';
4192: if($string =~ /^__HASH_REF__/) {
4193: ($value, $string)=&str2hashref($string);
4194: if(defined($value->{'error'})) {
4195: $hash{'error'}='Bad data';
4196: return (\%hash, $string);
4197: }
4198: } elsif($string =~ /^__ARRAY_REF__/) {
4199: ($value, $string)=&str2arrayref($string);
4200: if($value->[0] eq 'Array reference error') {
4201: $hash{'error'}='Bad data';
4202: return (\%hash, $string);
4203: }
4204: } else {
4205: $value=&get_scalar(\$string,'__END_HASH_REF__');
4206: }
4207: $string =~ s/^&//;
4208:
4209: $hash{$key}=$value;
4210: }
4211:
4212: $string =~ s/^__END_HASH_REF__//;
4213:
4214: return (\%hash, $string);
4215: }
4216:
4217: sub str2array {
4218: my ($string)=@_;
4219: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4220: return @$array;
4221: }
4222:
4223: sub str2arrayref {
4224: my ($string) = @_;
4225: my @array;
4226:
4227: if($string !~ /^__ARRAY_REF__/) {
4228: if (! ($string eq '' || !defined($string))) {
4229: $array[0]='Array reference error';
4230: }
4231: return (\@array, $string);
4232: }
4233:
4234: $string =~ s/^__ARRAY_REF__//;
4235:
4236: while($string !~ /^__END_ARRAY_REF__/) {
4237: my $value='';
4238: if($string =~ /^__HASH_REF__/) {
4239: ($value, $string)=&str2hashref($string);
4240: if(defined($value->{'error'})) {
4241: $array[0] ='Array reference error';
4242: return (\@array, $string);
4243: }
4244: } elsif($string =~ /^__ARRAY_REF__/) {
4245: ($value, $string)=&str2arrayref($string);
4246: if($value->[0] eq 'Array reference error') {
4247: $array[0] ='Array reference error';
4248: return (\@array, $string);
4249: }
4250: } else {
4251: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4252: }
4253: $string =~ s/^&//;
4254:
4255: push(@array, $value);
4256: }
4257:
4258: $string =~ s/^__END_ARRAY_REF__//;
4259:
4260: return (\@array, $string);
4261: }
4262:
4263: # -------------------------------------------------------------------Temp Store
4264:
4265: sub tmpreset {
4266: my ($symb,$namespace,$domain,$stuname) = @_;
4267: if (!$symb) {
4268: $symb=&symbread();
4269: if (!$symb) { $symb= $env{'request.url'}; }
4270: }
4271: $symb=escape($symb);
4272:
4273: if (!$namespace) { $namespace=$env{'request.state'}; }
4274: $namespace=~s/\//\_/g;
4275: $namespace=~s/\W//g;
4276:
4277: if (!$domain) { $domain=$env{'user.domain'}; }
4278: if (!$stuname) { $stuname=$env{'user.name'}; }
4279: if ($domain eq 'public' && $stuname eq 'public') {
4280: $stuname=$ENV{'REMOTE_ADDR'};
4281: }
4282: my $path=LONCAPA::tempdir();
4283: my %hash;
4284: if (tie(%hash,'GDBM_File',
4285: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4286: &GDBM_WRCREAT(),0640)) {
4287: foreach my $key (keys(%hash)) {
4288: if ($key=~ /:$symb/) {
4289: delete($hash{$key});
4290: }
4291: }
4292: }
4293: }
4294:
4295: sub tmpstore {
4296: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4297:
4298: if (!$symb) {
4299: $symb=&symbread();
4300: if (!$symb) { $symb= $env{'request.url'}; }
4301: }
4302: $symb=escape($symb);
4303:
4304: if (!$namespace) {
4305: # I don't think we would ever want to store this for a course.
4306: # it seems this will only be used if we don't have a course.
4307: #$namespace=$env{'request.course.id'};
4308: #if (!$namespace) {
4309: $namespace=$env{'request.state'};
4310: #}
4311: }
4312: $namespace=~s/\//\_/g;
4313: $namespace=~s/\W//g;
4314: if (!$domain) { $domain=$env{'user.domain'}; }
4315: if (!$stuname) { $stuname=$env{'user.name'}; }
4316: if ($domain eq 'public' && $stuname eq 'public') {
4317: $stuname=$ENV{'REMOTE_ADDR'};
4318: }
4319: my $now=time;
4320: my %hash;
4321: my $path=LONCAPA::tempdir();
4322: if (tie(%hash,'GDBM_File',
4323: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4324: &GDBM_WRCREAT(),0640)) {
4325: $hash{"version:$symb"}++;
4326: my $version=$hash{"version:$symb"};
4327: my $allkeys='';
4328: foreach my $key (keys(%$storehash)) {
4329: $allkeys.=$key.':';
4330: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
4331: }
4332: $hash{"$version:$symb:timestamp"}=$now;
4333: $allkeys.='timestamp';
4334: $hash{"$version:keys:$symb"}=$allkeys;
4335: if (untie(%hash)) {
4336: return 'ok';
4337: } else {
4338: return "error:$!";
4339: }
4340: } else {
4341: return "error:$!";
4342: }
4343: }
4344:
4345: # -----------------------------------------------------------------Temp Restore
4346:
4347: sub tmprestore {
4348: my ($symb,$namespace,$domain,$stuname) = @_;
4349:
4350: if (!$symb) {
4351: $symb=&symbread();
4352: if (!$symb) { $symb= $env{'request.url'}; }
4353: }
4354: $symb=escape($symb);
4355:
4356: if (!$namespace) { $namespace=$env{'request.state'}; }
4357:
4358: if (!$domain) { $domain=$env{'user.domain'}; }
4359: if (!$stuname) { $stuname=$env{'user.name'}; }
4360: if ($domain eq 'public' && $stuname eq 'public') {
4361: $stuname=$ENV{'REMOTE_ADDR'};
4362: }
4363: my %returnhash;
4364: $namespace=~s/\//\_/g;
4365: $namespace=~s/\W//g;
4366: my %hash;
4367: my $path=LONCAPA::tempdir();
4368: if (tie(%hash,'GDBM_File',
4369: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4370: &GDBM_READER(),0640)) {
4371: my $version=$hash{"version:$symb"};
4372: $returnhash{'version'}=$version;
4373: my $scope;
4374: for ($scope=1;$scope<=$version;$scope++) {
4375: my $vkeys=$hash{"$scope:keys:$symb"};
4376: my @keys=split(/:/,$vkeys);
4377: my $key;
4378: $returnhash{"$scope:keys"}=$vkeys;
4379: foreach $key (@keys) {
4380: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4381: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4382: }
4383: }
4384: if (!(untie(%hash))) {
4385: return "error:$!";
4386: }
4387: } else {
4388: return "error:$!";
4389: }
4390: return %returnhash;
4391: }
4392:
4393: # ----------------------------------------------------------------------- Store
4394:
4395: sub store {
4396: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4397: my $home='';
4398:
4399: if ($stuname) { $home=&homeserver($stuname,$domain); }
4400:
4401: $symb=&symbclean($symb);
4402: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4403:
4404: if (!$domain) { $domain=$env{'user.domain'}; }
4405: if (!$stuname) { $stuname=$env{'user.name'}; }
4406:
4407: &devalidate($symb,$stuname,$domain);
4408:
4409: $symb=escape($symb);
4410: if (!$namespace) {
4411: unless ($namespace=$env{'request.course.id'}) {
4412: return '';
4413: }
4414: }
4415: if (!$home) { $home=$env{'user.home'}; }
4416:
4417: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4418: $$storehash{'host'}=$perlvar{'lonHostID'};
4419:
4420: my $namevalue='';
4421: foreach my $key (keys(%$storehash)) {
4422: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4423: }
4424: $namevalue=~s/\&$//;
4425: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
4426: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4427: }
4428:
4429: # -------------------------------------------------------------- Critical Store
4430:
4431: sub cstore {
4432: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4433: my $home='';
4434:
4435: if ($stuname) { $home=&homeserver($stuname,$domain); }
4436:
4437: $symb=&symbclean($symb);
4438: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4439:
4440: if (!$domain) { $domain=$env{'user.domain'}; }
4441: if (!$stuname) { $stuname=$env{'user.name'}; }
4442:
4443: &devalidate($symb,$stuname,$domain);
4444:
4445: $symb=escape($symb);
4446: if (!$namespace) {
4447: unless ($namespace=$env{'request.course.id'}) {
4448: return '';
4449: }
4450: }
4451: if (!$home) { $home=$env{'user.home'}; }
4452:
4453: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4454: $$storehash{'host'}=$perlvar{'lonHostID'};
4455:
4456: my $namevalue='';
4457: foreach my $key (keys(%$storehash)) {
4458: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4459: }
4460: $namevalue=~s/\&$//;
4461: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
4462: return critical
4463: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4464: }
4465:
4466: # --------------------------------------------------------------------- Restore
4467:
4468: sub restore {
4469: my ($symb,$namespace,$domain,$stuname) = @_;
4470: my $home='';
4471:
4472: if ($stuname) { $home=&homeserver($stuname,$domain); }
4473:
4474: if (!$symb) {
4475: unless ($symb=escape(&symbread())) { return ''; }
4476: } else {
4477: $symb=&escape(&symbclean($symb));
4478: }
4479: if (!$namespace) {
4480: unless ($namespace=$env{'request.course.id'}) {
4481: return '';
4482: }
4483: }
4484: if (!$domain) { $domain=$env{'user.domain'}; }
4485: if (!$stuname) { $stuname=$env{'user.name'}; }
4486: if (!$home) { $home=$env{'user.home'}; }
4487: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4488:
4489: my %returnhash=();
4490: foreach my $line (split(/\&/,$answer)) {
4491: my ($name,$value)=split(/\=/,$line);
4492: $returnhash{&unescape($name)}=&thaw_unescape($value);
4493: }
4494: my $version;
4495: for ($version=1;$version<=$returnhash{'version'};$version++) {
4496: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4497: $returnhash{$item}=$returnhash{$version.':'.$item};
4498: }
4499: }
4500: return %returnhash;
4501: }
4502:
4503: # ---------------------------------------------------------- Course Description
4504: #
4505: #
4506:
4507: sub coursedescription {
4508: my ($courseid,$args)=@_;
4509: $courseid=~s/^\///;
4510: $courseid=~s/\_/\//g;
4511: my ($cdomain,$cnum)=split(/\//,$courseid);
4512: my $chome=&homeserver($cnum,$cdomain);
4513: my $normalid=$cdomain.'_'.$cnum;
4514: # need to always cache even if we get errors otherwise we keep
4515: # trying and trying and trying to get the course description.
4516: my %envhash=();
4517: my %returnhash=();
4518:
4519: my $expiretime=600;
4520: if ($env{'request.course.id'} eq $normalid) {
4521: $expiretime=120;
4522: }
4523:
4524: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4525: if (!$args->{'freshen_cache'}
4526: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4527: foreach my $key (keys(%env)) {
4528: next if ($key !~ /^\Q$prefix\E(.*)/);
4529: my ($setting) = $1;
4530: $returnhash{$setting} = $env{$key};
4531: }
4532: return %returnhash;
4533: }
4534:
4535: # get the data again
4536:
4537: if (!$args->{'one_time'}) {
4538: $envhash{'course.'.$normalid.'.last_cache'}=time;
4539: }
4540:
4541: if ($chome ne 'no_host') {
4542: %returnhash=&dump('environment',$cdomain,$cnum);
4543: if (!exists($returnhash{'con_lost'})) {
4544: my $username = $env{'user.name'}; # Defult username
4545: if(defined $args->{'user'}) {
4546: $username = $args->{'user'};
4547: }
4548: $returnhash{'home'}= $chome;
4549: $returnhash{'domain'} = $cdomain;
4550: $returnhash{'num'} = $cnum;
4551: if (!defined($returnhash{'type'})) {
4552: $returnhash{'type'} = 'Course';
4553: }
4554: while (my ($name,$value) = each %returnhash) {
4555: $envhash{'course.'.$normalid.'.'.$name}=$value;
4556: }
4557: $returnhash{'url'}=&clutter($returnhash{'url'});
4558: $returnhash{'fn'}=LONCAPA::tempdir() .
4559: $username.'_'.$cdomain.'_'.$cnum;
4560: $envhash{'course.'.$normalid.'.home'}=$chome;
4561: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4562: $envhash{'course.'.$normalid.'.num'}=$cnum;
4563: }
4564: }
4565: if (!$args->{'one_time'}) {
4566: &appenv(\%envhash);
4567: }
4568: return %returnhash;
4569: }
4570:
4571: sub update_released_required {
4572: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4573: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4574: $cid = $env{'request.course.id'};
4575: $cdom = $env{'course.'.$cid.'.domain'};
4576: $cnum = $env{'course.'.$cid.'.num'};
4577: $chome = $env{'course.'.$cid.'.home'};
4578: }
4579: if ($needsrelease) {
4580: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4581: my $needsupdate;
4582: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4583: $needsupdate = 1;
4584: } else {
4585: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4586: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4587: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4588: $needsupdate = 1;
4589: }
4590: }
4591: if ($needsupdate) {
4592: my %needshash = (
4593: 'internal.releaserequired' => $needsrelease,
4594: );
4595: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4596: if ($putresult eq 'ok') {
4597: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4598: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4599: if (ref($crsinfo{$cid}) eq 'HASH') {
4600: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4601: &courseidput($cdom,\%crsinfo,$chome,'notime');
4602: }
4603: }
4604: }
4605: }
4606: return;
4607: }
4608:
4609: # -------------------------------------------------See if a user is privileged
4610:
4611: sub privileged {
4612: my ($username,$domain)=@_;
4613:
4614: my %rolesdump = &dump("roles", $domain, $username) or return 0;
4615: my $now = time;
4616:
4617: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
4618: my ($trole, $tend, $tstart) = split(/_/, $role);
4619: if (($trole eq 'dc') || ($trole eq 'su')) {
4620: return 1 unless ($tend && $tend < $now)
4621: or ($tstart && $tstart > $now);
4622: }
4623: }
4624:
4625: return 0;
4626: }
4627:
4628: # -------------------------------------------------------- Get user privileges
4629:
4630: sub rolesinit {
4631: my ($domain, $username) = @_;
4632: my %userroles = ('user.login.time' => time);
4633: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
4634:
4635: # firstaccess and timerinterval are related to timed maps/resources.
4636: # also, blocking can be triggered by an activating timer
4637: # it's saved in the user's %env.
4638: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
4639: my %timerinterval = &dump('timerinterval', $domain, $username);
4640: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
4641: %timerintchk, %timerintenv);
4642:
4643: foreach my $key (keys(%firstaccess)) {
4644: my ($cid, $rest) = split(/\0/, $key);
4645: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
4646: }
4647:
4648: foreach my $key (keys(%timerinterval)) {
4649: my ($cid,$rest) = split(/\0/,$key);
4650: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
4651: }
4652:
4653: my %allroles=();
4654: my %allgroups=();
4655:
4656: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
4657: my $role = $rolesdump{$area};
4658: $area =~ s/\_\w\w$//;
4659:
4660: my ($trole, $tend, $tstart, $group_privs);
4661:
4662: if ($role =~ /^cr/) {
4663: # Custom role, defined by a user
4664: # e.g., user.role.cr/msu/smith/mynewrole
4665: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4666: $trole = $1;
4667: ($tend, $tstart) = split('_', $2);
4668: } else {
4669: $trole = $role;
4670: }
4671: } elsif ($role =~ m|^gr/|) {
4672: # Role of member in a group, defined within a course/community
4673: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
4674: ($trole, $tend, $tstart) = split(/_/, $role);
4675: next if $tstart eq '-1';
4676: ($trole, $group_privs) = split(/\//, $trole);
4677: $group_privs = &unescape($group_privs);
4678: } else {
4679: # Just a normal role, defined in roles.tab
4680: ($trole, $tend, $tstart) = split(/_/,$role);
4681: }
4682:
4683: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4684: $username);
4685: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
4686:
4687: # role expired or not available yet?
4688: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
4689: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
4690:
4691: next if $area eq '' or $trole eq '';
4692:
4693: my $spec = "$trole.$area";
4694: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
4695:
4696: if ($trole =~ /^cr\//) {
4697: # Custom role, defined by a user
4698: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4699: } elsif ($trole eq 'gr') {
4700: # Role of a member in a group, defined within a course/community
4701: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
4702: next;
4703: } else {
4704: # Normal role, defined in roles.tab
4705: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4706: }
4707:
4708: my $cid = $tdomain.'_'.$trest;
4709: unless ($firstaccchk{$cid}) {
4710: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
4711: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
4712: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
4713: $coursetimerstarts{$cid}{$item};
4714: }
4715: }
4716: $firstaccchk{$cid} = 1;
4717: }
4718: unless ($timerintchk{$cid}) {
4719: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
4720: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
4721: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
4722: $coursetimerintervals{$cid}{$item};
4723: }
4724: }
4725: $timerintchk{$cid} = 1;
4726: }
4727: }
4728:
4729: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
4730: \%allroles, \%allgroups);
4731: $env{'user.adv'} = $userroles{'user.adv'};
4732:
4733: return (\%userroles,\%firstaccenv,\%timerintenv);
4734: }
4735:
4736: sub set_arearole {
4737: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4738: # log the associated role with the area
4739: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
4740: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
4741: }
4742:
4743: sub custom_roleprivs {
4744: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4745: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4746: my $homsvr=homeserver($rauthor,$rdomain);
4747: if (&hostname($homsvr) ne '') {
4748: my ($rdummy,$roledef)=
4749: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4750: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4751: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4752: if (defined($syspriv)) {
4753: if ($trest =~ /^$match_community$/) {
4754: $syspriv =~ s/bre\&S//;
4755: }
4756: $$allroles{'cm./'}.=':'.$syspriv;
4757: $$allroles{$spec.'./'}.=':'.$syspriv;
4758: }
4759: if ($tdomain ne '') {
4760: if (defined($dompriv)) {
4761: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4762: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4763: }
4764: if (($trest ne '') && (defined($coursepriv))) {
4765: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4766: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4767: }
4768: }
4769: }
4770: }
4771: }
4772:
4773: sub group_roleprivs {
4774: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4775: my $access = 1;
4776: my $now = time;
4777: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4778: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4779: if ($access) {
4780: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
4781: $$allgroups{$course}{$group} .=':'.$group_privs;
4782: }
4783: }
4784:
4785: sub standard_roleprivs {
4786: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4787: if (defined($pr{$trole.':s'})) {
4788: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4789: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4790: }
4791: if ($tdomain ne '') {
4792: if (defined($pr{$trole.':d'})) {
4793: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4794: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4795: }
4796: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4797: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4798: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4799: }
4800: }
4801: }
4802:
4803: sub set_userprivs {
4804: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
4805: my $author=0;
4806: my $adv=0;
4807: my %grouproles = ();
4808: if (keys(%{$allgroups}) > 0) {
4809: my @groupkeys;
4810: foreach my $role (keys(%{$allroles})) {
4811: push(@groupkeys,$role);
4812: }
4813: if (ref($groups_roles) eq 'HASH') {
4814: foreach my $key (keys(%{$groups_roles})) {
4815: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4816: push(@groupkeys,$key);
4817: }
4818: }
4819: }
4820: if (@groupkeys > 0) {
4821: foreach my $role (@groupkeys) {
4822: my ($trole,$area,$sec,$extendedarea);
4823: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4824: $trole = $1;
4825: $area = $2;
4826: $sec = $3;
4827: $extendedarea = $area.$sec;
4828: if (exists($$allgroups{$area})) {
4829: foreach my $group (keys(%{$$allgroups{$area}})) {
4830: my $spec = $trole.'.'.$extendedarea;
4831: $grouproles{$spec.'.'.$area.'/'.$group} =
4832: $$allgroups{$area}{$group};
4833: }
4834: }
4835: }
4836: }
4837: }
4838: }
4839: foreach my $group (keys(%grouproles)) {
4840: $$allroles{$group} = $grouproles{$group};
4841: }
4842: foreach my $role (keys(%{$allroles})) {
4843: my %thesepriv;
4844: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
4845: foreach my $item (split(/:/,$$allroles{$role})) {
4846: if ($item ne '') {
4847: my ($privilege,$restrictions)=split(/&/,$item);
4848: if ($restrictions eq '') {
4849: $thesepriv{$privilege}='F';
4850: } elsif ($thesepriv{$privilege} ne 'F') {
4851: $thesepriv{$privilege}.=$restrictions;
4852: }
4853: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4854: }
4855: }
4856: my $thesestr='';
4857: foreach my $priv (sort(keys(%thesepriv))) {
4858: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4859: }
4860: $userroles->{'user.priv.'.$role} = $thesestr;
4861: }
4862: return ($author,$adv);
4863: }
4864:
4865: sub role_status {
4866: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
4867: my @pwhere = ();
4868: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4869: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4870: unless (!defined($$role) || $$role eq '') {
4871: $$where=join('.',@pwhere);
4872: $$trolecode=$$role.'.'.$$where;
4873: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4874: $$tstatus='is';
4875: if ($$tstart && $$tstart>$update) {
4876: $$tstatus='future';
4877: if ($$tstart<$now) {
4878: if ($$tstart && $$tstart>$refresh) {
4879: if (($$where ne '') && ($$role ne '')) {
4880: my (%allroles,%allgroups,$group_privs,
4881: %groups_roles,@rolecodes);
4882: my %userroles = (
4883: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4884: );
4885: @rolecodes = ('cm');
4886: my $spec=$$role.'.'.$$where;
4887: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4888: if ($$role =~ /^cr\//) {
4889: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
4890: push(@rolecodes,'cr');
4891: } elsif ($$role eq 'gr') {
4892: push(@rolecodes,$$role);
4893: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4894: $env{'user.name'});
4895: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
4896: (undef,my $group_privs) = split(/\//,$trole);
4897: $group_privs = &unescape($group_privs);
4898: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
4899: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4900: &get_groups_roles($tdomain,$trest,
4901: \%course_roles,\@rolecodes,
4902: \%groups_roles);
4903: } else {
4904: push(@rolecodes,$$role);
4905: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4906: }
4907: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4908: &appenv(\%userroles,\@rolecodes);
4909: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4910: }
4911: }
4912: $$tstatus = 'is';
4913: }
4914: }
4915: if ($$tend) {
4916: if ($$tend<$update) {
4917: $$tstatus='expired';
4918: } elsif ($$tend<$now) {
4919: $$tstatus='will_not';
4920: }
4921: }
4922: }
4923: }
4924: }
4925:
4926: sub get_groups_roles {
4927: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
4928: return unless((ref($cdom_courseroles) eq 'HASH') &&
4929: (ref($rolecodes) eq 'ARRAY') &&
4930: (ref($groups_roles) eq 'HASH'));
4931: if (keys(%{$cdom_courseroles}) > 0) {
4932: my ($cnum) = ($rest =~ /^($match_courseid)/);
4933: if ($cdom ne '' && $cnum ne '') {
4934: foreach my $key (keys(%{$cdom_courseroles})) {
4935: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
4936: my $crsrole = $1;
4937: my $crssec = $2;
4938: if ($crsrole =~ /^cr/) {
4939: unless (grep(/^cr$/,@{$rolecodes})) {
4940: push(@{$rolecodes},'cr');
4941: }
4942: } else {
4943: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
4944: push(@{$rolecodes},$crsrole);
4945: }
4946: }
4947: my $rolekey = "$crsrole./$cdom/$cnum";
4948: if ($crssec ne '') {
4949: $rolekey .= "/$crssec";
4950: }
4951: $rolekey .= './';
4952: $groups_roles->{$rolekey} = $rolecodes;
4953: }
4954: }
4955: }
4956: }
4957: return;
4958: }
4959:
4960: sub delete_env_groupprivs {
4961: my ($where,$courseroles,$possroles) = @_;
4962: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
4963: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
4964: unless (ref($courseroles->{$udom}) eq 'HASH') {
4965: %{$courseroles->{$udom}} =
4966: &get_my_roles('','','userroles',['active'],
4967: $possroles,[$udom],1);
4968: }
4969: if (ref($courseroles->{$udom}) eq 'HASH') {
4970: foreach my $item (keys(%{$courseroles->{$udom}})) {
4971: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
4972: my $area = '/'.$cdom.'/'.$cnum;
4973: my $privkey = "user.priv.$crsrole.$area";
4974: if ($crssec ne '') {
4975: $privkey .= '/'.$crssec;
4976: }
4977: $privkey .= ".$area/$group";
4978: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
4979: }
4980: }
4981: return;
4982: }
4983:
4984: sub check_adhoc_privs {
4985: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
4986: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4987: if ($env{$cckey}) {
4988: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
4989: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
4990: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
4991: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
4992: }
4993: } else {
4994: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
4995: }
4996: }
4997:
4998: sub set_adhoc_privileges {
4999: # role can be cc or ca
5000: my ($dcdom,$pickedcourse,$role,$caller) = @_;
5001: my $area = '/'.$dcdom.'/'.$pickedcourse;
5002: my $spec = $role.'.'.$area;
5003: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
5004: $env{'user.name'});
5005: my %ccrole = ();
5006: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5007: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5008: &appenv(\%userroles,[$role,'cm']);
5009: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5010: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5011: &appenv( {'request.role' => $spec,
5012: 'request.role.domain' => $dcdom,
5013: 'request.course.sec' => ''
5014: }
5015: );
5016: my $tadv=0;
5017: if (&allowed('adv') eq 'F') { $tadv=1; }
5018: &appenv({'request.role.adv' => $tadv});
5019: }
5020: }
5021:
5022: # --------------------------------------------------------------- get interface
5023:
5024: sub get {
5025: my ($namespace,$storearr,$udomain,$uname)=@_;
5026: my $items='';
5027: foreach my $item (@$storearr) {
5028: $items.=&escape($item).'&';
5029: }
5030: $items=~s/\&$//;
5031: if (!$udomain) { $udomain=$env{'user.domain'}; }
5032: if (!$uname) { $uname=$env{'user.name'}; }
5033: my $uhome=&homeserver($uname,$udomain);
5034:
5035: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
5036: my @pairs=split(/\&/,$rep);
5037: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5038: return @pairs;
5039: }
5040: my %returnhash=();
5041: my $i=0;
5042: foreach my $item (@$storearr) {
5043: $returnhash{$item}=&thaw_unescape($pairs[$i]);
5044: $i++;
5045: }
5046: return %returnhash;
5047: }
5048:
5049: # --------------------------------------------------------------- del interface
5050:
5051: sub del {
5052: my ($namespace,$storearr,$udomain,$uname)=@_;
5053: my $items='';
5054: foreach my $item (@$storearr) {
5055: $items.=&escape($item).'&';
5056: }
5057:
5058: $items=~s/\&$//;
5059: if (!$udomain) { $udomain=$env{'user.domain'}; }
5060: if (!$uname) { $uname=$env{'user.name'}; }
5061: my $uhome=&homeserver($uname,$udomain);
5062: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
5063: }
5064:
5065: # -------------------------------------------------------------- dump interface
5066:
5067: sub dump {
5068: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
5069: if (!$udomain) { $udomain=$env{'user.domain'}; }
5070: if (!$uname) { $uname=$env{'user.name'}; }
5071: my $uhome=&homeserver($uname,$udomain);
5072:
5073: if ($regexp) {
5074: $regexp=&escape($regexp);
5075: } else {
5076: $regexp='.';
5077: }
5078: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
5079: my @pairs=split(/\&/,$rep);
5080: my %returnhash=();
5081: if (!($rep =~ /^error/ )) {
5082: foreach my $item (@pairs) {
5083: my ($key,$value)=split(/=/,$item,2);
5084: $key = &unescape($key);
5085: next if ($key =~ /^error: 2 /);
5086: $returnhash{$key}=&thaw_unescape($value);
5087: }
5088: }
5089: return %returnhash;
5090: }
5091:
5092:
5093: # --------------------------------------------------------- dumpstore interface
5094:
5095: sub dumpstore {
5096: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
5097: if (!$udomain) { $udomain=$env{'user.domain'}; }
5098: if (!$uname) { $uname=$env{'user.name'}; }
5099: my $uhome=&homeserver($uname,$udomain);
5100: if ($regexp) {
5101: $regexp=&escape($regexp);
5102: } else {
5103: $regexp='.';
5104: }
5105: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
5106: my @pairs=split(/\&/,$rep);
5107: my %returnhash=();
5108: foreach my $item (@pairs) {
5109: my ($key,$value)=split(/=/,$item,2);
5110: next if ($key =~ /^error: 2 /);
5111: $returnhash{$key}=&thaw_unescape($value);
5112: }
5113: return %returnhash;
5114: }
5115:
5116: # -------------------------------------------------------------- keys interface
5117:
5118: sub getkeys {
5119: my ($namespace,$udomain,$uname)=@_;
5120: if (!$udomain) { $udomain=$env{'user.domain'}; }
5121: if (!$uname) { $uname=$env{'user.name'}; }
5122: my $uhome=&homeserver($uname,$udomain);
5123: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5124: my @keyarray=();
5125: foreach my $key (split(/\&/,$rep)) {
5126: next if ($key =~ /^error: 2 /);
5127: push(@keyarray,&unescape($key));
5128: }
5129: return @keyarray;
5130: }
5131:
5132: # --------------------------------------------------------------- currentdump
5133: sub currentdump {
5134: my ($courseid,$sdom,$sname)=@_;
5135: $courseid = $env{'request.course.id'} if (! defined($courseid));
5136: $sdom = $env{'user.domain'} if (! defined($sdom));
5137: $sname = $env{'user.name'} if (! defined($sname));
5138: my $uhome = &homeserver($sname,$sdom);
5139: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5140: return if ($rep =~ /^(error:|no_such_host)/);
5141: #
5142: my %returnhash=();
5143: #
5144: if ($rep eq "unknown_cmd") {
5145: # an old lond will not know currentdump
5146: # Do a dump and make it look like a currentdump
5147: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
5148: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5149: my %hash = @tmp;
5150: @tmp=();
5151: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
5152: } else {
5153: my @pairs=split(/\&/,$rep);
5154: foreach my $pair (@pairs) {
5155: my ($key,$value)=split(/=/,$pair,2);
5156: my ($symb,$param) = split(/:/,$key);
5157: $returnhash{&unescape($symb)}->{&unescape($param)} =
5158: &thaw_unescape($value);
5159: }
5160: }
5161: return %returnhash;
5162: }
5163:
5164: sub convert_dump_to_currentdump{
5165: my %hash = %{shift()};
5166: my %returnhash;
5167: # Code ripped from lond, essentially. The only difference
5168: # here is the unescaping done by lonnet::dump(). Conceivably
5169: # we might run in to problems with parameter names =~ /^v\./
5170: while (my ($key,$value) = each(%hash)) {
5171: my ($v,$symb,$param) = split(/:/,$key);
5172: $symb = &unescape($symb);
5173: $param = &unescape($param);
5174: next if ($v eq 'version' || $symb eq 'keys');
5175: next if (exists($returnhash{$symb}) &&
5176: exists($returnhash{$symb}->{$param}) &&
5177: $returnhash{$symb}->{'v.'.$param} > $v);
5178: $returnhash{$symb}->{$param}=$value;
5179: $returnhash{$symb}->{'v.'.$param}=$v;
5180: }
5181: #
5182: # Remove all of the keys in the hashes which keep track of
5183: # the version of the parameter.
5184: while (my ($symb,$param_hash) = each(%returnhash)) {
5185: # use a foreach because we are going to delete from the hash.
5186: foreach my $key (keys(%$param_hash)) {
5187: delete($param_hash->{$key}) if ($key =~ /^v\./);
5188: }
5189: }
5190: return \%returnhash;
5191: }
5192:
5193: # ------------------------------------------------------ critical inc interface
5194:
5195: sub cinc {
5196: return &inc(@_,'critical');
5197: }
5198:
5199: # --------------------------------------------------------------- inc interface
5200:
5201: sub inc {
5202: my ($namespace,$store,$udomain,$uname,$critical) = @_;
5203: if (!$udomain) { $udomain=$env{'user.domain'}; }
5204: if (!$uname) { $uname=$env{'user.name'}; }
5205: my $uhome=&homeserver($uname,$udomain);
5206: my $items='';
5207: if (! ref($store)) {
5208: # got a single value, so use that instead
5209: $items = &escape($store).'=&';
5210: } elsif (ref($store) eq 'SCALAR') {
5211: $items = &escape($$store).'=&';
5212: } elsif (ref($store) eq 'ARRAY') {
5213: $items = join('=&',map {&escape($_);} @{$store});
5214: } elsif (ref($store) eq 'HASH') {
5215: while (my($key,$value) = each(%{$store})) {
5216: $items.= &escape($key).'='.&escape($value).'&';
5217: }
5218: }
5219: $items=~s/\&$//;
5220: if ($critical) {
5221: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5222: } else {
5223: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5224: }
5225: }
5226:
5227: # --------------------------------------------------------------- put interface
5228:
5229: sub put {
5230: my ($namespace,$storehash,$udomain,$uname)=@_;
5231: if (!$udomain) { $udomain=$env{'user.domain'}; }
5232: if (!$uname) { $uname=$env{'user.name'}; }
5233: my $uhome=&homeserver($uname,$udomain);
5234: my $items='';
5235: foreach my $item (keys(%$storehash)) {
5236: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5237: }
5238: $items=~s/\&$//;
5239: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
5240: }
5241:
5242: # ------------------------------------------------------------ newput interface
5243:
5244: sub newput {
5245: my ($namespace,$storehash,$udomain,$uname)=@_;
5246: if (!$udomain) { $udomain=$env{'user.domain'}; }
5247: if (!$uname) { $uname=$env{'user.name'}; }
5248: my $uhome=&homeserver($uname,$udomain);
5249: my $items='';
5250: foreach my $key (keys(%$storehash)) {
5251: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5252: }
5253: $items=~s/\&$//;
5254: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5255: }
5256:
5257: # --------------------------------------------------------- putstore interface
5258:
5259: sub putstore {
5260: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5261: if (!$udomain) { $udomain=$env{'user.domain'}; }
5262: if (!$uname) { $uname=$env{'user.name'}; }
5263: my $uhome=&homeserver($uname,$udomain);
5264: my $items='';
5265: foreach my $key (keys(%$storehash)) {
5266: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
5267: }
5268: $items=~s/\&$//;
5269: my $esc_symb=&escape($symb);
5270: my $esc_v=&escape($version);
5271: my $reply =
5272: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
5273: $uhome);
5274: if ($reply eq 'unknown_cmd') {
5275: # gfall back to way things use to be done
5276: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5277: $uname);
5278: }
5279: return $reply;
5280: }
5281:
5282: sub old_putstore {
5283: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5284: if (!$udomain) { $udomain=$env{'user.domain'}; }
5285: if (!$uname) { $uname=$env{'user.name'}; }
5286: my $uhome=&homeserver($uname,$udomain);
5287: my %newstorehash;
5288: foreach my $item (keys(%$storehash)) {
5289: my $key = $version.':'.&escape($symb).':'.$item;
5290: $newstorehash{$key} = $storehash->{$item};
5291: }
5292: my $items='';
5293: my %allitems = ();
5294: foreach my $item (keys(%newstorehash)) {
5295: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
5296: my $key = $1.':keys:'.$2;
5297: $allitems{$key} .= $3.':';
5298: }
5299: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
5300: }
5301: foreach my $item (keys(%allitems)) {
5302: $allitems{$item} =~ s/\:$//;
5303: $items.= $item.'='.$allitems{$item}.'&';
5304: }
5305: $items=~s/\&$//;
5306: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
5307: }
5308:
5309: # ------------------------------------------------------ critical put interface
5310:
5311: sub cput {
5312: my ($namespace,$storehash,$udomain,$uname)=@_;
5313: if (!$udomain) { $udomain=$env{'user.domain'}; }
5314: if (!$uname) { $uname=$env{'user.name'}; }
5315: my $uhome=&homeserver($uname,$udomain);
5316: my $items='';
5317: foreach my $item (keys(%$storehash)) {
5318: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5319: }
5320: $items=~s/\&$//;
5321: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
5322: }
5323:
5324: # -------------------------------------------------------------- eget interface
5325:
5326: sub eget {
5327: my ($namespace,$storearr,$udomain,$uname)=@_;
5328: my $items='';
5329: foreach my $item (@$storearr) {
5330: $items.=&escape($item).'&';
5331: }
5332: $items=~s/\&$//;
5333: if (!$udomain) { $udomain=$env{'user.domain'}; }
5334: if (!$uname) { $uname=$env{'user.name'}; }
5335: my $uhome=&homeserver($uname,$udomain);
5336: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
5337: my @pairs=split(/\&/,$rep);
5338: my %returnhash=();
5339: my $i=0;
5340: foreach my $item (@$storearr) {
5341: $returnhash{$item}=&thaw_unescape($pairs[$i]);
5342: $i++;
5343: }
5344: return %returnhash;
5345: }
5346:
5347: # ------------------------------------------------------------ tmpput interface
5348: sub tmpput {
5349: my ($storehash,$server,$context)=@_;
5350: my $items='';
5351: foreach my $item (keys(%$storehash)) {
5352: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5353: }
5354: $items=~s/\&$//;
5355: if (defined($context)) {
5356: $items .= ':'.&escape($context);
5357: }
5358: return &reply("tmpput:$items",$server);
5359: }
5360:
5361: # ------------------------------------------------------------ tmpget interface
5362: sub tmpget {
5363: my ($token,$server)=@_;
5364: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5365: my $rep=&reply("tmpget:$token",$server);
5366: my %returnhash;
5367: foreach my $item (split(/\&/,$rep)) {
5368: my ($key,$value)=split(/=/,$item);
5369: next if ($key =~ /^error: 2 /);
5370: $returnhash{&unescape($key)}=&thaw_unescape($value);
5371: }
5372: return %returnhash;
5373: }
5374:
5375: # ------------------------------------------------------------ tmpdel interface
5376: sub tmpdel {
5377: my ($token,$server)=@_;
5378: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5379: return &reply("tmpdel:$token",$server);
5380: }
5381:
5382: # -------------------------------------------------- portfolio access checking
5383:
5384: sub portfolio_access {
5385: my ($requrl) = @_;
5386: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5387: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
5388: if ($result) {
5389: my %setters;
5390: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5391: my ($startblock,$endblock) =
5392: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5393: if ($startblock && $endblock) {
5394: return 'B';
5395: }
5396: } else {
5397: my ($startblock,$endblock) =
5398: &Apache::loncommon::blockcheck(\%setters,'port');
5399: if ($startblock && $endblock) {
5400: return 'B';
5401: }
5402: }
5403: }
5404: if ($result eq 'ok') {
5405: return 'F';
5406: } elsif ($result =~ /^[^:]+:guest_/) {
5407: return 'A';
5408: }
5409: return '';
5410: }
5411:
5412: sub get_portfolio_access {
5413: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5414:
5415: if (!ref($access_hash)) {
5416: my $current_perms = &get_portfile_permissions($udom,$unum);
5417: my %access_controls = &get_access_controls($current_perms,$group,
5418: $file_name);
5419: $access_hash = $access_controls{$file_name};
5420: }
5421:
5422: my ($public,$guest,@domains,@users,@courses,@groups);
5423: my $now = time;
5424: if (ref($access_hash) eq 'HASH') {
5425: foreach my $key (keys(%{$access_hash})) {
5426: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5427: if ($start > $now) {
5428: next;
5429: }
5430: if ($end && $end<$now) {
5431: next;
5432: }
5433: if ($scope eq 'public') {
5434: $public = $key;
5435: last;
5436: } elsif ($scope eq 'guest') {
5437: $guest = $key;
5438: } elsif ($scope eq 'domains') {
5439: push(@domains,$key);
5440: } elsif ($scope eq 'users') {
5441: push(@users,$key);
5442: } elsif ($scope eq 'course') {
5443: push(@courses,$key);
5444: } elsif ($scope eq 'group') {
5445: push(@groups,$key);
5446: }
5447: }
5448: if ($public) {
5449: return 'ok';
5450: }
5451: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5452: if ($guest) {
5453: return $guest;
5454: }
5455: } else {
5456: if (@domains > 0) {
5457: foreach my $domkey (@domains) {
5458: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
5459: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
5460: return 'ok';
5461: }
5462: }
5463: }
5464: }
5465: if (@users > 0) {
5466: foreach my $userkey (@users) {
5467: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
5468: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
5469: if (ref($item) eq 'HASH') {
5470: if (($item->{'uname'} eq $env{'user.name'}) &&
5471: ($item->{'udom'} eq $env{'user.domain'})) {
5472: return 'ok';
5473: }
5474: }
5475: }
5476: }
5477: }
5478: }
5479: my %roleshash;
5480: my @courses_and_groups = @courses;
5481: push(@courses_and_groups,@groups);
5482: if (@courses_and_groups > 0) {
5483: my (%allgroups,%allroles);
5484: my ($start,$end,$role,$sec,$group);
5485: foreach my $envkey (%env) {
5486: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
5487: my $cid = $2.'_'.$3;
5488: if ($1 eq 'gr') {
5489: $group = $4;
5490: $allgroups{$cid}{$group} = $env{$envkey};
5491: } else {
5492: if ($4 eq '') {
5493: $sec = 'none';
5494: } else {
5495: $sec = $4;
5496: }
5497: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5498: }
5499: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
5500: my $cid = $2.'_'.$3;
5501: if ($4 eq '') {
5502: $sec = 'none';
5503: } else {
5504: $sec = $4;
5505: }
5506: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5507: }
5508: }
5509: if (keys(%allroles) == 0) {
5510: return;
5511: }
5512: foreach my $key (@courses_and_groups) {
5513: my %content = %{$$access_hash{$key}};
5514: my $cnum = $content{'number'};
5515: my $cdom = $content{'domain'};
5516: my $cid = $cdom.'_'.$cnum;
5517: if (!exists($allroles{$cid})) {
5518: next;
5519: }
5520: foreach my $role_id (keys(%{$content{'roles'}})) {
5521: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5522: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5523: my @status = @{$content{'roles'}{$role_id}{'access'}};
5524: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5525: foreach my $role (keys(%{$allroles{$cid}})) {
5526: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5527: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5528: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5529: if (grep/^all$/,@sections) {
5530: return 'ok';
5531: } else {
5532: if (grep/^$sec$/,@sections) {
5533: return 'ok';
5534: }
5535: }
5536: }
5537: }
5538: if (keys(%{$allgroups{$cid}}) == 0) {
5539: if (grep/^none$/,@groups) {
5540: return 'ok';
5541: }
5542: } else {
5543: if (grep/^all$/,@groups) {
5544: return 'ok';
5545: }
5546: foreach my $group (keys(%{$allgroups{$cid}})) {
5547: if (grep/^$group$/,@groups) {
5548: return 'ok';
5549: }
5550: }
5551: }
5552: }
5553: }
5554: }
5555: }
5556: }
5557: if ($guest) {
5558: return $guest;
5559: }
5560: }
5561: }
5562: return;
5563: }
5564:
5565: sub course_group_datechecker {
5566: my ($dates,$now,$status) = @_;
5567: my ($start,$end) = split(/\./,$dates);
5568: if (!$start && !$end) {
5569: return 'ok';
5570: }
5571: if (grep/^active$/,@{$status}) {
5572: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5573: return 'ok';
5574: }
5575: }
5576: if (grep/^previous$/,@{$status}) {
5577: if ($end > $now ) {
5578: return 'ok';
5579: }
5580: }
5581: if (grep/^future$/,@{$status}) {
5582: if ($start > $now) {
5583: return 'ok';
5584: }
5585: }
5586: return;
5587: }
5588:
5589: sub parse_portfolio_url {
5590: my ($url) = @_;
5591:
5592: my ($type,$udom,$unum,$group,$file_name);
5593:
5594: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
5595: $type = 1;
5596: $udom = $1;
5597: $unum = $2;
5598: $file_name = $3;
5599: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
5600: $type = 2;
5601: $udom = $1;
5602: $unum = $2;
5603: $group = $3;
5604: $file_name = $3.'/'.$4;
5605: }
5606: if (wantarray) {
5607: return ($type,$udom,$unum,$file_name,$group);
5608: }
5609: return $type;
5610: }
5611:
5612: sub is_portfolio_url {
5613: my ($url) = @_;
5614: return scalar(&parse_portfolio_url($url));
5615: }
5616:
5617: sub is_portfolio_file {
5618: my ($file) = @_;
5619: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
5620: return 1;
5621: }
5622: return;
5623: }
5624:
5625: sub usertools_access {
5626: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
5627: my ($access,%tools);
5628: if ($context eq '') {
5629: $context = 'tools';
5630: }
5631: if ($context eq 'requestcourses') {
5632: %tools = (
5633: official => 1,
5634: unofficial => 1,
5635: community => 1,
5636: );
5637: } else {
5638: %tools = (
5639: aboutme => 1,
5640: blog => 1,
5641: portfolio => 1,
5642: );
5643: }
5644: return if (!defined($tools{$tool}));
5645:
5646: if ((!defined($udom)) || (!defined($uname))) {
5647: $udom = $env{'user.domain'};
5648: $uname = $env{'user.name'};
5649: }
5650:
5651: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5652: if ($action ne 'reload') {
5653: if ($context eq 'requestcourses') {
5654: return $env{'environment.canrequest.'.$tool};
5655: } else {
5656: return $env{'environment.availabletools.'.$tool};
5657: }
5658: }
5659: }
5660:
5661: my ($toolstatus,$inststatus);
5662:
5663: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5664: ($action ne 'reload')) {
5665: $toolstatus = $env{'environment.'.$context.'.'.$tool};
5666: $inststatus = $env{'environment.inststatus'};
5667: } else {
5668: if (ref($userenvref) eq 'HASH') {
5669: $toolstatus = $userenvref->{$context.'.'.$tool};
5670: $inststatus = $userenvref->{'inststatus'};
5671: } else {
5672: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5673: $toolstatus = $userenv{$context.'.'.$tool};
5674: $inststatus = $userenv{'inststatus'};
5675: }
5676: }
5677:
5678: if ($toolstatus ne '') {
5679: if ($toolstatus) {
5680: $access = 1;
5681: } else {
5682: $access = 0;
5683: }
5684: return $access;
5685: }
5686:
5687: my ($is_adv,%domdef);
5688: if (ref($is_advref) eq 'HASH') {
5689: $is_adv = $is_advref->{'is_adv'};
5690: } else {
5691: $is_adv = &is_advanced_user($udom,$uname);
5692: }
5693: if (ref($domdefref) eq 'HASH') {
5694: %domdef = %{$domdefref};
5695: } else {
5696: %domdef = &get_domain_defaults($udom);
5697: }
5698: if (ref($domdef{$tool}) eq 'HASH') {
5699: if ($is_adv) {
5700: if ($domdef{$tool}{'_LC_adv'} ne '') {
5701: if ($domdef{$tool}{'_LC_adv'}) {
5702: $access = 1;
5703: } else {
5704: $access = 0;
5705: }
5706: return $access;
5707: }
5708: }
5709: if ($inststatus ne '') {
5710: my ($hasaccess,$hasnoaccess);
5711: foreach my $affiliation (split(/:/,$inststatus)) {
5712: if ($domdef{$tool}{$affiliation} ne '') {
5713: if ($domdef{$tool}{$affiliation}) {
5714: $hasaccess = 1;
5715: } else {
5716: $hasnoaccess = 1;
5717: }
5718: }
5719: }
5720: if ($hasaccess || $hasnoaccess) {
5721: if ($hasaccess) {
5722: $access = 1;
5723: } elsif ($hasnoaccess) {
5724: $access = 0;
5725: }
5726: return $access;
5727: }
5728: } else {
5729: if ($domdef{$tool}{'default'} ne '') {
5730: if ($domdef{$tool}{'default'}) {
5731: $access = 1;
5732: } elsif ($domdef{$tool}{'default'} == 0) {
5733: $access = 0;
5734: }
5735: return $access;
5736: }
5737: }
5738: } else {
5739: if ($context eq 'tools') {
5740: $access = 1;
5741: } else {
5742: $access = 0;
5743: }
5744: return $access;
5745: }
5746: }
5747:
5748: sub is_course_owner {
5749: my ($cdom,$cnum,$udom,$uname) = @_;
5750: if (($udom eq '') || ($uname eq '')) {
5751: $udom = $env{'user.domain'};
5752: $uname = $env{'user.name'};
5753: }
5754: unless (($udom eq '') || ($uname eq '')) {
5755: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5756: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5757: return 1;
5758: } else {
5759: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5760: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5761: return 1;
5762: }
5763: }
5764: }
5765: }
5766: return;
5767: }
5768:
5769: sub is_advanced_user {
5770: my ($udom,$uname) = @_;
5771: if ($udom ne '' && $uname ne '') {
5772: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5773: if (wantarray) {
5774: return ($env{'user.adv'},$env{'user.author'});
5775: } else {
5776: return $env{'user.adv'};
5777: }
5778: }
5779: }
5780: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5781: my %allroles;
5782: my ($is_adv,$is_author);
5783: foreach my $role (keys(%roleshash)) {
5784: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5785: my $area = '/'.$tdomain.'/'.$trest;
5786: if ($sec ne '') {
5787: $area .= '/'.$sec;
5788: }
5789: if (($area ne '') && ($trole ne '')) {
5790: my $spec=$trole.'.'.$area;
5791: if ($trole =~ /^cr\//) {
5792: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5793: } elsif ($trole ne 'gr') {
5794: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5795: }
5796: if ($trole eq 'au') {
5797: $is_author = 1;
5798: }
5799: }
5800: }
5801: foreach my $role (keys(%allroles)) {
5802: last if ($is_adv);
5803: foreach my $item (split(/:/,$allroles{$role})) {
5804: if ($item ne '') {
5805: my ($privilege,$restrictions)=split(/&/,$item);
5806: if ($privilege eq 'adv') {
5807: $is_adv = 1;
5808: last;
5809: }
5810: }
5811: }
5812: }
5813: if (wantarray) {
5814: return ($is_adv,$is_author);
5815: }
5816: return $is_adv;
5817: }
5818:
5819: sub check_can_request {
5820: my ($dom,$can_request,$request_domains) = @_;
5821: my $canreq = 0;
5822: my ($types,$typename) = &Apache::loncommon::course_types();
5823: my @options = ('approval','validate','autolimit');
5824: my $optregex = join('|',@options);
5825: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5826: foreach my $type (@{$types}) {
5827: if (&usertools_access($env{'user.name'},
5828: $env{'user.domain'},
5829: $type,undef,'requestcourses')) {
5830: $canreq ++;
5831: if (ref($request_domains) eq 'HASH') {
5832: push(@{$request_domains->{$type}},$env{'user.domain'});
5833: }
5834: if ($dom eq $env{'user.domain'}) {
5835: $can_request->{$type} = 1;
5836: }
5837: }
5838: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5839: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5840: if (@curr > 0) {
5841: foreach my $item (@curr) {
5842: if (ref($request_domains) eq 'HASH') {
5843: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5844: if ($otherdom ne '') {
5845: if (ref($request_domains->{$type}) eq 'ARRAY') {
5846: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5847: push(@{$request_domains->{$type}},$otherdom);
5848: }
5849: } else {
5850: push(@{$request_domains->{$type}},$otherdom);
5851: }
5852: }
5853: }
5854: }
5855: unless($dom eq $env{'user.domain'}) {
5856: $canreq ++;
5857: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5858: $can_request->{$type} = 1;
5859: }
5860: }
5861: }
5862: }
5863: }
5864: }
5865: return $canreq;
5866: }
5867:
5868: # ---------------------------------------------- Custom access rule evaluation
5869:
5870: sub customaccess {
5871: my ($priv,$uri)=@_;
5872: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
5873: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
5874: $udom = &LONCAPA::clean_domain($udom);
5875: $ucrs = &LONCAPA::clean_username($ucrs);
5876: my $access=0;
5877: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
5878: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5879: if ($type eq 'user') {
5880: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5881: my ($tdom,$tuname)=split(m{/},$scope);
5882: if ($tdom) {
5883: if ($tdom ne $env{'user.domain'}) { next; }
5884: }
5885: if ($tuname) {
5886: if ($tuname ne $env{'user.name'}) { next; }
5887: }
5888: $access=($effect eq 'allow');
5889: last;
5890: }
5891: } else {
5892: if ($role) {
5893: if ($role ne $urole) { next; }
5894: }
5895: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5896: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5897: if ($tdom) {
5898: if ($tdom ne $udom) { next; }
5899: }
5900: if ($tcrs) {
5901: if ($tcrs ne $ucrs) { next; }
5902: }
5903: if ($tsec) {
5904: if ($tsec ne $usec) { next; }
5905: }
5906: $access=($effect eq 'allow');
5907: last;
5908: }
5909: if ($realm eq '' && $role eq '') {
5910: $access=($effect eq 'allow');
5911: }
5912: }
5913: }
5914: return $access;
5915: }
5916:
5917: # ------------------------------------------------- Check for a user privilege
5918:
5919: sub allowed {
5920: my ($priv,$uri,$symb,$role)=@_;
5921: my $ver_orguri=$uri;
5922: $uri=&deversion($uri);
5923: my $orguri=$uri;
5924: $uri=&declutter($uri);
5925:
5926: if ($priv eq 'evb') {
5927: # Evade communication block restrictions for specified role in a course
5928: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5929: return $1;
5930: } else {
5931: return;
5932: }
5933: }
5934:
5935: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
5936: # Free bre access to adm and meta resources
5937: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
5938: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5939: && ($priv eq 'bre')) {
5940: return 'F';
5941: }
5942:
5943: # Free bre access to user's own portfolio contents
5944: my ($space,$domain,$name,@dir)=split('/',$uri);
5945: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
5946: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
5947: my %setters;
5948: my ($startblock,$endblock) =
5949: &Apache::loncommon::blockcheck(\%setters,'port');
5950: if ($startblock && $endblock) {
5951: return 'B';
5952: } else {
5953: return 'F';
5954: }
5955: }
5956:
5957: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
5958: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5959: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5960: if (exists($env{'request.course.id'})) {
5961: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5962: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5963: if (($domain eq $cdom) && ($name eq $cnum)) {
5964: my $courseprivid=$env{'request.course.id'};
5965: $courseprivid=~s/\_/\//;
5966: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5967: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5968: return $1;
5969: } else {
5970: if ($env{'request.course.sec'}) {
5971: $courseprivid.='/'.$env{'request.course.sec'};
5972: }
5973: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5974: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5975: return $2;
5976: }
5977: }
5978: }
5979: }
5980: }
5981:
5982: # Free bre to public access
5983:
5984: if ($priv eq 'bre') {
5985: my $copyright=&metadata($uri,'copyright');
5986: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
5987: return 'F';
5988: }
5989: if ($copyright eq 'priv') {
5990: $uri=~/([^\/]+)\/([^\/]+)\//;
5991: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
5992: return '';
5993: }
5994: }
5995: if ($copyright eq 'domain') {
5996: $uri=~/([^\/]+)\/([^\/]+)\//;
5997: unless (($env{'user.domain'} eq $1) ||
5998: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
5999: return '';
6000: }
6001: }
6002: if ($env{'request.role'}=~ /li\.\//) {
6003: # Library role, so allow browsing of resources in this domain.
6004: return 'F';
6005: }
6006: if ($copyright eq 'custom') {
6007: unless (&customaccess($priv,$uri)) { return ''; }
6008: }
6009: }
6010: # Domain coordinator is trying to create a course
6011: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
6012: # uri is the requested domain in this case.
6013: # comparison to 'request.role.domain' shows if the user has selected
6014: # a role of dc for the domain in question.
6015: return 'F' if ($uri eq $env{'request.role.domain'});
6016: }
6017:
6018: my $thisallowed='';
6019: my $statecond=0;
6020: my $courseprivid='';
6021:
6022: my $ownaccess;
6023: # Community Coordinator or Assistant Co-author browsing resource space.
6024: if (($priv eq 'bro') && ($env{'user.author'})) {
6025: if ($uri eq '') {
6026: $ownaccess = 1;
6027: } else {
6028: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6029: my $udom = $env{'user.domain'};
6030: my $uname = $env{'user.name'};
6031: if ($uri =~ m{^\Q$udom\E/?$}) {
6032: $ownaccess = 1;
6033: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
6034: unless ($uri =~ m{\.\./}) {
6035: $ownaccess = 1;
6036: }
6037: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6038: my $now = time;
6039: if ($uri =~ m{^([^/]+)/?$}) {
6040: my $adom = $1;
6041: foreach my $key (keys(%env)) {
6042: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
6043: my ($start,$end) = split('.',$env{$key});
6044: if (($now >= $start) && (!$end || $end < $now)) {
6045: $ownaccess = 1;
6046: last;
6047: }
6048: }
6049: }
6050: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6051: my $adom = $1;
6052: my $aname = $2;
6053: foreach my $role ('ca','aa') {
6054: if ($env{"user.role.$role./$adom/$aname"}) {
6055: my ($start,$end) =
6056: split('.',$env{"user.role.$role./$adom/$aname"});
6057: if (($now >= $start) && (!$end || $end < $now)) {
6058: $ownaccess = 1;
6059: last;
6060: }
6061: }
6062: }
6063: }
6064: }
6065: }
6066: }
6067: }
6068:
6069: # Course
6070:
6071: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
6072: unless (($priv eq 'bro') && (!$ownaccess)) {
6073: $thisallowed.=$1;
6074: }
6075: }
6076:
6077: # Domain
6078:
6079: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
6080: =~/\Q$priv\E\&([^\:]*)/) {
6081: unless (($priv eq 'bro') && (!$ownaccess)) {
6082: $thisallowed.=$1;
6083: }
6084: }
6085:
6086: # User who is not author or co-author might still be able to edit
6087: # resource of an author in the domain (e.g., if Domain Coordinator).
6088: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6089: (&allowed('mdc',$env{'request.course.id'}))) {
6090: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6091: $thisallowed.=$1;
6092: }
6093: }
6094:
6095: # Course: uri itself is a course
6096: my $courseuri=$uri;
6097: $courseuri=~s/\_(\d)/\/$1/;
6098: $courseuri=~s/^([^\/])/\/$1/;
6099:
6100: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
6101: =~/\Q$priv\E\&([^\:]*)/) {
6102: unless (($priv eq 'bro') && (!$ownaccess)) {
6103: $thisallowed.=$1;
6104: }
6105: }
6106:
6107: # URI is an uploaded document for this course, default permissions don't matter
6108: # not allowing 'edit' access (editupload) to uploaded course docs
6109: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
6110: $thisallowed='';
6111: my ($match)=&is_on_map($uri);
6112: if ($match) {
6113: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6114: =~/\Q$priv\E\&([^\:]*)/) {
6115: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6116: if (@blockers > 0) {
6117: $thisallowed = 'B';
6118: } else {
6119: $thisallowed.=$1;
6120: }
6121: }
6122: } else {
6123: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
6124: if ($refuri) {
6125: if ($refuri =~ m|^/adm/|) {
6126: $thisallowed='F';
6127: } else {
6128: $refuri=&declutter($refuri);
6129: my ($match) = &is_on_map($refuri);
6130: if ($match) {
6131: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6132: if (@blockers > 0) {
6133: $thisallowed = 'B';
6134: } else {
6135: $thisallowed='F';
6136: }
6137: }
6138: }
6139: }
6140: }
6141: }
6142:
6143: if ($priv eq 'bre'
6144: && $thisallowed ne 'F'
6145: && $thisallowed ne '2'
6146: && &is_portfolio_url($uri)) {
6147: $thisallowed = &portfolio_access($uri);
6148: }
6149:
6150: # Full access at system, domain or course-wide level? Exit.
6151: if ($thisallowed=~/F/) {
6152: return 'F';
6153: }
6154:
6155: # If this is generating or modifying users, exit with special codes
6156:
6157: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6158: if (($priv eq 'cca') || ($priv eq 'caa')) {
6159: my ($audom,$auname)=split('/',$uri);
6160: # no author name given, so this just checks on the general right to make a co-author in this domain
6161: unless ($auname) { return $thisallowed; }
6162: # an author name is given, so we are about to actually make a co-author for a certain account
6163: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6164: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6165: ($audom ne $env{'request.role.domain'}))) { return ''; }
6166: }
6167: return $thisallowed;
6168: }
6169: #
6170: # Gathered so far: system, domain and course wide privileges
6171: #
6172: # Course: See if uri or referer is an individual resource that is part of
6173: # the course
6174:
6175: if ($env{'request.course.id'}) {
6176:
6177: $courseprivid=$env{'request.course.id'};
6178: if ($env{'request.course.sec'}) {
6179: $courseprivid.='/'.$env{'request.course.sec'};
6180: }
6181: $courseprivid=~s/\_/\//;
6182: my $checkreferer=1;
6183: my ($match,$cond)=&is_on_map($uri);
6184: if ($match) {
6185: $statecond=$cond;
6186: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
6187: =~/\Q$priv\E\&([^\:]*)/) {
6188: my $value = $1;
6189: if ($priv eq 'bre') {
6190: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6191: if (@blockers > 0) {
6192: $thisallowed = 'B';
6193: } else {
6194: $thisallowed.=$value;
6195: }
6196: } else {
6197: $thisallowed.=$value;
6198: }
6199: $checkreferer=0;
6200: }
6201: }
6202:
6203: if ($checkreferer) {
6204: my $refuri=$env{'httpref.'.$orguri};
6205: unless ($refuri) {
6206: foreach my $key (keys(%env)) {
6207: if ($key=~/^httpref\..*\*/) {
6208: my $pattern=$key;
6209: $pattern=~s/^httpref\.\/res\///;
6210: $pattern=~s/\*/\[\^\/\]\+/g;
6211: $pattern=~s/\//\\\//g;
6212: if ($orguri=~/$pattern/) {
6213: $refuri=$env{$key};
6214: }
6215: }
6216: }
6217: }
6218:
6219: if ($refuri) {
6220: $refuri=&declutter($refuri);
6221: my ($match,$cond)=&is_on_map($refuri);
6222: if ($match) {
6223: my $refstatecond=$cond;
6224: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
6225: =~/\Q$priv\E\&([^\:]*)/) {
6226: my $value = $1;
6227: if ($priv eq 'bre') {
6228: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6229: if (@blockers > 0) {
6230: $thisallowed = 'B';
6231: } else {
6232: $thisallowed.=$value;
6233: }
6234: } else {
6235: $thisallowed.=$value;
6236: }
6237: $uri=$refuri;
6238: $statecond=$refstatecond;
6239: }
6240: }
6241: }
6242: }
6243: }
6244:
6245: #
6246: # Gathered now: all privileges that could apply, and condition number
6247: #
6248: #
6249: # Full or no access?
6250: #
6251:
6252: if ($thisallowed=~/F/) {
6253: return 'F';
6254: }
6255:
6256: unless ($thisallowed) {
6257: return '';
6258: }
6259:
6260: # Restrictions exist, deal with them
6261: #
6262: # C:according to course preferences
6263: # R:according to resource settings
6264: # L:unless locked
6265: # X:according to user session state
6266: #
6267:
6268: # Possibly locked functionality, check all courses
6269: # Locks might take effect only after 10 minutes cache expiration for other
6270: # courses, and 2 minutes for current course
6271:
6272: my $envkey;
6273: if ($thisallowed=~/L/) {
6274: foreach $envkey (keys(%env)) {
6275: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6276: my $courseid=$2;
6277: my $roleid=$1.'.'.$2;
6278: $courseid=~s/^\///;
6279: my $expiretime=600;
6280: if ($env{'request.role'} eq $roleid) {
6281: $expiretime=120;
6282: }
6283: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6284: my $prefix='course.'.$cdom.'_'.$cnum.'.';
6285: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
6286: &coursedescription($courseid,{'freshen_cache' => 1});
6287: }
6288: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6289: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6290: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6291: &log($env{'user.domain'},$env{'user.name'},
6292: $env{'user.home'},
6293: 'Locked by res: '.$priv.' for '.$uri.' due to '.
6294: $cdom.'/'.$cnum.'/'.$csec.' expire '.
6295: $env{$prefix.'priv.'.$priv.'.lock.expire'});
6296: return '';
6297: }
6298: }
6299: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6300: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6301: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6302: &log($env{'user.domain'},$env{'user.name'},
6303: $env{'user.home'},
6304: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
6305: $cdom.'/'.$cnum.'/'.$csec.' expire '.
6306: $env{$prefix.'priv.'.$priv.'.lock.expire'});
6307: return '';
6308: }
6309: }
6310: }
6311: }
6312: }
6313:
6314: #
6315: # Rest of the restrictions depend on selected course
6316: #
6317:
6318: unless ($env{'request.course.id'}) {
6319: if ($thisallowed eq 'A') {
6320: return 'A';
6321: } elsif ($thisallowed eq 'B') {
6322: return 'B';
6323: } else {
6324: return '1';
6325: }
6326: }
6327:
6328: #
6329: # Now user is definitely in a course
6330: #
6331:
6332:
6333: # Course preferences
6334:
6335: if ($thisallowed=~/C/) {
6336: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6337: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6338: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
6339: =~/\Q$rolecode\E/) {
6340: if (($priv ne 'pch') && ($priv ne 'plc')) {
6341: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6342: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6343: $env{'request.course.id'});
6344: }
6345: return '';
6346: }
6347:
6348: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
6349: =~/\Q$unamedom\E/) {
6350: if (($priv ne 'pch') && ($priv ne 'plc')) {
6351: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6352: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6353: $env{'request.course.id'});
6354: }
6355: return '';
6356: }
6357: }
6358:
6359: # Resource preferences
6360:
6361: if ($thisallowed=~/R/) {
6362: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6363: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
6364: if (($priv ne 'pch') && ($priv ne 'plc')) {
6365: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6366: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6367: }
6368: return '';
6369: }
6370: }
6371:
6372: # Restricted by state or randomout?
6373:
6374: if ($thisallowed=~/X/) {
6375: if ($env{'acc.randomout'}) {
6376: if (!$symb) { $symb=&symbread($uri,1); }
6377: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
6378: return '';
6379: }
6380: }
6381: if (&condval($statecond)) {
6382: return '2';
6383: } else {
6384: return '';
6385: }
6386: }
6387:
6388: if ($thisallowed eq 'A') {
6389: return 'A';
6390: } elsif ($thisallowed eq 'B') {
6391: return 'B';
6392: }
6393: return 'F';
6394: }
6395:
6396: sub get_comm_blocks {
6397: my ($cdom,$cnum) = @_;
6398: if ($cdom eq '' || $cnum eq '') {
6399: return unless ($env{'request.course.id'});
6400: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6401: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6402: }
6403: my %commblocks;
6404: my $hashid=$cdom.'_'.$cnum;
6405: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
6406: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
6407: %commblocks = %{$blocksref};
6408: } else {
6409: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
6410: my $cachetime = 600;
6411: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
6412: }
6413: return %commblocks;
6414: }
6415:
6416: sub has_comm_blocking {
6417: my ($priv,$symb,$uri,$blocks) = @_;
6418: return unless ($env{'request.course.id'});
6419: return unless ($priv eq 'bre');
6420: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
6421: my %commblocks;
6422: if (ref($blocks) eq 'HASH') {
6423: %commblocks = %{$blocks};
6424: } else {
6425: %commblocks = &get_comm_blocks();
6426: }
6427: return unless (keys(%commblocks) > 0);
6428: if (!$symb) { $symb=&symbread($uri,1); }
6429: my ($map,$resid,undef)=&decode_symb($symb);
6430: my %tocheck = (
6431: maps => $map,
6432: resources => $symb,
6433: );
6434: my @blockers;
6435: my $now = time;
6436: my $navmap = Apache::lonnavmaps::navmap->new();
6437: foreach my $block (keys(%commblocks)) {
6438: if ($block =~ /^(\d+)____(\d+)$/) {
6439: my ($start,$end) = ($1,$2);
6440: if ($start <= $now && $end >= $now) {
6441: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
6442: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
6443: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
6444: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
6445: unless (grep(/^\Q$block\E$/,@blockers)) {
6446: push(@blockers,$block);
6447: }
6448: }
6449: }
6450: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
6451: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
6452: unless (grep(/^\Q$block\E$/,@blockers)) {
6453: push(@blockers,$block);
6454: }
6455: }
6456: }
6457: }
6458: }
6459: }
6460: } elsif ($block =~ /^firstaccess____(.+)$/) {
6461: my $item = $1;
6462: my @to_test;
6463: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
6464: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
6465: my $check_interval;
6466: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
6467: my @interval;
6468: my $type = 'map';
6469: if ($item eq 'course') {
6470: $type = 'course';
6471: @interval=&EXT("resource.0.interval");
6472: } else {
6473: if ($item =~ /___\d+___/) {
6474: $type = 'resource';
6475: @interval=&EXT("resource.0.interval",$item);
6476: if (ref($navmap)) {
6477: my $res = $navmap->getBySymb($item);
6478: push(@to_test,$res);
6479: }
6480: } else {
6481: my $mapsymb = &symbread($item,1);
6482: if ($mapsymb) {
6483: if (ref($navmap)) {
6484: my $mapres = $navmap->getBySymb($mapsymb);
6485: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
6486: foreach my $res (@to_test) {
6487: my $symb = $res->symb();
6488: next if ($symb eq $mapsymb);
6489: if ($symb ne '') {
6490: @interval=&EXT("resource.0.interval",$symb);
6491: last;
6492: }
6493: }
6494: }
6495: }
6496: }
6497: }
6498: if ($interval[0] =~ /\d+/) {
6499: my $first_access;
6500: if ($type eq 'resource') {
6501: $first_access=&get_first_access($interval[1],$item);
6502: } elsif ($type eq 'map') {
6503: $first_access=&get_first_access($interval[1],undef,$item);
6504: } else {
6505: $first_access=&get_first_access($interval[1]);
6506: }
6507: if ($first_access) {
6508: my $timesup = $first_access+$interval[0];
6509: if ($timesup > $now) {
6510: foreach my $res (@to_test) {
6511: if ($res->is_problem()) {
6512: if ($res->completable()) {
6513: unless (grep(/^\Q$block\E$/,@blockers)) {
6514: push(@blockers,$block);
6515: }
6516: last;
6517: }
6518: }
6519: }
6520: }
6521: }
6522: }
6523: }
6524: }
6525: }
6526: }
6527: }
6528: return @blockers;
6529: }
6530:
6531: sub check_docs_block {
6532: my ($docsblock,$tocheck) =@_;
6533: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
6534: return;
6535: }
6536: if (ref($docsblock->{'maps'}) eq 'HASH') {
6537: if ($tocheck->{'maps'}) {
6538: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
6539: return 1;
6540: }
6541: }
6542: }
6543: if (ref($docsblock->{'resources'}) eq 'HASH') {
6544: if ($tocheck->{'resources'}) {
6545: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
6546: return 1;
6547: }
6548: }
6549: }
6550: return;
6551: }
6552:
6553: #
6554: # Removes the versino from a URI and
6555: # splits it in to its filename and path to the filename.
6556: # Seems like File::Basename could have done this more clearly.
6557: # Parameters:
6558: # $uri - input URI
6559: # Returns:
6560: # Two element list consisting of
6561: # $pathname - the URI up to and excluding the trailing /
6562: # $filename - The part of the URI following the last /
6563: # NOTE:
6564: # Another realization of this is simply:
6565: # use File::Basename;
6566: # ...
6567: # $uri = shift;
6568: # $filename = basename($uri);
6569: # $path = dirname($uri);
6570: # return ($filename, $path);
6571: #
6572: # The implementation below is probably faster however.
6573: #
6574: sub split_uri_for_cond {
6575: my $uri=&deversion(&declutter(shift));
6576: my @uriparts=split(/\//,$uri);
6577: my $filename=pop(@uriparts);
6578: my $pathname=join('/',@uriparts);
6579: return ($pathname,$filename);
6580: }
6581: # --------------------------------------------------- Is a resource on the map?
6582:
6583: sub is_on_map {
6584: my ($pathname,$filename) = &split_uri_for_cond(shift);
6585: #Trying to find the conditional for the file
6586: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
6587: /\&\Q$filename\E\:([\d\|]+)\&/);
6588: if ($match) {
6589: return (1,$1);
6590: } else {
6591: return (0,0);
6592: }
6593: }
6594:
6595: # --------------------------------------------------------- Get symb from alias
6596:
6597: sub get_symb_from_alias {
6598: my $symb=shift;
6599: my ($map,$resid,$url)=&decode_symb($symb);
6600: # Already is a symb
6601: if ($url) { return $symb; }
6602: # Must be an alias
6603: my $aliassymb='';
6604: my %bighash;
6605: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6606: &GDBM_READER(),0640)) {
6607: my $rid=$bighash{'mapalias_'.$symb};
6608: if ($rid) {
6609: my ($mapid,$resid)=split(/\./,$rid);
6610: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
6611: $resid,$bighash{'src_'.$rid});
6612: }
6613: untie %bighash;
6614: }
6615: return $aliassymb;
6616: }
6617:
6618: # ----------------------------------------------------------------- Define Role
6619:
6620: sub definerole {
6621: if (allowed('mcr','/')) {
6622: my ($rolename,$sysrole,$domrole,$courole)=@_;
6623: foreach my $role (split(':',$sysrole)) {
6624: my ($crole,$cqual)=split(/\&/,$role);
6625: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
6626: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
6627: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
6628: return "refused:s:$crole&$cqual";
6629: }
6630: }
6631: }
6632: foreach my $role (split(':',$domrole)) {
6633: my ($crole,$cqual)=split(/\&/,$role);
6634: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
6635: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
6636: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
6637: return "refused:d:$crole&$cqual";
6638: }
6639: }
6640: }
6641: foreach my $role (split(':',$courole)) {
6642: my ($crole,$cqual)=split(/\&/,$role);
6643: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
6644: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
6645: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
6646: return "refused:c:$crole&$cqual";
6647: }
6648: }
6649: }
6650: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
6651: "$env{'user.domain'}:$env{'user.name'}:".
6652: "rolesdef_$rolename=".
6653: escape($sysrole.'_'.$domrole.'_'.$courole);
6654: return reply($command,$env{'user.home'});
6655: } else {
6656: return 'refused';
6657: }
6658: }
6659:
6660: # ---------------- Make a metadata query against the network of library servers
6661:
6662: sub metadata_query {
6663: my ($query,$custom,$customshow,$server_array)=@_;
6664: my %rhash;
6665: my %libserv = &all_library();
6666: my @server_list = (defined($server_array) ? @$server_array
6667: : keys(%libserv) );
6668: for my $server (@server_list) {
6669: unless ($custom or $customshow) {
6670: my $reply=&reply("querysend:".&escape($query),$server);
6671: $rhash{$server}=$reply;
6672: }
6673: else {
6674: my $reply=&reply("querysend:".&escape($query).':'.
6675: &escape($custom).':'.&escape($customshow),
6676: $server);
6677: $rhash{$server}=$reply;
6678: }
6679: }
6680: return \%rhash;
6681: }
6682:
6683: # ----------------------------------------- Send log queries and wait for reply
6684:
6685: sub log_query {
6686: my ($uname,$udom,$query,%filters)=@_;
6687: my $uhome=&homeserver($uname,$udom);
6688: if ($uhome eq 'no_host') { return 'error: no_host'; }
6689: my $uhost=&hostname($uhome);
6690: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
6691: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
6692: $uhome);
6693: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
6694: return get_query_reply($queryid);
6695: }
6696:
6697: # -------------------------- Update MySQL table for portfolio file
6698:
6699: sub update_portfolio_table {
6700: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
6701: if ($group ne '') {
6702: $file_name =~s /^\Q$group\E//;
6703: }
6704: my $homeserver = &homeserver($uname,$udom);
6705: my $queryid=
6706: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
6707: ':'.&escape($file_name).':'.$action,$homeserver);
6708: my $reply = &get_query_reply($queryid);
6709: return $reply;
6710: }
6711:
6712: # -------------------------- Update MySQL allusers table
6713:
6714: sub update_allusers_table {
6715: my ($uname,$udom,$names) = @_;
6716: my $homeserver = &homeserver($uname,$udom);
6717: my $queryid=
6718: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
6719: 'lastname='.&escape($names->{'lastname'}).'%%'.
6720: 'firstname='.&escape($names->{'firstname'}).'%%'.
6721: 'middlename='.&escape($names->{'middlename'}).'%%'.
6722: 'generation='.&escape($names->{'generation'}).'%%'.
6723: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
6724: 'id='.&escape($names->{'id'}),$homeserver);
6725: return;
6726: }
6727:
6728: # ------- Request retrieval of institutional classlists for course(s)
6729:
6730: sub fetch_enrollment_query {
6731: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
6732: my $homeserver;
6733: my $maxtries = 1;
6734: if ($context eq 'automated') {
6735: $homeserver = $perlvar{'lonHostID'};
6736: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
6737: } else {
6738: $homeserver = &homeserver($cnum,$dom);
6739: }
6740: my $host=&hostname($homeserver);
6741: my $cmd = '';
6742: foreach my $affiliate (keys(%{$affiliatesref})) {
6743: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
6744: }
6745: $cmd =~ s/%%$//;
6746: $cmd = &escape($cmd);
6747: my $query = 'fetchenrollment';
6748: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
6749: unless ($queryid=~/^\Q$host\E\_/) {
6750: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
6751: return 'error: '.$queryid;
6752: }
6753: my $reply = &get_query_reply($queryid);
6754: my $tries = 1;
6755: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6756: $reply = &get_query_reply($queryid);
6757: $tries ++;
6758: }
6759: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6760: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6761: } else {
6762: my @responses = split(/:/,$reply);
6763: if ($homeserver eq $perlvar{'lonHostID'}) {
6764: foreach my $line (@responses) {
6765: my ($key,$value) = split(/=/,$line,2);
6766: $$replyref{$key} = $value;
6767: }
6768: } else {
6769: my $pathname = LONCAPA::tempdir();
6770: foreach my $line (@responses) {
6771: my ($key,$value) = split(/=/,$line);
6772: $$replyref{$key} = $value;
6773: if ($value > 0) {
6774: foreach my $item (@{$$affiliatesref{$key}}) {
6775: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
6776: my $destname = $pathname.'/'.$filename;
6777: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
6778: if ($xml_classlist =~ /^error/) {
6779: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6780: } else {
6781: if ( open(FILE,">$destname") ) {
6782: print FILE &unescape($xml_classlist);
6783: close(FILE);
6784: } else {
6785: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
6786: }
6787: }
6788: }
6789: }
6790: }
6791: }
6792: return 'ok';
6793: }
6794: return 'error';
6795: }
6796:
6797: sub get_query_reply {
6798: my $queryid=shift;
6799: my $replyfile=LONCAPA::tempdir().$queryid;
6800: my $reply='';
6801: for (1..100) {
6802: sleep 2;
6803: if (-e $replyfile.'.end') {
6804: if (open(my $fh,$replyfile)) {
6805: $reply = join('',<$fh>);
6806: close($fh);
6807: } else { return 'error: reply_file_error'; }
6808: return &unescape($reply);
6809: }
6810: }
6811: return 'timeout:'.$queryid;
6812: }
6813:
6814: sub courselog_query {
6815: #
6816: # possible filters:
6817: # url: url or symb
6818: # username
6819: # domain
6820: # action: view, submit, grade
6821: # start: timestamp
6822: # end: timestamp
6823: #
6824: my (%filters)=@_;
6825: unless ($env{'request.course.id'}) { return 'no_course'; }
6826: if ($filters{'url'}) {
6827: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6828: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6829: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6830: }
6831: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6832: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6833: return &log_query($cname,$cdom,'courselog',%filters);
6834: }
6835:
6836: sub userlog_query {
6837: #
6838: # possible filters:
6839: # action: log check role
6840: # start: timestamp
6841: # end: timestamp
6842: #
6843: my ($uname,$udom,%filters)=@_;
6844: return &log_query($uname,$udom,'userlog',%filters);
6845: }
6846:
6847: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6848:
6849: sub auto_run {
6850: my ($cnum,$cdom) = @_;
6851: my $response = 0;
6852: my $settings;
6853: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6854: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6855: $settings = $domconfig{'autoenroll'};
6856: if ($settings->{'run'} eq '1') {
6857: $response = 1;
6858: }
6859: } else {
6860: my $homeserver;
6861: if (&is_course($cdom,$cnum)) {
6862: $homeserver = &homeserver($cnum,$cdom);
6863: } else {
6864: $homeserver = &domain($cdom,'primary');
6865: }
6866: if ($homeserver ne 'no_host') {
6867: $response = &reply('autorun:'.$cdom,$homeserver);
6868: }
6869: }
6870: return $response;
6871: }
6872:
6873: sub auto_get_sections {
6874: my ($cnum,$cdom,$inst_coursecode) = @_;
6875: my $homeserver;
6876: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6877: $homeserver = &homeserver($cnum,$cdom);
6878: }
6879: if (!defined($homeserver)) {
6880: if ($cdom =~ /^$match_domain$/) {
6881: $homeserver = &domain($cdom,'primary');
6882: }
6883: }
6884: my @secs;
6885: if (defined($homeserver)) {
6886: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6887: unless ($response eq 'refused') {
6888: @secs = split(/:/,$response);
6889: }
6890: }
6891: return @secs;
6892: }
6893:
6894: sub auto_new_course {
6895: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
6896: my $homeserver = &homeserver($cnum,$cdom);
6897: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
6898: return $response;
6899: }
6900:
6901: sub auto_validate_courseID {
6902: my ($cnum,$cdom,$inst_course_id) = @_;
6903: my $homeserver = &homeserver($cnum,$cdom);
6904: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
6905: return $response;
6906: }
6907:
6908: sub auto_validate_instcode {
6909: my ($cnum,$cdom,$instcode,$owner) = @_;
6910: my ($homeserver,$response);
6911: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6912: $homeserver = &homeserver($cnum,$cdom);
6913: }
6914: if (!defined($homeserver)) {
6915: if ($cdom =~ /^$match_domain$/) {
6916: $homeserver = &domain($cdom,'primary');
6917: }
6918: }
6919: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6920: &escape($instcode).':'.&escape($owner),$homeserver));
6921: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6922: return ($outcome,$description);
6923: }
6924:
6925: sub auto_create_password {
6926: my ($cnum,$cdom,$authparam,$udom) = @_;
6927: my ($homeserver,$response);
6928: my $create_passwd = 0;
6929: my $authchk = '';
6930: if ($udom =~ /^$match_domain$/) {
6931: $homeserver = &domain($udom,'primary');
6932: }
6933: if ($homeserver eq '') {
6934: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6935: $homeserver = &homeserver($cnum,$cdom);
6936: }
6937: }
6938: if ($homeserver eq '') {
6939: $authchk = 'nodomain';
6940: } else {
6941: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6942: if ($response eq 'refused') {
6943: $authchk = 'refused';
6944: } else {
6945: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
6946: }
6947: }
6948: return ($authparam,$create_passwd,$authchk);
6949: }
6950:
6951: sub auto_photo_permission {
6952: my ($cnum,$cdom,$students) = @_;
6953: my $homeserver = &homeserver($cnum,$cdom);
6954: my ($outcome,$perm_reqd,$conditions) =
6955: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
6956: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6957: return (undef,undef);
6958: }
6959: return ($outcome,$perm_reqd,$conditions);
6960: }
6961:
6962: sub auto_checkphotos {
6963: my ($uname,$udom,$pid) = @_;
6964: my $homeserver = &homeserver($uname,$udom);
6965: my ($result,$resulttype);
6966: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
6967: &escape($uname).':'.&escape($pid),
6968: $homeserver));
6969: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6970: return (undef,undef);
6971: }
6972: if ($outcome) {
6973: ($result,$resulttype) = split(/:/,$outcome);
6974: }
6975: return ($result,$resulttype);
6976: }
6977:
6978: sub auto_photochoice {
6979: my ($cnum,$cdom) = @_;
6980: my $homeserver = &homeserver($cnum,$cdom);
6981: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
6982: &escape($cdom),
6983: $homeserver)));
6984: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6985: return (undef,undef);
6986: }
6987: return ($update,$comment);
6988: }
6989:
6990: sub auto_photoupdate {
6991: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6992: my $homeserver = &homeserver($cnum,$dom);
6993: my $host=&hostname($homeserver);
6994: my $cmd = '';
6995: my $maxtries = 1;
6996: foreach my $affiliate (keys(%{$affiliatesref})) {
6997: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
6998: }
6999: $cmd =~ s/%%$//;
7000: $cmd = &escape($cmd);
7001: my $query = 'institutionalphotos';
7002: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7003: unless ($queryid=~/^\Q$host\E\_/) {
7004: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7005: return 'error: '.$queryid;
7006: }
7007: my $reply = &get_query_reply($queryid);
7008: my $tries = 1;
7009: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7010: $reply = &get_query_reply($queryid);
7011: $tries ++;
7012: }
7013: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7014: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7015: } else {
7016: my @responses = split(/:/,$reply);
7017: my $outcome = shift(@responses);
7018: foreach my $item (@responses) {
7019: my ($key,$value) = split(/=/,$item);
7020: $$photo{$key} = $value;
7021: }
7022: return $outcome;
7023: }
7024: return 'error';
7025: }
7026:
7027: sub auto_instcode_format {
7028: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7029: $cat_order) = @_;
7030: my $courses = '';
7031: my @homeservers;
7032: if ($caller eq 'global') {
7033: my %servers = &get_servers($codedom,'library');
7034: foreach my $tryserver (keys(%servers)) {
7035: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7036: push(@homeservers,$tryserver);
7037: }
7038: }
7039: } elsif ($caller eq 'requests') {
7040: if ($codedom =~ /^$match_domain$/) {
7041: my $chome = &domain($codedom,'primary');
7042: unless ($chome eq 'no_host') {
7043: push(@homeservers,$chome);
7044: }
7045: }
7046: } else {
7047: push(@homeservers,&homeserver($caller,$codedom));
7048: }
7049: foreach my $code (keys(%{$instcodes})) {
7050: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
7051: }
7052: chop($courses);
7053: my $ok_response = 0;
7054: my $response;
7055: while (@homeservers > 0 && $ok_response == 0) {
7056: my $server = shift(@homeservers);
7057: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7058: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7059: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
7060: split(/:/,$response);
7061: %{$codes} = (%{$codes},&str2hash($codes_str));
7062: push(@{$codetitles},&str2array($codetitles_str));
7063: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7064: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7065: $ok_response = 1;
7066: }
7067: }
7068: if ($ok_response) {
7069: return 'ok';
7070: } else {
7071: return $response;
7072: }
7073: }
7074:
7075: sub auto_instcode_defaults {
7076: my ($domain,$returnhash,$code_order) = @_;
7077: my @homeservers;
7078:
7079: my %servers = &get_servers($domain,'library');
7080: foreach my $tryserver (keys(%servers)) {
7081: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7082: push(@homeservers,$tryserver);
7083: }
7084: }
7085:
7086: my $response;
7087: foreach my $server (@homeservers) {
7088: $response=&reply('autoinstcodedefaults:'.$domain,$server);
7089: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7090:
7091: foreach my $pair (split(/\&/,$response)) {
7092: my ($name,$value)=split(/\=/,$pair);
7093: if ($name eq 'code_order') {
7094: @{$code_order} = split(/\&/,&unescape($value));
7095: } else {
7096: $returnhash->{&unescape($name)}=&unescape($value);
7097: }
7098: }
7099: return 'ok';
7100: }
7101:
7102: return $response;
7103: }
7104:
7105: sub auto_possible_instcodes {
7106: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7107: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7108: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7109: return;
7110: }
7111: my (@homeservers,$uhome);
7112: if (defined(&domain($domain,'primary'))) {
7113: $uhome=&domain($domain,'primary');
7114: push(@homeservers,&domain($domain,'primary'));
7115: } else {
7116: my %servers = &get_servers($domain,'library');
7117: foreach my $tryserver (keys(%servers)) {
7118: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7119: push(@homeservers,$tryserver);
7120: }
7121: }
7122: }
7123: my $response;
7124: foreach my $server (@homeservers) {
7125: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7126: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7127: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7128: split(':',$response);
7129: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7130: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
7131: foreach my $item (split('&',$cat_title)) {
7132: my ($name,$value)=split('=',$item);
7133: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
7134: }
7135: foreach my $item (split('&',$cat_order)) {
7136: my ($name,$value)=split('=',$item);
7137: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
7138: }
7139: return 'ok';
7140: }
7141: return $response;
7142: }
7143:
7144: sub auto_courserequest_checks {
7145: my ($dom) = @_;
7146: my ($homeserver,%validations);
7147: if ($dom =~ /^$match_domain$/) {
7148: $homeserver = &domain($dom,'primary');
7149: }
7150: unless ($homeserver eq 'no_host') {
7151: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7152: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7153: my @items = split(/&/,$response);
7154: foreach my $item (@items) {
7155: my ($key,$value) = split('=',$item);
7156: $validations{&unescape($key)} = &thaw_unescape($value);
7157: }
7158: }
7159: }
7160: return %validations;
7161: }
7162:
7163: sub auto_courserequest_validation {
7164: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
7165: my ($homeserver,$response);
7166: if ($dom =~ /^$match_domain$/) {
7167: $homeserver = &domain($dom,'primary');
7168: }
7169: unless ($homeserver eq 'no_host') {
7170:
7171: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
7172: ':'.&escape($crstype).':'.&escape($inststatuslist).
7173: ':'.&escape($instcode).':'.&escape($instseclist),
7174: $homeserver));
7175: }
7176: return $response;
7177: }
7178:
7179: sub auto_validate_class_sec {
7180: my ($cdom,$cnum,$owners,$inst_class) = @_;
7181: my $homeserver = &homeserver($cnum,$cdom);
7182: my $ownerlist;
7183: if (ref($owners) eq 'ARRAY') {
7184: $ownerlist = join(',',@{$owners});
7185: } else {
7186: $ownerlist = $owners;
7187: }
7188: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
7189: &escape($ownerlist).':'.$cdom,$homeserver);
7190: return $response;
7191: }
7192:
7193: # ------------------------------------------------------- Course Group routines
7194:
7195: sub get_coursegroups {
7196: my ($cdom,$cnum,$group,$namespace) = @_;
7197: return(&dump($namespace,$cdom,$cnum,$group));
7198: }
7199:
7200: sub modify_coursegroup {
7201: my ($cdom,$cnum,$groupsettings) = @_;
7202: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7203: }
7204:
7205: sub toggle_coursegroup_status {
7206: my ($cdom,$cnum,$group,$action) = @_;
7207: my ($from_namespace,$to_namespace);
7208: if ($action eq 'delete') {
7209: $from_namespace = 'coursegroups';
7210: $to_namespace = 'deleted_groups';
7211: } else {
7212: $from_namespace = 'deleted_groups';
7213: $to_namespace = 'coursegroups';
7214: }
7215: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
7216: if (my $tmp = &error(%curr_group)) {
7217: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7218: return ('read error',$tmp);
7219: } else {
7220: my %savedsettings = %curr_group;
7221: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
7222: my $deloutcome;
7223: if ($result eq 'ok') {
7224: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
7225: } else {
7226: return ('write error',$result);
7227: }
7228: if ($deloutcome eq 'ok') {
7229: return 'ok';
7230: } else {
7231: return ('delete error',$deloutcome);
7232: }
7233: }
7234: }
7235:
7236: sub modify_group_roles {
7237: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
7238: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7239: my $role = 'gr/'.&escape($userprivs);
7240: my ($uname,$udom) = split(/:/,$user);
7241: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
7242: if ($result eq 'ok') {
7243: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7244: }
7245: return $result;
7246: }
7247:
7248: sub modify_coursegroup_membership {
7249: my ($cdom,$cnum,$membership) = @_;
7250: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7251: return $result;
7252: }
7253:
7254: sub get_active_groups {
7255: my ($udom,$uname,$cdom,$cnum) = @_;
7256: my $now = time;
7257: my %groups = ();
7258: foreach my $key (keys(%env)) {
7259: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
7260: my ($start,$end) = split(/\./,$env{$key});
7261: if (($end!=0) && ($end<$now)) { next; }
7262: if (($start!=0) && ($start>$now)) { next; }
7263: if ($1 eq $cdom && $2 eq $cnum) {
7264: $groups{$3} = $env{$key} ;
7265: }
7266: }
7267: }
7268: return %groups;
7269: }
7270:
7271: sub get_group_membership {
7272: my ($cdom,$cnum,$group) = @_;
7273: return(&dump('groupmembership',$cdom,$cnum,$group));
7274: }
7275:
7276: sub get_users_groups {
7277: my ($udom,$uname,$courseid) = @_;
7278: my @usersgroups;
7279: my $cachetime=1800;
7280:
7281: my $hashid="$udom:$uname:$courseid";
7282: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
7283: if (defined($cached)) {
7284: @usersgroups = split(/:/,$grouplist);
7285: } else {
7286: $grouplist = '';
7287: my $courseurl = &courseid_to_courseurl($courseid);
7288: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
7289: my $access_end = $env{'course.'.$courseid.
7290: '.default_enrollment_end_date'};
7291: my $now = time;
7292: foreach my $key (keys(%roleshash)) {
7293: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
7294: my $group = $1;
7295: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
7296: my $start = $2;
7297: my $end = $1;
7298: if ($start == -1) { next; } # deleted from group
7299: if (($start!=0) && ($start>$now)) { next; }
7300: if (($end!=0) && ($end<$now)) {
7301: if ($access_end && $access_end < $now) {
7302: if ($access_end - $end < 86400) {
7303: push(@usersgroups,$group);
7304: }
7305: }
7306: next;
7307: }
7308: push(@usersgroups,$group);
7309: }
7310: }
7311: }
7312: @usersgroups = &sort_course_groups($courseid,@usersgroups);
7313: $grouplist = join(':',@usersgroups);
7314: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
7315: }
7316: return @usersgroups;
7317: }
7318:
7319: sub devalidate_getgroups_cache {
7320: my ($udom,$uname,$cdom,$cnum)=@_;
7321: my $courseid = $cdom.'_'.$cnum;
7322:
7323: my $hashid="$udom:$uname:$courseid";
7324: &devalidate_cache_new('getgroups',$hashid);
7325: }
7326:
7327: # ------------------------------------------------------------------ Plain Text
7328:
7329: sub plaintext {
7330: my ($short,$type,$cid,$forcedefault) = @_;
7331: if ($short =~ m{^cr/}) {
7332: return (split('/',$short))[-1];
7333: }
7334: if (!defined($cid)) {
7335: $cid = $env{'request.course.id'};
7336: }
7337: my %rolenames = (
7338: Course => 'std',
7339: Community => 'alt1',
7340: );
7341: if ($cid ne '') {
7342: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
7343: unless ($forcedefault) {
7344: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
7345: &Apache::lonlocal::mt_escape(\$roletext);
7346: return &Apache::lonlocal::mt($roletext);
7347: }
7348: }
7349: }
7350: if ((defined($type)) && (defined($rolenames{$type})) &&
7351: (defined($rolenames{$type})) &&
7352: (defined($prp{$short}{$rolenames{$type}}))) {
7353: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
7354: } elsif ($cid ne '') {
7355: my $crstype = $env{'course.'.$cid.'.type'};
7356: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
7357: (defined($prp{$short}{$rolenames{$crstype}}))) {
7358: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
7359: }
7360: }
7361: return &Apache::lonlocal::mt($prp{$short}{'std'});
7362: }
7363:
7364: # ----------------------------------------------------------------- Assign Role
7365:
7366: sub assignrole {
7367: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
7368: $context)=@_;
7369: my $mrole;
7370: if ($role =~ /^cr\//) {
7371: my $cwosec=$url;
7372: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
7373: unless (&allowed('ccr',$cwosec)) {
7374: my $refused = 1;
7375: if ($context eq 'requestcourses') {
7376: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7377: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
7378: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
7379: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7380: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7381: if ($crsenv{'internal.courseowner'} eq
7382: $env{'user.name'}.':'.$env{'user.domain'}) {
7383: $refused = '';
7384: }
7385: }
7386: }
7387: }
7388: }
7389: if ($refused) {
7390: &logthis('Refused custom assignrole: '.
7391: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
7392: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
7393: return 'refused';
7394: }
7395: }
7396: $mrole='cr';
7397: } elsif ($role =~ /^gr\//) {
7398: my $cwogrp=$url;
7399: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
7400: unless (&allowed('mdg',$cwogrp)) {
7401: &logthis('Refused group assignrole: '.
7402: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
7403: $env{'user.name'}.' at '.$env{'user.domain'});
7404: return 'refused';
7405: }
7406: $mrole='gr';
7407: } else {
7408: my $cwosec=$url;
7409: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
7410: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
7411: my $refused;
7412: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
7413: if (!(&allowed('c'.$role,$url))) {
7414: $refused = 1;
7415: }
7416: } else {
7417: $refused = 1;
7418: }
7419: if ($refused) {
7420: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7421: if (!$selfenroll && $context eq 'course') {
7422: my %crsenv;
7423: if ($role eq 'cc' || $role eq 'co') {
7424: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7425: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
7426: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
7427: if ($crsenv{'internal.courseowner'} eq
7428: $env{'user.name'}.':'.$env{'user.domain'}) {
7429: $refused = '';
7430: }
7431: }
7432: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
7433: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
7434: if ($crsenv{'internal.courseowner'} eq
7435: $env{'user.name'}.':'.$env{'user.domain'}) {
7436: $refused = '';
7437: }
7438: }
7439: }
7440: }
7441: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7442: $refused = '';
7443: } elsif ($context eq 'requestcourses') {
7444: my @possroles = ('st','ta','ep','in','cc','co');
7445: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
7446: my $wrongcc;
7447: if ($cnum =~ /^$match_community$/) {
7448: $wrongcc = 1 if ($role eq 'cc');
7449: } else {
7450: $wrongcc = 1 if ($role eq 'co');
7451: }
7452: unless ($wrongcc) {
7453: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7454: if ($crsenv{'internal.courseowner'} eq
7455: $env{'user.name'}.':'.$env{'user.domain'}) {
7456: $refused = '';
7457: }
7458: }
7459: }
7460: }
7461: if ($refused) {
7462: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
7463: ' '.$role.' '.$end.' '.$start.' by '.
7464: $env{'user.name'}.' at '.$env{'user.domain'});
7465: return 'refused';
7466: }
7467: }
7468: } elsif ($role eq 'au') {
7469: if ($url ne '/'.$udom.'/') {
7470: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
7471: ' to assign author role for '.$uname.':'.$udom.
7472: ' in domain: '.$url.' refused (wrong domain).');
7473: return 'refused';
7474: }
7475: }
7476: $mrole=$role;
7477: }
7478: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7479: "$udom:$uname:$url".'_'."$mrole=$role";
7480: if ($end) { $command.='_'.$end; }
7481: if ($start) {
7482: if ($end) {
7483: $command.='_'.$start;
7484: } else {
7485: $command.='_0_'.$start;
7486: }
7487: }
7488: my $origstart = $start;
7489: my $origend = $end;
7490: my $delflag;
7491: # actually delete
7492: if ($deleteflag) {
7493: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
7494: # modify command to delete the role
7495: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
7496: "$udom:$uname:$url".'_'."$mrole";
7497: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
7498: # set start and finish to negative values for userrolelog
7499: $start=-1;
7500: $end=-1;
7501: $delflag = 1;
7502: }
7503: }
7504: # send command
7505: my $answer=&reply($command,&homeserver($uname,$udom));
7506: # log new user role if status is ok
7507: if ($answer eq 'ok') {
7508: &userrolelog($role,$uname,$udom,$url,$start,$end);
7509: # for course roles, perform group memberships changes triggered by role change.
7510: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
7511: unless ($role =~ /^gr/) {
7512: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
7513: $origstart,$selfenroll,$context);
7514: }
7515: if ($role eq 'cc') {
7516: &autoupdate_coowners($url,$end,$start,$uname,$udom);
7517: }
7518: }
7519: return $answer;
7520: }
7521:
7522: sub autoupdate_coowners {
7523: my ($url,$end,$start,$uname,$udom) = @_;
7524: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
7525: if (($cdom ne '') && ($cnum ne '')) {
7526: my $now = time;
7527: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
7528: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
7529: my %coursehash = &coursedescription($cdom.'_'.$cnum);
7530: my $instcode = $coursehash{'internal.coursecode'};
7531: if ($instcode ne '') {
7532: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
7533: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
7534: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
7535: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
7536: if ($result eq 'valid') {
7537: if ($coursehash{'internal.co-owners'}) {
7538: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7539: push(@newcoowners,$coowner);
7540: }
7541: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
7542: push(@newcoowners,$uname.':'.$udom);
7543: }
7544: @newcoowners = sort(@newcoowners);
7545: } else {
7546: push(@newcoowners,$uname.':'.$udom);
7547: }
7548: } else {
7549: if ($coursehash{'internal.co-owners'}) {
7550: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7551: unless ($coowner eq $uname.':'.$udom) {
7552: push(@newcoowners,$coowner);
7553: }
7554: }
7555: unless (@newcoowners > 0) {
7556: $delcoowners = 1;
7557: $coowners = '';
7558: }
7559: }
7560: }
7561: if (@newcoowners || $delcoowners) {
7562: &store_coowners($cdom,$cnum,$coursehash{'home'},
7563: $delcoowners,@newcoowners);
7564: }
7565: }
7566: }
7567: }
7568: }
7569: }
7570: }
7571:
7572: sub store_coowners {
7573: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
7574: my $cid = $cdom.'_'.$cnum;
7575: my ($coowners,$delresult,$putresult);
7576: if (@newcoowners) {
7577: $coowners = join(',',@newcoowners);
7578: my %coownershash = (
7579: 'internal.co-owners' => $coowners,
7580: );
7581: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
7582: if ($putresult eq 'ok') {
7583: if ($env{'course.'.$cid.'.num'} eq $cnum) {
7584: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
7585: }
7586: }
7587: }
7588: if ($delcoowners) {
7589: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
7590: if ($delresult eq 'ok') {
7591: if ($env{'course.'.$cid.'.internal.co-owners'}) {
7592: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
7593: }
7594: }
7595: }
7596: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
7597: my %crsinfo =
7598: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
7599: if (ref($crsinfo{$cid}) eq 'HASH') {
7600: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
7601: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
7602: }
7603: }
7604: }
7605:
7606: # -------------------------------------------------- Modify user authentication
7607: # Overrides without validation
7608:
7609: sub modifyuserauth {
7610: my ($udom,$uname,$umode,$upass)=@_;
7611: my $uhome=&homeserver($uname,$udom);
7612: unless (&allowed('mau',$udom)) { return 'refused'; }
7613: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
7614: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7615: ' in domain '.$env{'request.role.domain'});
7616: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
7617: &escape($upass),$uhome);
7618: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
7619: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
7620: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7621: &log($udom,,$uname,$uhome,
7622: 'Authentication changed by '.$env{'user.domain'}.', '.
7623: $env{'user.name'}.', '.$umode.
7624: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7625: unless ($reply eq 'ok') {
7626: &logthis('Authentication mode error: '.$reply);
7627: return 'error: '.$reply;
7628: }
7629: return 'ok';
7630: }
7631:
7632: # --------------------------------------------------------------- Modify a user
7633:
7634: sub modifyuser {
7635: my ($udom, $uname, $uid,
7636: $umode, $upass, $first,
7637: $middle, $last, $gene,
7638: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
7639: $udom= &LONCAPA::clean_domain($udom);
7640: $uname=&LONCAPA::clean_username($uname);
7641: my $showcandelete = 'none';
7642: if (ref($candelete) eq 'ARRAY') {
7643: if (@{$candelete} > 0) {
7644: $showcandelete = join(', ',@{$candelete});
7645: }
7646: }
7647: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
7648: $umode.', '.$first.', '.$middle.', '.
7649: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
7650: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
7651: ' desiredhome not specified').
7652: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7653: ' in domain '.$env{'request.role.domain'});
7654: my $uhome=&homeserver($uname,$udom,'true');
7655: my $newuser;
7656: if ($uhome eq 'no_host') {
7657: $newuser = 1;
7658: }
7659: # ----------------------------------------------------------------- Create User
7660: if (($uhome eq 'no_host') &&
7661: (($umode && $upass) || ($umode eq 'localauth'))) {
7662: my $unhome='';
7663: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
7664: $unhome = $desiredhome;
7665: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
7666: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
7667: } else { # load balancing routine for determining $unhome
7668: my $loadm=10000000;
7669: my %servers = &get_servers($udom,'library');
7670: foreach my $tryserver (keys(%servers)) {
7671: my $answer=reply('load',$tryserver);
7672: if (($answer=~/\d+/) && ($answer<$loadm)) {
7673: $loadm=$answer;
7674: $unhome=$tryserver;
7675: }
7676: }
7677: }
7678: if (($unhome eq '') || ($unhome eq 'no_host')) {
7679: return 'error: unable to find a home server for '.$uname.
7680: ' in domain '.$udom;
7681: }
7682: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
7683: &escape($upass),$unhome);
7684: unless ($reply eq 'ok') {
7685: return 'error: '.$reply;
7686: }
7687: $uhome=&homeserver($uname,$udom,'true');
7688: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
7689: return 'error: unable verify users home machine.';
7690: }
7691: } # End of creation of new user
7692: # ---------------------------------------------------------------------- Add ID
7693: if ($uid) {
7694: $uid=~tr/A-Z/a-z/;
7695: my %uidhash=&idrget($udom,$uname);
7696: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
7697: && (!$forceid)) {
7698: unless ($uid eq $uidhash{$uname}) {
7699: return 'error: user id "'.$uid.'" does not match '.
7700: 'current user id "'.$uidhash{$uname}.'".';
7701: }
7702: } else {
7703: &idput($udom,($uname => $uid));
7704: }
7705: }
7706: # -------------------------------------------------------------- Add names, etc
7707: my @tmp=&get('environment',
7708: ['firstname','middlename','lastname','generation','id',
7709: 'permanentemail','inststatus'],
7710: $udom,$uname);
7711: my (%names,%oldnames);
7712: if ($tmp[0] =~ m/^error:.*/) {
7713: %names=();
7714: } else {
7715: %names = @tmp;
7716: %oldnames = %names;
7717: }
7718: #
7719: # If name, email and/or uid are blank (e.g., because an uploaded file
7720: # of users did not contain them), do not overwrite existing values
7721: # unless field is in $candelete array ref.
7722: #
7723:
7724: my @fields = ('firstname','middlename','lastname','generation',
7725: 'permanentemail','id');
7726: my %newvalues;
7727: if (ref($candelete) eq 'ARRAY') {
7728: foreach my $field (@fields) {
7729: if (grep(/^\Q$field\E$/,@{$candelete})) {
7730: if ($field eq 'firstname') {
7731: $names{$field} = $first;
7732: } elsif ($field eq 'middlename') {
7733: $names{$field} = $middle;
7734: } elsif ($field eq 'lastname') {
7735: $names{$field} = $last;
7736: } elsif ($field eq 'generation') {
7737: $names{$field} = $gene;
7738: } elsif ($field eq 'permanentemail') {
7739: $names{$field} = $email;
7740: } elsif ($field eq 'id') {
7741: $names{$field} = $uid;
7742: }
7743: }
7744: }
7745: }
7746: if ($first) { $names{'firstname'} = $first; }
7747: if (defined($middle)) { $names{'middlename'} = $middle; }
7748: if ($last) { $names{'lastname'} = $last; }
7749: if (defined($gene)) { $names{'generation'} = $gene; }
7750: if ($email) {
7751: $email=~s/[^\w\@\.\-\,]//gs;
7752: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
7753: }
7754: if ($uid) { $names{'id'} = $uid; }
7755: if (defined($inststatus)) {
7756: $names{'inststatus'} = '';
7757: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
7758: if (ref($usertypes) eq 'HASH') {
7759: my @okstatuses;
7760: foreach my $item (split(/:/,$inststatus)) {
7761: if (defined($usertypes->{$item})) {
7762: push(@okstatuses,$item);
7763: }
7764: }
7765: if (@okstatuses) {
7766: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
7767: }
7768: }
7769: }
7770: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
7771: $umode.', '.$first.', '.$middle.', '.
7772: $last.', '.$gene.', '.$email.', '.$inststatus;
7773: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
7774: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
7775: } else {
7776: $logmsg .= ' during self creation';
7777: }
7778: my $changed;
7779: if ($newuser) {
7780: $changed = 1;
7781: } else {
7782: foreach my $field (@fields) {
7783: if ($names{$field} ne $oldnames{$field}) {
7784: $changed = 1;
7785: last;
7786: }
7787: }
7788: }
7789: unless ($changed) {
7790: $logmsg = 'No changes in user information needed for: '.$logmsg;
7791: &logthis($logmsg);
7792: return 'ok';
7793: }
7794: my $reply = &put('environment', \%names, $udom,$uname);
7795: if ($reply ne 'ok') {
7796: return 'error: '.$reply;
7797: }
7798: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7799: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7800: }
7801: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7802: &devalidate_cache_new('namescache',$uname.':'.$udom);
7803: $logmsg = 'Success modifying user '.$logmsg;
7804: &logthis($logmsg);
7805: return 'ok';
7806: }
7807:
7808: # -------------------------------------------------------------- Modify student
7809:
7810: sub modifystudent {
7811: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
7812: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
7813: $selfenroll,$context,$inststatus)=@_;
7814: if (!$cid) {
7815: unless ($cid=$env{'request.course.id'}) {
7816: return 'not_in_class';
7817: }
7818: }
7819: # --------------------------------------------------------------- Make the user
7820: my $reply=&modifyuser
7821: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
7822: $desiredhome,$email,$inststatus);
7823: unless ($reply eq 'ok') { return $reply; }
7824: # This will cause &modify_student_enrollment to get the uid from the
7825: # students environment
7826: $uid = undef if (!$forceid);
7827: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
7828: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
7829: return $reply;
7830: }
7831:
7832: sub modify_student_enrollment {
7833: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
7834: my ($cdom,$cnum,$chome);
7835: if (!$cid) {
7836: unless ($cid=$env{'request.course.id'}) {
7837: return 'not_in_class';
7838: }
7839: $cdom=$env{'course.'.$cid.'.domain'};
7840: $cnum=$env{'course.'.$cid.'.num'};
7841: } else {
7842: ($cdom,$cnum)=split(/_/,$cid);
7843: }
7844: $chome=$env{'course.'.$cid.'.home'};
7845: if (!$chome) {
7846: $chome=&homeserver($cnum,$cdom);
7847: }
7848: if (!$chome) { return 'unknown_course'; }
7849: # Make sure the user exists
7850: my $uhome=&homeserver($uname,$udom);
7851: if (($uhome eq '') || ($uhome eq 'no_host')) {
7852: return 'error: no such user';
7853: }
7854: # Get student data if we were not given enough information
7855: if (!defined($first) || $first eq '' ||
7856: !defined($last) || $last eq '' ||
7857: !defined($uid) || $uid eq '' ||
7858: !defined($middle) || $middle eq '' ||
7859: !defined($gene) || $gene eq '') {
7860: # They did not supply us with enough data to enroll the student, so
7861: # we need to pick up more information.
7862: my %tmp = &get('environment',
7863: ['firstname','middlename','lastname', 'generation','id']
7864: ,$udom,$uname);
7865:
7866: #foreach my $key (keys(%tmp)) {
7867: # &logthis("key $key = ".$tmp{$key});
7868: #}
7869: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7870: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7871: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
7872: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
7873: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7874: }
7875: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
7876: my $user = "$uname:$udom";
7877: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
7878: my $reply=cput('classlist',
7879: {$user =>
7880: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
7881: $cdom,$cnum);
7882: if (($reply eq 'ok') || ($reply eq 'delayed')) {
7883: &devalidate_getsection_cache($udom,$uname,$cid);
7884: } else {
7885: return 'error: '.$reply;
7886: }
7887: # Add student role to user
7888: my $uurl='/'.$cid;
7889: $uurl=~s/\_/\//g;
7890: if ($usec) {
7891: $uurl.='/'.$usec;
7892: }
7893: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
7894: $selfenroll,$context);
7895: if ($result ne 'ok') {
7896: if ($old_entry{$user} ne '') {
7897: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
7898: } else {
7899: $reply = &del('classlist',[$user],$cdom,$cnum);
7900: }
7901: }
7902: return $result;
7903: }
7904:
7905: sub format_name {
7906: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7907: my $name;
7908: if ($first ne 'lastname') {
7909: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7910: } else {
7911: if ($lastname=~/\S/) {
7912: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7913: $name=~s/\s+,/,/;
7914: } else {
7915: $name.= $firstname.' '.$middlename.' '.$generation;
7916: }
7917: }
7918: $name=~s/^\s+//;
7919: $name=~s/\s+$//;
7920: $name=~s/\s+/ /g;
7921: return $name;
7922: }
7923:
7924: # ------------------------------------------------- Write to course preferences
7925:
7926: sub writecoursepref {
7927: my ($courseid,%prefs)=@_;
7928: $courseid=~s/^\///;
7929: $courseid=~s/\_/\//g;
7930: my ($cdomain,$cnum)=split(/\//,$courseid);
7931: my $chome=homeserver($cnum,$cdomain);
7932: if (($chome eq '') || ($chome eq 'no_host')) {
7933: return 'error: no such course';
7934: }
7935: my $cstring='';
7936: foreach my $pref (keys(%prefs)) {
7937: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
7938: }
7939: $cstring=~s/\&$//;
7940: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7941: }
7942:
7943: # ---------------------------------------------------------- Make/modify course
7944:
7945: sub createcourse {
7946: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
7947: $course_owner,$crstype,$cnum,$context,$category)=@_;
7948: $url=&declutter($url);
7949: my $cid='';
7950: if ($context eq 'requestcourses') {
7951: my $can_create = 0;
7952: my ($ownername,$ownerdom) = split(':',$course_owner);
7953: if ($udom eq $ownerdom) {
7954: if (&usertools_access($ownername,$ownerdom,$category,undef,
7955: $context)) {
7956: $can_create = 1;
7957: }
7958: } else {
7959: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7960: $category);
7961: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7962: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7963: if (@curr > 0) {
7964: my @options = qw(approval validate autolimit);
7965: my $optregex = join('|',@options);
7966: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7967: $can_create = 1;
7968: }
7969: }
7970: }
7971: }
7972: if ($can_create) {
7973: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7974: unless (&allowed('ccc',$udom)) {
7975: return 'refused';
7976: }
7977: }
7978: } else {
7979: return 'refused';
7980: }
7981: } elsif (!&allowed('ccc',$udom)) {
7982: return 'refused';
7983: }
7984: # --------------------------------------------------------------- Get Unique ID
7985: my $uname;
7986: if ($cnum =~ /^$match_courseid$/) {
7987: my $chome=&homeserver($cnum,$udom,'true');
7988: if (($chome eq '') || ($chome eq 'no_host')) {
7989: $uname = $cnum;
7990: } else {
7991: $uname = &generate_coursenum($udom,$crstype);
7992: }
7993: } else {
7994: $uname = &generate_coursenum($udom,$crstype);
7995: }
7996: return $uname if ($uname =~ /^error/);
7997: # -------------------------------------------------- Check supplied server name
7998: if (!defined($course_server)) {
7999: if (defined(&domain($udom,'primary'))) {
8000: $course_server = &domain($udom,'primary');
8001: } else {
8002: $course_server = $env{'user.home'};
8003: }
8004: }
8005: my %host_servers =
8006: &Apache::lonnet::get_servers($udom,'library');
8007: unless ($host_servers{$course_server}) {
8008: return 'error: invalid home server for course: '.$course_server;
8009: }
8010: # ------------------------------------------------------------- Make the course
8011: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
8012: $course_server);
8013: unless ($reply eq 'ok') { return 'error: '.$reply; }
8014: my $uhome=&homeserver($uname,$udom,'true');
8015: if (($uhome eq '') || ($uhome eq 'no_host')) {
8016: return 'error: no such course';
8017: }
8018: # ----------------------------------------------------------------- Course made
8019: # log existence
8020: my $now = time;
8021: my $newcourse = {
8022: $udom.'_'.$uname => {
8023: description => $description,
8024: inst_code => $inst_code,
8025: owner => $course_owner,
8026: type => $crstype,
8027: creator => $env{'user.name'}.':'.
8028: $env{'user.domain'},
8029: created => $now,
8030: context => $context,
8031: },
8032: };
8033: &courseidput($udom,$newcourse,$uhome,'notime');
8034: # set toplevel url
8035: my $topurl=$url;
8036: unless ($nonstandard) {
8037: # ------------------------------------------ For standard courses, make top url
8038: my $mapurl=&clutter($url);
8039: if ($mapurl eq '/res/') { $mapurl=''; }
8040: $env{'form.initmap'}=(<<ENDINITMAP);
8041: <map>
8042: <resource id="1" type="start"></resource>
8043: <resource id="2" src="$mapurl"></resource>
8044: <resource id="3" type="finish"></resource>
8045: <link index="1" from="1" to="2"></link>
8046: <link index="2" from="2" to="3"></link>
8047: </map>
8048: ENDINITMAP
8049: $topurl=&declutter(
8050: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
8051: );
8052: }
8053: # ----------------------------------------------------------- Write preferences
8054: &writecoursepref($udom.'_'.$uname,
8055: ('description' => $description,
8056: 'url' => $topurl,
8057: 'internal.creator' => $env{'user.name'}.':'.
8058: $env{'user.domain'},
8059: 'internal.created' => $now,
8060: 'internal.creationcontext' => $context)
8061: );
8062: return '/'.$udom.'/'.$uname;
8063: }
8064:
8065: # ------------------------------------------------------------------- Create ID
8066: sub generate_coursenum {
8067: my ($udom,$crstype) = @_;
8068: my $domdesc = &domain($udom);
8069: return 'error: invalid domain' if ($domdesc eq '');
8070: my $first;
8071: if ($crstype eq 'Community') {
8072: $first = '0';
8073: } else {
8074: $first = int(1+rand(9));
8075: }
8076: my $uname=$first.
8077: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8078: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8079: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8080: # ----------------------------------------------- Make sure that does not exist
8081: my $uhome=&homeserver($uname,$udom,'true');
8082: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8083: if ($crstype eq 'Community') {
8084: $first = '0';
8085: } else {
8086: $first = int(1+rand(9));
8087: }
8088: $uname=$first.
8089: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8090: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8091: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8092: $uhome=&homeserver($uname,$udom,'true');
8093: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8094: return 'error: unable to generate unique course-ID';
8095: }
8096: }
8097: return $uname;
8098: }
8099:
8100: sub is_course {
8101: my ($cdom, $cnum) = scalar(@_) == 1 ?
8102: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8103:
8104: return unless $cdom and $cnum;
8105:
8106: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8107: '.');
8108:
8109: return unless exists($courses{$cdom.'_'.$cnum});
8110: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
8111: }
8112:
8113: sub store_userdata {
8114: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
8115: my $result;
8116: if ($datakey ne '') {
8117: if (ref($storehash) eq 'HASH') {
8118: if ($udom eq '' || $uname eq '') {
8119: $udom = $env{'user.domain'};
8120: $uname = $env{'user.name'};
8121: }
8122: my $uhome=&homeserver($uname,$udom);
8123: if (($uhome eq '') || ($uhome eq 'no_host')) {
8124: $result = 'error: no_host';
8125: } else {
8126: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8127: $storehash->{'host'} = $perlvar{'lonHostID'};
8128:
8129: my $namevalue='';
8130: foreach my $key (keys(%{$storehash})) {
8131: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8132: }
8133: $namevalue=~s/\&$//;
8134: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8135: $namevalue,$uhome);
8136: }
8137: } else {
8138: $result = 'error: data to store was not a hash reference';
8139: }
8140: } else {
8141: $result= 'error: invalid requestkey';
8142: }
8143: return $result;
8144: }
8145:
8146: # ---------------------------------------------------------- Assign Custom Role
8147:
8148: sub assigncustomrole {
8149: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
8150: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
8151: $end,$start,$deleteflag,$selfenroll,$context);
8152: }
8153:
8154: # ----------------------------------------------------------------- Revoke Role
8155:
8156: sub revokerole {
8157: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
8158: my $now=time;
8159: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
8160: }
8161:
8162: # ---------------------------------------------------------- Revoke Custom Role
8163:
8164: sub revokecustomrole {
8165: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
8166: my $now=time;
8167: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
8168: $deleteflag,$selfenroll,$context);
8169: }
8170:
8171: # ------------------------------------------------------------ Disk usage
8172: sub diskusage {
8173: my ($udom,$uname,$directorypath,$getpropath)=@_;
8174: $directorypath =~ s/\/$//;
8175: my $listing=&reply('du2:'.&escape($directorypath).':'
8176: .&escape($getpropath).':'.&escape($uname).':'
8177: .&escape($udom),homeserver($uname,$udom));
8178: if ($listing eq 'unknown_cmd') {
8179: if ($getpropath) {
8180: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8181: }
8182: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8183: }
8184: return $listing;
8185: }
8186:
8187: sub is_locked {
8188: my ($file_name, $domain, $user, $which) = @_;
8189: my @check;
8190: my $is_locked;
8191: push (@check,$file_name);
8192: my %locked = &get('file_permissions',\@check,
8193: $env{'user.domain'},$env{'user.name'});
8194: my ($tmp)=keys(%locked);
8195: if ($tmp=~/^error:/) { undef(%locked); }
8196:
8197: if (ref($locked{$file_name}) eq 'ARRAY') {
8198: $is_locked = 'false';
8199: foreach my $entry (@{$locked{$file_name}}) {
8200: if (ref($entry) eq 'ARRAY') {
8201: $is_locked = 'true';
8202: if (ref($which) eq 'ARRAY') {
8203: push(@{$which},$entry);
8204: } else {
8205: last;
8206: }
8207: }
8208: }
8209: } else {
8210: $is_locked = 'false';
8211: }
8212: return $is_locked;
8213: }
8214:
8215: sub declutter_portfile {
8216: my ($file) = @_;
8217: $file =~ s{^(/portfolio/|portfolio/)}{/};
8218: return $file;
8219: }
8220:
8221: # ------------------------------------------------------------- Mark as Read Only
8222:
8223: sub mark_as_readonly {
8224: my ($domain,$user,$files,$what) = @_;
8225: my %current_permissions = &dump('file_permissions',$domain,$user);
8226: my ($tmp)=keys(%current_permissions);
8227: if ($tmp=~/^error:/) { undef(%current_permissions); }
8228: foreach my $file (@{$files}) {
8229: $file = &declutter_portfile($file);
8230: push(@{$current_permissions{$file}},$what);
8231: }
8232: &put('file_permissions',\%current_permissions,$domain,$user);
8233: return;
8234: }
8235:
8236: # ------------------------------------------------------------Save Selected Files
8237:
8238: sub save_selected_files {
8239: my ($user, $path, @files) = @_;
8240: my $filename = $user."savedfiles";
8241: my @other_files = &files_not_in_path($user, $path);
8242: open (OUT, '>'.$tmpdir.$filename);
8243: foreach my $file (@files) {
8244: print (OUT $env{'form.currentpath'}.$file."\n");
8245: }
8246: foreach my $file (@other_files) {
8247: print (OUT $file."\n");
8248: }
8249: close (OUT);
8250: return 'ok';
8251: }
8252:
8253: sub clear_selected_files {
8254: my ($user) = @_;
8255: my $filename = $user."savedfiles";
8256: open (OUT, '>'.LONCAPA::tempdir().$filename);
8257: print (OUT undef);
8258: close (OUT);
8259: return ("ok");
8260: }
8261:
8262: sub files_in_path {
8263: my ($user, $path) = @_;
8264: my $filename = $user."savedfiles";
8265: my %return_files;
8266: open (IN, '<'.LONCAPA::tempdir().$filename);
8267: while (my $line_in = <IN>) {
8268: chomp ($line_in);
8269: my @paths_and_file = split (m!/!, $line_in);
8270: my $file_part = pop (@paths_and_file);
8271: my $path_part = join ('/', @paths_and_file);
8272: $path_part.='/';
8273: my $path_and_file = $path_part.$file_part;
8274: if ($path_part eq $path) {
8275: $return_files{$file_part}= 'selected';
8276: }
8277: }
8278: close (IN);
8279: return (\%return_files);
8280: }
8281:
8282: # called in portfolio select mode, to show files selected NOT in current directory
8283: sub files_not_in_path {
8284: my ($user, $path) = @_;
8285: my $filename = $user."savedfiles";
8286: my @return_files;
8287: my $path_part;
8288: open(IN, '<'.LONCAPA::.$filename);
8289: while (my $line = <IN>) {
8290: #ok, I know it's clunky, but I want it to work
8291: my @paths_and_file = split(m|/|, $line);
8292: my $file_part = pop(@paths_and_file);
8293: chomp($file_part);
8294: my $path_part = join('/', @paths_and_file);
8295: $path_part .= '/';
8296: my $path_and_file = $path_part.$file_part;
8297: if ($path_part ne $path) {
8298: push(@return_files, ($path_and_file));
8299: }
8300: }
8301: close(OUT);
8302: return (@return_files);
8303: }
8304:
8305: #----------------------------------------------Get portfolio file permissions
8306:
8307: sub get_portfile_permissions {
8308: my ($domain,$user) = @_;
8309: my %current_permissions = &dump('file_permissions',$domain,$user);
8310: my ($tmp)=keys(%current_permissions);
8311: if ($tmp=~/^error:/) { undef(%current_permissions); }
8312: return \%current_permissions;
8313: }
8314:
8315: #---------------------------------------------Get portfolio file access controls
8316:
8317: sub get_access_controls {
8318: my ($current_permissions,$group,$file) = @_;
8319: my %access;
8320: my $real_file = $file;
8321: $file =~ s/\.meta$//;
8322: if (defined($file)) {
8323: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
8324: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
8325: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
8326: }
8327: }
8328: } else {
8329: foreach my $key (keys(%{$current_permissions})) {
8330: if ($key =~ /\0accesscontrol$/) {
8331: if (defined($group)) {
8332: if ($key !~ m-^\Q$group\E/-) {
8333: next;
8334: }
8335: }
8336: my ($fullpath) = split(/\0/,$key);
8337: if (ref($$current_permissions{$key}) eq 'HASH') {
8338: foreach my $control (keys(%{$$current_permissions{$key}})) {
8339: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
8340: }
8341: }
8342: }
8343: }
8344: }
8345: return %access;
8346: }
8347:
8348: sub modify_access_controls {
8349: my ($file_name,$changes,$domain,$user)=@_;
8350: my ($outcome,$deloutcome);
8351: my %store_permissions;
8352: my %new_values;
8353: my %new_control;
8354: my %translation;
8355: my @deletions = ();
8356: my $now = time;
8357: if (exists($$changes{'activate'})) {
8358: if (ref($$changes{'activate'}) eq 'HASH') {
8359: my @newitems = sort(keys(%{$$changes{'activate'}}));
8360: my $numnew = scalar(@newitems);
8361: for (my $i=0; $i<$numnew; $i++) {
8362: my $newkey = $newitems[$i];
8363: my $newid = &Apache::loncommon::get_cgi_id();
8364: if ($newkey =~ /^\d+:/) {
8365: $newkey =~ s/^(\d+)/$newid/;
8366: $translation{$1} = $newid;
8367: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
8368: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
8369: $translation{$1} = $newid;
8370: }
8371: $new_values{$file_name."\0".$newkey} =
8372: $$changes{'activate'}{$newitems[$i]};
8373: $new_control{$newkey} = $now;
8374: }
8375: }
8376: }
8377: my %todelete;
8378: my %changed_items;
8379: foreach my $action ('delete','update') {
8380: if (exists($$changes{$action})) {
8381: if (ref($$changes{$action}) eq 'HASH') {
8382: foreach my $key (keys(%{$$changes{$action}})) {
8383: my ($itemnum) = ($key =~ /^([^:]+):/);
8384: if ($action eq 'delete') {
8385: $todelete{$itemnum} = 1;
8386: } else {
8387: $changed_items{$itemnum} = $key;
8388: }
8389: }
8390: }
8391: }
8392: }
8393: # get lock on access controls for file.
8394: my $lockhash = {
8395: $file_name."\0".'locked_access_records' => $env{'user.name'}.
8396: ':'.$env{'user.domain'},
8397: };
8398: my $tries = 0;
8399: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8400:
8401: while (($gotlock ne 'ok') && $tries <3) {
8402: $tries ++;
8403: sleep 1;
8404: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8405: }
8406: if ($gotlock eq 'ok') {
8407: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
8408: my ($tmp)=keys(%curr_permissions);
8409: if ($tmp=~/^error:/) { undef(%curr_permissions); }
8410: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
8411: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
8412: if (ref($curr_controls) eq 'HASH') {
8413: foreach my $control_item (keys(%{$curr_controls})) {
8414: my ($itemnum) = ($control_item =~ /^([^:]+):/);
8415: if (defined($todelete{$itemnum})) {
8416: push(@deletions,$file_name."\0".$control_item);
8417: } else {
8418: if (defined($changed_items{$itemnum})) {
8419: $new_control{$changed_items{$itemnum}} = $now;
8420: push(@deletions,$file_name."\0".$control_item);
8421: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
8422: } else {
8423: $new_control{$control_item} = $$curr_controls{$control_item};
8424: }
8425: }
8426: }
8427: }
8428: }
8429: my ($group);
8430: if (&is_course($domain,$user)) {
8431: ($group,my $file) = split(/\//,$file_name,2);
8432: }
8433: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
8434: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
8435: $outcome = &put('file_permissions',\%new_values,$domain,$user);
8436: # remove lock
8437: my @del_lock = ($file_name."\0".'locked_access_records');
8438: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
8439: my $sqlresult =
8440: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
8441: $group);
8442: } else {
8443: $outcome = "error: could not obtain lockfile\n";
8444: }
8445: return ($outcome,$deloutcome,\%new_values,\%translation);
8446: }
8447:
8448: sub make_public_indefinitely {
8449: my ($requrl) = @_;
8450: my $now = time;
8451: my $action = 'activate';
8452: my $aclnum = 0;
8453: if (&is_portfolio_url($requrl)) {
8454: my (undef,$udom,$unum,$file_name,$group) =
8455: &parse_portfolio_url($requrl);
8456: my $current_perms = &get_portfile_permissions($udom,$unum);
8457: my %access_controls = &get_access_controls($current_perms,
8458: $group,$file_name);
8459: foreach my $key (keys(%{$access_controls{$file_name}})) {
8460: my ($num,$scope,$end,$start) =
8461: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
8462: if ($scope eq 'public') {
8463: if ($start <= $now && $end == 0) {
8464: $action = 'none';
8465: } else {
8466: $action = 'update';
8467: $aclnum = $num;
8468: }
8469: last;
8470: }
8471: }
8472: if ($action eq 'none') {
8473: return 'ok';
8474: } else {
8475: my %changes;
8476: my $newend = 0;
8477: my $newstart = $now;
8478: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
8479: $changes{$action}{$newkey} = {
8480: type => 'public',
8481: time => {
8482: start => $newstart,
8483: end => $newend,
8484: },
8485: };
8486: my ($outcome,$deloutcome,$new_values,$translation) =
8487: &modify_access_controls($file_name,\%changes,$udom,$unum);
8488: return $outcome;
8489: }
8490: } else {
8491: return 'invalid';
8492: }
8493: }
8494:
8495: #------------------------------------------------------Get Marked as Read Only
8496:
8497: sub get_marked_as_readonly {
8498: my ($domain,$user,$what,$group) = @_;
8499: my $current_permissions = &get_portfile_permissions($domain,$user);
8500: my @readonly_files;
8501: my $cmp1=$what;
8502: if (ref($what)) { $cmp1=join('',@{$what}) };
8503: while (my ($file_name,$value) = each(%{$current_permissions})) {
8504: if (defined($group)) {
8505: if ($file_name !~ m-^\Q$group\E/-) {
8506: next;
8507: }
8508: }
8509: if (ref($value) eq "ARRAY"){
8510: foreach my $stored_what (@{$value}) {
8511: my $cmp2=$stored_what;
8512: if (ref($stored_what) eq 'ARRAY') {
8513: $cmp2=join('',@{$stored_what});
8514: }
8515: if ($cmp1 eq $cmp2) {
8516: push(@readonly_files, $file_name);
8517: last;
8518: } elsif (!defined($what)) {
8519: push(@readonly_files, $file_name);
8520: last;
8521: }
8522: }
8523: }
8524: }
8525: return @readonly_files;
8526: }
8527: #-----------------------------------------------------------Get Marked as Read Only Hash
8528:
8529: sub get_marked_as_readonly_hash {
8530: my ($current_permissions,$group,$what) = @_;
8531: my %readonly_files;
8532: while (my ($file_name,$value) = each(%{$current_permissions})) {
8533: if (defined($group)) {
8534: if ($file_name !~ m-^\Q$group\E/-) {
8535: next;
8536: }
8537: }
8538: if (ref($value) eq "ARRAY"){
8539: foreach my $stored_what (@{$value}) {
8540: if (ref($stored_what) eq 'ARRAY') {
8541: foreach my $lock_descriptor(@{$stored_what}) {
8542: if ($lock_descriptor eq 'graded') {
8543: $readonly_files{$file_name} = 'graded';
8544: } elsif ($lock_descriptor eq 'handback') {
8545: $readonly_files{$file_name} = 'handback';
8546: } else {
8547: if (!exists($readonly_files{$file_name})) {
8548: $readonly_files{$file_name} = 'locked';
8549: }
8550: }
8551: }
8552: }
8553: }
8554: }
8555: }
8556: return %readonly_files;
8557: }
8558: # ------------------------------------------------------------ Unmark as Read Only
8559:
8560: sub unmark_as_readonly {
8561: # unmarks $file_name (if $file_name is defined), or all files locked by $what
8562: # for portfolio submissions, $what contains [$symb,$crsid]
8563: my ($domain,$user,$what,$file_name,$group) = @_;
8564: $file_name = &declutter_portfile($file_name);
8565: my $symb_crs = $what;
8566: if (ref($what)) { $symb_crs=join('',@$what); }
8567: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
8568: my ($tmp)=keys(%current_permissions);
8569: if ($tmp=~/^error:/) { undef(%current_permissions); }
8570: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
8571: foreach my $file (@readonly_files) {
8572: my $clean_file = &declutter_portfile($file);
8573: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
8574: my $current_locks = $current_permissions{$file};
8575: my @new_locks;
8576: my @del_keys;
8577: if (ref($current_locks) eq "ARRAY"){
8578: foreach my $locker (@{$current_locks}) {
8579: my $compare=$locker;
8580: if (ref($locker) eq 'ARRAY') {
8581: $compare=join('',@{$locker});
8582: if ($compare ne $symb_crs) {
8583: push(@new_locks, $locker);
8584: }
8585: }
8586: }
8587: if (scalar(@new_locks) > 0) {
8588: $current_permissions{$file} = \@new_locks;
8589: } else {
8590: push(@del_keys, $file);
8591: &del('file_permissions',\@del_keys, $domain, $user);
8592: delete($current_permissions{$file});
8593: }
8594: }
8595: }
8596: &put('file_permissions',\%current_permissions,$domain,$user);
8597: return;
8598: }
8599:
8600: # ------------------------------------------------------------ Directory lister
8601:
8602: sub dirlist {
8603: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
8604: $uri=~s/^\///;
8605: $uri=~s/\/$//;
8606: my ($udom, $uname);
8607: if ($getuserdir) {
8608: $udom = $userdomain;
8609: $uname = $username;
8610: } else {
8611: (undef,$udom,$uname)=split(/\//,$uri);
8612: if(defined($userdomain)) {
8613: $udom = $userdomain;
8614: }
8615: if(defined($username)) {
8616: $uname = $username;
8617: }
8618: }
8619: my ($dirRoot,$listing,@listing_results);
8620:
8621: $dirRoot = $perlvar{'lonDocRoot'};
8622: if (defined($getpropath)) {
8623: $dirRoot = &propath($udom,$uname);
8624: $dirRoot =~ s/\/$//;
8625: } elsif (defined($getuserdir)) {
8626: my $subdir=$uname.'__';
8627: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
8628: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
8629: ."/$udom/$subdir/$uname";
8630: } elsif (defined($alternateRoot)) {
8631: $dirRoot = $alternateRoot;
8632: }
8633:
8634: if($udom) {
8635: if($uname) {
8636: my $uhome = &homeserver($uname,$udom);
8637: if ($uhome eq 'no_host') {
8638: return ([],'no_host');
8639: }
8640: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
8641: .$getuserdir.':'.&escape($dirRoot)
8642: .':'.&escape($uname).':'.&escape($udom),$uhome);
8643: if ($listing eq 'unknown_cmd') {
8644: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
8645: } else {
8646: @listing_results = map { &unescape($_); } split(/:/,$listing);
8647: }
8648: if ($listing eq 'unknown_cmd') {
8649: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
8650: @listing_results = split(/:/,$listing);
8651: } else {
8652: @listing_results = map { &unescape($_); } split(/:/,$listing);
8653: }
8654: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
8655: ($listing eq 'rejected') || ($listing eq 'refused') ||
8656: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8657: return ([],$listing);
8658: } else {
8659: return (\@listing_results);
8660: }
8661: } elsif(!$alternateRoot) {
8662: my (%allusers,%listerror);
8663: my %servers = &get_servers($udom,'library');
8664: foreach my $tryserver (keys(%servers)) {
8665: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
8666: &escape($udom),$tryserver);
8667: if ($listing eq 'unknown_cmd') {
8668: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
8669: $udom, $tryserver);
8670: } else {
8671: @listing_results = map { &unescape($_); } split(/:/,$listing);
8672: }
8673: if ($listing eq 'unknown_cmd') {
8674: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
8675: $udom, $tryserver);
8676: @listing_results = split(/:/,$listing);
8677: } else {
8678: @listing_results =
8679: map { &unescape($_); } split(/:/,$listing);
8680: }
8681: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
8682: ($listing eq 'rejected') || ($listing eq 'refused') ||
8683: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8684: $listerror{$tryserver} = $listing;
8685: } else {
8686: foreach my $line (@listing_results) {
8687: my ($entry) = split(/&/,$line,2);
8688: $allusers{$entry} = 1;
8689: }
8690: }
8691: }
8692: my @alluserslist=();
8693: foreach my $user (sort(keys(%allusers))) {
8694: push(@alluserslist,$user.'&user');
8695: }
8696: return (\@alluserslist);
8697: } else {
8698: return ([],'missing username');
8699: }
8700: } elsif(!defined($getpropath)) {
8701: my $path = $perlvar{'lonDocRoot'}.'/res/';
8702: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
8703: return (\@all_domains);
8704: } else {
8705: return ([],'missing domain');
8706: }
8707: }
8708:
8709: # --------------------------------------------- GetFileTimestamp
8710: # This function utilizes dirlist and returns the date stamp for
8711: # when it was last modified. It will also return an error of -1
8712: # if an error occurs
8713:
8714: sub GetFileTimestamp {
8715: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
8716: $studentDomain = &LONCAPA::clean_domain($studentDomain);
8717: $studentName = &LONCAPA::clean_username($studentName);
8718: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
8719: undef,$getuserdir);
8720: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8721: return -1;
8722: }
8723: if (ref($fileref) eq 'ARRAY') {
8724: my @stats = split('&',$fileref->[0]);
8725: # @stats contains first the filename, then the stat output
8726: return $stats[10]; # so this is 10 instead of 9.
8727: } else {
8728: return -1;
8729: }
8730: }
8731:
8732: sub stat_file {
8733: my ($uri) = @_;
8734: $uri = &clutter_with_no_wrapper($uri);
8735:
8736: my ($udom,$uname,$file);
8737: if ($uri =~ m-^/(uploaded|editupload)/-) {
8738: ($udom,$uname,$file) =
8739: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
8740: $file = 'userfiles/'.$file;
8741: }
8742: if ($uri =~ m-^/res/-) {
8743: ($udom,$uname) =
8744: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
8745: $file = $uri;
8746: }
8747:
8748: if (!$udom || !$uname || !$file) {
8749: # unable to handle the uri
8750: return ();
8751: }
8752: my $getpropath;
8753: if ($file =~ /^userfiles\//) {
8754: $getpropath = 1;
8755: }
8756: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
8757: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8758: return ();
8759: } else {
8760: if (ref($listref) eq 'ARRAY') {
8761: my @stats = split('&',$listref->[0]);
8762: shift(@stats); #filename is first
8763: return @stats;
8764: }
8765: }
8766: return ();
8767: }
8768:
8769: # -------------------------------------------------------- Value of a Condition
8770:
8771: # gets the value of a specific preevaluated condition
8772: # stored in the string $env{user.state.<cid>}
8773: # or looks up a condition reference in the bighash and if if hasn't
8774: # already been evaluated recurses into docondval to get the value of
8775: # the condition, then memoizing it to
8776: # $env{user.state.<cid>.<condition>}
8777: sub directcondval {
8778: my $number=shift;
8779: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
8780: &Apache::lonuserstate::evalstate();
8781: }
8782: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
8783: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
8784: } elsif ($number =~ /^_/) {
8785: my $sub_condition;
8786: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8787: &GDBM_READER(),0640)) {
8788: $sub_condition=$bighash{'conditions'.$number};
8789: untie(%bighash);
8790: }
8791: my $value = &docondval($sub_condition);
8792: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
8793: return $value;
8794: }
8795: if ($env{'user.state.'.$env{'request.course.id'}}) {
8796: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
8797: } else {
8798: return 2;
8799: }
8800: }
8801:
8802: # get the collection of conditions for this resource
8803: sub condval {
8804: my $condidx=shift;
8805: my $allpathcond='';
8806: foreach my $cond (split(/\|/,$condidx)) {
8807: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8808: $allpathcond.=
8809: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8810: }
8811: }
8812: $allpathcond=~s/\|$//;
8813: return &docondval($allpathcond);
8814: }
8815:
8816: #evaluates an expression of conditions
8817: sub docondval {
8818: my ($allpathcond) = @_;
8819: my $result=0;
8820: if ($env{'request.course.id'}
8821: && defined($allpathcond)) {
8822: my $operand='|';
8823: my @stack;
8824: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8825: if ($chunk eq '(') {
8826: push @stack,($operand,$result);
8827: } elsif ($chunk eq ')') {
8828: my $before=pop @stack;
8829: if (pop @stack eq '&') {
8830: $result=$result>$before?$before:$result;
8831: } else {
8832: $result=$result>$before?$result:$before;
8833: }
8834: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8835: $operand=$chunk;
8836: } else {
8837: my $new=directcondval($chunk);
8838: if ($operand eq '&') {
8839: $result=$result>$new?$new:$result;
8840: } else {
8841: $result=$result>$new?$result:$new;
8842: }
8843: }
8844: }
8845: }
8846: return $result;
8847: }
8848:
8849: # ---------------------------------------------------- Devalidate courseresdata
8850:
8851: sub devalidatecourseresdata {
8852: my ($coursenum,$coursedomain)=@_;
8853: my $hashid=$coursenum.':'.$coursedomain;
8854: &devalidate_cache_new('courseres',$hashid);
8855: }
8856:
8857:
8858: # --------------------------------------------------- Course Resourcedata Query
8859: #
8860: # Parameters:
8861: # $coursenum - Number of the course.
8862: # $coursedomain - Domain at which the course was created.
8863: # Returns:
8864: # A hash of the course parameters along (I think) with timestamps
8865: # and version info.
8866:
8867: sub get_courseresdata {
8868: my ($coursenum,$coursedomain)=@_;
8869: my $coursehom=&homeserver($coursenum,$coursedomain);
8870: my $hashid=$coursenum.':'.$coursedomain;
8871: my ($result,$cached)=&is_cached_new('courseres',$hashid);
8872: my %dumpreply;
8873: unless (defined($cached)) {
8874: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
8875: $result=\%dumpreply;
8876: my ($tmp) = keys(%dumpreply);
8877: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
8878: &do_cache_new('courseres',$hashid,$result,600);
8879: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8880: return $tmp;
8881: } elsif ($tmp =~ /^(error)/) {
8882: $result=undef;
8883: &do_cache_new('courseres',$hashid,$result,600);
8884: }
8885: }
8886: return $result;
8887: }
8888:
8889: sub devalidateuserresdata {
8890: my ($uname,$udom)=@_;
8891: my $hashid="$udom:$uname";
8892: &devalidate_cache_new('userres',$hashid);
8893: }
8894:
8895: sub get_userresdata {
8896: my ($uname,$udom)=@_;
8897: #most student don\'t have any data set, check if there is some data
8898: if (&EXT_cache_status($udom,$uname)) { return undef; }
8899:
8900: my $hashid="$udom:$uname";
8901: my ($result,$cached)=&is_cached_new('userres',$hashid);
8902: if (!defined($cached)) {
8903: my %resourcedata=&dump('resourcedata',$udom,$uname);
8904: $result=\%resourcedata;
8905: &do_cache_new('userres',$hashid,$result,600);
8906: }
8907: my ($tmp)=keys(%$result);
8908: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8909: return $result;
8910: }
8911: #error 2 occurs when the .db doesn't exist
8912: if ($tmp!~/error: 2 /) {
8913: &logthis("<font color=\"blue\">WARNING:".
8914: " Trying to get resource data for ".
8915: $uname." at ".$udom.": ".
8916: $tmp."</font>");
8917: } elsif ($tmp=~/error: 2 /) {
8918: #&EXT_cache_set($udom,$uname);
8919: &do_cache_new('userres',$hashid,undef,600);
8920: undef($tmp); # not really an error so don't send it back
8921: }
8922: return $tmp;
8923: }
8924: #----------------------------------------------- resdata - return resource data
8925: # Purpose:
8926: # Return resource data for either users or for a course.
8927: # Parameters:
8928: # $name - Course/user name.
8929: # $domain - Name of the domain the user/course is registered on.
8930: # $type - Type of thing $name is (must be 'course' or 'user'
8931: # @which - Array of names of resources desired.
8932: # Returns:
8933: # The value of the first reasource in @which that is found in the
8934: # resource hash.
8935: # Exceptional Conditions:
8936: # If the $type passed in is not valid (not the string 'course' or
8937: # 'user', an undefined reference is returned.
8938: # If none of the resources are found, an undef is returned
8939: sub resdata {
8940: my ($name,$domain,$type,@which)=@_;
8941: my $result;
8942: if ($type eq 'course') {
8943: $result=&get_courseresdata($name,$domain);
8944: } elsif ($type eq 'user') {
8945: $result=&get_userresdata($name,$domain);
8946: }
8947: if (!ref($result)) { return $result; }
8948: foreach my $item (@which) {
8949: if (defined($result->{$item->[0]})) {
8950: return [$result->{$item->[0]},$item->[1]];
8951: }
8952: }
8953: return undef;
8954: }
8955:
8956: #
8957: # EXT resource caching routines
8958: #
8959:
8960: sub clear_EXT_cache_status {
8961: &delenv('cache.EXT.');
8962: }
8963:
8964: sub EXT_cache_status {
8965: my ($target_domain,$target_user) = @_;
8966: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
8967: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
8968: # We know already the user has no data
8969: return 1;
8970: } else {
8971: return 0;
8972: }
8973: }
8974:
8975: sub EXT_cache_set {
8976: my ($target_domain,$target_user) = @_;
8977: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
8978: #&appenv({$cachename => time});
8979: }
8980:
8981: # --------------------------------------------------------- Value of a Variable
8982: sub EXT {
8983:
8984: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
8985: unless ($varname) { return ''; }
8986: #get real user name/domain, courseid and symb
8987: my $courseid;
8988: my $publicuser;
8989: if ($symbparm) {
8990: $symbparm=&get_symb_from_alias($symbparm);
8991: }
8992: if (!($uname && $udom)) {
8993: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
8994: if (!$symbparm) { $symbparm=$cursymb; }
8995: } else {
8996: $courseid=$env{'request.course.id'};
8997: }
8998: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8999: my $rest;
9000: if (defined($therest[0])) {
9001: $rest=join('.',@therest);
9002: } else {
9003: $rest='';
9004: }
9005:
9006: my $qualifierrest=$qualifier;
9007: if ($rest) { $qualifierrest.='.'.$rest; }
9008: my $spacequalifierrest=$space;
9009: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
9010: if ($realm eq 'user') {
9011: # --------------------------------------------------------------- user.resource
9012: if ($space eq 'resource') {
9013: if ( (defined($Apache::lonhomework::parsing_a_problem)
9014: || defined($Apache::lonhomework::parsing_a_task))
9015: &&
9016: ($symbparm eq &symbread()) ) {
9017: # if we are in the middle of processing the resource the
9018: # get the value we are planning on committing
9019: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9020: return $Apache::lonhomework::results{$qualifierrest};
9021: } else {
9022: return $Apache::lonhomework::history{$qualifierrest};
9023: }
9024: } else {
9025: my %restored;
9026: if ($publicuser || $env{'request.state'} eq 'construct') {
9027: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9028: } else {
9029: %restored=&restore($symbparm,$courseid,$udom,$uname);
9030: }
9031: return $restored{$qualifierrest};
9032: }
9033: # ----------------------------------------------------------------- user.access
9034: } elsif ($space eq 'access') {
9035: # FIXME - not supporting calls for a specific user
9036: return &allowed($qualifier,$rest);
9037: # ------------------------------------------ user.preferences, user.environment
9038: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
9039: if (($uname eq $env{'user.name'}) &&
9040: ($udom eq $env{'user.domain'})) {
9041: return $env{join('.',('environment',$qualifierrest))};
9042: } else {
9043: my %returnhash;
9044: if (!$publicuser) {
9045: %returnhash=&userenvironment($udom,$uname,
9046: $qualifierrest);
9047: }
9048: return $returnhash{$qualifierrest};
9049: }
9050: # ----------------------------------------------------------------- user.course
9051: } elsif ($space eq 'course') {
9052: # FIXME - not supporting calls for a specific user
9053: return $env{join('.',('request.course',$qualifier))};
9054: # ------------------------------------------------------------------- user.role
9055: } elsif ($space eq 'role') {
9056: # FIXME - not supporting calls for a specific user
9057: my ($role,$where)=split(/\./,$env{'request.role'});
9058: if ($qualifier eq 'value') {
9059: return $role;
9060: } elsif ($qualifier eq 'extent') {
9061: return $where;
9062: }
9063: # ----------------------------------------------------------------- user.domain
9064: } elsif ($space eq 'domain') {
9065: return $udom;
9066: # ------------------------------------------------------------------- user.name
9067: } elsif ($space eq 'name') {
9068: return $uname;
9069: # ---------------------------------------------------- Any other user namespace
9070: } else {
9071: my %reply;
9072: if (!$publicuser) {
9073: %reply=&get($space,[$qualifierrest],$udom,$uname);
9074: }
9075: return $reply{$qualifierrest};
9076: }
9077: } elsif ($realm eq 'query') {
9078: # ---------------------------------------------- pull stuff out of query string
9079: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9080: [$spacequalifierrest]);
9081: return $env{'form.'.$spacequalifierrest};
9082: } elsif ($realm eq 'request') {
9083: # ------------------------------------------------------------- request.browser
9084: if ($space eq 'browser') {
9085: return $env{'browser.'.$qualifier};
9086: # ------------------------------------------------------------ request.filename
9087: } else {
9088: return $env{'request.'.$spacequalifierrest};
9089: }
9090: } elsif ($realm eq 'course') {
9091: # ---------------------------------------------------------- course.description
9092: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
9093: } elsif ($realm eq 'resource') {
9094:
9095: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
9096: if (!$symbparm) { $symbparm=&symbread(); }
9097: }
9098:
9099: if ($space eq 'title') {
9100: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9101: return &gettitle($symbparm);
9102: }
9103:
9104: if ($space eq 'map') {
9105: my ($map) = &decode_symb($symbparm);
9106: return &symbread($map);
9107: }
9108: if ($space eq 'filename') {
9109: if ($symbparm) {
9110: return &clutter((&decode_symb($symbparm))[2]);
9111: }
9112: return &hreflocation('',$env{'request.filename'});
9113: }
9114:
9115: my ($section, $group, @groups);
9116: my ($courselevelm,$courselevel);
9117: if ($symbparm && defined($courseid) &&
9118: $courseid eq $env{'request.course.id'}) {
9119:
9120: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
9121:
9122: # ----------------------------------------------------- Cascading lookup scheme
9123: my $symbp=$symbparm;
9124: my $mapp=&deversion((&decode_symb($symbp))[0]);
9125:
9126: my $symbparm=$symbp.'.'.$spacequalifierrest;
9127: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9128:
9129: if (($env{'user.name'} eq $uname) &&
9130: ($env{'user.domain'} eq $udom)) {
9131: $section=$env{'request.course.sec'};
9132: @groups = split(/:/,$env{'request.course.groups'});
9133: @groups=&sort_course_groups($courseid,@groups);
9134: } else {
9135: if (! defined($usection)) {
9136: $section=&getsection($udom,$uname,$courseid);
9137: } else {
9138: $section = $usection;
9139: }
9140: @groups = &get_users_groups($udom,$uname,$courseid);
9141: }
9142:
9143: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9144: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9145: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9146:
9147: $courselevel=$courseid.'.'.$spacequalifierrest;
9148: my $courselevelr=$courseid.'.'.$symbparm;
9149: $courselevelm=$courseid.'.'.$mapparm;
9150:
9151: # ----------------------------------------------------------- first, check user
9152:
9153: my $userreply=&resdata($uname,$udom,'user',
9154: ([$courselevelr,'resource'],
9155: [$courselevelm,'map' ],
9156: [$courselevel, 'course' ]));
9157: if (defined($userreply)) { return &get_reply($userreply); }
9158:
9159: # ------------------------------------------------ second, check some of course
9160: my $coursereply;
9161: if (@groups > 0) {
9162: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9163: $mapparm,$spacequalifierrest);
9164: if (defined($coursereply)) { return &get_reply($coursereply); }
9165: }
9166:
9167: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9168: $env{'course.'.$courseid.'.domain'},
9169: 'course',
9170: ([$seclevelr, 'resource'],
9171: [$seclevelm, 'map' ],
9172: [$seclevel, 'course' ],
9173: [$courselevelr,'resource']));
9174: if (defined($coursereply)) { return &get_reply($coursereply); }
9175:
9176: # ------------------------------------------------------ third, check map parms
9177: my %parmhash=();
9178: my $thisparm='';
9179: if (tie(%parmhash,'GDBM_File',
9180: $env{'request.course.fn'}.'_parms.db',
9181: &GDBM_READER(),0640)) {
9182: $thisparm=$parmhash{$symbparm};
9183: untie(%parmhash);
9184: }
9185: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
9186: }
9187: # ------------------------------------------ fourth, look in resource metadata
9188:
9189: $spacequalifierrest=~s/\./\_/;
9190: my $filename;
9191: if (!$symbparm) { $symbparm=&symbread(); }
9192: if ($symbparm) {
9193: $filename=(&decode_symb($symbparm))[2];
9194: } else {
9195: $filename=$env{'request.filename'};
9196: }
9197: my $metadata=&metadata($filename,$spacequalifierrest);
9198: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
9199: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
9200: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
9201:
9202: # ---------------------------------------------- fourth, look in rest of course
9203: if ($symbparm && defined($courseid) &&
9204: $courseid eq $env{'request.course.id'}) {
9205: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9206: $env{'course.'.$courseid.'.domain'},
9207: 'course',
9208: ([$courselevelm,'map' ],
9209: [$courselevel, 'course']));
9210: if (defined($coursereply)) { return &get_reply($coursereply); }
9211: }
9212: # ------------------------------------------------------------------ Cascade up
9213: unless ($space eq '0') {
9214: my @parts=split(/_/,$space);
9215: my $id=pop(@parts);
9216: my $part=join('_',@parts);
9217: if ($part eq '') { $part='0'; }
9218: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
9219: $symbparm,$udom,$uname,$section,1);
9220: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
9221: }
9222: if ($recurse) { return undef; }
9223: my $pack_def=&packages_tab_default($filename,$varname);
9224: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
9225: # ---------------------------------------------------- Any other user namespace
9226: } elsif ($realm eq 'environment') {
9227: # ----------------------------------------------------------------- environment
9228: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
9229: return $env{'environment.'.$spacequalifierrest};
9230: } else {
9231: if ($uname eq 'anonymous' && $udom eq '') {
9232: return '';
9233: }
9234: my %returnhash=&userenvironment($udom,$uname,
9235: $spacequalifierrest);
9236: return $returnhash{$spacequalifierrest};
9237: }
9238: } elsif ($realm eq 'system') {
9239: # ----------------------------------------------------------------- system.time
9240: if ($space eq 'time') {
9241: return time;
9242: }
9243: } elsif ($realm eq 'server') {
9244: # ----------------------------------------------------------------- system.time
9245: if ($space eq 'name') {
9246: return $ENV{'SERVER_NAME'};
9247: }
9248: }
9249: return '';
9250: }
9251:
9252: sub get_reply {
9253: my ($reply_value) = @_;
9254: if (ref($reply_value) eq 'ARRAY') {
9255: if (wantarray) {
9256: return @$reply_value;
9257: }
9258: return $reply_value->[0];
9259: } else {
9260: return $reply_value;
9261: }
9262: }
9263:
9264: sub check_group_parms {
9265: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
9266: my @groupitems = ();
9267: my $resultitem;
9268: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
9269: foreach my $group (@{$groups}) {
9270: foreach my $level (@levels) {
9271: my $item = $courseid.'.['.$group.'].'.$level->[0];
9272: push(@groupitems,[$item,$level->[1]]);
9273: }
9274: }
9275: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
9276: $env{'course.'.$courseid.'.domain'},
9277: 'course',@groupitems);
9278: return $coursereply;
9279: }
9280:
9281: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
9282: my ($courseid,@groups) = @_;
9283: @groups = sort(@groups);
9284: return @groups;
9285: }
9286:
9287: sub packages_tab_default {
9288: my ($uri,$varname)=@_;
9289: my (undef,$part,$name)=split(/\./,$varname);
9290:
9291: my (@extension,@specifics,$do_default);
9292: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
9293: my ($pack_type,$pack_part)=split(/_/,$package,2);
9294: if ($pack_type eq 'default') {
9295: $do_default=1;
9296: } elsif ($pack_type eq 'extension') {
9297: push(@extension,[$package,$pack_type,$pack_part]);
9298: } elsif ($pack_part eq $part || $pack_type eq 'part') {
9299: # only look at packages defaults for packages that this id is
9300: push(@specifics,[$package,$pack_type,$pack_part]);
9301: }
9302: }
9303: # first look for a package that matches the requested part id
9304: foreach my $package (@specifics) {
9305: my (undef,$pack_type,$pack_part)=@{$package};
9306: next if ($pack_part ne $part);
9307: if (defined($packagetab{"$pack_type&$name&default"})) {
9308: return $packagetab{"$pack_type&$name&default"};
9309: }
9310: }
9311: # look for any possible matching non extension_ package
9312: foreach my $package (@specifics) {
9313: my (undef,$pack_type,$pack_part)=@{$package};
9314: if (defined($packagetab{"$pack_type&$name&default"})) {
9315: return $packagetab{"$pack_type&$name&default"};
9316: }
9317: if ($pack_type eq 'part') { $pack_part='0'; }
9318: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
9319: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
9320: }
9321: }
9322: # look for any posible extension_ match
9323: foreach my $package (@extension) {
9324: my ($package,$pack_type)=@{$package};
9325: if (defined($packagetab{"$pack_type&$name&default"})) {
9326: return $packagetab{"$pack_type&$name&default"};
9327: }
9328: if (defined($packagetab{$package."&$name&default"})) {
9329: return $packagetab{$package."&$name&default"};
9330: }
9331: }
9332: # look for a global default setting
9333: if ($do_default && defined($packagetab{"default&$name&default"})) {
9334: return $packagetab{"default&$name&default"};
9335: }
9336: return undef;
9337: }
9338:
9339: sub add_prefix_and_part {
9340: my ($prefix,$part)=@_;
9341: my $keyroot;
9342: if (defined($prefix) && $prefix !~ /^__/) {
9343: # prefix that has a part already
9344: $keyroot=$prefix;
9345: } elsif (defined($prefix)) {
9346: # prefix that is missing a part
9347: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
9348: } else {
9349: # no prefix at all
9350: if (defined($part)) { $keyroot='_'.$part; }
9351: }
9352: return $keyroot;
9353: }
9354:
9355: # ---------------------------------------------------------------- Get metadata
9356:
9357: my %metaentry;
9358: my %importedpartids;
9359: sub metadata {
9360: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
9361: $uri=&declutter($uri);
9362: # if it is a non metadata possible uri return quickly
9363: if (($uri eq '') ||
9364: (($uri =~ m|^/*adm/|) &&
9365: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
9366: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
9367: return undef;
9368: }
9369: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
9370: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
9371: return undef;
9372: }
9373: my $filename=$uri;
9374: $uri=~s/\.meta$//;
9375: #
9376: # Is the metadata already cached?
9377: # Look at timestamp of caching
9378: # Everything is cached by the main uri, libraries are never directly cached
9379: #
9380: if (!defined($liburi)) {
9381: my ($result,$cached)=&is_cached_new('meta',$uri);
9382: if (defined($cached)) { return $result->{':'.$what}; }
9383: }
9384: {
9385: # Imported parts would go here
9386: my %importedids=();
9387: my @origfileimportpartids=();
9388: my $importedparts=0;
9389: #
9390: # Is this a recursive call for a library?
9391: #
9392: # if (! exists($metacache{$uri})) {
9393: # $metacache{$uri}={};
9394: # }
9395: my $cachetime = 60*60;
9396: if ($liburi) {
9397: $liburi=&declutter($liburi);
9398: $filename=$liburi;
9399: } else {
9400: &devalidate_cache_new('meta',$uri);
9401: undef(%metaentry);
9402: }
9403: my %metathesekeys=();
9404: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
9405: my $metastring;
9406: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
9407: my $which = &hreflocation('','/'.($liburi || $uri));
9408: $metastring =
9409: &Apache::lonnet::ssi_body($which,
9410: ('grade_target' => 'meta'));
9411: $cachetime = 1; # only want this cached in the child not long term
9412: } elsif (($uri !~ m -^(editupload)/-) &&
9413: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
9414: my $file=&filelocation('',&clutter($filename));
9415: #push(@{$metaentry{$uri.'.file'}},$file);
9416: $metastring=&getfile($file);
9417: }
9418: my $parser=HTML::LCParser->new(\$metastring);
9419: my $token;
9420: undef %metathesekeys;
9421: while ($token=$parser->get_token) {
9422: if ($token->[0] eq 'S') {
9423: if (defined($token->[2]->{'package'})) {
9424: #
9425: # This is a package - get package info
9426: #
9427: my $package=$token->[2]->{'package'};
9428: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9429: if (defined($token->[2]->{'id'})) {
9430: $keyroot.='_'.$token->[2]->{'id'};
9431: }
9432: if ($metaentry{':packages'}) {
9433: $metaentry{':packages'}.=','.$package.$keyroot;
9434: } else {
9435: $metaentry{':packages'}=$package.$keyroot;
9436: }
9437: foreach my $pack_entry (keys(%packagetab)) {
9438: my $part=$keyroot;
9439: $part=~s/^\_//;
9440: if ($pack_entry=~/^\Q$package\E\&/ ||
9441: $pack_entry=~/^\Q$package\E_0\&/) {
9442: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
9443: # ignore package.tab specified default values
9444: # here &package_tab_default() will fetch those
9445: if ($subp eq 'default') { next; }
9446: my $value=$packagetab{$pack_entry};
9447: my $unikey;
9448: if ($pack =~ /_0$/) {
9449: $unikey='parameter_0_'.$name;
9450: $part=0;
9451: } else {
9452: $unikey='parameter'.$keyroot.'_'.$name;
9453: }
9454: if ($subp eq 'display') {
9455: $value.=' [Part: '.$part.']';
9456: }
9457: $metaentry{':'.$unikey.'.part'}=$part;
9458: $metathesekeys{$unikey}=1;
9459: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9460: $metaentry{':'.$unikey.'.'.$subp}=$value;
9461: }
9462: if (defined($metaentry{':'.$unikey.'.default'})) {
9463: $metaentry{':'.$unikey}=
9464: $metaentry{':'.$unikey.'.default'};
9465: }
9466: }
9467: }
9468: } else {
9469: #
9470: # This is not a package - some other kind of start tag
9471: #
9472: my $entry=$token->[1];
9473: my $unikey='';
9474:
9475: if ($entry eq 'import') {
9476: #
9477: # Importing a library here
9478: #
9479: my $location=$parser->get_text('/import');
9480: my $dir=$filename;
9481: $dir=~s|[^/]*$||;
9482: $location=&filelocation($dir,$location);
9483:
9484: my $importmode=$token->[2]->{'importmode'};
9485: if ($importmode eq 'problem') {
9486: # Import as problem/response
9487: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9488: } elsif ($importmode eq 'part') {
9489: # Import as part(s)
9490: $importedparts=1;
9491: # We need to get the original file and the imported file to get the part order correct
9492: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
9493: # Load and inspect original file
9494: if ($#origfileimportpartids<0) {
9495: undef(%importedpartids);
9496: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
9497: my $origfile=&getfile($origfilelocation);
9498: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9499: }
9500:
9501: # Load and inspect imported file
9502: my $impfile=&getfile($location);
9503: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9504: if ($#impfilepartids>=0) {
9505: # This problem had parts
9506: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
9507: } else {
9508: # Importing by turning a single problem into a problem part
9509: # It gets the import-tags ID as part-ID
9510: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
9511: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
9512: }
9513: } else {
9514: # Normal import
9515: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9516: if (defined($token->[2]->{'id'})) {
9517: $unikey.='_'.$token->[2]->{'id'};
9518: }
9519: }
9520:
9521: if ($depthcount<20) {
9522: my $metadata =
9523: &metadata($uri,'keys', $location,$unikey,
9524: $depthcount+1);
9525: foreach my $meta (split(',',$metadata)) {
9526: $metaentry{':'.$meta}=$metaentry{':'.$meta};
9527: $metathesekeys{$meta}=1;
9528: }
9529:
9530: }
9531: } else {
9532: #
9533: # Not importing, some other kind of non-package, non-library start tag
9534: #
9535: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
9536: if (defined($token->[2]->{'id'})) {
9537: $unikey.='_'.$token->[2]->{'id'};
9538: }
9539: if (defined($token->[2]->{'name'})) {
9540: $unikey.='_'.$token->[2]->{'name'};
9541: }
9542: $metathesekeys{$unikey}=1;
9543: foreach my $param (@{$token->[3]}) {
9544: $metaentry{':'.$unikey.'.'.$param} =
9545: $token->[2]->{$param};
9546: }
9547: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
9548: my $default=$metaentry{':'.$unikey.'.default'};
9549: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
9550: # only ws inside the tag, and not in default, so use default
9551: # as value
9552: $metaentry{':'.$unikey}=$default;
9553: } elsif ( $internaltext =~ /\S/ ) {
9554: # something interesting inside the tag
9555: $metaentry{':'.$unikey}=$internaltext;
9556: } else {
9557: # no interesting values, don't set a default
9558: }
9559: # end of not-a-package not-a-library import
9560: }
9561: # end of not-a-package start tag
9562: }
9563: # the next is the end of "start tag"
9564: }
9565: }
9566: my ($extension) = ($uri =~ /\.(\w+)$/);
9567: $extension = lc($extension);
9568: if ($extension eq 'htm') { $extension='html'; }
9569:
9570: foreach my $key (keys(%packagetab)) {
9571: #no specific packages #how's our extension
9572: if ($key!~/^extension_\Q$extension\E&/) { next; }
9573: &metadata_create_package_def($uri,$key,'extension_'.$extension,
9574: \%metathesekeys);
9575: }
9576:
9577: if (!exists($metaentry{':packages'})
9578: || $packagetab{"import_defaults&extension_$extension"}) {
9579: foreach my $key (keys(%packagetab)) {
9580: #no specific packages well let's get default then
9581: if ($key!~/^default&/) { next; }
9582: &metadata_create_package_def($uri,$key,'default',
9583: \%metathesekeys);
9584: }
9585: }
9586: # are there custom rights to evaluate
9587: if ($metaentry{':copyright'} eq 'custom') {
9588:
9589: #
9590: # Importing a rights file here
9591: #
9592: unless ($depthcount) {
9593: my $location=$metaentry{':customdistributionfile'};
9594: my $dir=$filename;
9595: $dir=~s|[^/]*$||;
9596: $location=&filelocation($dir,$location);
9597: my $rights_metadata =
9598: &metadata($uri,'keys',$location,'_rights',
9599: $depthcount+1);
9600: foreach my $rights (split(',',$rights_metadata)) {
9601: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
9602: $metathesekeys{$rights}=1;
9603: }
9604: }
9605: }
9606: # uniqifiy package listing
9607: my %seen;
9608: my @uniq_packages =
9609: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
9610: $metaentry{':packages'} = join(',',@uniq_packages);
9611:
9612: if ($importedparts) {
9613: # We had imported parts and need to rebuild partorder
9614: $metaentry{':partorder'}='';
9615: $metathesekeys{'partorder'}=1;
9616: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
9617: if ($origfileimportpartids[$index] eq 'part') {
9618: # original part, part of the problem
9619: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
9620: } else {
9621: # we have imported parts at this position
9622: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
9623: }
9624: }
9625: $metaentry{':partorder'}=~s/^\,//;
9626: }
9627:
9628: $metaentry{':keys'} = join(',',keys(%metathesekeys));
9629: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
9630: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
9631: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
9632: # this is the end of "was not already recently cached
9633: }
9634: return $metaentry{':'.$what};
9635: }
9636:
9637: sub metadata_create_package_def {
9638: my ($uri,$key,$package,$metathesekeys)=@_;
9639: my ($pack,$name,$subp)=split(/\&/,$key);
9640: if ($subp eq 'default') { next; }
9641:
9642: if (defined($metaentry{':packages'})) {
9643: $metaentry{':packages'}.=','.$package;
9644: } else {
9645: $metaentry{':packages'}=$package;
9646: }
9647: my $value=$packagetab{$key};
9648: my $unikey;
9649: $unikey='parameter_0_'.$name;
9650: $metaentry{':'.$unikey.'.part'}=0;
9651: $$metathesekeys{$unikey}=1;
9652: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9653: $metaentry{':'.$unikey.'.'.$subp}=$value;
9654: }
9655: if (defined($metaentry{':'.$unikey.'.default'})) {
9656: $metaentry{':'.$unikey}=
9657: $metaentry{':'.$unikey.'.default'};
9658: }
9659: }
9660:
9661: sub metadata_generate_part0 {
9662: my ($metadata,$metacache,$uri) = @_;
9663: my %allnames;
9664: foreach my $metakey (keys(%$metadata)) {
9665: if ($metakey=~/^parameter\_(.*)/) {
9666: my $part=$$metacache{':'.$metakey.'.part'};
9667: my $name=$$metacache{':'.$metakey.'.name'};
9668: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
9669: $allnames{$name}=$part;
9670: }
9671: }
9672: }
9673: foreach my $name (keys(%allnames)) {
9674: $$metadata{"parameter_0_$name"}=1;
9675: my $key=":parameter_0_$name";
9676: $$metacache{"$key.part"}='0';
9677: $$metacache{"$key.name"}=$name;
9678: $$metacache{"$key.type"}=$$metacache{':parameter_'.
9679: $allnames{$name}.'_'.$name.
9680: '.type'};
9681: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
9682: '.display'};
9683: my $expr='[Part: '.$allnames{$name}.']';
9684: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
9685: $$metacache{"$key.display"}=$olddis;
9686: }
9687: }
9688:
9689: # ------------------------------------------------------ Devalidate title cache
9690:
9691: sub devalidate_title_cache {
9692: my ($url)=@_;
9693: if (!$env{'request.course.id'}) { return; }
9694: my $symb=&symbread($url);
9695: if (!$symb) { return; }
9696: my $key=$env{'request.course.id'}."\0".$symb;
9697: &devalidate_cache_new('title',$key);
9698: }
9699:
9700: # ------------------------------------------------- Get the title of a course
9701:
9702: sub current_course_title {
9703: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
9704: }
9705: # ------------------------------------------------- Get the title of a resource
9706:
9707: sub gettitle {
9708: my $urlsymb=shift;
9709: my $symb=&symbread($urlsymb);
9710: if ($symb) {
9711: my $key=$env{'request.course.id'}."\0".$symb;
9712: my ($result,$cached)=&is_cached_new('title',$key);
9713: if (defined($cached)) {
9714: return $result;
9715: }
9716: my ($map,$resid,$url)=&decode_symb($symb);
9717: my $title='';
9718: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
9719: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
9720: } else {
9721: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9722: &GDBM_READER(),0640)) {
9723: my $mapid=$bighash{'map_pc_'.&clutter($map)};
9724: $title=$bighash{'title_'.$mapid.'.'.$resid};
9725: untie(%bighash);
9726: }
9727: }
9728: $title=~s/\&colon\;/\:/gs;
9729: if ($title) {
9730: # Remember both $symb and $title for dynamic metadata
9731: $accesshash{$symb.'___crstitle'}=$title;
9732: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
9733: # Cache this title and then return it
9734: return &do_cache_new('title',$key,$title,600);
9735: }
9736: $urlsymb=$url;
9737: }
9738: my $title=&metadata($urlsymb,'title');
9739: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
9740: return $title;
9741: }
9742:
9743: sub get_slot {
9744: my ($which,$cnum,$cdom)=@_;
9745: if (!$cnum || !$cdom) {
9746: (undef,my $courseid)=&whichuser();
9747: $cdom=$env{'course.'.$courseid.'.domain'};
9748: $cnum=$env{'course.'.$courseid.'.num'};
9749: }
9750: my $key=join("\0",'slots',$cdom,$cnum,$which);
9751: my %slotinfo;
9752: if (exists($remembered{$key})) {
9753: $slotinfo{$which} = $remembered{$key};
9754: } else {
9755: %slotinfo=&get('slots',[$which],$cdom,$cnum);
9756: &Apache::lonhomework::showhash(%slotinfo);
9757: my ($tmp)=keys(%slotinfo);
9758: if ($tmp=~/^error:/) { return (); }
9759: $remembered{$key} = $slotinfo{$which};
9760: }
9761: if (ref($slotinfo{$which}) eq 'HASH') {
9762: return %{$slotinfo{$which}};
9763: }
9764: return $slotinfo{$which};
9765: }
9766:
9767: sub get_reservable_slots {
9768: my ($cnum,$cdom,$uname,$udom) = @_;
9769: my $now = time;
9770: my $reservable_info;
9771: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
9772: if (exists($remembered{$key})) {
9773: $reservable_info = $remembered{$key};
9774: } else {
9775: my %resv;
9776: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
9777: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
9778: $reservable_info = \%resv;
9779: $remembered{$key} = $reservable_info;
9780: }
9781: return $reservable_info;
9782: }
9783:
9784: sub get_course_slots {
9785: my ($cnum,$cdom) = @_;
9786: my $hashid=$cnum.':'.$cdom;
9787: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
9788: if (defined($cached)) {
9789: if (ref($result) eq 'HASH') {
9790: return %{$result};
9791: }
9792: } else {
9793: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
9794: my ($tmp) = keys(%slots);
9795: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9796: &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
9797: return %slots;
9798: }
9799: }
9800: return;
9801: }
9802:
9803: sub devalidate_slots_cache {
9804: my ($cnum,$cdom)=@_;
9805: my $hashid=$cnum.':'.$cdom;
9806: &devalidate_cache_new('allslots',$hashid);
9807: }
9808:
9809: # ------------------------------------------------- Update symbolic store links
9810:
9811: sub symblist {
9812: my ($mapname,%newhash)=@_;
9813: $mapname=&deversion(&declutter($mapname));
9814: my %hash;
9815: if (($env{'request.course.fn'}) && (%newhash)) {
9816: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
9817: &GDBM_WRCREAT(),0640)) {
9818: foreach my $url (keys(%newhash)) {
9819: next if ($url eq 'last_known'
9820: && $env{'form.no_update_last_known'});
9821: $hash{declutter($url)}=&encode_symb($mapname,
9822: $newhash{$url}->[1],
9823: $newhash{$url}->[0]);
9824: }
9825: if (untie(%hash)) {
9826: return 'ok';
9827: }
9828: }
9829: }
9830: return 'error';
9831: }
9832:
9833: # --------------------------------------------------------------- Verify a symb
9834:
9835: sub symbverify {
9836: my ($symb,$thisurl)=@_;
9837: my $thisfn=$thisurl;
9838: $thisfn=&declutter($thisfn);
9839: # direct jump to resource in page or to a sequence - will construct own symbs
9840: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
9841: # check URL part
9842: my ($map,$resid,$url)=&decode_symb($symb);
9843:
9844: unless ($url eq $thisfn) { return 0; }
9845:
9846: $symb=&symbclean($symb);
9847: $thisurl=&deversion($thisurl);
9848: $thisfn=&deversion($thisfn);
9849:
9850: my %bighash;
9851: my $okay=0;
9852:
9853: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9854: &GDBM_READER(),0640)) {
9855: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
9856: $thisurl =~ s/\?.+$//;
9857: }
9858: my $ids=$bighash{'ids_'.&clutter($thisurl)};
9859: unless ($ids) {
9860: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
9861: $ids=$bighash{$idkey};
9862: }
9863: if ($ids) {
9864: # ------------------------------------------------------------------- Has ID(s)
9865: foreach my $id (split(/\,/,$ids)) {
9866: my ($mapid,$resid)=split(/\./,$id);
9867: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
9868: $symb =~ s/\?.+$//;
9869: }
9870: if (
9871: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
9872: eq $symb) {
9873: if (($env{'request.role.adv'}) ||
9874: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
9875: ($thisurl eq '/adm/navmaps')) {
9876: $okay=1;
9877: }
9878: }
9879: }
9880: }
9881: untie(%bighash);
9882: }
9883: return $okay;
9884: }
9885:
9886: # --------------------------------------------------------------- Clean-up symb
9887:
9888: sub symbclean {
9889: my $symb=shift;
9890: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9891: # remove version from map
9892: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
9893:
9894: # remove version from URL
9895: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
9896:
9897: # remove wrapper
9898:
9899: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
9900: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
9901: return $symb;
9902: }
9903:
9904: # ---------------------------------------------- Split symb to find map and url
9905:
9906: sub encode_symb {
9907: my ($map,$resid,$url)=@_;
9908: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
9909: }
9910:
9911: sub decode_symb {
9912: my $symb=shift;
9913: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9914: my ($map,$resid,$url)=split(/___/,$symb);
9915: return (&fixversion($map),$resid,&fixversion($url));
9916: }
9917:
9918: sub fixversion {
9919: my $fn=shift;
9920: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
9921: my %bighash;
9922: my $uri=&clutter($fn);
9923: my $key=$env{'request.course.id'}.'_'.$uri;
9924: # is this cached?
9925: my ($result,$cached)=&is_cached_new('courseresversion',$key);
9926: if (defined($cached)) { return $result; }
9927: # unfortunately not cached, or expired
9928: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9929: &GDBM_READER(),0640)) {
9930: if ($bighash{'version_'.$uri}) {
9931: my $version=$bighash{'version_'.$uri};
9932: unless (($version eq 'mostrecent') ||
9933: ($version==&getversion($uri))) {
9934: $uri=~s/\.(\w+)$/\.$version\.$1/;
9935: }
9936: }
9937: untie %bighash;
9938: }
9939: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
9940: }
9941:
9942: sub deversion {
9943: my $url=shift;
9944: $url=~s/\.\d+\.(\w+)$/\.$1/;
9945: return $url;
9946: }
9947:
9948: # ------------------------------------------------------ Return symb list entry
9949:
9950: sub symbread {
9951: my ($thisfn,$donotrecurse)=@_;
9952: my $cache_str='request.symbread.cached.'.$thisfn;
9953: if (defined($env{$cache_str})) { return $env{$cache_str}; }
9954: # no filename provided? try from environment
9955: unless ($thisfn) {
9956: if ($env{'request.symb'}) {
9957: return $env{$cache_str}=&symbclean($env{'request.symb'});
9958: }
9959: $thisfn=$env{'request.filename'};
9960: }
9961: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
9962: # is that filename actually a symb? Verify, clean, and return
9963: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
9964: if (&symbverify($thisfn,$1)) {
9965: return $env{$cache_str}=&symbclean($thisfn);
9966: }
9967: }
9968: $thisfn=declutter($thisfn);
9969: my %hash;
9970: my %bighash;
9971: my $syval='';
9972: if (($env{'request.course.fn'}) && ($thisfn)) {
9973: my $targetfn = $thisfn;
9974: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
9975: $targetfn = 'adm/wrapper/'.$thisfn;
9976: }
9977: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9978: $targetfn=$1;
9979: }
9980: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
9981: &GDBM_READER(),0640)) {
9982: $syval=$hash{$targetfn};
9983: untie(%hash);
9984: }
9985: # ---------------------------------------------------------- There was an entry
9986: if ($syval) {
9987: #unless ($syval=~/\_\d+$/) {
9988: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
9989: #&appenv({'request.ambiguous' => $thisfn});
9990: #return $env{$cache_str}='';
9991: #}
9992: #$syval.=$1;
9993: #}
9994: } else {
9995: # ------------------------------------------------------- Was not in symb table
9996: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9997: &GDBM_READER(),0640)) {
9998: # ---------------------------------------------- Get ID(s) for current resource
9999: my $ids=$bighash{'ids_'.&clutter($thisfn)};
10000: unless ($ids) {
10001: $ids=$bighash{'ids_/'.$thisfn};
10002: }
10003: unless ($ids) {
10004: # alias?
10005: $ids=$bighash{'mapalias_'.$thisfn};
10006: }
10007: if ($ids) {
10008: # ------------------------------------------------------------------- Has ID(s)
10009: my @possibilities=split(/\,/,$ids);
10010: if ($#possibilities==0) {
10011: # ----------------------------------------------- There is only one possibility
10012: my ($mapid,$resid)=split(/\./,$ids);
10013: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10014: $resid,$thisfn);
10015: } elsif (!$donotrecurse) {
10016: # ------------------------------------------ There is more than one possibility
10017: my $realpossible=0;
10018: foreach my $id (@possibilities) {
10019: my $file=$bighash{'src_'.$id};
10020: if (&allowed('bre',$file)) {
10021: my ($mapid,$resid)=split(/\./,$id);
10022: if ($bighash{'map_type_'.$mapid} ne 'page') {
10023: $realpossible++;
10024: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10025: $resid,$thisfn);
10026: }
10027: }
10028: }
10029: if ($realpossible!=1) { $syval=''; }
10030: } else {
10031: $syval='';
10032: }
10033: }
10034: untie(%bighash)
10035: }
10036: }
10037: if ($syval) {
10038: return $env{$cache_str}=$syval;
10039: }
10040: }
10041: &appenv({'request.ambiguous' => $thisfn});
10042: return $env{$cache_str}='';
10043: }
10044:
10045: # ---------------------------------------------------------- Return random seed
10046:
10047: sub numval {
10048: my $txt=shift;
10049: $txt=~tr/A-J/0-9/;
10050: $txt=~tr/a-j/0-9/;
10051: $txt=~tr/K-T/0-9/;
10052: $txt=~tr/k-t/0-9/;
10053: $txt=~tr/U-Z/0-5/;
10054: $txt=~tr/u-z/0-5/;
10055: $txt=~s/\D//g;
10056: if ($_64bit) { if ($txt > 2**32) { return -1; } }
10057: return int($txt);
10058: }
10059:
10060: sub numval2 {
10061: my $txt=shift;
10062: $txt=~tr/A-J/0-9/;
10063: $txt=~tr/a-j/0-9/;
10064: $txt=~tr/K-T/0-9/;
10065: $txt=~tr/k-t/0-9/;
10066: $txt=~tr/U-Z/0-5/;
10067: $txt=~tr/u-z/0-5/;
10068: $txt=~s/\D//g;
10069: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10070: my $total;
10071: foreach my $val (@txts) { $total+=$val; }
10072: if ($_64bit) { if ($total > 2**32) { return -1; } }
10073: return int($total);
10074: }
10075:
10076: sub numval3 {
10077: use integer;
10078: my $txt=shift;
10079: $txt=~tr/A-J/0-9/;
10080: $txt=~tr/a-j/0-9/;
10081: $txt=~tr/K-T/0-9/;
10082: $txt=~tr/k-t/0-9/;
10083: $txt=~tr/U-Z/0-5/;
10084: $txt=~tr/u-z/0-5/;
10085: $txt=~s/\D//g;
10086: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10087: my $total;
10088: foreach my $val (@txts) { $total+=$val; }
10089: if ($_64bit) { $total=(($total<<32)>>32); }
10090: return $total;
10091: }
10092:
10093: sub digest {
10094: my ($data)=@_;
10095: my $digest=&Digest::MD5::md5($data);
10096: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10097: my ($e,$f);
10098: {
10099: use integer;
10100: $e=($a+$b);
10101: $f=($c+$d);
10102: if ($_64bit) {
10103: $e=(($e<<32)>>32);
10104: $f=(($f<<32)>>32);
10105: }
10106: }
10107: if (wantarray) {
10108: return ($e,$f);
10109: } else {
10110: my $g;
10111: {
10112: use integer;
10113: $g=($e+$f);
10114: if ($_64bit) {
10115: $g=(($g<<32)>>32);
10116: }
10117: }
10118: return $g;
10119: }
10120: }
10121:
10122: sub latest_rnd_algorithm_id {
10123: return '64bit5';
10124: }
10125:
10126: sub get_rand_alg {
10127: my ($courseid)=@_;
10128: if (!$courseid) { $courseid=(&whichuser())[1]; }
10129: if ($courseid) {
10130: return $env{"course.$courseid.rndseed"};
10131: }
10132: return &latest_rnd_algorithm_id();
10133: }
10134:
10135: sub validCODE {
10136: my ($CODE)=@_;
10137: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10138: return 0;
10139: }
10140:
10141: sub getCODE {
10142: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10143: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10144: defined($Apache::lonhomework::parsing_a_task) ) &&
10145: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10146: return $Apache::lonhomework::history{'resource.CODE'};
10147: }
10148: return undef;
10149: }
10150: #
10151: # Determines the random seed for a specific context:
10152: #
10153: # parameters:
10154: # symb - in course context the symb for the seed.
10155: # course_id - The course id of the form domain_coursenum.
10156: # domain - Domain for the user.
10157: # course - Course for the user.
10158: # cenv - environment of the course.
10159: #
10160: # NOTE:
10161: # All parameters are picked out of the environment if missing
10162: # or not defined.
10163: # If a symb cannot be determined the current time is used instead.
10164: #
10165: # For a given well defined symb, courside, domain, username,
10166: # and course environment, the seed is reproducible.
10167: #
10168: sub rndseed {
10169: my ($symb,$courseid,$domain,$username, $cenv)=@_;
10170: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10171: if (!defined($symb)) {
10172: unless ($symb=$wsymb) { return time; }
10173: }
10174: if (!defined $courseid) {
10175: $courseid=$wcourseid;
10176: }
10177: if (!defined $domain) { $domain=$wdomain; }
10178: if (!defined $username) { $username=$wusername }
10179:
10180: my $which;
10181: if (defined($cenv->{'rndseed'})) {
10182: $which = $cenv->{'rndseed'};
10183: } else {
10184: $which =&get_rand_alg($courseid);
10185: }
10186: if (defined(&getCODE())) {
10187:
10188: if ($which eq '64bit5') {
10189: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10190: } elsif ($which eq '64bit4') {
10191: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10192: } else {
10193: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10194: }
10195: } elsif ($which eq '64bit5') {
10196: return &rndseed_64bit5($symb,$courseid,$domain,$username);
10197: } elsif ($which eq '64bit4') {
10198: return &rndseed_64bit4($symb,$courseid,$domain,$username);
10199: } elsif ($which eq '64bit3') {
10200: return &rndseed_64bit3($symb,$courseid,$domain,$username);
10201: } elsif ($which eq '64bit2') {
10202: return &rndseed_64bit2($symb,$courseid,$domain,$username);
10203: } elsif ($which eq '64bit') {
10204: return &rndseed_64bit($symb,$courseid,$domain,$username);
10205: }
10206: return &rndseed_32bit($symb,$courseid,$domain,$username);
10207: }
10208:
10209: sub rndseed_32bit {
10210: my ($symb,$courseid,$domain,$username)=@_;
10211: {
10212: use integer;
10213: my $symbchck=unpack("%32C*",$symb) << 27;
10214: my $symbseed=numval($symb) << 22;
10215: my $namechck=unpack("%32C*",$username) << 17;
10216: my $nameseed=numval($username) << 12;
10217: my $domainseed=unpack("%32C*",$domain) << 7;
10218: my $courseseed=unpack("%32C*",$courseid);
10219: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
10220: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10221: #&logthis("rndseed :$num:$symb");
10222: if ($_64bit) { $num=(($num<<32)>>32); }
10223: return $num;
10224: }
10225: }
10226:
10227: sub rndseed_64bit {
10228: my ($symb,$courseid,$domain,$username)=@_;
10229: {
10230: use integer;
10231: my $symbchck=unpack("%32S*",$symb) << 21;
10232: my $symbseed=numval($symb) << 10;
10233: my $namechck=unpack("%32S*",$username);
10234:
10235: my $nameseed=numval($username) << 21;
10236: my $domainseed=unpack("%32S*",$domain) << 10;
10237: my $courseseed=unpack("%32S*",$courseid);
10238:
10239: my $num1=$symbchck+$symbseed+$namechck;
10240: my $num2=$nameseed+$domainseed+$courseseed;
10241: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10242: #&logthis("rndseed :$num:$symb");
10243: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10244: return "$num1,$num2";
10245: }
10246: }
10247:
10248: sub rndseed_64bit2 {
10249: my ($symb,$courseid,$domain,$username)=@_;
10250: {
10251: use integer;
10252: # strings need to be an even # of cahracters long, it it is odd the
10253: # last characters gets thrown away
10254: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10255: my $symbseed=numval($symb) << 10;
10256: my $namechck=unpack("%32S*",$username.' ');
10257:
10258: my $nameseed=numval($username) << 21;
10259: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10260: my $courseseed=unpack("%32S*",$courseid.' ');
10261:
10262: my $num1=$symbchck+$symbseed+$namechck;
10263: my $num2=$nameseed+$domainseed+$courseseed;
10264: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10265: #&logthis("rndseed :$num:$symb");
10266: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10267: return "$num1,$num2";
10268: }
10269: }
10270:
10271: sub rndseed_64bit3 {
10272: my ($symb,$courseid,$domain,$username)=@_;
10273: {
10274: use integer;
10275: # strings need to be an even # of cahracters long, it it is odd the
10276: # last characters gets thrown away
10277: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10278: my $symbseed=numval2($symb) << 10;
10279: my $namechck=unpack("%32S*",$username.' ');
10280:
10281: my $nameseed=numval2($username) << 21;
10282: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10283: my $courseseed=unpack("%32S*",$courseid.' ');
10284:
10285: my $num1=$symbchck+$symbseed+$namechck;
10286: my $num2=$nameseed+$domainseed+$courseseed;
10287: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10288: #&logthis("rndseed :$num1:$num2:$_64bit");
10289: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10290:
10291: return "$num1:$num2";
10292: }
10293: }
10294:
10295: sub rndseed_64bit4 {
10296: my ($symb,$courseid,$domain,$username)=@_;
10297: {
10298: use integer;
10299: # strings need to be an even # of cahracters long, it it is odd the
10300: # last characters gets thrown away
10301: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10302: my $symbseed=numval3($symb) << 10;
10303: my $namechck=unpack("%32S*",$username.' ');
10304:
10305: my $nameseed=numval3($username) << 21;
10306: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10307: my $courseseed=unpack("%32S*",$courseid.' ');
10308:
10309: my $num1=$symbchck+$symbseed+$namechck;
10310: my $num2=$nameseed+$domainseed+$courseseed;
10311: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10312: #&logthis("rndseed :$num1:$num2:$_64bit");
10313: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10314:
10315: return "$num1:$num2";
10316: }
10317: }
10318:
10319: sub rndseed_64bit5 {
10320: my ($symb,$courseid,$domain,$username)=@_;
10321: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
10322: return "$num1:$num2";
10323: }
10324:
10325: sub rndseed_CODE_64bit {
10326: my ($symb,$courseid,$domain,$username)=@_;
10327: {
10328: use integer;
10329: my $symbchck=unpack("%32S*",$symb.' ') << 16;
10330: my $symbseed=numval2($symb);
10331: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10332: my $CODEseed=numval(&getCODE());
10333: my $courseseed=unpack("%32S*",$courseid.' ');
10334: my $num1=$symbseed+$CODEchck;
10335: my $num2=$CODEseed+$courseseed+$symbchck;
10336: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10337: #&logthis("rndseed :$num1:$num2:$symb");
10338: if ($_64bit) { $num1=(($num1<<32)>>32); }
10339: if ($_64bit) { $num2=(($num2<<32)>>32); }
10340: return "$num1:$num2";
10341: }
10342: }
10343:
10344: sub rndseed_CODE_64bit4 {
10345: my ($symb,$courseid,$domain,$username)=@_;
10346: {
10347: use integer;
10348: my $symbchck=unpack("%32S*",$symb.' ') << 16;
10349: my $symbseed=numval3($symb);
10350: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10351: my $CODEseed=numval3(&getCODE());
10352: my $courseseed=unpack("%32S*",$courseid.' ');
10353: my $num1=$symbseed+$CODEchck;
10354: my $num2=$CODEseed+$courseseed+$symbchck;
10355: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10356: #&logthis("rndseed :$num1:$num2:$symb");
10357: if ($_64bit) { $num1=(($num1<<32)>>32); }
10358: if ($_64bit) { $num2=(($num2<<32)>>32); }
10359: return "$num1:$num2";
10360: }
10361: }
10362:
10363: sub rndseed_CODE_64bit5 {
10364: my ($symb,$courseid,$domain,$username)=@_;
10365: my $code = &getCODE();
10366: my ($num1,$num2)=&digest("$symb,$courseid,$code");
10367: return "$num1:$num2";
10368: }
10369:
10370: sub setup_random_from_rndseed {
10371: my ($rndseed)=@_;
10372: if ($rndseed =~/([,:])/) {
10373: my ($num1,$num2)=split(/[,:]/,$rndseed);
10374: &Math::Random::random_set_seed(abs($num1),abs($num2));
10375: } else {
10376: &Math::Random::random_set_seed_from_phrase($rndseed);
10377: }
10378: }
10379:
10380: sub latest_receipt_algorithm_id {
10381: return 'receipt3';
10382: }
10383:
10384: sub recunique {
10385: my $fucourseid=shift;
10386: my $unique;
10387: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10388: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10389: $unique=$env{"course.$fucourseid.internal.encseed"};
10390: } else {
10391: $unique=$perlvar{'lonReceipt'};
10392: }
10393: return unpack("%32C*",$unique);
10394: }
10395:
10396: sub recprefix {
10397: my $fucourseid=shift;
10398: my $prefix;
10399: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10400: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10401: $prefix=$env{"course.$fucourseid.internal.encpref"};
10402: } else {
10403: $prefix=$perlvar{'lonHostID'};
10404: }
10405: return unpack("%32C*",$prefix);
10406: }
10407:
10408: sub ireceipt {
10409: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
10410:
10411: my $return =&recprefix($fucourseid).'-';
10412:
10413: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10414: $env{'request.state'} eq 'construct') {
10415: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10416: return $return;
10417: }
10418:
10419: my $cuname=unpack("%32C*",$funame);
10420: my $cudom=unpack("%32C*",$fudom);
10421: my $cucourseid=unpack("%32C*",$fucourseid);
10422: my $cusymb=unpack("%32C*",$fusymb);
10423: my $cunique=&recunique($fucourseid);
10424: my $cpart=unpack("%32S*",$part);
10425: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10426:
10427: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
10428:
10429: $return.= ($cunique%$cuname+
10430: $cunique%$cudom+
10431: $cusymb%$cuname+
10432: $cusymb%$cudom+
10433: $cucourseid%$cuname+
10434: $cucourseid%$cudom+
10435: $cpart%$cuname+
10436: $cpart%$cudom);
10437: } else {
10438: $return.= ($cunique%$cuname+
10439: $cunique%$cudom+
10440: $cusymb%$cuname+
10441: $cusymb%$cudom+
10442: $cucourseid%$cuname+
10443: $cucourseid%$cudom);
10444: }
10445: return $return;
10446: }
10447:
10448: sub receipt {
10449: my ($part)=@_;
10450: my ($symb,$courseid,$domain,$name) = &whichuser();
10451: return &ireceipt($name,$domain,$courseid,$symb,$part);
10452: }
10453:
10454: sub whichuser {
10455: my ($passedsymb)=@_;
10456: my ($symb,$courseid,$domain,$name,$publicuser);
10457: if (defined($env{'form.grade_symb'})) {
10458: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10459: my $allowed=&allowed('vgr',$tmp_courseid);
10460: if (!$allowed &&
10461: exists($env{'request.course.sec'}) &&
10462: $env{'request.course.sec'} !~ /^\s*$/) {
10463: $allowed=&allowed('vgr',$tmp_courseid.
10464: '/'.$env{'request.course.sec'});
10465: }
10466: if ($allowed) {
10467: ($symb)=&get_env_multiple('form.grade_symb');
10468: $courseid=$tmp_courseid;
10469: ($domain)=&get_env_multiple('form.grade_domain');
10470: ($name)=&get_env_multiple('form.grade_username');
10471: return ($symb,$courseid,$domain,$name,$publicuser);
10472: }
10473: }
10474: if (!$passedsymb) {
10475: $symb=&symbread();
10476: } else {
10477: $symb=$passedsymb;
10478: }
10479: $courseid=$env{'request.course.id'};
10480: $domain=$env{'user.domain'};
10481: $name=$env{'user.name'};
10482: if ($name eq 'public' && $domain eq 'public') {
10483: if (!defined($env{'form.username'})) {
10484: $env{'form.username'}.=time.rand(10000000);
10485: }
10486: $name.=$env{'form.username'};
10487: }
10488: return ($symb,$courseid,$domain,$name,$publicuser);
10489:
10490: }
10491:
10492: # ------------------------------------------------------------ Serves up a file
10493: # returns either the contents of the file or
10494: # -1 if the file doesn't exist
10495: #
10496: # if the target is a file that was uploaded via DOCS,
10497: # a check will be made to see if a current copy exists on the local server,
10498: # if it does this will be served, otherwise a copy will be retrieved from
10499: # the home server for the course and stored in /home/httpd/html/userfiles on
10500: # the local server.
10501:
10502: sub getfile {
10503: my ($file) = @_;
10504: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
10505: &repcopy($file);
10506: return &readfile($file);
10507: }
10508:
10509: sub repcopy_userfile {
10510: my ($file)=@_;
10511: my $londocroot = $perlvar{'lonDocRoot'};
10512: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
10513: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
10514: my ($cdom,$cnum,$filename) =
10515: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
10516: my $uri="/uploaded/$cdom/$cnum/$filename";
10517: if (-e "$file") {
10518: # we already have a local copy, check it out
10519: my @fileinfo = stat($file);
10520: my $rtncode;
10521: my $info;
10522: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
10523: if ($lwpresp ne 'ok') {
10524: # there is no such file anymore, even though we had a local copy
10525: if ($rtncode eq '404') {
10526: unlink($file);
10527: }
10528: return -1;
10529: }
10530: if ($info < $fileinfo[9]) {
10531: # nice, the file we have is up-to-date, just say okay
10532: return 'ok';
10533: } else {
10534: # the file is outdated, get rid of it
10535: unlink($file);
10536: }
10537: }
10538: # one way or the other, at this point, we don't have the file
10539: # construct the correct path for the file
10540: my @parts = ($cdom,$cnum);
10541: if ($filename =~ m|^(.+)/[^/]+$|) {
10542: push @parts, split(/\//,$1);
10543: }
10544: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10545: foreach my $part (@parts) {
10546: $path .= '/'.$part;
10547: if (!-e $path) {
10548: mkdir($path,0770);
10549: }
10550: }
10551: # now the path exists for sure
10552: # get a user agent
10553: my $ua=new LWP::UserAgent;
10554: my $transferfile=$file.'.in.transfer';
10555: # FIXME: this should flock
10556: if (-e $transferfile) { return 'ok'; }
10557: my $request;
10558: $uri=~s/^\///;
10559: my $homeserver = &homeserver($cnum,$cdom);
10560: my $protocol = $protocol{$homeserver};
10561: $protocol = 'http' if ($protocol ne 'https');
10562: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
10563: my $response=$ua->request($request,$transferfile);
10564: # did it work?
10565: if ($response->is_error()) {
10566: unlink($transferfile);
10567: &logthis("Userfile repcopy failed for $uri");
10568: return -1;
10569: }
10570: # worked, rename the transfer file
10571: rename($transferfile,$file);
10572: return 'ok';
10573: }
10574:
10575: sub tokenwrapper {
10576: my $uri=shift;
10577: $uri=~s|^https?\://([^/]+)||;
10578: $uri=~s|^/||;
10579: $env{'user.environment'}=~/\/([^\/]+)\.id/;
10580: my $token=$1;
10581: my (undef,$udom,$uname,$file)=split('/',$uri,4);
10582: if ($udom && $uname && $file) {
10583: $file=~s|(\?\.*)*$||;
10584: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
10585: my $homeserver = &homeserver($uname,$udom);
10586: my $protocol = $protocol{$homeserver};
10587: $protocol = 'http' if ($protocol ne 'https');
10588: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
10589: (($uri=~/\?/)?'&':'?').'token='.$token.
10590: '&tokenissued='.$perlvar{'lonHostID'};
10591: } else {
10592: return '/adm/notfound.html';
10593: }
10594: }
10595:
10596: # call with reqtype HEAD: get last modification time
10597: # call with reqtype GET: get the file contents
10598: # Do not call this with reqtype GET for large files! It loads everything into memory
10599: #
10600: sub getuploaded {
10601: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10602: $uri=~s/^\///;
10603: my $homeserver = &homeserver($cnum,$cdom);
10604: my $protocol = $protocol{$homeserver};
10605: $protocol = 'http' if ($protocol ne 'https');
10606: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
10607: my $ua=new LWP::UserAgent;
10608: my $request=new HTTP::Request($reqtype,$uri);
10609: my $response=$ua->request($request);
10610: $$rtncode = $response->code;
10611: if (! $response->is_success()) {
10612: return 'failed';
10613: }
10614: if ($reqtype eq 'HEAD') {
10615: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
10616: } elsif ($reqtype eq 'GET') {
10617: $$info = $response->content;
10618: }
10619: return 'ok';
10620: }
10621:
10622: sub readfile {
10623: my $file = shift;
10624: if ( (! -e $file ) || ($file eq '') ) { return -1; };
10625: my $fh;
10626: open($fh,"<$file");
10627: my $a='';
10628: while (my $line = <$fh>) { $a .= $line; }
10629: return $a;
10630: }
10631:
10632: sub filelocation {
10633: my ($dir,$file) = @_;
10634: my $location;
10635: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
10636:
10637: if ($file =~ m-^/adm/-) {
10638: $file=~s-^/adm/wrapper/-/-;
10639: $file=~s-^/adm/coursedocs/showdoc/-/-;
10640: }
10641:
10642: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
10643: $location = $file;
10644: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
10645: my ($udom,$uname,$filename)=
10646: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
10647: my $home=&homeserver($uname,$udom);
10648: my $is_me=0;
10649: my @ids=¤t_machine_ids();
10650: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10651: if ($is_me) {
10652: $location=propath($udom,$uname).'/userfiles/'.$filename;
10653: } else {
10654: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10655: $udom.'/'.$uname.'/'.$filename;
10656: }
10657: } elsif ($file =~ m-^/adm/-) {
10658: $location = $perlvar{'lonDocRoot'}.'/'.$file;
10659: } else {
10660: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10661: $file=~s:^/(res|priv)/:/:;
10662: my $space=$1;
10663: if ( !( $file =~ m:^/:) ) {
10664: $location = $dir. '/'.$file;
10665: } else {
10666: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
10667: }
10668: }
10669: $location=~s://+:/:g; # remove duplicate /
10670: while ($location=~m{/\.\./}) {
10671: if ($location =~ m{/[^/]+/\.\./}) {
10672: $location=~ s{/[^/]+/\.\./}{/}g;
10673: } else {
10674: $location=~ s{/\.\./}{/}g;
10675: }
10676: } #remove dir/..
10677: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10678: return $location;
10679: }
10680:
10681: sub hreflocation {
10682: my ($dir,$file)=@_;
10683: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
10684: $file=filelocation($dir,$file);
10685: } elsif ($file=~m-^/adm/-) {
10686: $file=~s-^/adm/wrapper/-/-;
10687: $file=~s-^/adm/coursedocs/showdoc/-/-;
10688: }
10689: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10690: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10691: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
10692: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10693: {/uploaded/$1/$2/}x;
10694: }
10695: if ($file=~ m{^/userfiles/}) {
10696: $file =~ s{^/userfiles/}{/uploaded/};
10697: }
10698: return $file;
10699: }
10700:
10701:
10702:
10703:
10704:
10705: sub current_machine_domains {
10706: return &machine_domains(&hostname($perlvar{'lonHostID'}));
10707: }
10708:
10709: sub machine_domains {
10710: my ($hostname) = @_;
10711: my @domains;
10712: my %hostname = &all_hostnames();
10713: while( my($id, $name) = each(%hostname)) {
10714: # &logthis("-$id-$name-$hostname-");
10715: if ($hostname eq $name) {
10716: push(@domains,&host_domain($id));
10717: }
10718: }
10719: return @domains;
10720: }
10721:
10722: sub current_machine_ids {
10723: return &machine_ids(&hostname($perlvar{'lonHostID'}));
10724: }
10725:
10726: sub machine_ids {
10727: my ($hostname) = @_;
10728: $hostname ||= &hostname($perlvar{'lonHostID'});
10729: my @ids;
10730: my %name_to_host = &all_names();
10731: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10732: return @{ $name_to_host{$hostname} };
10733: }
10734: return;
10735: }
10736:
10737: sub additional_machine_domains {
10738: my @domains;
10739: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10740: while( my $line = <$fh>) {
10741: $line =~ s/\s//g;
10742: push(@domains,$line);
10743: }
10744: return @domains;
10745: }
10746:
10747: sub default_login_domain {
10748: my $domain = $perlvar{'lonDefDomain'};
10749: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10750: foreach my $posdom (¤t_machine_domains(),
10751: &additional_machine_domains()) {
10752: if (lc($posdom) eq lc($testdomain)) {
10753: $domain=$posdom;
10754: last;
10755: }
10756: }
10757: return $domain;
10758: }
10759:
10760: # ------------------------------------------------------------- Declutters URLs
10761:
10762: sub declutter {
10763: my $thisfn=shift;
10764: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10765: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10766: $thisfn=~s/^\///;
10767: $thisfn=~s|^adm/wrapper/||;
10768: $thisfn=~s|^adm/coursedocs/showdoc/||;
10769: $thisfn=~s/^res\///;
10770: $thisfn=~s/^priv\///;
10771: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10772: $thisfn=~s/\?.+$//;
10773: }
10774: return $thisfn;
10775: }
10776:
10777: # ------------------------------------------------------------- Clutter up URLs
10778:
10779: sub clutter {
10780: my $thisfn='/'.&declutter(shift);
10781: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
10782: || $thisfn =~ m{^/adm/(includes|pages)} ) {
10783: $thisfn='/res'.$thisfn;
10784: }
10785: if ($thisfn !~m|^/adm|) {
10786: if ($thisfn =~ m|^/ext/|) {
10787: $thisfn='/adm/wrapper'.$thisfn;
10788: } else {
10789: my ($ext) = ($thisfn =~ /\.(\w+)$/);
10790: my $embstyle=&Apache::loncommon::fileembstyle($ext);
10791: if ($embstyle eq 'ssi'
10792: || ($embstyle eq 'hdn')
10793: || ($embstyle eq 'rat')
10794: || ($embstyle eq 'prv')
10795: || ($embstyle eq 'ign')) {
10796: #do nothing with these
10797: } elsif (($embstyle eq 'img')
10798: || ($embstyle eq 'emb')
10799: || ($embstyle eq 'wrp')) {
10800: $thisfn='/adm/wrapper'.$thisfn;
10801: } elsif ($embstyle eq 'unk'
10802: && $thisfn!~/\.(sequence|page)$/) {
10803: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
10804: } else {
10805: # &logthis("Got a blank emb style");
10806: }
10807: }
10808: }
10809: return $thisfn;
10810: }
10811:
10812: sub clutter_with_no_wrapper {
10813: my $uri = &clutter(shift);
10814: if ($uri =~ m-^/adm/-) {
10815: $uri =~ s-^/adm/wrapper/-/-;
10816: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
10817: }
10818: return $uri;
10819: }
10820:
10821: sub freeze_escape {
10822: my ($value)=@_;
10823: if (ref($value)) {
10824: $value=&nfreeze($value);
10825: return '__FROZEN__'.&escape($value);
10826: }
10827: return &escape($value);
10828: }
10829:
10830:
10831: sub thaw_unescape {
10832: my ($value)=@_;
10833: if ($value =~ /^__FROZEN__/) {
10834: substr($value,0,10,undef);
10835: $value=&unescape($value);
10836: return &thaw($value);
10837: }
10838: return &unescape($value);
10839: }
10840:
10841: sub correct_line_ends {
10842: my ($result)=@_;
10843: $$result =~s/\r\n/\n/mg;
10844: $$result =~s/\r/\n/mg;
10845: }
10846: # ================================================================ Main Program
10847:
10848: sub goodbye {
10849: &logthis("Starting Shut down");
10850: #not converted to using infrastruture and probably shouldn't be
10851: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
10852: #converted
10853: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
10854: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10855: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10856: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
10857: #1.1 only
10858: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10859: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10860: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10861: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10862: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
10863: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10864: &logthis(sprintf("%-20s is %s",'hits',$hits));
10865: &flushcourselogs();
10866: &logthis("Shutting down");
10867: }
10868:
10869: sub get_dns {
10870: my ($url,$func,$ignore_cache) = @_;
10871: if (!$ignore_cache) {
10872: my ($content,$cached)=
10873: &Apache::lonnet::is_cached_new('dns',$url);
10874: if ($cached) {
10875: &$func($content);
10876: return;
10877: }
10878: }
10879:
10880: my %alldns;
10881: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10882: foreach my $dns (<$config>) {
10883: next if ($dns !~ /^\^(\S*)/x);
10884: my $line = $1;
10885: my ($host,$protocol) = split(/:/,$line);
10886: if ($protocol ne 'https') {
10887: $protocol = 'http';
10888: }
10889: $alldns{$host} = $protocol;
10890: }
10891: while (%alldns) {
10892: my ($dns) = keys(%alldns);
10893: my $ua=new LWP::UserAgent;
10894: $ua->timeout(30);
10895: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
10896: my $response=$ua->request($request);
10897: delete($alldns{$dns});
10898: next if ($response->is_error());
10899: my @content = split("\n",$response->content);
10900: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
10901: &$func(\@content);
10902: return;
10903: }
10904: close($config);
10905: my $which = (split('/',$url))[3];
10906: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10907: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
10908: my @content = <$config>;
10909: &$func(\@content);
10910: return;
10911: }
10912: # ------------------------------------------------------------ Read domain file
10913: {
10914: my $loaded;
10915: my %domain;
10916:
10917: sub parse_domain_tab {
10918: my ($lines) = @_;
10919: foreach my $line (@$lines) {
10920: next if ($line =~ /^(\#|\s*$ )/x);
10921:
10922: chomp($line);
10923: my ($name,@elements) = split(/:/,$line,9);
10924: my %this_domain;
10925: foreach my $field ('description', 'auth_def', 'auth_arg_def',
10926: 'lang_def', 'city', 'longi', 'lati',
10927: 'primary') {
10928: $this_domain{$field} = shift(@elements);
10929: }
10930: $domain{$name} = \%this_domain;
10931: }
10932: }
10933:
10934: sub reset_domain_info {
10935: undef($loaded);
10936: undef(%domain);
10937: }
10938:
10939: sub load_domain_tab {
10940: my ($ignore_cache) = @_;
10941: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
10942: my $fh;
10943: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10944: my @lines = <$fh>;
10945: &parse_domain_tab(\@lines);
10946: }
10947: close($fh);
10948: $loaded = 1;
10949: }
10950:
10951: sub domain {
10952: &load_domain_tab() if (!$loaded);
10953:
10954: my ($name,$what) = @_;
10955: return if ( !exists($domain{$name}) );
10956:
10957: if (!$what) {
10958: return $domain{$name}{'description'};
10959: }
10960: return $domain{$name}{$what};
10961: }
10962:
10963: sub domain_info {
10964: &load_domain_tab() if (!$loaded);
10965: return %domain;
10966: }
10967:
10968: }
10969:
10970:
10971: # ------------------------------------------------------------- Read hosts file
10972: {
10973: my %hostname;
10974: my %hostdom;
10975: my %libserv;
10976: my $loaded;
10977: my %name_to_host;
10978: my %internetdom;
10979: my %LC_dns_serv;
10980:
10981: sub parse_hosts_tab {
10982: my ($file) = @_;
10983: foreach my $configline (@$file) {
10984: next if ($configline =~ /^(\#|\s*$ )/x);
10985: chomp($configline);
10986: if ($configline =~ /^\^/) {
10987: if ($configline =~ /^\^([\w.\-]+)/) {
10988: $LC_dns_serv{$1} = 1;
10989: }
10990: next;
10991: }
10992: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
10993: $name=~s/\s//g;
10994: if ($id && $domain && $role && $name) {
10995: $hostname{$id}=$name;
10996: push(@{$name_to_host{$name}}, $id);
10997: $hostdom{$id}=$domain;
10998: if ($role eq 'library') { $libserv{$id}=$name; }
10999: if (defined($protocol)) {
11000: if ($protocol eq 'https') {
11001: $protocol{$id} = $protocol;
11002: } else {
11003: $protocol{$id} = 'http';
11004: }
11005: } else {
11006: $protocol{$id} = 'http';
11007: }
11008: if (defined($intdom)) {
11009: $internetdom{$id} = $intdom;
11010: }
11011: }
11012: }
11013: }
11014:
11015: sub reset_hosts_info {
11016: &purge_remembered();
11017: &reset_domain_info();
11018: &reset_hosts_ip_info();
11019: undef(%name_to_host);
11020: undef(%hostname);
11021: undef(%hostdom);
11022: undef(%libserv);
11023: undef($loaded);
11024: }
11025:
11026: sub load_hosts_tab {
11027: my ($ignore_cache) = @_;
11028: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11029: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11030: my @config = <$config>;
11031: &parse_hosts_tab(\@config);
11032: close($config);
11033: $loaded=1;
11034: }
11035:
11036: sub hostname {
11037: &load_hosts_tab() if (!$loaded);
11038:
11039: my ($lonid) = @_;
11040: return $hostname{$lonid};
11041: }
11042:
11043: sub all_hostnames {
11044: &load_hosts_tab() if (!$loaded);
11045:
11046: return %hostname;
11047: }
11048:
11049: sub all_names {
11050: &load_hosts_tab() if (!$loaded);
11051:
11052: return %name_to_host;
11053: }
11054:
11055: sub all_host_domain {
11056: &load_hosts_tab() if (!$loaded);
11057: return %hostdom;
11058: }
11059:
11060: sub is_library {
11061: &load_hosts_tab() if (!$loaded);
11062:
11063: return exists($libserv{$_[0]});
11064: }
11065:
11066: sub all_library {
11067: &load_hosts_tab() if (!$loaded);
11068:
11069: return %libserv;
11070: }
11071:
11072: sub unique_library {
11073: #2x reverse removes all hostnames that appear more than once
11074: my %unique = reverse &all_library();
11075: return reverse %unique;
11076: }
11077:
11078: sub get_servers {
11079: &load_hosts_tab() if (!$loaded);
11080:
11081: my ($domain,$type) = @_;
11082: my %possible_hosts = ($type eq 'library') ? %libserv
11083: : %hostname;
11084: my %result;
11085: if (ref($domain) eq 'ARRAY') {
11086: while ( my ($host,$hostname) = each(%possible_hosts)) {
11087: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11088: $result{$host} = $hostname;
11089: }
11090: }
11091: } else {
11092: while ( my ($host,$hostname) = each(%possible_hosts)) {
11093: if ($hostdom{$host} eq $domain) {
11094: $result{$host} = $hostname;
11095: }
11096: }
11097: }
11098: return %result;
11099: }
11100:
11101: sub get_unique_servers {
11102: my %unique = reverse &get_servers(@_);
11103: return reverse %unique;
11104: }
11105:
11106: sub host_domain {
11107: &load_hosts_tab() if (!$loaded);
11108:
11109: my ($lonid) = @_;
11110: return $hostdom{$lonid};
11111: }
11112:
11113: sub all_domains {
11114: &load_hosts_tab() if (!$loaded);
11115:
11116: my %seen;
11117: my @uniq = grep(!$seen{$_}++, values(%hostdom));
11118: return @uniq;
11119: }
11120:
11121: sub internet_dom {
11122: &load_hosts_tab() if (!$loaded);
11123:
11124: my ($lonid) = @_;
11125: return $internetdom{$lonid};
11126: }
11127:
11128: sub is_LC_dns {
11129: &load_hosts_tab() if (!$loaded);
11130:
11131: my ($hostname) = @_;
11132: return exists($LC_dns_serv{$hostname});
11133: }
11134:
11135: }
11136:
11137: {
11138: my %iphost;
11139: my %name_to_ip;
11140: my %lonid_to_ip;
11141:
11142: sub get_hosts_from_ip {
11143: my ($ip) = @_;
11144: my %iphosts = &get_iphost();
11145: if (ref($iphosts{$ip})) {
11146: return @{$iphosts{$ip}};
11147: }
11148: return;
11149: }
11150:
11151: sub reset_hosts_ip_info {
11152: undef(%iphost);
11153: undef(%name_to_ip);
11154: undef(%lonid_to_ip);
11155: }
11156:
11157: sub get_host_ip {
11158: my ($lonid) = @_;
11159: if (exists($lonid_to_ip{$lonid})) {
11160: return $lonid_to_ip{$lonid};
11161: }
11162: my $name=&hostname($lonid);
11163: my $ip = gethostbyname($name);
11164: return if (!$ip || length($ip) ne 4);
11165: $ip=inet_ntoa($ip);
11166: $name_to_ip{$name} = $ip;
11167: $lonid_to_ip{$lonid} = $ip;
11168: return $ip;
11169: }
11170:
11171: sub get_iphost {
11172: my ($ignore_cache) = @_;
11173:
11174: if (!$ignore_cache) {
11175: if (%iphost) {
11176: return %iphost;
11177: }
11178: my ($ip_info,$cached)=
11179: &Apache::lonnet::is_cached_new('iphost','iphost');
11180: if ($cached) {
11181: %iphost = %{$ip_info->[0]};
11182: %name_to_ip = %{$ip_info->[1]};
11183: %lonid_to_ip = %{$ip_info->[2]};
11184: return %iphost;
11185: }
11186: }
11187:
11188: # get yesterday's info for fallback
11189: my %old_name_to_ip;
11190: my ($ip_info,$cached)=
11191: &Apache::lonnet::is_cached_new('iphost','iphost');
11192: if ($cached) {
11193: %old_name_to_ip = %{$ip_info->[1]};
11194: }
11195:
11196: my %name_to_host = &all_names();
11197: foreach my $name (keys(%name_to_host)) {
11198: my $ip;
11199: if (!exists($name_to_ip{$name})) {
11200: $ip = gethostbyname($name);
11201: if (!$ip || length($ip) ne 4) {
11202: if (defined($old_name_to_ip{$name})) {
11203: $ip = $old_name_to_ip{$name};
11204: &logthis("Can't find $name defaulting to old $ip");
11205: } else {
11206: &logthis("Name $name no IP found");
11207: next;
11208: }
11209: } else {
11210: $ip=inet_ntoa($ip);
11211: }
11212: $name_to_ip{$name} = $ip;
11213: } else {
11214: $ip = $name_to_ip{$name};
11215: }
11216: foreach my $id (@{ $name_to_host{$name} }) {
11217: $lonid_to_ip{$id} = $ip;
11218: }
11219: push(@{$iphost{$ip}},@{$name_to_host{$name}});
11220: }
11221: &Apache::lonnet::do_cache_new('iphost','iphost',
11222: [\%iphost,\%name_to_ip,\%lonid_to_ip],
11223: 48*60*60);
11224:
11225: return %iphost;
11226: }
11227:
11228: #
11229: # Given a DNS returns the loncapa host name for that DNS
11230: #
11231: sub host_from_dns {
11232: my ($dns) = @_;
11233: my @hosts;
11234: my $ip;
11235:
11236: if (exists($name_to_ip{$dns})) {
11237: $ip = $name_to_ip{$dns};
11238: }
11239: if (!$ip) {
11240: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11241: if (length($ip) == 4) {
11242: $ip = &IO::Socket::inet_ntoa($ip);
11243: }
11244: }
11245: if ($ip) {
11246: @hosts = get_hosts_from_ip($ip);
11247: return $hosts[0];
11248: }
11249: return undef;
11250: }
11251:
11252: sub get_internet_names {
11253: my ($lonid) = @_;
11254: return if ($lonid eq '');
11255: my ($idnref,$cached)=
11256: &Apache::lonnet::is_cached_new('internetnames',$lonid);
11257: if ($cached) {
11258: return $idnref;
11259: }
11260: my $ip = &get_host_ip($lonid);
11261: my @hosts = &get_hosts_from_ip($ip);
11262: my %iphost = &get_iphost();
11263: my (@idns,%seen);
11264: foreach my $id (@hosts) {
11265: my $dom = &host_domain($id);
11266: my $prim_id = &domain($dom,'primary');
11267: my $prim_ip = &get_host_ip($prim_id);
11268: next if ($seen{$prim_ip});
11269: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
11270: foreach my $id (@{$iphost{$prim_ip}}) {
11271: my $intdom = &internet_dom($id);
11272: unless (grep(/^\Q$intdom\E$/,@idns)) {
11273: push(@idns,$intdom);
11274: }
11275: }
11276: }
11277: $seen{$prim_ip} = 1;
11278: }
11279: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
11280: }
11281:
11282: }
11283:
11284: sub all_loncaparevs {
11285: 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);
11286: }
11287:
11288: BEGIN {
11289:
11290: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
11291: unless ($readit) {
11292: {
11293: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
11294: %perlvar = (%perlvar,%{$configvars});
11295: }
11296:
11297:
11298: # ------------------------------------------------------ Read spare server file
11299: {
11300: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
11301:
11302: while (my $configline=<$config>) {
11303: chomp($configline);
11304: if ($configline) {
11305: my ($host,$type) = split(':',$configline,2);
11306: if (!defined($type) || $type eq '') { $type = 'default' };
11307: push(@{ $spareid{$type} }, $host);
11308: }
11309: }
11310: close($config);
11311: }
11312: # ------------------------------------------------------------ Read permissions
11313: {
11314: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
11315:
11316: while (my $configline=<$config>) {
11317: chomp($configline);
11318: if ($configline) {
11319: my ($role,$perm)=split(/ /,$configline);
11320: if ($perm ne '') { $pr{$role}=$perm; }
11321: }
11322: }
11323: close($config);
11324: }
11325:
11326: # -------------------------------------------- Read plain texts for permissions
11327: {
11328: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
11329:
11330: while (my $configline=<$config>) {
11331: chomp($configline);
11332: if ($configline) {
11333: my ($short,@plain)=split(/:/,$configline);
11334: %{$prp{$short}} = ();
11335: if (@plain > 0) {
11336: $prp{$short}{'std'} = $plain[0];
11337: for (my $i=1; $i<@plain; $i++) {
11338: $prp{$short}{'alt'.$i} = $plain[$i];
11339: }
11340: }
11341: }
11342: }
11343: close($config);
11344: }
11345:
11346: # ---------------------------------------------------------- Read package table
11347: {
11348: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
11349:
11350: while (my $configline=<$config>) {
11351: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
11352: chomp($configline);
11353: my ($short,$plain)=split(/:/,$configline);
11354: my ($pack,$name)=split(/\&/,$short);
11355: if ($plain ne '') {
11356: $packagetab{$pack.'&'.$name.'&name'}=$name;
11357: $packagetab{$short}=$plain;
11358: }
11359: }
11360: close($config);
11361: }
11362:
11363: # ---------------------------------------------------------- Read loncaparev table
11364: {
11365: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11366: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11367: while (my $configline=<$config>) {
11368: chomp($configline);
11369: my ($hostid,$loncaparev)=split(/:/,$configline);
11370: $loncaparevs{$hostid}=$loncaparev;
11371: }
11372: close($config);
11373: }
11374: }
11375: }
11376:
11377: # ---------------------------------------------------------- Read serverhostID table
11378: {
11379: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11380: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11381: while (my $configline=<$config>) {
11382: chomp($configline);
11383: my ($name,$id)=split(/:/,$configline);
11384: $serverhomeIDs{$name}=$id;
11385: }
11386: close($config);
11387: }
11388: }
11389: }
11390:
11391: {
11392: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11393: if (-e $file) {
11394: my $parser = HTML::LCParser->new($file);
11395: while (my $token = $parser->get_token()) {
11396: if ($token->[0] eq 'S') {
11397: my $item = $token->[1];
11398: my $name = $token->[2]{'name'};
11399: my $value = $token->[2]{'value'};
11400: if ($item ne '' && $name ne '' && $value ne '') {
11401: my $release = $parser->get_text();
11402: $release =~ s/(^\s*|\s*$ )//gx;
11403: $needsrelease{$item.':'.$name.':'.$value} = $release;
11404: }
11405: }
11406: }
11407: }
11408: }
11409:
11410: # ---------------------------------------------------------- Read managers table
11411: {
11412: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11413: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11414: while (my $configline=<$config>) {
11415: chomp($configline);
11416: next if ($configline =~ /^\#/);
11417: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11418: $managerstab{$configline} = 1;
11419: }
11420: }
11421: close($config);
11422: }
11423: }
11424: }
11425:
11426: # ------------- set up temporary directory
11427: {
11428: $tmpdir = LONCAPA::tempdir();
11429:
11430: }
11431:
11432: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
11433: 'compress_threshold'=> 20_000,
11434: });
11435:
11436: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
11437: $dumpcount=0;
11438: $locknum=0;
11439:
11440: &logtouch();
11441: &logthis('<font color="yellow">INFO: Read configuration</font>');
11442: $readit=1;
11443: {
11444: use integer;
11445: my $test=(2**32)+1;
11446: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
11447: &logthis(" Detected 64bit platform ($_64bit)");
11448: }
11449: }
11450: }
11451:
11452: 1;
11453: __END__
11454:
11455: =pod
11456:
11457: =head1 NAME
11458:
11459: Apache::lonnet - Subroutines to ask questions about things in the network.
11460:
11461: =head1 SYNOPSIS
11462:
11463: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
11464:
11465: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11466:
11467: Common parameters:
11468:
11469: =over 4
11470:
11471: =item *
11472:
11473: $uname : an internal username (if $cname expecting a course Id specifically)
11474:
11475: =item *
11476:
11477: $udom : a domain (if $cdom expecting a course's domain specifically)
11478:
11479: =item *
11480:
11481: $symb : a resource instance identifier
11482:
11483: =item *
11484:
11485: $namespace : the name of a .db file that contains the data needed or
11486: being set.
11487:
11488: =back
11489:
11490: =head1 OVERVIEW
11491:
11492: lonnet provides subroutines which interact with the
11493: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11494: about classes, users, and resources.
11495:
11496: For many of these objects you can also use this to store data about
11497: them or modify them in various ways.
11498:
11499: =head2 Symbs
11500:
11501: To identify a specific instance of a resource, LON-CAPA uses symbols
11502: or "symbs"X<symb>. These identifiers are built from the URL of the
11503: map, the resource number of the resource in the map, and the URL of
11504: the resource itself. The latter is somewhat redundant, but might help
11505: if maps change.
11506:
11507: An example is
11508:
11509: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11510:
11511: The respective map entry is
11512:
11513: <resource id="19" src="/res/msu/korte/tests/part12.problem"
11514: title="Problem 2">
11515: </resource>
11516:
11517: Symbs are used by the random number generator, as well as to store and
11518: restore data specific to a certain instance of for example a problem.
11519:
11520: =head2 Storing And Retrieving Data
11521:
11522: X<store()>X<cstore()>X<restore()>Three of the most important functions
11523: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11524: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11525: is is the non-critical message twin of cstore. These functions are for
11526: handlers to store a perl hash to a user's permanent data space in an
11527: easy manner, and to retrieve it again on another call. It is expected
11528: that a handler would use this once at the beginning to retrieve data,
11529: and then again once at the end to send only the new data back.
11530:
11531: The data is stored in the user's data directory on the user's
11532: homeserver under the ID of the course.
11533:
11534: The hash that is returned by restore will have all of the previous
11535: value for all of the elements of the hash.
11536:
11537: Example:
11538:
11539: #creating a hash
11540: my %hash;
11541: $hash{'foo'}='bar';
11542:
11543: #storing it
11544: &Apache::lonnet::cstore(\%hash);
11545:
11546: #changing a value
11547: $hash{'foo'}='notbar';
11548:
11549: #adding a new value
11550: $hash{'bar'}='foo';
11551: &Apache::lonnet::cstore(\%hash);
11552:
11553: #retrieving the hash
11554: my %history=&Apache::lonnet::restore();
11555:
11556: #print the hash
11557: foreach my $key (sort(keys(%history))) {
11558: print("\%history{$key} = $history{$key}");
11559: }
11560:
11561: Will print out:
11562:
11563: %history{1:foo} = bar
11564: %history{1:keys} = foo:timestamp
11565: %history{1:timestamp} = 990455579
11566: %history{2:bar} = foo
11567: %history{2:foo} = notbar
11568: %history{2:keys} = foo:bar:timestamp
11569: %history{2:timestamp} = 990455580
11570: %history{bar} = foo
11571: %history{foo} = notbar
11572: %history{timestamp} = 990455580
11573: %history{version} = 2
11574:
11575: Note that the special hash entries C<keys>, C<version> and
11576: C<timestamp> were added to the hash. C<version> will be equal to the
11577: total number of versions of the data that have been stored. The
11578: C<timestamp> attribute will be the UNIX time the hash was
11579: stored. C<keys> is available in every historical section to list which
11580: keys were added or changed at a specific historical revision of a
11581: hash.
11582:
11583: B<Warning>: do not store the hash that restore returns directly. This
11584: will cause a mess since it will restore the historical keys as if the
11585: were new keys. I.E. 1:foo will become 1:1:foo etc.
11586:
11587: Calling convention:
11588:
11589: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11590: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
11591:
11592: For more detailed information, see lonnet specific documentation.
11593:
11594: =head1 RETURN MESSAGES
11595:
11596: =over 4
11597:
11598: =item * B<con_lost>: unable to contact remote host
11599:
11600: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11601: when the connection is brought back up
11602:
11603: =item * B<con_failed>: unable to contact remote host and unable to save message
11604: for later delivery
11605:
11606: =item * B<error:>: an error a occurred, a description of the error follows the :
11607:
11608: =item * B<no_such_host>: unable to fund a host associated with the user/domain
11609: that was requested
11610:
11611: =back
11612:
11613: =head1 PUBLIC SUBROUTINES
11614:
11615: =head2 Session Environment Functions
11616:
11617: =over 4
11618:
11619: =item *
11620: X<appenv()>
11621: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
11622: the user envirnoment file, and will be restored for each access this
11623: user makes during this session, also modifies the %env for the current
11624: process. Optional rolesarrayref - if defined contains a reference to an array
11625: of roles which are exempt from the restriction on modifying user.role entries
11626: in the user's environment.db and in %env.
11627:
11628: =item *
11629: X<delenv()>
11630: B<delenv($delthis,$regexp)>: removes all items from the session
11631: environment file that begin with $delthis. If the
11632: optional second arg - $regexp - is true, $delthis is treated as a
11633: regular expression, otherwise \Q$delthis\E is used.
11634: The values are also deleted from the current processes %env.
11635:
11636: =item * get_env_multiple($name)
11637:
11638: gets $name from the %env hash, it seemlessly handles the cases where multiple
11639: values may be defined and end up as an array ref.
11640:
11641: returns an array of values
11642:
11643: =back
11644:
11645: =head2 User Information
11646:
11647: =over 4
11648:
11649: =item *
11650: X<queryauthenticate()>
11651: B<queryauthenticate($uname,$udom)>: try to determine user's current
11652: authentication scheme
11653:
11654: =item *
11655: X<authenticate()>
11656: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
11657: authenticate user from domain's lib servers (first use the current
11658: one). C<$upass> should be the users password.
11659: $checkdefauth is optional (value is 1 if a check should be made to
11660: authenticate user using default authentication method, and allow
11661: account creation if username does not have account in the domain).
11662: $clientcancheckhost is optional (value is 1 if checking whether the
11663: server can host will occur on the client side in lonauth.pm).
11664:
11665: =item *
11666: X<homeserver()>
11667: B<homeserver($uname,$udom)>: find the server which has
11668: the user's directory and files (there must be only one), this caches
11669: the answer, and also caches if there is a borken connection.
11670:
11671: =item *
11672: X<idget()>
11673: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11674: (IDs are a unique resource in a domain, there must be only 1 ID per
11675: username, and only 1 username per ID in a specific domain) (returns
11676: hash: id=>name,id=>name)
11677:
11678: =item *
11679: X<idrget()>
11680: B<idrget($udom,@unames)>: find the IDs behind a list of
11681: usernames (returns hash: name=>id,name=>id)
11682:
11683: =item *
11684: X<idput()>
11685: B<idput($udom,%ids)>: store away a list of names and associated IDs
11686:
11687: =item *
11688: X<rolesinit()>
11689: B<rolesinit($udom,$username)>: get user privileges.
11690: returns user role, first access and timer interval hashes
11691:
11692: =item *
11693: X<privileged()>
11694: B<privileged($username,$domain)>: returns a true if user has a
11695: privileged and active role (i.e. su or dc), false otherwise.
11696:
11697: =item *
11698: X<getsection()>
11699: B<getsection($udom,$uname,$cname)>: finds the section of student in the
11700: course $cname, return section name/number or '' for "not in course"
11701: and '-1' for "no section"
11702:
11703: =item *
11704: X<userenvironment()>
11705: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
11706: passed in @what from the requested user's environment, returns a hash
11707:
11708: =item *
11709: X<userlog_query()>
11710: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11711: activity.log file. %filters defines filters applied when parsing the
11712: log file. These can be start or end timestamps, or the type of action
11713: - log to look for Login or Logout events, check for Checkin or
11714: Checkout, role for role selection. The response is in the form
11715: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
11716: escaped strings of the action recorded in the activity.log file.
11717:
11718: =back
11719:
11720: =head2 User Roles
11721:
11722: =over 4
11723:
11724: =item *
11725:
11726: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
11727: F: full access
11728: U,I,K: authentication modes (cxx only)
11729: '': forbidden
11730: 1: user needs to choose course
11731: 2: browse allowed
11732: A: passphrase authentication needed
11733:
11734: =item *
11735:
11736: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11737: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11738: and course level
11739:
11740: =item *
11741:
11742: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
11743: (rolesplain.tab); plain text explanation of a user role term.
11744: $type is Course (default) or Community.
11745: If $forcedefault evaluates to true, text returned will be default
11746: text for $type. Otherwise, if this is a course, the text returned
11747: will be a custom name for the role (if defined in the course's
11748: environment). If no custom name is defined the default is returned.
11749:
11750: =item *
11751:
11752: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
11753: All arguments are optional. Returns a hash of a roles, either for
11754: co-author/assistant author roles for a user's Construction Space
11755: (default), or if $context is 'userroles', roles for the user himself,
11756: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11757: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11758: For each key, value is set to colon-separated start and end times for
11759: the role. If no username and domain are specified, will default to
11760: current user/domain. Types, roles, and roledoms are references to arrays
11761: of role statuses (active, future or previous), roles
11762: (e.g., cc,in, st etc.) and domains of the roles which can be used
11763: to restrict the list of roles reported. If no array ref is
11764: provided for types, will default to return only active roles.
11765:
11766: =back
11767:
11768: =head2 User Modification
11769:
11770: =over 4
11771:
11772: =item *
11773:
11774: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
11775: user for the level given by URL. Optional start and end dates (leave empty
11776: string or zero for "no date")
11777:
11778: =item *
11779:
11780: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11781: change a users, password, possible return values are: ok,
11782: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11783: refused
11784:
11785: =item *
11786:
11787: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
11788:
11789: =item *
11790:
11791: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11792: $forceid,$desiredhome,$email,$inststatus,$candelete) :
11793:
11794: will update user information (firstname,middlename,lastname,generation,
11795: permanentemail), and if forceid is true, student/employee ID also.
11796: A user's institutional affiliation(s) can also be updated.
11797: User information fields will not be overwritten with empty entries
11798: unless the field is included in the $candelete array reference.
11799: This array is included when a single user is modified via "Manage Users",
11800: or when Autoupdate.pl is run by cron in a domain.
11801:
11802: =item *
11803:
11804: modifystudent
11805:
11806: modify a student's enrollment and identification information.
11807: The course id is resolved based on the current users environment.
11808: This means the envoking user must be a course coordinator or otherwise
11809: associated with a course.
11810:
11811: This call is essentially a wrapper for lonnet::modifyuser and
11812: lonnet::modify_student_enrollment
11813:
11814: Inputs:
11815:
11816: =over 4
11817:
11818: =item B<$udom> Student's loncapa domain
11819:
11820: =item B<$uname> Student's loncapa login name
11821:
11822: =item B<$uid> Student/Employee ID
11823:
11824: =item B<$umode> Student's authentication mode
11825:
11826: =item B<$upass> Student's password
11827:
11828: =item B<$first> Student's first name
11829:
11830: =item B<$middle> Student's middle name
11831:
11832: =item B<$last> Student's last name
11833:
11834: =item B<$gene> Student's generation
11835:
11836: =item B<$usec> Student's section in course
11837:
11838: =item B<$end> Unix time of the roles expiration
11839:
11840: =item B<$start> Unix time of the roles start date
11841:
11842: =item B<$forceid> If defined, allow $uid to be changed
11843:
11844: =item B<$desiredhome> server to use as home server for student
11845:
11846: =item B<$email> Student's permanent e-mail address
11847:
11848: =item B<$type> Type of enrollment (auto or manual)
11849:
11850: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
11851:
11852: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
11853:
11854: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
11855:
11856: =item B<$context> role change context (shown in User Management Logs display in a course)
11857:
11858: =item B<$inststatus> institutional status of user - : separated string of escaped status types
11859:
11860: =back
11861:
11862: =item *
11863:
11864: modify_student_enrollment
11865:
11866: Change a students enrollment status in a class. The environment variable
11867: 'role.request.course' must be defined for this function to proceed.
11868:
11869: Inputs:
11870:
11871: =over 4
11872:
11873: =item $udom, students domain
11874:
11875: =item $uname, students name
11876:
11877: =item $uid, students user id
11878:
11879: =item $first, students first name
11880:
11881: =item $middle
11882:
11883: =item $last
11884:
11885: =item $gene
11886:
11887: =item $usec
11888:
11889: =item $end
11890:
11891: =item $start
11892:
11893: =item $type
11894:
11895: =item $locktype
11896:
11897: =item $cid
11898:
11899: =item $selfenroll
11900:
11901: =item $context
11902:
11903: =back
11904:
11905:
11906: =item *
11907:
11908: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11909: custom role; give a custom role to a user for the level given by URL. Specify
11910: name and domain of role author, and role name
11911:
11912: =item *
11913:
11914: revokerole($udom,$uname,$url,$role) : revoke a role for url
11915:
11916: =item *
11917:
11918: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11919:
11920: =back
11921:
11922: =head2 Course Infomation
11923:
11924: =over 4
11925:
11926: =item *
11927:
11928: coursedescription($courseid,$options) : returns a hash of information about the
11929: specified course id, including all environment settings for the
11930: course, the description of the course will be in the hash under the
11931: key 'description'
11932:
11933: $options is an optional parameter that if supplied is a hash reference that controls
11934: what how this function works. It has the following key/values:
11935:
11936: =over 4
11937:
11938: =item freshen_cache
11939:
11940: If defined, and the environment cache for the course is valid, it is
11941: returned in the returned hash.
11942:
11943: =item one_time
11944:
11945: If defined, the last cache time is set to _now_
11946:
11947: =item user
11948:
11949: If defined, the supplied username is used instead of the current user.
11950:
11951:
11952: =back
11953:
11954: =item *
11955:
11956: resdata($name,$domain,$type,@which) : request for current parameter
11957: setting for a specific $type, where $type is either 'course' or 'user',
11958: @what should be a list of parameters to ask about. This routine caches
11959: answers for 5 minutes.
11960:
11961: =item *
11962:
11963: get_courseresdata($courseid, $domain) : dump the entire course resource
11964: data base, returning a hash that is keyed by the resource name and has
11965: values that are the resource value. I believe that the timestamps and
11966: versions are also returned.
11967:
11968:
11969: =back
11970:
11971: =head2 Course Modification
11972:
11973: =over 4
11974:
11975: =item *
11976:
11977: writecoursepref($courseid,%prefs) : write preferences (environment
11978: database) for a course
11979:
11980: =item *
11981:
11982: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11983:
11984: =item *
11985:
11986: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
11987:
11988: =item *
11989:
11990: is_course($courseid), is_course($cdom, $cnum)
11991:
11992: Accepts either a combined $courseid (in the form of domain_courseid) or the
11993: two component version $cdom, $cnum. It checks if the specified course exists.
11994:
11995: Returns:
11996: undef if the course doesn't exist, otherwise
11997: in scalar context the combined courseid.
11998: in list context the two components of the course identifier, domain and
11999: courseid.
12000:
12001: =back
12002:
12003: =head2 Resource Subroutines
12004:
12005: =over 4
12006:
12007: =item *
12008:
12009: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12010:
12011: =item *
12012:
12013: repcopy($filename) : subscribes to the requested file, and attempts to
12014: replicate from the owning library server, Might return
12015: 'unavailable', 'not_found', 'forbidden', 'ok', or
12016: 'bad_request', also attempts to grab the metadata for the
12017: resource. Expects the local filesystem pathname
12018: (/home/httpd/html/res/....)
12019:
12020: =back
12021:
12022: =head2 Resource Information
12023:
12024: =over 4
12025:
12026: =item *
12027:
12028: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12029: a vairety of different possible values, $varname should be a request
12030: string, and the other parameters can be used to specify who and what
12031: one is asking about.
12032:
12033: Possible values for $varname are environment.lastname (or other item
12034: from the envirnment hash), user.name (or someother aspect about the
12035: user), resource.0.maxtries (or some other part and parameter of a
12036: resource)
12037:
12038: =item *
12039:
12040: directcondval($number) : get current value of a condition; reads from a state
12041: string
12042:
12043: =item *
12044:
12045: condval($condidx) : value of condition index based on state
12046:
12047: =item *
12048:
12049: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12050: resource's metadata, $what should be either a specific key, or either
12051: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12052: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12053:
12054: this function automatically caches all requests
12055:
12056: =item *
12057:
12058: metadata_query($query,$custom,$customshow) : make a metadata query against the
12059: network of library servers; returns file handle of where SQL and regex results
12060: will be stored for query
12061:
12062: =item *
12063:
12064: symbread($filename) : return symbolic list entry (filename argument optional);
12065: returns the data handle
12066:
12067: =item *
12068:
12069: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
12070: a possible symb for the URL in $thisfn, and if is an encryypted
12071: resource that the user accessed using /enc/ returns a 1 on success, 0
12072: on failure, user must be in a course, as it assumes the existance of
12073: the course initial hash, and uses $env('request.course.id'}
12074:
12075:
12076: =item *
12077:
12078: symbclean($symb) : removes versions numbers from a symb, returns the
12079: cleaned symb
12080:
12081: =item *
12082:
12083: is_on_map($uri) : checks if the $uri is somewhere on the current
12084: course map, user must be in a course for it to work.
12085:
12086: =item *
12087:
12088: numval($salt) : return random seed value (addend for rndseed)
12089:
12090: =item *
12091:
12092: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12093: a random seed, all arguments are optional, if they aren't sent it uses the
12094: environment to derive them. Note: if symb isn't sent and it can't get one
12095: from &symbread it will use the current time as its return value
12096:
12097: =item *
12098:
12099: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12100: unfakeable, receipt
12101:
12102: =item *
12103:
12104: receipt() : API to ireceipt working off of env values; given out to users
12105:
12106: =item *
12107:
12108: countacc($url) : count the number of accesses to a given URL
12109:
12110: =item *
12111:
12112: 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
12113:
12114: =item *
12115:
12116: 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)
12117:
12118: =item *
12119:
12120: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
12121:
12122: =item *
12123:
12124: devalidate($symb) : devalidate temporary spreadsheet calculations,
12125: forcing spreadsheet to reevaluate the resource scores next time.
12126:
12127: =back
12128:
12129: =head2 Storing/Retreiving Data
12130:
12131: =over 4
12132:
12133: =item *
12134:
12135: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12136: for this url; hashref needs to be given and should be a \%hashname; the
12137: remaining args aren't required and if they aren't passed or are '' they will
12138: be derived from the env
12139:
12140: =item *
12141:
12142: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12143: uses critical subroutine
12144:
12145: =item *
12146:
12147: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12148: all args are optional
12149:
12150: =item *
12151:
12152: dumpstore($namespace,$udom,$uname,$regexp,$range) :
12153: dumps the complete (or key matching regexp) namespace into a hash
12154: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12155: normally &store()ed into
12156:
12157: $range should be either an integer '100' (give me the first 100
12158: matching records)
12159: or be two integers sperated by a - with no spaces
12160: '30-50' (give me the 30th through the 50th matching
12161: records)
12162:
12163:
12164: =item *
12165:
12166: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12167: replaces a &store() version of data with a replacement set of data
12168: for a particular resource in a namespace passed in the $storehash hash
12169: reference
12170:
12171: =item *
12172:
12173: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12174: works very similar to store/cstore, but all data is stored in a
12175: temporary location and can be reset using tmpreset, $storehash should
12176: be a hash reference, returns nothing on success
12177:
12178: =item *
12179:
12180: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12181: similar to restore, but all data is stored in a temporary location and
12182: can be reset using tmpreset. Returns a hash of values on success,
12183: error string otherwise.
12184:
12185: =item *
12186:
12187: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
12188: deltes all keys for $symb form the temporary storage hash.
12189:
12190: =item *
12191:
12192: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12193: reference filled in from namesp ($udom and $uname are optional)
12194:
12195: =item *
12196:
12197: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
12198: namesp ($udom and $uname are optional)
12199:
12200: =item *
12201:
12202: dump($namespace,$udom,$uname,$regexp,$range) :
12203: dumps the complete (or key matching regexp) namespace into a hash
12204: ($udom, $uname, $regexp, $range are optional)
12205:
12206: $range should be either an integer '100' (give me the first 100
12207: matching records)
12208: or be two integers sperated by a - with no spaces
12209: '30-50' (give me the 30th through the 50th matching
12210: records)
12211: =item *
12212:
12213: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
12214: $store can be a scalar, an array reference, or if the amount to be
12215: incremented is > 1, a hash reference.
12216:
12217: ($udom and $uname are optional)
12218:
12219: =item *
12220:
12221: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
12222: ($udom and $uname are optional)
12223:
12224: =item *
12225:
12226: cput($namespace,$storehash,$udom,$uname) : critical put
12227: ($udom and $uname are optional)
12228:
12229: =item *
12230:
12231: newput($namespace,$storehash,$udom,$uname) :
12232:
12233: Attempts to store the items in the $storehash, but only if they don't
12234: currently exist, if this succeeds you can be certain that you have
12235: successfully created a new key value pair in the $namespace db.
12236:
12237:
12238: Args:
12239: $namespace: name of database to store values to
12240: $storehash: hashref to store to the db
12241: $udom: (optional) domain of user containing the db
12242: $uname: (optional) name of user caontaining the db
12243:
12244: Returns:
12245: 'ok' -> succeeded in storing all keys of $storehash
12246: 'key_exists: <key>' -> failed to anything out of $storehash, as at
12247: least <key> already existed in the db (other
12248: requested keys may also already exist)
12249: 'error: <msg>' -> unable to tie the DB or other error occurred
12250: 'con_lost' -> unable to contact request server
12251: 'refused' -> action was not allowed by remote machine
12252:
12253:
12254: =item *
12255:
12256: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12257: reference filled in from namesp (encrypts the return communication)
12258: ($udom and $uname are optional)
12259:
12260: =item *
12261:
12262: log($udom,$name,$home,$message) : write to permanent log for user; use
12263: critical subroutine
12264:
12265: =item *
12266:
12267: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
12268: array reference filled in from namespace found in domain level on either
12269: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
12270:
12271: =item *
12272:
12273: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
12274: domain level either on specified domain server ($uhome) or primary domain
12275: server ($udom and $uhome are optional)
12276:
12277: =item *
12278:
12279: get_domain_defaults($target_domain) : returns hash with defaults for
12280: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
12281: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
12282: or localauth), initial password or a kerberos realm, language (e.g., en-us).
12283: Values are retrieved from cache (if current), or from domain's configuration.db
12284: (if available), or lastly from values in lonTabs/dns_domain,tab,
12285: or lonTabs/domain.tab.
12286:
12287: %domdefaults = &get_auth_defaults($target_domain);
12288:
12289: =back
12290:
12291: =head2 Network Status Functions
12292:
12293: =over 4
12294:
12295: =item *
12296:
12297: dirlist() : return directory list based on URI (first arg).
12298:
12299: Inputs: 1 required, 5 optional.
12300:
12301: =over
12302:
12303: =item
12304: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
12305:
12306: =item
12307: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
12308:
12309: =item
12310: $username - username of user/course to be listed. Extracted from $uri if absent.
12311:
12312: =item
12313: $getpropath - boolean: 1 if prepend path using &propath().
12314:
12315: =item
12316: $getuserdir - boolean: 1 if prepend path for "userfiles".
12317:
12318: =item
12319: $alternateRoot - path to prepend in place of path from $uri.
12320:
12321: =back
12322:
12323: Returns: Array of up to two items.
12324:
12325: =over
12326:
12327: a reference to an array of files/subdirectories
12328:
12329: =over
12330:
12331: Each element in the array of files/subdirectories is a & separated list of
12332: item name and the result of running stat on the item. If dirlist was requested
12333: for a file instead of a directory, the item name will be ''. For a directory
12334: listing, if the item is a metadata file, the element will end &N&M
12335: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
12336: default copyright set (1).
12337:
12338: =back
12339:
12340: a scalar containing error condition (if encountered).
12341:
12342: =over
12343:
12344: =item
12345: no_host (no homeserver identified for $username:$domain).
12346:
12347: =item
12348: no_such_host (server contacted for listing not identified as valid host).
12349:
12350: =item
12351: con_lost (connection to remote server failed).
12352:
12353: =item
12354: refused (invalid $username:$domain received on lond side).
12355:
12356: =item
12357: no_such_dir (directory at specified path on lond side does not exist).
12358:
12359: =item
12360: empty (directory at specified path on lond side is empty).
12361:
12362: =over
12363:
12364: This is currently not encountered because the &ls3, &ls2,
12365: &ls (_handler) routines on the lond side do not filter out
12366: . and .. from a directory listing.
12367:
12368: =back
12369:
12370: =back
12371:
12372: =back
12373:
12374: =item *
12375:
12376: spareserver() : find server with least workload from spare.tab
12377:
12378:
12379: =item *
12380:
12381: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
12382: if there is no corresponding loncapa host.
12383:
12384: =back
12385:
12386:
12387: =head2 Apache Request
12388:
12389: =over 4
12390:
12391: =item *
12392:
12393: ssi($url,%hash) : server side include, does a complete request cycle on url to
12394: localhost, posts hash
12395:
12396: =back
12397:
12398: =head2 Data to String to Data
12399:
12400: =over 4
12401:
12402: =item *
12403:
12404: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12405: and '&' separators, supports elements that are arrayrefs and hashrefs
12406:
12407: =item *
12408:
12409: hashref2str($hashref) : convert a hashref into a string complete with
12410: escaping and '=' and '&' separators, supports elements that are
12411: arrayrefs and hashrefs
12412:
12413: =item *
12414:
12415: arrayref2str($arrayref) : convert an arrayref into a string complete
12416: with escaping and '&' separators, supports elements that are arrayrefs
12417: and hashrefs
12418:
12419: =item *
12420:
12421: str2hash($string) : convert string to hash using unescaping and
12422: splitting on '=' and '&', supports elements that are arrayrefs and
12423: hashrefs
12424:
12425: =item *
12426:
12427: str2array($string) : convert string to hash using unescaping and
12428: splitting on '&', supports elements that are arrayrefs and hashrefs
12429:
12430: =back
12431:
12432: =head2 Logging Routines
12433:
12434:
12435: These routines allow one to make log messages in the lonnet.log and
12436: lonnet.perm logfiles.
12437:
12438: =over 4
12439:
12440: =item *
12441:
12442: logtouch() : make sure the logfile, lonnet.log, exists
12443:
12444: =item *
12445:
12446: logthis() : append message to the normal lonnet.log file, it gets
12447: preiodically rolled over and deleted.
12448:
12449: =item *
12450:
12451: logperm() : append a permanent message to lonnet.perm.log, this log
12452: file never gets deleted by any automated portion of the system, only
12453: messages of critical importance should go in here.
12454:
12455:
12456: =back
12457:
12458: =head2 General File Helper Routines
12459:
12460: =over 4
12461:
12462: =item *
12463:
12464: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12465: (a) files in /uploaded
12466: (i) If a local copy of the file exists -
12467: compares modification date of local copy with last-modified date for
12468: definitive version stored on home server for course. If local copy is
12469: stale, requests a new version from the home server and stores it.
12470: If the original has been removed from the home server, then local copy
12471: is unlinked.
12472: (ii) If local copy does not exist -
12473: requests the file from the home server and stores it.
12474:
12475: If $caller is 'uploadrep':
12476: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12477: for request for files originally uploaded via DOCS.
12478: - returns 'ok' if fresh local copy now available, -1 otherwise.
12479:
12480: Otherwise:
12481: This indicates a call from the content generation phase of the request.
12482: - returns the entire contents of the file or -1.
12483:
12484: (b) files in /res
12485: - returns the entire contents of a file or -1;
12486: it properly subscribes to and replicates the file if neccessary.
12487:
12488:
12489: =item *
12490:
12491: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12492: reference
12493:
12494: returns either a stat() list of data about the file or an empty list
12495: if the file doesn't exist or couldn't find out about it (connection
12496: problems or user unknown)
12497:
12498: =item *
12499:
12500: filelocation($dir,$file) : returns file system location of a file
12501: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12502: directory that relative $file lookups are to looked in ($dir of /a/dir
12503: and a file of ../bob will become /a/bob)
12504:
12505: =item *
12506:
12507: hreflocation($dir,$file) : returns file system location or a URL; same as
12508: filelocation except for hrefs
12509:
12510: =item *
12511:
12512: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12513:
12514: =back
12515:
12516: =head2 Usererfile file routines (/uploaded*)
12517:
12518: =over 4
12519:
12520: =item *
12521:
12522: userfileupload(): main rotine for putting a file in a user or course's
12523: filespace, arguments are,
12524:
12525: formname - required - this is the name of the element in $env where the
12526: filename, and the contents of the file to create/modifed exist
12527: the filename is in $env{'form.'.$formname.'.filename'} and the
12528: contents of the file is located in $env{'form.'.$formname}
12529: context - if coursedoc, store the file in the course of the active role
12530: of the current user;
12531: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12532: if 'canceloverwrite': delete file in tmp/overwrites directory
12533: subdir - required - subdirectory to put the file in under ../userfiles/
12534: if undefined, it will be placed in "unknown"
12535:
12536: (This routine calls clean_filename() to remove any dangerous
12537: characters from the filename, and then calls finuserfileupload() to
12538: complete the transaction)
12539:
12540: returns either the url of the uploaded file (/uploaded/....) if successful
12541: and /adm/notfound.html if unsuccessful
12542:
12543: =item *
12544:
12545: clean_filename(): routine for cleaing a filename up for storage in
12546: userfile space, argument is:
12547:
12548: filename - proposed filename
12549:
12550: returns: the new clean filename
12551:
12552: =item *
12553:
12554: finishuserfileupload(): routine that creates and sends the file to
12555: userspace, probably shouldn't be called directly
12556:
12557: docuname: username or courseid of destination for the file
12558: docudom: domain of user/course of destination for the file
12559: formname: same as for userfileupload()
12560: fname: filename (including subdirectories) for the file
12561: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12562: allfiles: reference to hash used to store objects found by parser
12563: codebase: reference to hash used for codebases of java objects found by parser
12564: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12565: thumbheight: height (pixels) of thumbnail to be created for uploaded image
12566: resizewidth: width to be used to resize image using resizeImage from ImageMagick
12567: resizeheight: height to be used to resize image using resizeImage from ImageMagick
12568: context: if 'overwrite', will move the uploaded file from its temporary location to
12569: userfiles to facilitate overwriting a previously uploaded file with same name.
12570: mimetype: reference to scalar to accommodate mime type determined
12571: from File::MMagic if $parser = parse.
12572:
12573: returns either the url of the uploaded file (/uploaded/....) if successful
12574: and /adm/notfound.html if unsuccessful (or an error message if context
12575: was 'overwrite').
12576:
12577:
12578: =item *
12579:
12580: renameuserfile(): renames an existing userfile to a new name
12581:
12582: Args:
12583: docuname: username or courseid of destination for the file
12584: docudom: domain of user/course of destination for the file
12585: old: current file name (including any subdirs under userfiles)
12586: new: desired file name (including any subdirs under userfiles)
12587:
12588: =item *
12589:
12590: mkdiruserfile(): creates a directory is a userfiles dir
12591:
12592: Args:
12593: docuname: username or courseid of destination for the file
12594: docudom: domain of user/course of destination for the file
12595: dir: dir to create (including any subdirs under userfiles)
12596:
12597: =item *
12598:
12599: removeuserfile(): removes a file that exists in userfiles
12600:
12601: Args:
12602: docuname: username or courseid of destination for the file
12603: docudom: domain of user/course of destination for the file
12604: fname: filname to delete (including any subdirs under userfiles)
12605:
12606: =item *
12607:
12608: removeuploadedurl(): convience function for removeuserfile()
12609:
12610: Args:
12611: url: a full /uploaded/... url to delete
12612:
12613: =item *
12614:
12615: get_portfile_permissions():
12616: Args:
12617: domain: domain of user or course contain the portfolio files
12618: user: name of user or num of course contain the portfolio files
12619: Returns:
12620: hashref of a dump of the proper file_permissions.db
12621:
12622:
12623: =item *
12624:
12625: get_access_controls():
12626:
12627: Args:
12628: current_permissions: the hash ref returned from get_portfile_permissions()
12629: group: (optional) the group you want the files associated with
12630: file: (optional) the file you want access info on
12631:
12632: Returns:
12633: a hash (keys are file names) of hashes containing
12634: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12635: values are XML containing access control settings (see below)
12636:
12637: Internal notes:
12638:
12639: access controls are stored in file_permissions.db as key=value pairs.
12640: key -> path to file/file_name\0uniqueID:scope_end_start
12641: where scope -> public,guest,course,group,domains or users.
12642: end -> UNIX time for end of access (0 -> no end date)
12643: start -> UNIX time for start of access
12644:
12645: value -> XML description of access control
12646: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12647: <start></start>
12648: <end></end>
12649:
12650: <password></password> for scope type = guest
12651:
12652: <domain></domain> for scope type = course or group
12653: <number></number>
12654: <roles id="">
12655: <role></role>
12656: <access></access>
12657: <section></section>
12658: <group></group>
12659: </roles>
12660:
12661: <dom></dom> for scope type = domains
12662:
12663: <users> for scope type = users
12664: <user>
12665: <uname></uname>
12666: <udom></udom>
12667: </user>
12668: </users>
12669: </scope>
12670:
12671: Access data is also aggregated for each file in an additional key=value pair:
12672: key -> path to file/file_name\0accesscontrol
12673: value -> reference to hash
12674: hash contains key = value pairs
12675: where key = uniqueID:scope_end_start
12676: value = UNIX time record was last updated
12677:
12678: Used to improve speed of look-ups of access controls for each file.
12679:
12680: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12681:
12682: modify_access_controls():
12683:
12684: Modifies access controls for a portfolio file
12685: Args
12686: 1. file name
12687: 2. reference to hash of required changes,
12688: 3. domain
12689: 4. username
12690: where domain,username are the domain of the portfolio owner
12691: (either a user or a course)
12692:
12693: Returns:
12694: 1. result of additions or updates ('ok' or 'error', with error message).
12695: 2. result of deletions ('ok' or 'error', with error message).
12696: 3. reference to hash of any new or updated access controls.
12697: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12698: key = integer (inbound ID)
12699: value = uniqueID
12700:
12701: =back
12702:
12703: =head2 HTTP Helper Routines
12704:
12705: =over 4
12706:
12707: =item *
12708:
12709: escape() : unpack non-word characters into CGI-compatible hex codes
12710:
12711: =item *
12712:
12713: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12714:
12715: =back
12716:
12717: =head1 PRIVATE SUBROUTINES
12718:
12719: =head2 Underlying communication routines (Shouldn't call)
12720:
12721: =over 4
12722:
12723: =item *
12724:
12725: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12726:
12727: =item *
12728:
12729: reply() : uses subreply to send a message to remote machine, logs all failures
12730:
12731: =item *
12732:
12733: critical() : passes a critical message to another server; if cannot
12734: get through then place message in connection buffer directory and
12735: returns con_delayed, if incapable of saving message, returns
12736: con_failed
12737:
12738: =item *
12739:
12740: reconlonc() : tries to reconnect lonc client processes.
12741:
12742: =back
12743:
12744: =head2 Resource Access Logging
12745:
12746: =over 4
12747:
12748: =item *
12749:
12750: flushcourselogs() : flush (save) buffer logs and access logs
12751:
12752: =item *
12753:
12754: courselog($what) : save message for course in hash
12755:
12756: =item *
12757:
12758: courseacclog($what) : save message for course using &courselog(). Perform
12759: special processing for specific resource types (problems, exams, quizzes, etc).
12760:
12761: =item *
12762:
12763: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12764: as a PerlChildExitHandler
12765:
12766: =back
12767:
12768: =head2 Other
12769:
12770: =over 4
12771:
12772: =item *
12773:
12774: symblist($mapname,%newhash) : update symbolic storage links
12775:
12776: =back
12777:
12778: =cut
12779:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>