1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.1359 2017/11/13 00:49:31 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 HTTP::Date;
75: use Image::Magick;
76:
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( sleep 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: use LONCAPA::LWPReq;
104:
105: use File::Copy;
106:
107: my $readit;
108: my $max_connection_retries = 20; # Or some such value.
109:
110: require Exporter;
111:
112: our @ISA = qw (Exporter);
113: our @EXPORT = qw(%env);
114:
115:
116: # ------------------------------------ Logging (parameters, docs, slots, roles)
117: {
118: my $logid;
119: sub write_log {
120: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
121: if ($context eq 'course') {
122: if (($cnum eq '') || ($cdom eq '')) {
123: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
124: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
125: }
126: }
127: $logid ++;
128: my $now = time();
129: my $id=$now.'00000'.$$.'00000'.$logid;
130: my $logentry = {
131: $id => {
132: 'exe_uname' => $env{'user.name'},
133: 'exe_udom' => $env{'user.domain'},
134: 'exe_time' => $now,
135: 'exe_ip' => $ENV{'REMOTE_ADDR'},
136: 'delflag' => $delflag,
137: 'logentry' => $storehash,
138: 'uname' => $uname,
139: 'udom' => $udom,
140: }
141: };
142: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
143: }
144: }
145:
146: sub logtouch {
147: my $execdir=$perlvar{'lonDaemons'};
148: unless (-e "$execdir/logs/lonnet.log") {
149: open(my $fh,">>","$execdir/logs/lonnet.log");
150: close $fh;
151: }
152: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
153: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
154: }
155:
156: sub logthis {
157: my $message=shift;
158: my $execdir=$perlvar{'lonDaemons'};
159: my $now=time;
160: my $local=localtime($now);
161: if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
162: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
163: print $fh $logstring;
164: close($fh);
165: }
166: return 1;
167: }
168:
169: sub logperm {
170: my $message=shift;
171: my $execdir=$perlvar{'lonDaemons'};
172: my $now=time;
173: my $local=localtime($now);
174: if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
175: print $fh "$now:$message:$local\n";
176: close($fh);
177: }
178: return 1;
179: }
180:
181: sub create_connection {
182: my ($hostname,$lonid) = @_;
183: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
184: Type => SOCK_STREAM,
185: Timeout => 10);
186: return 0 if (!$client);
187: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
188: my $result = <$client>;
189: chomp($result);
190: return 1 if ($result eq 'done');
191: return 0;
192: }
193:
194: sub get_server_timezone {
195: my ($cnum,$cdom) = @_;
196: my $home=&homeserver($cnum,$cdom);
197: if ($home ne 'no_host') {
198: my $cachetime = 24*3600;
199: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
200: if (defined($cached)) {
201: return $timezone;
202: } else {
203: my $timezone = &reply('servertimezone',$home);
204: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
205: }
206: }
207: }
208:
209: sub get_server_distarch {
210: my ($lonhost,$ignore_cache) = @_;
211: if (defined($lonhost)) {
212: if (!defined(&hostname($lonhost))) {
213: return;
214: }
215: my $cachetime = 12*3600;
216: if (!$ignore_cache) {
217: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
218: if (defined($cached)) {
219: return $distarch;
220: }
221: }
222: my $rep = &reply('serverdistarch',$lonhost);
223: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
224: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
225: $rep eq '') {
226: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
227: }
228: }
229: return;
230: }
231:
232: sub get_servercerts_info {
233: my ($lonhost,$context) = @_;
234: my ($rep,$uselocal);
235: if (grep { $_ eq $lonhost } ¤t_machine_ids()) {
236: $uselocal = 1;
237: }
238: if (($context ne 'cgi') && ($uselocal)) {
239: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
240: if ($distro eq '') {
241: $uselocal = 0;
242: } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
243: if ($1 < 6) {
244: $uselocal = 0;
245: }
246: } elsif ($distro =~ /^(?:sles)(\d+)$/) {
247: if ($1 < 12) {
248: $uselocal = 0;
249: }
250: }
251: }
252: if ($uselocal) {
253: $rep = LONCAPA::Lond::server_certs(\%perlvar);
254: } else {
255: $rep=&reply('servercerts',$lonhost);
256: }
257: my ($result,%returnhash);
258: if (defined($lonhost)) {
259: if (!defined(&hostname($lonhost))) {
260: return;
261: }
262: }
263: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
264: ($rep eq 'unknown_cmd')) {
265: $result = $rep;
266: } else {
267: $result = 'ok';
268: my @pairs=split(/\&/,$rep);
269: foreach my $item (@pairs) {
270: my ($key,$value)=split(/=/,$item,2);
271: my $what = &unescape($key);
272: $returnhash{$what}=&thaw_unescape($value);
273: }
274: }
275: return ($result,\%returnhash);
276: }
277:
278: sub get_server_loncaparev {
279: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
280: if (defined($lonhost)) {
281: if (!defined(&hostname($lonhost))) {
282: undef($lonhost);
283: }
284: }
285: if (!defined($lonhost)) {
286: if (defined(&domain($dom,'primary'))) {
287: $lonhost=&domain($dom,'primary');
288: if ($lonhost eq 'no_host') {
289: undef($lonhost);
290: }
291: }
292: }
293: if (defined($lonhost)) {
294: my $cachetime = 12*3600;
295: if (!$ignore_cache) {
296: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
297: if (defined($cached)) {
298: return $loncaparev;
299: }
300: }
301: my ($answer,$loncaparev);
302: my @ids=¤t_machine_ids();
303: if (grep(/^\Q$lonhost\E$/,@ids)) {
304: $answer = $perlvar{'lonVersion'};
305: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
306: $loncaparev = $1;
307: }
308: } else {
309: $answer = &reply('serverloncaparev',$lonhost);
310: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
311: if ($caller eq 'loncron') {
312: my $protocol = $protocol{$lonhost};
313: $protocol = 'http' if ($protocol ne 'https');
314: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
315: my $request=new HTTP::Request('GET',$url);
316: my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
317: unless ($response->is_error()) {
318: my $content = $response->content;
319: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
320: $loncaparev = $1;
321: }
322: }
323: } else {
324: $loncaparev = $loncaparevs{$lonhost};
325: }
326: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
327: $loncaparev = $1;
328: }
329: }
330: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
331: }
332: }
333:
334: sub get_server_homeID {
335: my ($hostname,$ignore_cache,$caller) = @_;
336: unless ($ignore_cache) {
337: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
338: if (defined($cached)) {
339: return $serverhomeID;
340: }
341: }
342: my $cachetime = 12*3600;
343: my $serverhomeID;
344: if ($caller eq 'loncron') {
345: my @machine_ids = &machine_ids($hostname);
346: foreach my $id (@machine_ids) {
347: my $response = &reply('serverhomeID',$id);
348: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
349: $serverhomeID = $response;
350: last;
351: }
352: }
353: if ($serverhomeID eq '') {
354: $serverhomeID = $machine_ids[-1];
355: }
356: } else {
357: $serverhomeID = $serverhomeIDs{$hostname};
358: }
359: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
360: }
361:
362: sub get_remote_globals {
363: my ($lonhost,$whathash,$ignore_cache) = @_;
364: my ($result,%returnhash,%whatneeded);
365: if (ref($whathash) eq 'HASH') {
366: foreach my $what (sort(keys(%{$whathash}))) {
367: my $hashid = $lonhost.'-'.$what;
368: my ($response,$cached);
369: unless ($ignore_cache) {
370: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
371: }
372: if (defined($cached)) {
373: $returnhash{$what} = $response;
374: } else {
375: $whatneeded{$what} = 1;
376: }
377: }
378: if (keys(%whatneeded) == 0) {
379: $result = 'ok';
380: } else {
381: my $requested = &freeze_escape(\%whatneeded);
382: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
383: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
384: ($rep eq 'unknown_cmd')) {
385: $result = $rep;
386: } else {
387: $result = 'ok';
388: my @pairs=split(/\&/,$rep);
389: foreach my $item (@pairs) {
390: my ($key,$value)=split(/=/,$item,2);
391: my $what = &unescape($key);
392: my $hashid = $lonhost.'-'.$what;
393: $returnhash{$what}=&thaw_unescape($value);
394: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
395: }
396: }
397: }
398: }
399: return ($result,\%returnhash);
400: }
401:
402: sub remote_devalidate_cache {
403: my ($lonhost,$cachekeys) = @_;
404: my $items;
405: return unless (ref($cachekeys) eq 'ARRAY');
406: my $cachestr = join('&',@{$cachekeys});
407: my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
408: return $response;
409: }
410:
411: # -------------------------------------------------- Non-critical communication
412: sub subreply {
413: my ($cmd,$server)=@_;
414: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
415: #
416: # With loncnew process trimming, there's a timing hole between lonc server
417: # process exit and the master server picking up the listen on the AF_UNIX
418: # socket. In that time interval, a lock file will exist:
419:
420: my $lockfile=$peerfile.".lock";
421: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
422: sleep(0.1);
423: }
424: # At this point, either a loncnew parent is listening or an old lonc
425: # or loncnew child is listening so we can connect or everything's dead.
426: #
427: # We'll give the connection a few tries before abandoning it. If
428: # connection is not possible, we'll con_lost back to the client.
429: #
430: my $client;
431: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
432: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
433: Type => SOCK_STREAM,
434: Timeout => 10);
435: if ($client) {
436: last; # Connected!
437: } else {
438: &create_connection(&hostname($server),$server);
439: }
440: sleep(0.1); # Try again later if failed connection.
441: }
442: my $answer;
443: if ($client) {
444: print $client "sethost:$server:$cmd\n";
445: $answer=<$client>;
446: if (!$answer) { $answer="con_lost"; }
447: chomp($answer);
448: } else {
449: $answer = 'con_lost'; # Failed connection.
450: }
451: return $answer;
452: }
453:
454: sub reply {
455: my ($cmd,$server)=@_;
456: unless (defined(&hostname($server))) { return 'no_such_host'; }
457: my $answer=subreply($cmd,$server);
458: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
459: &logthis("<font color=\"blue\">WARNING:".
460: " $cmd to $server returned $answer</font>");
461: }
462: return $answer;
463: }
464:
465: # ----------------------------------------------------------- Send USR1 to lonc
466:
467: sub reconlonc {
468: my ($lonid) = @_;
469: if ($lonid) {
470: my $hostname = &hostname($lonid);
471: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
472: if ($hostname && -e $peerfile) {
473: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
474: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
475: Type => SOCK_STREAM,
476: Timeout => 10);
477: if ($client) {
478: print $client ("reset_retries\n");
479: my $answer=<$client>;
480: #reset just this one.
481: }
482: }
483: return;
484: }
485:
486: &logthis("Trying to reconnect lonc");
487: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
488: if (open(my $fh,"<",$loncfile)) {
489: my $loncpid=<$fh>;
490: chomp($loncpid);
491: if (kill 0 => $loncpid) {
492: &logthis("lonc at pid $loncpid responding, sending USR1");
493: kill USR1 => $loncpid;
494: sleep 1;
495: } else {
496: &logthis(
497: "<font color=\"blue\">WARNING:".
498: " lonc at pid $loncpid not responding, giving up</font>");
499: }
500: } else {
501: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
502: }
503: }
504:
505: # ------------------------------------------------------ Critical communication
506:
507: sub critical {
508: my ($cmd,$server)=@_;
509: unless (&hostname($server)) {
510: &logthis("<font color=\"blue\">WARNING:".
511: " Critical message to unknown server ($server)</font>");
512: return 'no_such_host';
513: }
514: my $answer=reply($cmd,$server);
515: if ($answer eq 'con_lost') {
516: &reconlonc($server);
517: my $answer=reply($cmd,$server);
518: if ($answer eq 'con_lost') {
519: my $now=time;
520: my $middlename=$cmd;
521: $middlename=substr($middlename,0,16);
522: $middlename=~s/\W//g;
523: my $dfilename=
524: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
525: $dumpcount++;
526: {
527: my $dfh;
528: if (open($dfh,">",$dfilename)) {
529: print $dfh "$cmd\n";
530: close($dfh);
531: }
532: }
533: sleep 1;
534: my $wcmd='';
535: {
536: my $dfh;
537: if (open($dfh,"<",$dfilename)) {
538: $wcmd=<$dfh>;
539: close($dfh);
540: }
541: }
542: chomp($wcmd);
543: if ($wcmd eq $cmd) {
544: &logthis("<font color=\"blue\">WARNING: ".
545: "Connection buffer $dfilename: $cmd</font>");
546: &logperm("D:$server:$cmd");
547: return 'con_delayed';
548: } else {
549: &logthis("<font color=\"red\">CRITICAL:"
550: ." Critical connection failed: $server $cmd</font>");
551: &logperm("F:$server:$cmd");
552: return 'con_failed';
553: }
554: }
555: }
556: return $answer;
557: }
558:
559: # ------------------------------------------- check if return value is an error
560:
561: sub error {
562: my ($result) = @_;
563: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
564: if ($2 == 2) { return undef; }
565: return $1;
566: }
567: return undef;
568: }
569:
570: sub convert_and_load_session_env {
571: my ($lonidsdir,$handle)=@_;
572: my @profile;
573: {
574: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
575: if (!$opened) {
576: return 0;
577: }
578: flock($idf,LOCK_SH);
579: @profile=<$idf>;
580: close($idf);
581: }
582: my %temp_env;
583: foreach my $line (@profile) {
584: if ($line !~ m/=/) {
585: return 0;
586: }
587: chomp($line);
588: my ($envname,$envvalue)=split(/=/,$line,2);
589: $temp_env{&unescape($envname)} = &unescape($envvalue);
590: }
591: unlink("$lonidsdir/$handle.id");
592: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
593: 0640)) {
594: %disk_env = %temp_env;
595: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
596: untie(%disk_env);
597: }
598: return 1;
599: }
600:
601: # ------------------------------------------- Transfer profile into environment
602: my $env_loaded;
603: sub transfer_profile_to_env {
604: my ($lonidsdir,$handle,$force_transfer) = @_;
605: if (!$force_transfer && $env_loaded) { return; }
606:
607: if (!defined($lonidsdir)) {
608: $lonidsdir = $perlvar{'lonIDsDir'};
609: }
610: if (!defined($handle)) {
611: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
612: }
613:
614: my $convert;
615: {
616: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
617: if (!$opened) {
618: return;
619: }
620: flock($idf,LOCK_SH);
621: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
622: &GDBM_READER(),0640)) {
623: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
624: untie(%disk_env);
625: } else {
626: $convert = 1;
627: }
628: }
629: if ($convert) {
630: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
631: &logthis("Failed to load session, or convert session.");
632: }
633: }
634:
635: my %remove;
636: while ( my $envname = each(%env) ) {
637: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
638: if ($time < time-300) {
639: $remove{$key}++;
640: }
641: }
642: }
643:
644: $env{'user.environment'} = "$lonidsdir/$handle.id";
645: $env_loaded=1;
646: foreach my $expired_key (keys(%remove)) {
647: &delenv($expired_key);
648: }
649: }
650:
651: # ---------------------------------------------------- Check for valid session
652: sub check_for_valid_session {
653: my ($r,$name,$userhashref,$domref) = @_;
654: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
655: my ($linkname,$pubname);
656: if ($name eq '') {
657: $name = 'lonID';
658: $linkname = 'lonLinkID';
659: $pubname = 'lonPubID';
660: }
661: my $lonid=$cookies{$name};
662: if (!$lonid) {
663: if (($name eq 'lonID') && ($ENV{'SERVER_PORT'} != 443) && ($linkname)) {
664: $lonid=$cookies{$linkname};
665: }
666: if (!$lonid) {
667: if (($name eq 'lonID') && ($pubname)) {
668: $lonid=$cookies{$pubname};
669: }
670: }
671: }
672: return undef if (!$lonid);
673:
674: my $handle=&LONCAPA::clean_handle($lonid->value);
675: my $lonidsdir;
676: if ($name eq 'lonDAV') {
677: $lonidsdir=$r->dir_config('lonDAVsessDir');
678: } else {
679: $lonidsdir=$r->dir_config('lonIDsDir');
680: }
681: if (!-e "$lonidsdir/$handle.id") {
682: if ((ref($domref)) && ($name eq 'lonID') &&
683: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
684: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
685: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
686: $$domref = $possudom;
687: }
688: }
689: return undef;
690: }
691:
692: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
693: return undef if (!$opened);
694:
695: flock($idf,LOCK_SH);
696: my %disk_env;
697: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
698: &GDBM_READER(),0640)) {
699: return undef;
700: }
701:
702: if (!defined($disk_env{'user.name'})
703: || !defined($disk_env{'user.domain'})) {
704: return undef;
705: }
706:
707: if (ref($userhashref) eq 'HASH') {
708: $userhashref->{'name'} = $disk_env{'user.name'};
709: $userhashref->{'domain'} = $disk_env{'user.domain'};
710: }
711:
712: return $handle;
713: }
714:
715: sub timed_flock {
716: my ($file,$lock_type) = @_;
717: my $failed=0;
718: eval {
719: local $SIG{__DIE__}='DEFAULT';
720: local $SIG{ALRM}=sub {
721: $failed=1;
722: die("failed lock");
723: };
724: alarm(13);
725: flock($file,$lock_type);
726: alarm(0);
727: };
728: if ($failed) {
729: return undef;
730: } else {
731: return 1;
732: }
733: }
734:
735: # ---------------------------------------------------------- Append Environment
736:
737: sub appenv {
738: my ($newenv,$roles) = @_;
739: if (ref($newenv) eq 'HASH') {
740: foreach my $key (keys(%{$newenv})) {
741: my $refused = 0;
742: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
743: $refused = 1;
744: if (ref($roles) eq 'ARRAY') {
745: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
746: if (grep(/^\Q$role\E$/,@{$roles})) {
747: $refused = 0;
748: }
749: }
750: }
751: if ($refused) {
752: &logthis("<font color=\"blue\">WARNING: ".
753: "Attempt to modify environment ".$key." to ".$newenv->{$key}
754: .'</font>');
755: delete($newenv->{$key});
756: } else {
757: $env{$key}=$newenv->{$key};
758: }
759: }
760: my $opened = open(my $env_file,'+<',$env{'user.environment'});
761: if ($opened
762: && &timed_flock($env_file,LOCK_EX)
763: &&
764: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
765: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
766: while (my ($key,$value) = each(%{$newenv})) {
767: $disk_env{$key} = $value;
768: }
769: untie(%disk_env);
770: }
771: }
772: return 'ok';
773: }
774: # ----------------------------------------------------- Delete from Environment
775:
776: sub delenv {
777: my ($delthis,$regexp,$roles) = @_;
778: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
779: my $refused = 1;
780: if (ref($roles) eq 'ARRAY') {
781: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
782: if (grep(/^\Q$role\E$/,@{$roles})) {
783: $refused = 0;
784: }
785: }
786: if ($refused) {
787: &logthis("<font color=\"blue\">WARNING: ".
788: "Attempt to delete from environment ".$delthis);
789: return 'error';
790: }
791: }
792: my $opened = open(my $env_file,'+<',$env{'user.environment'});
793: if ($opened
794: && &timed_flock($env_file,LOCK_EX)
795: &&
796: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
797: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
798: foreach my $key (keys(%disk_env)) {
799: if ($regexp) {
800: if ($key=~/^$delthis/) {
801: delete($env{$key});
802: delete($disk_env{$key});
803: }
804: } else {
805: if ($key=~/^\Q$delthis\E/) {
806: delete($env{$key});
807: delete($disk_env{$key});
808: }
809: }
810: }
811: untie(%disk_env);
812: }
813: return 'ok';
814: }
815:
816: sub get_env_multiple {
817: my ($name) = @_;
818: my @values;
819: if (defined($env{$name})) {
820: # exists is it an array
821: if (ref($env{$name})) {
822: @values=@{ $env{$name} };
823: } else {
824: $values[0]=$env{$name};
825: }
826: }
827: return(@values);
828: }
829:
830: # ------------------------------------------------------------------- Locking
831:
832: sub set_lock {
833: my ($text)=@_;
834: $locknum++;
835: my $id=$$.'-'.$locknum;
836: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
837: 'session.lock.'.$id => $text});
838: return $id;
839: }
840:
841: sub get_locks {
842: my $num=0;
843: my %texts=();
844: foreach my $lock (split(/\,/,$env{'session.locks'})) {
845: if ($lock=~/\w/) {
846: $num++;
847: $texts{$lock}=$env{'session.lock.'.$lock};
848: }
849: }
850: return ($num,%texts);
851: }
852:
853: sub remove_lock {
854: my ($id)=@_;
855: my $newlocks='';
856: foreach my $lock (split(/\,/,$env{'session.locks'})) {
857: if (($lock=~/\w/) && ($lock ne $id)) {
858: $newlocks.=','.$lock;
859: }
860: }
861: &appenv({'session.locks' => $newlocks});
862: &delenv('session.lock.'.$id);
863: }
864:
865: sub remove_all_locks {
866: my $activelocks=$env{'session.locks'};
867: foreach my $lock (split(/\,/,$env{'session.locks'})) {
868: if ($lock=~/\w/) {
869: &remove_lock($lock);
870: }
871: }
872: }
873:
874:
875: # ------------------------------------------ Find out current server userload
876: sub userload {
877: my $numusers=0;
878: {
879: opendir(LONIDS,$perlvar{'lonIDsDir'});
880: my $filename;
881: my $curtime=time;
882: while ($filename=readdir(LONIDS)) {
883: next if ($filename eq '.' || $filename eq '..');
884: next if ($filename =~ /publicuser_\d+\.id/);
885: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
886: if ($curtime-$mtime < 1800) { $numusers++; }
887: }
888: closedir(LONIDS);
889: }
890: my $userloadpercent=0;
891: my $maxuserload=$perlvar{'lonUserLoadLim'};
892: if ($maxuserload) {
893: $userloadpercent=100*$numusers/$maxuserload;
894: }
895: $userloadpercent=sprintf("%.2f",$userloadpercent);
896: return $userloadpercent;
897: }
898:
899: # ------------------------------ Find server with least workload from spare.tab
900:
901: sub spareserver {
902: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
903: my $spare_server;
904: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
905: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
906: : $userloadpercent;
907: my ($uint_dom,$remotesessions);
908: if (($udom ne '') && (&domain($udom) ne '')) {
909: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
910: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
911: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
912: $remotesessions = $udomdefaults{'remotesessions'};
913: }
914: my $spareshash = &this_host_spares($udom);
915: if (ref($spareshash) eq 'HASH') {
916: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
917: foreach my $try_server (@{ $spareshash->{'primary'} }) {
918: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
919: $try_server));
920: ($spare_server, $lowest_load) =
921: &compare_server_load($try_server, $spare_server, $lowest_load);
922: }
923: }
924:
925: my $found_server = ($spare_server ne '' && $lowest_load < 100);
926:
927: if (!$found_server) {
928: if (ref($spareshash->{'default'}) eq 'ARRAY') {
929: foreach my $try_server (@{ $spareshash->{'default'} }) {
930: next unless (&spare_can_host($udom,$uint_dom,
931: $remotesessions,$try_server));
932: ($spare_server, $lowest_load) =
933: &compare_server_load($try_server, $spare_server, $lowest_load);
934: }
935: }
936: }
937: }
938:
939: if (!$want_server_name) {
940: my $protocol = 'http';
941: if ($protocol{$spare_server} eq 'https') {
942: $protocol = $protocol{$spare_server};
943: }
944: if (defined($spare_server)) {
945: my $hostname = &hostname($spare_server);
946: if (defined($hostname)) {
947: $spare_server = $protocol.'://'.$hostname;
948: }
949: }
950: }
951: return $spare_server;
952: }
953:
954: sub compare_server_load {
955: my ($try_server, $spare_server, $lowest_load, $required) = @_;
956:
957: if ($required) {
958: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
959: my $remoterev = &get_server_loncaparev(undef,$try_server);
960: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
961: if (($major eq '' && $minor eq '') ||
962: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
963: return ($spare_server,$lowest_load);
964: }
965: }
966:
967: my $loadans = &reply('load', $try_server);
968: my $userloadans = &reply('userload',$try_server);
969:
970: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
971: return ($spare_server, $lowest_load); #didn't get a number from the server
972: }
973:
974: my $load;
975: if ($loadans =~ /\d/) {
976: if ($userloadans =~ /\d/) {
977: #both are numbers, pick the bigger one
978: $load = ($loadans > $userloadans) ? $loadans
979: : $userloadans;
980: } else {
981: $load = $loadans;
982: }
983: } else {
984: $load = $userloadans;
985: }
986:
987: if (($load =~ /\d/) && ($load < $lowest_load)) {
988: $spare_server = $try_server;
989: $lowest_load = $load;
990: }
991: return ($spare_server,$lowest_load);
992: }
993:
994: # --------------------------- ask offload servers if user already has a session
995: sub find_existing_session {
996: my ($udom,$uname) = @_;
997: my $spareshash = &this_host_spares($udom);
998: if (ref($spareshash) eq 'HASH') {
999: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
1000: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1001: return $try_server if (&has_user_session($try_server, $udom, $uname));
1002: }
1003: }
1004: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1005: foreach my $try_server (@{ $spareshash->{'default'} }) {
1006: return $try_server if (&has_user_session($try_server, $udom, $uname));
1007: }
1008: }
1009: }
1010: return;
1011: }
1012:
1013: # -------------------------------- ask if server already has a session for user
1014: sub has_user_session {
1015: my ($lonid,$udom,$uname) = @_;
1016: my $result = &reply(join(':','userhassession',
1017: map {&escape($_)} ($udom,$uname)),$lonid);
1018: return 1 if ($result eq 'ok');
1019:
1020: return 0;
1021: }
1022:
1023: # --------- determine least loaded server in a user's domain which allows login
1024:
1025: sub choose_server {
1026: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1027: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1028: my %servers = &get_servers($udom);
1029: my $lowest_load = 30000;
1030: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1031: if ($skiploadbal) {
1032: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1033: unless (defined($cached)) {
1034: my $cachetime = 60*60*24;
1035: my %domconfig =
1036: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1037: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1038: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1039: $cachetime);
1040: }
1041: }
1042: }
1043: foreach my $lonhost (keys(%servers)) {
1044: if ($skiploadbal) {
1045: if (ref($balancers) eq 'HASH') {
1046: next if (exists($balancers->{$lonhost}));
1047: }
1048: }
1049: my $loginvia;
1050: if ($checkloginvia) {
1051: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1052: if ($loginvia) {
1053: my ($server,$path) = split(/:/,$loginvia);
1054: ($login_host, $lowest_load) =
1055: &compare_server_load($server, $login_host, $lowest_load, $required);
1056: if ($login_host eq $server) {
1057: $portal_path = $path;
1058: $isredirect = 1;
1059: }
1060: } else {
1061: ($login_host, $lowest_load) =
1062: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1063: if ($login_host eq $lonhost) {
1064: $portal_path = '';
1065: $isredirect = '';
1066: }
1067: }
1068: } else {
1069: ($login_host, $lowest_load) =
1070: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1071: }
1072: }
1073: if ($login_host ne '') {
1074: $hostname = &hostname($login_host);
1075: }
1076: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1077: }
1078:
1079: # --------------------------------------------- Try to change a user's password
1080:
1081: sub changepass {
1082: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1083: $currentpass = &escape($currentpass);
1084: $newpass = &escape($newpass);
1085: my $lonhost = $perlvar{'lonHostID'};
1086: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1087: $server);
1088: if (! $answer) {
1089: &logthis("No reply on password change request to $server ".
1090: "by $uname in domain $udom.");
1091: } elsif ($answer =~ "^ok") {
1092: &logthis("$uname in $udom successfully changed their password ".
1093: "on $server.");
1094: } elsif ($answer =~ "^pwchange_failure") {
1095: &logthis("$uname in $udom was unable to change their password ".
1096: "on $server. The action was blocked by either lcpasswd ".
1097: "or pwchange");
1098: } elsif ($answer =~ "^non_authorized") {
1099: &logthis("$uname in $udom did not get their password correct when ".
1100: "attempting to change it on $server.");
1101: } elsif ($answer =~ "^auth_mode_error") {
1102: &logthis("$uname in $udom attempted to change their password despite ".
1103: "not being locally or internally authenticated on $server.");
1104: } elsif ($answer =~ "^unknown_user") {
1105: &logthis("$uname in $udom attempted to change their password ".
1106: "on $server but were unable to because $server is not ".
1107: "their home server.");
1108: } elsif ($answer =~ "^refused") {
1109: &logthis("$server refused to change $uname in $udom password because ".
1110: "it was sent an unencrypted request to change the password.");
1111: } elsif ($answer =~ "invalid_client") {
1112: &logthis("$server refused to change $uname in $udom password because ".
1113: "it was a reset by e-mail originating from an invalid server.");
1114: }
1115: return $answer;
1116: }
1117:
1118: # ----------------------- Try to determine user's current authentication scheme
1119:
1120: sub queryauthenticate {
1121: my ($uname,$udom)=@_;
1122: my $uhome=&homeserver($uname,$udom);
1123: if (!$uhome) {
1124: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1125: return 'no_host';
1126: }
1127: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1128: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1129: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1130: }
1131: return $answer;
1132: }
1133:
1134: # --------- Try to authenticate user from domain's lib servers (first this one)
1135:
1136: sub authenticate {
1137: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1138: $upass=&escape($upass);
1139: $uname= &LONCAPA::clean_username($uname);
1140: my $uhome=&homeserver($uname,$udom,1);
1141: my $newhome;
1142: if ((!$uhome) || ($uhome eq 'no_host')) {
1143: # Maybe the machine was offline and only re-appeared again recently?
1144: &reconlonc();
1145: # One more
1146: $uhome=&homeserver($uname,$udom,1);
1147: if (($uhome eq 'no_host') && $checkdefauth) {
1148: if (defined(&domain($udom,'primary'))) {
1149: $newhome=&domain($udom,'primary');
1150: }
1151: if ($newhome ne '') {
1152: $uhome = $newhome;
1153: }
1154: }
1155: if ((!$uhome) || ($uhome eq 'no_host')) {
1156: &logthis("User $uname at $udom is unknown in authenticate");
1157: return 'no_host';
1158: }
1159: }
1160: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1161: if ($answer eq 'authorized') {
1162: if ($newhome) {
1163: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1164: return 'no_account_on_host';
1165: } else {
1166: &logthis("User $uname at $udom authorized by $uhome");
1167: return $uhome;
1168: }
1169: }
1170: if ($answer eq 'non_authorized') {
1171: &logthis("User $uname at $udom rejected by $uhome");
1172: return 'no_host';
1173: }
1174: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1175: return 'no_host';
1176: }
1177:
1178: sub can_host_session {
1179: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1180: my $canhost = 1;
1181: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1182: if (ref($remotesessions) eq 'HASH') {
1183: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1184: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1185: $canhost = 0;
1186: } else {
1187: $canhost = 1;
1188: }
1189: }
1190: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1191: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1192: $canhost = 1;
1193: } else {
1194: $canhost = 0;
1195: }
1196: }
1197: if ($canhost) {
1198: if ($remotesessions->{'version'} ne '') {
1199: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1200: if ($reqmajor ne '' && $reqminor ne '') {
1201: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1202: my $major = $1;
1203: my $minor = $2;
1204: if (($major < $reqmajor ) ||
1205: (($major == $reqmajor) && ($minor < $reqminor))) {
1206: $canhost = 0;
1207: }
1208: } else {
1209: $canhost = 0;
1210: }
1211: }
1212: }
1213: }
1214: }
1215: if ($canhost) {
1216: if (ref($hostedsessions) eq 'HASH') {
1217: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1218: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1219: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1220: if (($uint_dom ne '') &&
1221: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1222: $canhost = 0;
1223: } else {
1224: $canhost = 1;
1225: }
1226: }
1227: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1228: if (($uint_dom ne '') &&
1229: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1230: $canhost = 1;
1231: } else {
1232: $canhost = 0;
1233: }
1234: }
1235: }
1236: }
1237: return $canhost;
1238: }
1239:
1240: sub spare_can_host {
1241: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1242: my $canhost=1;
1243: my $try_server_hostname = &hostname($try_server);
1244: my $serverhomeID = &get_server_homeID($try_server_hostname);
1245: my $serverhomedom = &host_domain($serverhomeID);
1246: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1247: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1248: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1249: $canhost = 0;
1250: }
1251: }
1252: if (($canhost) && ($uint_dom)) {
1253: my @intdoms;
1254: my $internet_names = &get_internet_names($try_server);
1255: if (ref($internet_names) eq 'ARRAY') {
1256: @intdoms = @{$internet_names};
1257: }
1258: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1259: my $remoterev = &get_server_loncaparev(undef,$try_server);
1260: $canhost = &can_host_session($udom,$try_server,$remoterev,
1261: $remotesessions,
1262: $defdomdefaults{'hostedsessions'});
1263: }
1264: }
1265: return $canhost;
1266: }
1267:
1268: sub this_host_spares {
1269: my ($dom) = @_;
1270: my ($dom_in_use,$lonhost_in_use,$result);
1271: my @hosts = ¤t_machine_ids();
1272: foreach my $lonhost (@hosts) {
1273: if (&host_domain($lonhost) eq $dom) {
1274: $dom_in_use = $dom;
1275: $lonhost_in_use = $lonhost;
1276: last;
1277: }
1278: }
1279: if ($dom_in_use ne '') {
1280: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1281: }
1282: if (ref($result) ne 'HASH') {
1283: $lonhost_in_use = $perlvar{'lonHostID'};
1284: $dom_in_use = &host_domain($lonhost_in_use);
1285: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1286: if (ref($result) ne 'HASH') {
1287: $result = \%spareid;
1288: }
1289: }
1290: return $result;
1291: }
1292:
1293: sub spares_for_offload {
1294: my ($dom_in_use,$lonhost_in_use) = @_;
1295: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1296: if (defined($cached)) {
1297: return $result;
1298: } else {
1299: my $cachetime = 60*60*24;
1300: my %domconfig =
1301: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1302: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1303: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1304: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1305: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1306: }
1307: }
1308: }
1309: }
1310: return;
1311: }
1312:
1313: sub get_lonbalancer_config {
1314: my ($servers) = @_;
1315: my ($currbalancer,$currtargets);
1316: if (ref($servers) eq 'HASH') {
1317: foreach my $server (keys(%{$servers})) {
1318: my %what = (
1319: spareid => 1,
1320: perlvar => 1,
1321: );
1322: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1323: if ($result eq 'ok') {
1324: if (ref($returnhash) eq 'HASH') {
1325: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1326: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1327: $currbalancer = $server;
1328: $currtargets = {};
1329: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1330: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1331: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1332: }
1333: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1334: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1335: }
1336: }
1337: last;
1338: }
1339: }
1340: }
1341: }
1342: }
1343: }
1344: return ($currbalancer,$currtargets);
1345: }
1346:
1347: sub check_loadbalancing {
1348: my ($uname,$udom,$caller) = @_;
1349: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1350: $rule_in_effect,$offloadto,$otherserver);
1351: my $lonhost = $perlvar{'lonHostID'};
1352: my @hosts = ¤t_machine_ids();
1353: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1354: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1355: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1356: my $serverhomedom = &host_domain($lonhost);
1357: my $domneedscache;
1358: my $cachetime = 60*60*24;
1359:
1360: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1361: $dom_in_use = $udom;
1362: $homeintdom = 1;
1363: } else {
1364: $dom_in_use = $serverhomedom;
1365: }
1366: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1367: unless (defined($cached)) {
1368: my %domconfig =
1369: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1370: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1371: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1372: } else {
1373: $domneedscache = $dom_in_use;
1374: }
1375: }
1376: if (ref($result) eq 'HASH') {
1377: ($is_balancer,$currtargets,$currrules) =
1378: &check_balancer_result($result,@hosts);
1379: if ($is_balancer) {
1380: if (ref($currrules) eq 'HASH') {
1381: if ($homeintdom) {
1382: if ($uname ne '') {
1383: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1384: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1385: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1386: $rule_in_effect = $currrules->{'_LC_author'};
1387: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1388: $rule_in_effect = $currrules->{'_LC_adv'}
1389: }
1390: }
1391: if ($rule_in_effect eq '') {
1392: my %userenv = &userenvironment($udom,$uname,'inststatus');
1393: if ($userenv{'inststatus'} ne '') {
1394: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1395: my ($othertitle,$usertypes,$types) =
1396: &Apache::loncommon::sorted_inst_types($udom);
1397: if (ref($types) eq 'ARRAY') {
1398: foreach my $type (@{$types}) {
1399: if (grep(/^\Q$type\E$/,@statuses)) {
1400: if (exists($currrules->{$type})) {
1401: $rule_in_effect = $currrules->{$type};
1402: }
1403: }
1404: }
1405: }
1406: } else {
1407: if (exists($currrules->{'default'})) {
1408: $rule_in_effect = $currrules->{'default'};
1409: }
1410: }
1411: }
1412: } else {
1413: if (exists($currrules->{'default'})) {
1414: $rule_in_effect = $currrules->{'default'};
1415: }
1416: }
1417: } else {
1418: if ($currrules->{'_LC_external'} ne '') {
1419: $rule_in_effect = $currrules->{'_LC_external'};
1420: }
1421: }
1422: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1423: $uname,$udom);
1424: }
1425: }
1426: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1427: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1428: unless (defined($cached)) {
1429: my %domconfig =
1430: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1431: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1432: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1433: } else {
1434: $domneedscache = $serverhomedom;
1435: }
1436: }
1437: if (ref($result) eq 'HASH') {
1438: ($is_balancer,$currtargets,$currrules) =
1439: &check_balancer_result($result,@hosts);
1440: if ($is_balancer) {
1441: if (ref($currrules) eq 'HASH') {
1442: if ($currrules->{'_LC_internetdom'} ne '') {
1443: $rule_in_effect = $currrules->{'_LC_internetdom'};
1444: }
1445: }
1446: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1447: $uname,$udom);
1448: }
1449: } else {
1450: if ($perlvar{'lonBalancer'} eq 'yes') {
1451: $is_balancer = 1;
1452: $offloadto = &this_host_spares($dom_in_use);
1453: }
1454: unless (defined($cached)) {
1455: $domneedscache = $serverhomedom;
1456: }
1457: }
1458: } else {
1459: if ($perlvar{'lonBalancer'} eq 'yes') {
1460: $is_balancer = 1;
1461: $offloadto = &this_host_spares($dom_in_use);
1462: }
1463: unless (defined($cached)) {
1464: $domneedscache = $serverhomedom;
1465: }
1466: }
1467: if ($domneedscache) {
1468: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1469: }
1470: if ($is_balancer) {
1471: my $lowest_load = 30000;
1472: if (ref($offloadto) eq 'HASH') {
1473: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1474: foreach my $try_server (@{$offloadto->{'primary'}}) {
1475: ($otherserver,$lowest_load) =
1476: &compare_server_load($try_server,$otherserver,$lowest_load);
1477: }
1478: }
1479: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1480:
1481: if (!$found_server) {
1482: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1483: foreach my $try_server (@{$offloadto->{'default'}}) {
1484: ($otherserver,$lowest_load) =
1485: &compare_server_load($try_server,$otherserver,$lowest_load);
1486: }
1487: }
1488: }
1489: } elsif (ref($offloadto) eq 'ARRAY') {
1490: if (@{$offloadto} == 1) {
1491: $otherserver = $offloadto->[0];
1492: } elsif (@{$offloadto} > 1) {
1493: foreach my $try_server (@{$offloadto}) {
1494: ($otherserver,$lowest_load) =
1495: &compare_server_load($try_server,$otherserver,$lowest_load);
1496: }
1497: }
1498: }
1499: unless ($caller eq 'login') {
1500: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1501: $is_balancer = 0;
1502: if ($uname ne '' && $udom ne '') {
1503: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1504:
1505: &appenv({'user.loadbalexempt' => $lonhost,
1506: 'user.loadbalcheck.time' => time});
1507: }
1508: }
1509: }
1510: }
1511: }
1512: return ($is_balancer,$otherserver);
1513: }
1514:
1515: sub check_balancer_result {
1516: my ($result,@hosts) = @_;
1517: my ($is_balancer,$currtargets,$currrules);
1518: if (ref($result) eq 'HASH') {
1519: if ($result->{'lonhost'} ne '') {
1520: my $currbalancer = $result->{'lonhost'};
1521: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1522: $is_balancer = 1;
1523: $currtargets = $result->{'targets'};
1524: $currrules = $result->{'rules'};
1525: }
1526: } else {
1527: foreach my $key (keys(%{$result})) {
1528: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1529: (ref($result->{$key}) eq 'HASH')) {
1530: $is_balancer = 1;
1531: $currrules = $result->{$key}{'rules'};
1532: $currtargets = $result->{$key}{'targets'};
1533: last;
1534: }
1535: }
1536: }
1537: }
1538: return ($is_balancer,$currtargets,$currrules);
1539: }
1540:
1541: sub get_loadbalancer_targets {
1542: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1543: my $offloadto;
1544: if ($rule_in_effect eq 'none') {
1545: return [$perlvar{'lonHostID'}];
1546: } elsif ($rule_in_effect eq '') {
1547: $offloadto = $currtargets;
1548: } else {
1549: if ($rule_in_effect eq 'homeserver') {
1550: my $homeserver = &homeserver($uname,$udom);
1551: if ($homeserver ne 'no_host') {
1552: $offloadto = [$homeserver];
1553: }
1554: } elsif ($rule_in_effect eq 'externalbalancer') {
1555: my %domconfig =
1556: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1557: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1558: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1559: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1560: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1561: }
1562: }
1563: } else {
1564: my %servers = &internet_dom_servers($udom);
1565: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1566: if (&hostname($remotebalancer) ne '') {
1567: $offloadto = [$remotebalancer];
1568: }
1569: }
1570: } elsif (&hostname($rule_in_effect) ne '') {
1571: $offloadto = [$rule_in_effect];
1572: }
1573: }
1574: return $offloadto;
1575: }
1576:
1577: sub internet_dom_servers {
1578: my ($dom) = @_;
1579: my (%uniqservers,%servers);
1580: my $primaryserver = &hostname(&domain($dom,'primary'));
1581: my @machinedoms = &machine_domains($primaryserver);
1582: foreach my $mdom (@machinedoms) {
1583: my %currservers = %servers;
1584: my %server = &get_servers($mdom);
1585: %servers = (%currservers,%server);
1586: }
1587: my %by_hostname;
1588: foreach my $id (keys(%servers)) {
1589: push(@{$by_hostname{$servers{$id}}},$id);
1590: }
1591: foreach my $hostname (sort(keys(%by_hostname))) {
1592: if (@{$by_hostname{$hostname}} > 1) {
1593: my $match = 0;
1594: foreach my $id (@{$by_hostname{$hostname}}) {
1595: if (&host_domain($id) eq $dom) {
1596: $uniqservers{$id} = $hostname;
1597: $match = 1;
1598: }
1599: }
1600: unless ($match) {
1601: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1602: }
1603: } else {
1604: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1605: }
1606: }
1607: return %uniqservers;
1608: }
1609:
1610: sub trusted_domains {
1611: my ($cmdtype,$calldom) = @_;
1612: my ($trusted,$untrusted);
1613: if (&domain($calldom) eq '') {
1614: return ($trusted,$untrusted);
1615: }
1616: unless ($cmdtype =~ /^(content|shared|enroll|coaurem|domroles|catalog|reqcrs|msg)$/) {
1617: return ($trusted,$untrusted);
1618: }
1619: my $callprimary = &domain($calldom,'primary');
1620: my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
1621: if ($intcalldom eq '') {
1622: return ($trusted,$untrusted);
1623: }
1624:
1625: my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
1626: unless (defined($cached)) {
1627: my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
1628: &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
1629: $trustconfig = $domconfig{'trust'};
1630: }
1631: if (ref($trustconfig)) {
1632: my (%possexc,%possinc,@allexc,@allinc);
1633: if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
1634: if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
1635: map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}};
1636: }
1637: if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1638: map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
1639: }
1640: }
1641: if (keys(%possexc)) {
1642: if (keys(%possinc)) {
1643: foreach my $key (sort(keys(%possexc))) {
1644: next if ($key eq $intcalldom);
1645: unless ($possinc{$key}) {
1646: push(@allexc,$key);
1647: }
1648: }
1649: } else {
1650: @allexc = sort(keys(%possexc));
1651: }
1652: }
1653: if (keys(%possinc)) {
1654: $possinc{$intcalldom} = 1;
1655: @allinc = sort(keys(%possinc));
1656: }
1657: if ((@allexc > 0) || (@allinc > 0)) {
1658: my %doms_by_intdom;
1659: my %allintdoms = &all_host_intdom();
1660: my %alldoms = &all_host_domain();
1661: foreach my $key (%allintdoms) {
1662: if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
1663: unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
1664: push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
1665: }
1666: } else {
1667: $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}];
1668: }
1669: }
1670: foreach my $exc (@allexc) {
1671: if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1672: $untrusted = $doms_by_intdom{$exc};
1673: }
1674: }
1675: foreach my $inc (@allinc) {
1676: if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1677: $trusted = $doms_by_intdom{$inc};
1678: }
1679: }
1680: }
1681: }
1682: return ($trusted,$untrusted);
1683: }
1684:
1685: sub will_trust {
1686: my ($cmdtype,$domain,$possdom) = @_;
1687: return 1 if ($domain eq $possdom);
1688: my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
1689: my $willtrust;
1690: if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
1691: if (grep(/^\Q$domain\E$/,@{$trustedref})) {
1692: $willtrust = 1;
1693: }
1694: } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
1695: unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
1696: $willtrust = 1;
1697: }
1698: } else {
1699: $willtrust = 1;
1700: }
1701: return $willtrust;
1702: }
1703:
1704: # ---------------------- Find the homebase for a user from domain's lib servers
1705:
1706: my %homecache;
1707: sub homeserver {
1708: my ($uname,$udom,$ignoreBadCache)=@_;
1709: my $index="$uname:$udom";
1710:
1711: if (exists($homecache{$index})) { return $homecache{$index}; }
1712:
1713: my %servers = &get_servers($udom,'library');
1714: foreach my $tryserver (keys(%servers)) {
1715: next if ($ignoreBadCache ne 'true' &&
1716: exists($badServerCache{$tryserver}));
1717:
1718: my $answer=reply("home:$udom:$uname",$tryserver);
1719: if ($answer eq 'found') {
1720: delete($badServerCache{$tryserver});
1721: return $homecache{$index}=$tryserver;
1722: } elsif ($answer eq 'no_host') {
1723: $badServerCache{$tryserver}=1;
1724: }
1725: }
1726: return 'no_host';
1727: }
1728:
1729: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1730:
1731: sub idget {
1732: my ($udom,$idsref,$namespace)=@_;
1733: my %returnhash=();
1734: my @ids=();
1735: if (ref($idsref) eq 'ARRAY') {
1736: @ids = @{$idsref};
1737: } else {
1738: return %returnhash;
1739: }
1740: if ($namespace eq '') {
1741: $namespace = 'ids';
1742: }
1743:
1744: my %servers = &get_servers($udom,'library');
1745: foreach my $tryserver (keys(%servers)) {
1746: my $idlist=join('&', map { &escape($_); } @ids);
1747: if ($namespace eq 'ids') {
1748: $idlist=~tr/A-Z/a-z/;
1749: }
1750: my $reply;
1751: if ($namespace eq 'ids') {
1752: $reply=&reply("idget:$udom:".$idlist,$tryserver);
1753: } else {
1754: $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
1755: }
1756: my @answer=();
1757: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1758: @answer=split(/\&/,$reply);
1759: } ;
1760: my $i;
1761: for ($i=0;$i<=$#ids;$i++) {
1762: if ($answer[$i]) {
1763: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1764: }
1765: }
1766: }
1767: return %returnhash;
1768: }
1769:
1770: # ------------------------------------- Find the IDs behind a list of usernames
1771:
1772: sub idrget {
1773: my ($udom,@unames)=@_;
1774: my %returnhash=();
1775: foreach my $uname (@unames) {
1776: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1777: }
1778: return %returnhash;
1779: }
1780:
1781: # Store away a list of names and associated student/employee IDs or clicker IDs
1782:
1783: sub idput {
1784: my ($udom,$idsref,$uhom,$namespace)=@_;
1785: my %servers=();
1786: my %ids=();
1787: my %byid = ();
1788: if (ref($idsref) eq 'HASH') {
1789: %ids=%{$idsref};
1790: }
1791: if ($namespace eq '') {
1792: $namespace = 'ids';
1793: }
1794: foreach my $uname (keys(%ids)) {
1795: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1796: if ($uhom eq '') {
1797: $uhom=&homeserver($uname,$udom);
1798: }
1799: if ($uhom ne 'no_host') {
1800: my $esc_unam=&escape($uname);
1801: if ($namespace eq 'ids') {
1802: my $id=&escape($ids{$uname});
1803: $id=~tr/A-Z/a-z/;
1804: my $esc_unam=&escape($uname);
1805: $servers{$uhom}.=$id.'='.$esc_unam.'&';
1806: } else {
1807: my @currids = split(/,/,$ids{$uname});
1808: foreach my $id (@currids) {
1809: $byid{$uhom}{$id} .= $uname.',';
1810: }
1811: }
1812: }
1813: }
1814: if ($namespace eq 'clickers') {
1815: foreach my $server (keys(%byid)) {
1816: if (ref($byid{$server}) eq 'HASH') {
1817: foreach my $id (keys(%{$byid{$server}})) {
1818: $byid{$server} =~ s/,$//;
1819: $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&';
1820: }
1821: }
1822: }
1823: }
1824: foreach my $server (keys(%servers)) {
1825: $servers{$server} =~ s/\&$//;
1826: if ($namespace eq 'ids') {
1827: &critical('idput:'.$udom.':'.$servers{$server},$server);
1828: } else {
1829: &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
1830: }
1831: }
1832: }
1833:
1834: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1835:
1836: sub iddel {
1837: my ($udom,$idshashref,$uhome,$namespace)=@_;
1838: my %result=();
1839: my %ids=();
1840: my %byid = ();
1841: if (ref($idshashref) eq 'HASH') {
1842: %ids=%{$idshashref};
1843: } else {
1844: return %result;
1845: }
1846: if ($namespace eq '') {
1847: $namespace = 'ids';
1848: }
1849: my %servers=();
1850: while (my ($id,$unamestr) = each(%ids)) {
1851: if ($namespace eq 'ids') {
1852: my $uhom = $uhome;
1853: if ($uhom eq '') {
1854: $uhom=&homeserver($unamestr,$udom);
1855: }
1856: if ($uhom ne 'no_host') {
1857: $servers{$uhom}.='&'.&escape($id);
1858: }
1859: } else {
1860: my @curritems = split(/,/,$ids{$id});
1861: foreach my $uname (@curritems) {
1862: my $uhom = $uhome;
1863: if ($uhom eq '') {
1864: $uhom=&homeserver($uname,$udom);
1865: }
1866: if ($uhom ne 'no_host') {
1867: $byid{$uhom}{$id} .= $uname.',';
1868: }
1869: }
1870: }
1871: }
1872: if ($namespace eq 'clickers') {
1873: foreach my $server (keys(%byid)) {
1874: if (ref($byid{$server}) eq 'HASH') {
1875: foreach my $id (keys(%{$byid{$server}})) {
1876: $byid{$server}{$id} =~ s/,$//;
1877: $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
1878: }
1879: }
1880: }
1881: }
1882: foreach my $server (keys(%servers)) {
1883: $servers{$server} =~ s/\&$//;
1884: if ($namespace eq 'ids') {
1885: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1886: } elsif ($namespace eq 'clickers') {
1887: $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
1888: }
1889: }
1890: return %result;
1891: }
1892:
1893: # ----- Update clicker ID-to-username look-ups in clickers.db on library server
1894:
1895: sub updateclickers {
1896: my ($udom,$action,$idshashref,$uhome,$critical) = @_;
1897: my %clickers;
1898: if (ref($idshashref) eq 'HASH') {
1899: %clickers=%{$idshashref};
1900: } else {
1901: return;
1902: }
1903: my $items='';
1904: foreach my $item (keys(%clickers)) {
1905: $items.=&escape($item).'='.&escape($clickers{$item}).'&';
1906: }
1907: $items=~s/\&$//;
1908: my $request = "updateclickers:$udom:$action:$items";
1909: if ($critical) {
1910: return &critical($request,$uhome);
1911: } else {
1912: return &reply($request,$uhome);
1913: }
1914: }
1915:
1916: # ------------------------------dump from db file owned by domainconfig user
1917: sub dump_dom {
1918: my ($namespace, $udom, $regexp) = @_;
1919:
1920: $udom ||= $env{'user.domain'};
1921:
1922: return () unless $udom;
1923:
1924: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1925: }
1926:
1927: # ------------------------------------------ get items from domain db files
1928:
1929: sub get_dom {
1930: my ($namespace,$storearr,$udom,$uhome)=@_;
1931: return if ($udom eq 'public');
1932: my $items='';
1933: foreach my $item (@$storearr) {
1934: $items.=&escape($item).'&';
1935: }
1936: $items=~s/\&$//;
1937: if (!$udom) {
1938: $udom=$env{'user.domain'};
1939: return if ($udom eq 'public');
1940: if (defined(&domain($udom,'primary'))) {
1941: $uhome=&domain($udom,'primary');
1942: } else {
1943: undef($uhome);
1944: }
1945: } else {
1946: if (!$uhome) {
1947: if (defined(&domain($udom,'primary'))) {
1948: $uhome=&domain($udom,'primary');
1949: }
1950: }
1951: }
1952: if ($udom && $uhome && ($uhome ne 'no_host')) {
1953: my $rep;
1954: if ($namespace =~ /^enc/) {
1955: $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
1956: } else {
1957: $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1958: }
1959: my %returnhash;
1960: if ($rep eq '' || $rep =~ /^error: 2 /) {
1961: return %returnhash;
1962: }
1963: my @pairs=split(/\&/,$rep);
1964: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1965: return @pairs;
1966: }
1967: my $i=0;
1968: foreach my $item (@$storearr) {
1969: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1970: $i++;
1971: }
1972: return %returnhash;
1973: } else {
1974: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1975: }
1976: }
1977:
1978: # -------------------------------------------- put items in domain db files
1979:
1980: sub put_dom {
1981: my ($namespace,$storehash,$udom,$uhome)=@_;
1982: if (!$udom) {
1983: $udom=$env{'user.domain'};
1984: if (defined(&domain($udom,'primary'))) {
1985: $uhome=&domain($udom,'primary');
1986: } else {
1987: undef($uhome);
1988: }
1989: } else {
1990: if (!$uhome) {
1991: if (defined(&domain($udom,'primary'))) {
1992: $uhome=&domain($udom,'primary');
1993: }
1994: }
1995: }
1996: if ($udom && $uhome && ($uhome ne 'no_host')) {
1997: my $items='';
1998: foreach my $item (keys(%$storehash)) {
1999: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
2000: }
2001: $items=~s/\&$//;
2002: if ($namespace =~ /^enc/) {
2003: return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
2004: } else {
2005: return &reply("putdom:$udom:$namespace:$items",$uhome);
2006: }
2007: } else {
2008: &logthis("put_dom failed - no homeserver and/or domain");
2009: }
2010: }
2011:
2012: # --------------------- newput for items in db file owned by domainconfig user
2013: sub newput_dom {
2014: my ($namespace,$storehash,$udom) = @_;
2015: my $result;
2016: if (!$udom) {
2017: $udom=$env{'user.domain'};
2018: }
2019: if ($udom) {
2020: my $uname = &get_domainconfiguser($udom);
2021: $result = &newput($namespace,$storehash,$udom,$uname);
2022: }
2023: return $result;
2024: }
2025:
2026: # --------------------- delete for items in db file owned by domainconfig user
2027: sub del_dom {
2028: my ($namespace,$storearr,$udom)=@_;
2029: if (ref($storearr) eq 'ARRAY') {
2030: if (!$udom) {
2031: $udom=$env{'user.domain'};
2032: }
2033: if ($udom) {
2034: my $uname = &get_domainconfiguser($udom);
2035: return &del($namespace,$storearr,$udom,$uname);
2036: }
2037: }
2038: }
2039:
2040: # ----------------------------------construct domainconfig user for a domain
2041: sub get_domainconfiguser {
2042: my ($udom) = @_;
2043: return $udom.'-domainconfig';
2044: }
2045:
2046: sub retrieve_inst_usertypes {
2047: my ($udom) = @_;
2048: my (%returnhash,@order);
2049: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
2050: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
2051: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
2052: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
2053: } else {
2054: if (defined(&domain($udom,'primary'))) {
2055: my $uhome=&domain($udom,'primary');
2056: my $rep=&reply("inst_usertypes:$udom",$uhome);
2057: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
2058: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
2059: return (\%returnhash,\@order);
2060: }
2061: my ($hashitems,$orderitems) = split(/:/,$rep);
2062: my @pairs=split(/\&/,$hashitems);
2063: foreach my $item (@pairs) {
2064: my ($key,$value)=split(/=/,$item,2);
2065: $key = &unescape($key);
2066: next if ($key =~ /^error: 2 /);
2067: $returnhash{$key}=&thaw_unescape($value);
2068: }
2069: my @esc_order = split(/\&/,$orderitems);
2070: foreach my $item (@esc_order) {
2071: push(@order,&unescape($item));
2072: }
2073: } else {
2074: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
2075: }
2076: return (\%returnhash,\@order);
2077: }
2078: }
2079:
2080: sub is_domainimage {
2081: my ($url) = @_;
2082: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
2083: if (&domain($1) ne '') {
2084: return '1';
2085: }
2086: }
2087: return;
2088: }
2089:
2090: sub inst_directory_query {
2091: my ($srch) = @_;
2092: my $udom = $srch->{'srchdomain'};
2093: my %results;
2094: my $homeserver = &domain($udom,'primary');
2095: my $outcome;
2096: if ($homeserver ne '') {
2097: unless ($homeserver eq $perlvar{'lonHostID'}) {
2098: if ($srch->{'srchby'} eq 'email') {
2099: my $lcrev = &get_server_loncaparev(undef,$homeserver);
2100: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2101: if (($major eq '' && $minor eq '') || ($major < 2) ||
2102: (($major == 2) && ($minor < 12))) {
2103: return;
2104: }
2105: }
2106: }
2107: my $queryid=&reply("querysend:instdirsearch:".
2108: &escape($srch->{'srchby'}).':'.
2109: &escape($srch->{'srchterm'}).':'.
2110: &escape($srch->{'srchtype'}),$homeserver);
2111: my $host=&hostname($homeserver);
2112: if ($queryid !~/^\Q$host\E\_/) {
2113: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
2114: return;
2115: }
2116: my $response = &get_query_reply($queryid);
2117: my $maxtries = 5;
2118: my $tries = 1;
2119: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2120: $response = &get_query_reply($queryid);
2121: $tries ++;
2122: }
2123:
2124: if (!&error($response) && $response ne 'refused') {
2125: if ($response eq 'unavailable') {
2126: $outcome = $response;
2127: } else {
2128: $outcome = 'ok';
2129: my @matches = split(/\n/,$response);
2130: foreach my $match (@matches) {
2131: my ($key,$value) = split(/=/,$match);
2132: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2133: }
2134: }
2135: }
2136: }
2137: return ($outcome,%results);
2138: }
2139:
2140: sub usersearch {
2141: my ($srch) = @_;
2142: my $dom = $srch->{'srchdomain'};
2143: my %results;
2144: my %libserv = &all_library();
2145: my $query = 'usersearch';
2146: foreach my $tryserver (keys(%libserv)) {
2147: if (&host_domain($tryserver) eq $dom) {
2148: unless ($tryserver eq $perlvar{'lonHostID'}) {
2149: if ($srch->{'srchby'} eq 'email') {
2150: my $lcrev = &get_server_loncaparev(undef,$tryserver);
2151: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2152: next if (($major eq '' && $minor eq '') || ($major < 2) ||
2153: (($major == 2) && ($minor < 12)));
2154: }
2155: }
2156: my $host=&hostname($tryserver);
2157: my $queryid=
2158: &reply("querysend:".&escape($query).':'.
2159: &escape($srch->{'srchby'}).':'.
2160: &escape($srch->{'srchtype'}).':'.
2161: &escape($srch->{'srchterm'}),$tryserver);
2162: if ($queryid !~/^\Q$host\E\_/) {
2163: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
2164: next;
2165: }
2166: my $reply = &get_query_reply($queryid);
2167: my $maxtries = 1;
2168: my $tries = 1;
2169: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2170: $reply = &get_query_reply($queryid);
2171: $tries ++;
2172: }
2173: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2174: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2175: } else {
2176: my @matches;
2177: if ($reply =~ /\n/) {
2178: @matches = split(/\n/,$reply);
2179: } else {
2180: @matches = split(/\&/,$reply);
2181: }
2182: foreach my $match (@matches) {
2183: my ($uname,$udom,%userhash);
2184: foreach my $entry (split(/:/,$match)) {
2185: my ($key,$value) =
2186: map {&unescape($_);} split(/=/,$entry);
2187: $userhash{$key} = $value;
2188: if ($key eq 'username') {
2189: $uname = $value;
2190: } elsif ($key eq 'domain') {
2191: $udom = $value;
2192: }
2193: }
2194: $results{$uname.':'.$udom} = \%userhash;
2195: }
2196: }
2197: }
2198: }
2199: return %results;
2200: }
2201:
2202: sub get_instuser {
2203: my ($udom,$uname,$id) = @_;
2204: my $homeserver = &domain($udom,'primary');
2205: my ($outcome,%results);
2206: if ($homeserver ne '') {
2207: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2208: &escape($id).':'.&escape($udom),$homeserver);
2209: my $host=&hostname($homeserver);
2210: if ($queryid !~/^\Q$host\E\_/) {
2211: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2212: return;
2213: }
2214: my $response = &get_query_reply($queryid);
2215: my $maxtries = 5;
2216: my $tries = 1;
2217: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2218: $response = &get_query_reply($queryid);
2219: $tries ++;
2220: }
2221: if (!&error($response) && $response ne 'refused') {
2222: if ($response eq 'unavailable') {
2223: $outcome = $response;
2224: } else {
2225: $outcome = 'ok';
2226: my @matches = split(/\n/,$response);
2227: foreach my $match (@matches) {
2228: my ($key,$value) = split(/=/,$match);
2229: $results{&unescape($key)} = &thaw_unescape($value);
2230: }
2231: }
2232: }
2233: }
2234: my %userinfo;
2235: if (ref($results{$uname}) eq 'HASH') {
2236: %userinfo = %{$results{$uname}};
2237: }
2238: return ($outcome,%userinfo);
2239: }
2240:
2241: sub get_multiple_instusers {
2242: my ($udom,$users,$caller) = @_;
2243: my ($outcome,$results);
2244: if (ref($users) eq 'HASH') {
2245: my $count = keys(%{$users});
2246: my $requested = &freeze_escape($users);
2247: my $homeserver = &domain($udom,'primary');
2248: if ($homeserver ne '') {
2249: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2250: my $host=&hostname($homeserver);
2251: if ($queryid !~/^\Q$host\E\_/) {
2252: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2253: ' for host: '.$homeserver.'in domain '.$udom);
2254: return ($outcome,$results);
2255: }
2256: my $response = &get_query_reply($queryid);
2257: my $maxtries = 5;
2258: if ($count > 100) {
2259: $maxtries = 1+int($count/20);
2260: }
2261: my $tries = 1;
2262: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2263: $response = &get_query_reply($queryid);
2264: $tries ++;
2265: }
2266: if ($response eq '') {
2267: $results = {};
2268: foreach my $key (keys(%{$users})) {
2269: my ($uname,$id);
2270: if ($caller eq 'id') {
2271: $id = $key;
2272: } else {
2273: $uname = $key;
2274: }
2275: my ($resp,%info) = &get_instuser($udom,$uname,$id);
2276: $outcome = $resp;
2277: if ($resp eq 'ok') {
2278: %{$results} = (%{$results}, %info);
2279: } else {
2280: last;
2281: }
2282: }
2283: } elsif(!&error($response) && ($response ne 'refused')) {
2284: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2285: $outcome = $response;
2286: } else {
2287: ($outcome,my $userdata) = split(/=/,$response,2);
2288: if ($outcome eq 'ok') {
2289: $results = &thaw_unescape($userdata);
2290: }
2291: }
2292: }
2293: }
2294: }
2295: return ($outcome,$results);
2296: }
2297:
2298: sub inst_rulecheck {
2299: my ($udom,$uname,$id,$item,$rules) = @_;
2300: my %returnhash;
2301: if ($udom ne '') {
2302: if (ref($rules) eq 'ARRAY') {
2303: @{$rules} = map {&escape($_);} (@{$rules});
2304: my $rulestr = join(':',@{$rules});
2305: my $homeserver=&domain($udom,'primary');
2306: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
2307: my $response;
2308: if ($item eq 'username') {
2309: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2310: ':'.&escape($uname).':'.$rulestr,
2311: $homeserver));
2312: } elsif ($item eq 'id') {
2313: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2314: ':'.&escape($id).':'.$rulestr,
2315: $homeserver));
2316: } elsif ($item eq 'selfcreate') {
2317: $response=&unescape(&reply('instselfcreatecheck:'.
2318: &escape($udom).':'.&escape($uname).
2319: ':'.$rulestr,$homeserver));
2320: }
2321: if ($response ne 'refused') {
2322: my @pairs=split(/\&/,$response);
2323: foreach my $item (@pairs) {
2324: my ($key,$value)=split(/=/,$item,2);
2325: $key = &unescape($key);
2326: next if ($key =~ /^error: 2 /);
2327: $returnhash{$key}=&thaw_unescape($value);
2328: }
2329: }
2330: }
2331: }
2332: }
2333: return %returnhash;
2334: }
2335:
2336: sub inst_userrules {
2337: my ($udom,$check) = @_;
2338: my (%ruleshash,@ruleorder);
2339: if ($udom ne '') {
2340: my $homeserver=&domain($udom,'primary');
2341: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
2342: my $response;
2343: if ($check eq 'id') {
2344: $response=&reply('instidrules:'.&escape($udom),
2345: $homeserver);
2346: } elsif ($check eq 'email') {
2347: $response=&reply('instemailrules:'.&escape($udom),
2348: $homeserver);
2349: } else {
2350: $response=&reply('instuserrules:'.&escape($udom),
2351: $homeserver);
2352: }
2353: if (($response ne 'refused') && ($response ne 'error') &&
2354: ($response ne 'unknown_cmd') &&
2355: ($response ne 'no_such_host')) {
2356: my ($hashitems,$orderitems) = split(/:/,$response);
2357: my @pairs=split(/\&/,$hashitems);
2358: foreach my $item (@pairs) {
2359: my ($key,$value)=split(/=/,$item,2);
2360: $key = &unescape($key);
2361: next if ($key =~ /^error: 2 /);
2362: $ruleshash{$key}=&thaw_unescape($value);
2363: }
2364: my @esc_order = split(/\&/,$orderitems);
2365: foreach my $item (@esc_order) {
2366: push(@ruleorder,&unescape($item));
2367: }
2368: }
2369: }
2370: }
2371: return (\%ruleshash,\@ruleorder);
2372: }
2373:
2374: # ------------- Get Authentication, Language and User Tools Defaults for Domain
2375:
2376: sub get_domain_defaults {
2377: my ($domain,$ignore_cache) = @_;
2378: return if (($domain eq '') || ($domain eq 'public'));
2379: my $cachetime = 60*60*24;
2380: unless ($ignore_cache) {
2381: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2382: if (defined($cached)) {
2383: if (ref($result) eq 'HASH') {
2384: return %{$result};
2385: }
2386: }
2387: }
2388: my %domdefaults;
2389: my %domconfig =
2390: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
2391: 'requestcourses','inststatus',
2392: 'coursedefaults','usersessions',
2393: 'requestauthor','selfenrollment',
2394: 'coursecategories','ssl','autoenroll',
2395: 'trust','helpsettings'],$domain);
2396: my @coursetypes = ('official','unofficial','community','textbook','placement');
2397: if (ref($domconfig{'defaults'}) eq 'HASH') {
2398: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2399: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2400: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
2401: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
2402: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
2403: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
2404: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2405: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2406: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
2407: } else {
2408: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2409: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2410: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2411: }
2412: if (ref($domconfig{'quotas'}) eq 'HASH') {
2413: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2414: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2415: } else {
2416: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
2417: }
2418: my @usertools = ('aboutme','blog','webdav','portfolio');
2419: foreach my $item (@usertools) {
2420: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2421: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2422: }
2423: }
2424: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2425: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2426: }
2427: }
2428: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
2429: foreach my $item ('official','unofficial','community','textbook','placement') {
2430: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2431: }
2432: }
2433: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2434: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2435: }
2436: if (ref($domconfig{'inststatus'}) eq 'HASH') {
2437: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
2438: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2439: }
2440: }
2441: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
2442: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
2443: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2444: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2445: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2446: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2447: }
2448: foreach my $type (@coursetypes) {
2449: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2450: unless ($type eq 'community') {
2451: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2452: }
2453: }
2454: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2455: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2456: }
2457: if ($domdefaults{'postsubmit'} eq 'on') {
2458: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2459: $domdefaults{$type.'postsubtimeout'} =
2460: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2461: }
2462: }
2463: }
2464: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2465: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2466: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2467: if (@clonecodes) {
2468: $domdefaults{'canclone'} = join('+',@clonecodes);
2469: }
2470: }
2471: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2472: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2473: }
2474: if ($domconfig{'coursedefaults'}{'texengine'}) {
2475: $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
2476: }
2477: }
2478: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2479: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2480: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2481: }
2482: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2483: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2484: }
2485: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2486: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2487: }
2488: }
2489: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2490: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2491: my @settings = ('types','registered','enroll_dates','access_dates','section',
2492: 'approval','limit');
2493: foreach my $type (@coursetypes) {
2494: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2495: my @mgrdc = ();
2496: foreach my $item (@settings) {
2497: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2498: push(@mgrdc,$item);
2499: }
2500: }
2501: if (@mgrdc) {
2502: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2503: }
2504: }
2505: }
2506: }
2507: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2508: foreach my $type (@coursetypes) {
2509: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2510: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2511: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2512: }
2513: }
2514: }
2515: }
2516: }
2517: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2518: $domdefaults{'catauth'} = 'std';
2519: $domdefaults{'catunauth'} = 'std';
2520: if ($domconfig{'coursecategories'}{'auth'}) {
2521: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2522: }
2523: if ($domconfig{'coursecategories'}{'unauth'}) {
2524: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2525: }
2526: }
2527: if (ref($domconfig{'ssl'}) eq 'HASH') {
2528: if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
2529: $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
2530: }
2531: if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
2532: $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
2533: }
2534: if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
2535: $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
2536: }
2537: }
2538: if (ref($domconfig{'trust'}) eq 'HASH') {
2539: my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
2540: foreach my $prefix (@prefixes) {
2541: if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
2542: $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
2543: }
2544: }
2545: }
2546: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2547: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2548: }
2549: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2550: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2551: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2552: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2553: }
2554: }
2555: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
2556: return %domdefaults;
2557: }
2558:
2559: sub course_portal_url {
2560: my ($cnum,$cdom) = @_;
2561: my $chome = &homeserver($cnum,$cdom);
2562: my $hostname = &hostname($chome);
2563: my $protocol = $protocol{$chome};
2564: $protocol = 'http' if ($protocol ne 'https');
2565: my %domdefaults = &get_domain_defaults($cdom);
2566: my $firsturl;
2567: if ($domdefaults{'portal_def'}) {
2568: $firsturl = $domdefaults{'portal_def'};
2569: } else {
2570: $firsturl = $protocol.'://'.$hostname;
2571: }
2572: return $firsturl;
2573: }
2574:
2575: # --------------------------------------------------- Assign a key to a student
2576:
2577: sub assign_access_key {
2578: #
2579: # a valid key looks like uname:udom#comments
2580: # comments are being appended
2581: #
2582: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2583: $kdom=
2584: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
2585: $knum=
2586: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
2587: $cdom=
2588: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2589: $cnum=
2590: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2591: $udom=$env{'user.name'} unless (defined($udom));
2592: $uname=$env{'user.domain'} unless (defined($uname));
2593: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
2594: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
2595: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
2596: # assigned to this person
2597: # - this should not happen,
2598: # unless something went wrong
2599: # the first time around
2600: # ready to assign
2601: $logentry=$1.'; '.$logentry;
2602: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
2603: $kdom,$knum) eq 'ok') {
2604: # key now belongs to user
2605: my $envkey='key.'.$cdom.'_'.$cnum;
2606: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
2607: &appenv({'environment.'.$envkey => $ckey});
2608: return 'ok';
2609: } else {
2610: return
2611: 'error: Count not permanently assign key, will need to be re-entered later.';
2612: }
2613: } else {
2614: return 'error: Could not assign key, try again later.';
2615: }
2616: } elsif (!$existing{$ckey}) {
2617: # the key does not exist
2618: return 'error: The key does not exist';
2619: } else {
2620: # the key is somebody else's
2621: return 'error: The key is already in use';
2622: }
2623: }
2624:
2625: # ------------------------------------------ put an additional comment on a key
2626:
2627: sub comment_access_key {
2628: #
2629: # a valid key looks like uname:udom#comments
2630: # comments are being appended
2631: #
2632: my ($ckey,$cdom,$cnum,$logentry)=@_;
2633: $cdom=
2634: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2635: $cnum=
2636: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2637: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2638: if ($existing{$ckey}) {
2639: $existing{$ckey}.='; '.$logentry;
2640: # ready to assign
2641: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
2642: $cdom,$cnum) eq 'ok') {
2643: return 'ok';
2644: } else {
2645: return 'error: Count not store comment.';
2646: }
2647: } else {
2648: # the key does not exist
2649: return 'error: The key does not exist';
2650: }
2651: }
2652:
2653: # ------------------------------------------------------ Generate a set of keys
2654:
2655: sub generate_access_keys {
2656: my ($number,$cdom,$cnum,$logentry)=@_;
2657: $cdom=
2658: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2659: $cnum=
2660: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2661: unless (&allowed('mky',$cdom)) { return 0; }
2662: unless (($cdom) && ($cnum)) { return 0; }
2663: if ($number>10000) { return 0; }
2664: sleep(2); # make sure don't get same seed twice
2665: srand(time()^($$+($$<<15))); # from "Programming Perl"
2666: my $total=0;
2667: for (my $i=1;$i<=$number;$i++) {
2668: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2669: sprintf("%lx",int(100000*rand)).'-'.
2670: sprintf("%lx",int(100000*rand));
2671: $newkey=~s/1/g/g; # folks mix up 1 and l
2672: $newkey=~s/0/h/g; # and also 0 and O
2673: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2674: if ($existing{$newkey}) {
2675: $i--;
2676: } else {
2677: if (&put('accesskeys',
2678: { $newkey => '# generated '.localtime().
2679: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
2680: '; '.$logentry },
2681: $cdom,$cnum) eq 'ok') {
2682: $total++;
2683: }
2684: }
2685: }
2686: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
2687: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2688: return $total;
2689: }
2690:
2691: # ------------------------------------------------------- Validate an accesskey
2692:
2693: sub validate_access_key {
2694: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2695: $cdom=
2696: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2697: $cnum=
2698: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2699: $udom=$env{'user.domain'} unless (defined($udom));
2700: $uname=$env{'user.name'} unless (defined($uname));
2701: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2702: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
2703: }
2704:
2705: # ------------------------------------- Find the section of student in a course
2706: sub devalidate_getsection_cache {
2707: my ($udom,$unam,$courseid)=@_;
2708: my $hashid="$udom:$unam:$courseid";
2709: &devalidate_cache_new('getsection',$hashid);
2710: }
2711:
2712: sub courseid_to_courseurl {
2713: my ($courseid) = @_;
2714: #already url style courseid
2715: return $courseid if ($courseid =~ m{^/});
2716:
2717: if (exists($env{'course.'.$courseid.'.num'})) {
2718: my $cnum = $env{'course.'.$courseid.'.num'};
2719: my $cdom = $env{'course.'.$courseid.'.domain'};
2720: return "/$cdom/$cnum";
2721: }
2722:
2723: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2724: if (exists($courseinfo{'num'})) {
2725: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2726: }
2727:
2728: return undef;
2729: }
2730:
2731: sub getsection {
2732: my ($udom,$unam,$courseid)=@_;
2733: my $cachetime=1800;
2734:
2735: my $hashid="$udom:$unam:$courseid";
2736: my ($result,$cached)=&is_cached_new('getsection',$hashid);
2737: if (defined($cached)) { return $result; }
2738:
2739: my %Pending;
2740: my %Expired;
2741: #
2742: # Each role can either have not started yet (pending), be active,
2743: # or have expired.
2744: #
2745: # If there is an active role, we are done.
2746: #
2747: # If there is more than one role which has not started yet,
2748: # choose the one which will start sooner
2749: # If there is one role which has not started yet, return it.
2750: #
2751: # If there is more than one expired role, choose the one which ended last.
2752: # If there is a role which has expired, return it.
2753: #
2754: $courseid = &courseid_to_courseurl($courseid);
2755: my %roleshash = &dump('roles',$udom,$unam,$courseid);
2756: foreach my $key (keys(%roleshash)) {
2757: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
2758: my $section=$1;
2759: if ($key eq $courseid.'_st') { $section=''; }
2760: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
2761: my $now=time;
2762: if (defined($end) && $end && ($now > $end)) {
2763: $Expired{$end}=$section;
2764: next;
2765: }
2766: if (defined($start) && $start && ($now < $start)) {
2767: $Pending{$start}=$section;
2768: next;
2769: }
2770: return &do_cache_new('getsection',$hashid,$section,$cachetime);
2771: }
2772: #
2773: # Presumedly there will be few matching roles from the above
2774: # loop and the sorting time will be negligible.
2775: if (scalar(keys(%Pending))) {
2776: my ($time) = sort {$a <=> $b} keys(%Pending);
2777: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
2778: }
2779: if (scalar(keys(%Expired))) {
2780: my @sorted = sort {$a <=> $b} keys(%Expired);
2781: my $time = pop(@sorted);
2782: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
2783: }
2784: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
2785: }
2786:
2787: sub save_cache {
2788: &purge_remembered();
2789: #&Apache::loncommon::validate_page();
2790: undef(%env);
2791: undef($env_loaded);
2792: }
2793:
2794: my $to_remember=-1;
2795: my %remembered;
2796: my %accessed;
2797: my $kicks=0;
2798: my $hits=0;
2799: sub make_key {
2800: my ($name,$id) = @_;
2801: if (length($id) > 65
2802: && length(&escape($id)) > 200) {
2803: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2804: }
2805: return &escape($name.':'.$id);
2806: }
2807:
2808: sub devalidate_cache_new {
2809: my ($name,$id,$debug) = @_;
2810: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
2811: my $remembered_id=$name.':'.$id;
2812: $id=&make_key($name,$id);
2813: $memcache->delete($id);
2814: delete($remembered{$remembered_id});
2815: delete($accessed{$remembered_id});
2816: }
2817:
2818: sub is_cached_new {
2819: my ($name,$id,$debug) = @_;
2820: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
2821: if (exists($remembered{$remembered_id})) {
2822: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2823: $accessed{$remembered_id}=[&gettimeofday()];
2824: $hits++;
2825: return ($remembered{$remembered_id},1);
2826: }
2827: $id=&make_key($name,$id);
2828: my $value = $memcache->get($id);
2829: if (!(defined($value))) {
2830: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
2831: return (undef,undef);
2832: }
2833: if ($value eq '__undef__') {
2834: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2835: $value=undef;
2836: }
2837: &make_room($remembered_id,$value,$debug);
2838: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2839: return ($value,1);
2840: }
2841:
2842: sub do_cache_new {
2843: my ($name,$id,$value,$time,$debug) = @_;
2844: my $remembered_id=$name.':'.$id;
2845: $id=&make_key($name,$id);
2846: my $setvalue=$value;
2847: if (!defined($setvalue)) {
2848: $setvalue='__undef__';
2849: }
2850: if (!defined($time) ) {
2851: $time=600;
2852: }
2853: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
2854: my $result = $memcache->set($id,$setvalue,$time);
2855: if (! $result) {
2856: &logthis("caching of id -> $id failed");
2857: $memcache->disconnect_all();
2858: }
2859: # need to make a copy of $value
2860: &make_room($remembered_id,$value,$debug);
2861: return $value;
2862: }
2863:
2864: sub make_room {
2865: my ($remembered_id,$value,$debug)=@_;
2866:
2867: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
2868: : $value;
2869: if ($to_remember<0) { return; }
2870: $accessed{$remembered_id}=[&gettimeofday()];
2871: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2872: my $to_kick;
2873: my $max_time=0;
2874: foreach my $other (keys(%accessed)) {
2875: if (&tv_interval($accessed{$other}) > $max_time) {
2876: $to_kick=$other;
2877: $max_time=&tv_interval($accessed{$other});
2878: }
2879: }
2880: delete($remembered{$to_kick});
2881: delete($accessed{$to_kick});
2882: $kicks++;
2883: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
2884: return;
2885: }
2886:
2887: sub purge_remembered {
2888: #&logthis("Tossing ".scalar(keys(%remembered)));
2889: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
2890: undef(%remembered);
2891: undef(%accessed);
2892: }
2893: # ------------------------------------- Read an entry from a user's environment
2894:
2895: sub userenvironment {
2896: my ($udom,$unam,@what)=@_;
2897: my $items;
2898: foreach my $item (@what) {
2899: $items.=&escape($item).'&';
2900: }
2901: $items=~s/\&$//;
2902: my %returnhash=();
2903: my $uhome = &homeserver($unam,$udom);
2904: unless ($uhome eq 'no_host') {
2905: my @answer=split(/\&/,
2906: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
2907: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2908: return %returnhash;
2909: }
2910: my $i;
2911: for ($i=0;$i<=$#what;$i++) {
2912: $returnhash{$what[$i]}=&unescape($answer[$i]);
2913: }
2914: }
2915: return %returnhash;
2916: }
2917:
2918: # ---------------------------------------------------------- Get a studentphoto
2919: sub studentphoto {
2920: my ($udom,$unam,$ext) = @_;
2921: my $home=&Apache::lonnet::homeserver($unam,$udom);
2922: if (defined($env{'request.course.id'})) {
2923: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
2924: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2925: return(&retrievestudentphoto($udom,$unam,$ext));
2926: } else {
2927: my ($result,$perm_reqd)=
2928: &Apache::lonnet::auto_photo_permission($unam,$udom);
2929: if ($result eq 'ok') {
2930: if (!($perm_reqd eq 'yes')) {
2931: return(&retrievestudentphoto($udom,$unam,$ext));
2932: }
2933: }
2934: }
2935: }
2936: } else {
2937: my ($result,$perm_reqd) =
2938: &Apache::lonnet::auto_photo_permission($unam,$udom);
2939: if ($result eq 'ok') {
2940: if (!($perm_reqd eq 'yes')) {
2941: return(&retrievestudentphoto($udom,$unam,$ext));
2942: }
2943: }
2944: }
2945: return '/adm/lonKaputt/lonlogo_broken.gif';
2946: }
2947:
2948: sub retrievestudentphoto {
2949: my ($udom,$unam,$ext,$type) = @_;
2950: my $home=&Apache::lonnet::homeserver($unam,$udom);
2951: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2952: if ($ret eq 'ok') {
2953: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2954: if ($type eq 'thumbnail') {
2955: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2956: }
2957: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2958: return $tokenurl;
2959: } else {
2960: if ($type eq 'thumbnail') {
2961: return '/adm/lonKaputt/genericstudent_tn.gif';
2962: } else {
2963: return '/adm/lonKaputt/lonlogo_broken.gif';
2964: }
2965: }
2966: }
2967:
2968: # -------------------------------------------------------------------- New chat
2969:
2970: sub chatsend {
2971: my ($newentry,$anon,$group)=@_;
2972: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2973: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2974: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
2975: &reply('chatsend:'.$cdom.':'.$cnum.':'.
2976: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
2977: &escape($newentry)).':'.$group,$chome);
2978: }
2979:
2980: # ------------------------------------------ Find current version of a resource
2981:
2982: sub getversion {
2983: my $fname=&clutter(shift);
2984: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
2985: return ¤tversion(&filelocation('',$fname));
2986: }
2987:
2988: sub currentversion {
2989: my $fname=shift;
2990: my $author=$fname;
2991: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2992: my ($udom,$uname)=split(/\//,$author);
2993: my $home=&homeserver($uname,$udom);
2994: if ($home eq 'no_host') {
2995: return -1;
2996: }
2997: my $answer=&reply("currentversion:$fname",$home);
2998: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2999: return -1;
3000: }
3001: return $answer;
3002: }
3003:
3004: #
3005: # Return special version number of resource if set by override, empty otherwise
3006: #
3007: sub usedversion {
3008: my $fname=shift;
3009: unless ($fname) { $fname=$env{'request.uri'}; }
3010: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
3011: if ($urlversion) { return $urlversion; }
3012: return '';
3013: }
3014:
3015: # ----------------------------- Subscribe to a resource, return URL if possible
3016:
3017: sub subscribe {
3018: my $fname=shift;
3019: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
3020: $fname=~s/[\n\r]//g;
3021: my $author=$fname;
3022: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3023: my ($udom,$uname)=split(/\//,$author);
3024: my $home=homeserver($uname,$udom);
3025: if ($home eq 'no_host') {
3026: return 'not_found';
3027: }
3028: my $answer=reply("sub:$fname",$home);
3029: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3030: $answer.=' by '.$home;
3031: }
3032: return $answer;
3033: }
3034:
3035: # -------------------------------------------------------------- Replicate file
3036:
3037: sub repcopy {
3038: my $filename=shift;
3039: $filename=~s/\/+/\//g;
3040: my $londocroot = $perlvar{'lonDocRoot'};
3041: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
3042: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
3043: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3044: $filename=~m{^/*(uploaded|editupload)/}) {
3045: return &repcopy_userfile($filename);
3046: }
3047: $filename=~s/[\n\r]//g;
3048: my $transname="$filename.in.transfer";
3049: # FIXME: this should flock
3050: if ((-e $filename) || (-e $transname)) { return 'ok'; }
3051: my $remoteurl=subscribe($filename);
3052: if ($remoteurl =~ /^con_lost by/) {
3053: &logthis("Subscribe returned $remoteurl: $filename");
3054: return 'unavailable';
3055: } elsif ($remoteurl eq 'not_found') {
3056: #&logthis("Subscribe returned not_found: $filename");
3057: return 'not_found';
3058: } elsif ($remoteurl =~ /^rejected by/) {
3059: &logthis("Subscribe returned $remoteurl: $filename");
3060: return 'forbidden';
3061: } elsif ($remoteurl eq 'directory') {
3062: return 'ok';
3063: } else {
3064: my $author=$filename;
3065: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3066: my ($udom,$uname)=split(/\//,$author);
3067: my $home=homeserver($uname,$udom);
3068: unless ($home eq $perlvar{'lonHostID'}) {
3069: my @parts=split(/\//,$filename);
3070: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
3071: if ($path ne "$londocroot/res") {
3072: &logthis("Malconfiguration for replication: $filename");
3073: return 'bad_request';
3074: }
3075: my $count;
3076: for ($count=5;$count<$#parts;$count++) {
3077: $path.="/$parts[$count]";
3078: if ((-e $path)!=1) {
3079: mkdir($path,0777);
3080: }
3081: }
3082: my $request=new HTTP::Request('GET',"$remoteurl");
3083: my $response;
3084: if ($remoteurl =~ m{/raw/}) {
3085: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
3086: } else {
3087: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
3088: }
3089: if ($response->is_error()) {
3090: unlink($transname);
3091: my $message=$response->status_line;
3092: &logthis("<font color=\"blue\">WARNING:"
3093: ." LWP get: $message: $filename</font>");
3094: return 'unavailable';
3095: } else {
3096: if ($remoteurl!~/\.meta$/) {
3097: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
3098: my $mresponse;
3099: if ($remoteurl =~ m{/raw/}) {
3100: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
3101: } else {
3102: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
3103: }
3104: if ($mresponse->is_error()) {
3105: unlink($filename.'.meta');
3106: &logthis(
3107: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
3108: }
3109: }
3110: rename($transname,$filename);
3111: return 'ok';
3112: }
3113: }
3114: }
3115: }
3116:
3117: # ------------------------------------------------ Get server side include body
3118: sub ssi_body {
3119: my ($filelink,%form)=@_;
3120: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3121: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3122: }
3123: my $output='';
3124: my $response;
3125: if ($filelink=~/^https?\:/) {
3126: ($output,$response)=&externalssi($filelink);
3127: } else {
3128: $filelink .= $filelink=~/\?/ ? '&' : '?';
3129: $filelink .= 'inhibitmenu=yes';
3130: ($output,$response)=&ssi($filelink,%form);
3131: }
3132: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
3133: $output=~s/^.*?\<body[^\>]*\>//si;
3134: $output=~s/\<\/body\s*\>.*?$//si;
3135: if (wantarray) {
3136: return ($output, $response);
3137: } else {
3138: return $output;
3139: }
3140: }
3141:
3142: # --------------------------------------------------------- Server Side Include
3143:
3144: sub absolute_url {
3145: my ($host_name) = @_;
3146: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3147: if ($host_name eq '') {
3148: $host_name = $ENV{'SERVER_NAME'};
3149: }
3150: return $protocol.$host_name;
3151: }
3152:
3153: #
3154: # Server side include.
3155: # Parameters:
3156: # fn Possibly encrypted resource name/id.
3157: # form Hash that describes how the rendering should be done
3158: # and other things.
3159: # Returns:
3160: # Scalar context: The content of the response.
3161: # Array context: 2 element list of the content and the full response object.
3162: #
3163: sub ssi {
3164:
3165: my ($fn,%form)=@_;
3166: my $request;
3167:
3168: $form{'no_update_last_known'}=1;
3169: &Apache::lonenc::check_encrypt(\$fn);
3170: if (%form) {
3171: $request=new HTTP::Request('POST',&absolute_url().$fn);
3172: $request->content(join('&',map {
3173: my $name = escape($_);
3174: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3175: ? join("&$name=", map {escape($_) } @{$form{$_}})
3176: : &escape($form{$_}) );
3177: } keys(%form)));
3178: } else {
3179: $request=new HTTP::Request('GET',&absolute_url().$fn);
3180: }
3181:
3182: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
3183: my $lonhost = $perlvar{'lonHostID'};
3184: my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar);
3185:
3186: if (wantarray) {
3187: return ($response->content, $response);
3188: } else {
3189: return $response->content;
3190: }
3191: }
3192:
3193: sub externalssi {
3194: my ($url)=@_;
3195: my $request=new HTTP::Request('GET',$url);
3196: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
3197: if (wantarray) {
3198: return ($response->content, $response);
3199: } else {
3200: return $response->content;
3201: }
3202: }
3203:
3204:
3205: # If the local copy of a replicated resource is outdated, trigger a
3206: # connection from the homeserver to flush the delayed queue. If no update
3207: # happens, remove local copies of outdated resource (and corresponding
3208: # metadata file).
3209:
3210: sub remove_stale_resfile {
3211: my ($url) = @_;
3212: my $removed;
3213: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3214: my $audom = $1;
3215: my $auname = $2;
3216: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
3217: my $homeserver = &homeserver($auname,$audom);
3218: unless (($homeserver eq 'no_host') ||
3219: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3220: my $fname = &filelocation('',$url);
3221: if (-e $fname) {
3222: my $protocol = $protocol{$homeserver};
3223: $protocol = 'http' if ($protocol ne 'https');
3224: my $hostname = &hostname($homeserver);
3225: if ($hostname) {
3226: my $uri = &declutter($url);
3227: my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
3228: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
3229: if ($response->is_success()) {
3230: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3231: my $locmodtime = (stat($fname))[9];
3232: if ($locmodtime < $remmodtime) {
3233: my $stale;
3234: my $answer = &reply('pong',$homeserver);
3235: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3236: sleep(0.2);
3237: $locmodtime = (stat($fname))[9];
3238: if ($locmodtime < $remmodtime) {
3239: my $posstransfer = $fname.'.in.transfer';
3240: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3241: $removed = 1;
3242: } else {
3243: $stale = 1;
3244: }
3245: } else {
3246: $removed = 1;
3247: }
3248: } else {
3249: $stale = 1;
3250: }
3251: if ($stale) {
3252: unlink($fname);
3253: if ($uri!~/\.meta$/) {
3254: unlink($fname.'.meta');
3255: }
3256: &reply("unsub:$fname",$homeserver);
3257: $removed = 1;
3258: }
3259: }
3260: }
3261: }
3262: }
3263: }
3264: }
3265: }
3266: return $removed;
3267: }
3268:
3269: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3270:
3271: sub allowuploaded {
3272: my ($srcurl,$url)=@_;
3273: $url=&clutter(&declutter($url));
3274: my $dir=$url;
3275: $dir=~s/\/[^\/]+$//;
3276: my %httpref=();
3277: my $httpurl=&hreflocation('',$url);
3278: $httpref{'httpref.'.$httpurl}=$srcurl;
3279: &Apache::lonnet::appenv(\%httpref);
3280: }
3281:
3282: #
3283: # Determine if the current user should be able to edit a particular resource,
3284: # when viewing in course context.
3285: # (a) When viewing resource used to determine if "Edit" item is included in
3286: # Functions.
3287: # (b) When displaying folder contents in course editor, used to determine if
3288: # "Edit" link will be displayed alongside resource.
3289: #
3290: # input: six args -- filename (decluttered), course number, course domain,
3291: # url, symb (if registered) and group (if this is a group
3292: # item -- e.g., bulletin board, group page etc.).
3293: # output: array of five scalars --
3294: # $cfile -- url for file editing if editable on current server
3295: # $home -- homeserver of resource (i.e., for author if published,
3296: # or course if uploaded.).
3297: # $switchserver -- 1 if server switch will be needed.
3298: # $forceedit -- 1 if icon/link should be to go to edit mode
3299: # $forceview -- 1 if icon/link should be to go to view mode
3300: #
3301:
3302: sub can_edit_resource {
3303: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3304: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3305: #
3306: # For aboutme pages user can only edit his/her own.
3307: #
3308: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
3309: my ($sdom,$sname) = ($1,$2);
3310: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3311: $home = $env{'user.home'};
3312: $cfile = $resurl;
3313: if ($env{'form.forceedit'}) {
3314: $forceview = 1;
3315: } else {
3316: $forceedit = 1;
3317: }
3318: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3319: } else {
3320: return;
3321: }
3322: }
3323:
3324: if ($env{'request.course.id'}) {
3325: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3326: if ($group ne '') {
3327: # if this is a group homepage or group bulletin board, check group privs
3328: my $allowed = 0;
3329: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3330: if ((&allowed('mdg',$env{'request.course.id'}.
3331: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3332: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3333: $allowed = 1;
3334: }
3335: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3336: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3337: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3338: $allowed = 1;
3339: }
3340: }
3341: if ($allowed) {
3342: $home=&homeserver($cnum,$cdom);
3343: if ($env{'form.forceedit'}) {
3344: $forceview = 1;
3345: } else {
3346: $forceedit = 1;
3347: }
3348: $cfile = $resurl;
3349: } else {
3350: return;
3351: }
3352: } else {
3353: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3354: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3355: return;
3356: }
3357: } elsif (!$crsedit) {
3358: #
3359: # No edit allowed where CC has switched to student role.
3360: #
3361: return;
3362: }
3363: }
3364: }
3365:
3366: if ($file ne '') {
3367: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
3368: if (&is_course_upload($file,$cnum,$cdom)) {
3369: $uploaded = 1;
3370: $incourse = 1;
3371: if ($file =~/\.(htm|html|css|js|txt)$/) {
3372: $cfile = &hreflocation('',$file);
3373: if ($env{'form.forceedit'}) {
3374: $forceview = 1;
3375: } else {
3376: $forceedit = 1;
3377: }
3378: }
3379: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3380: $incourse = 1;
3381: if ($env{'form.forceedit'}) {
3382: $forceview = 1;
3383: } else {
3384: $forceedit = 1;
3385: }
3386: $cfile = $resurl;
3387: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3388: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3389: $incourse = 1;
3390: if ($env{'form.forceedit'}) {
3391: $forceview = 1;
3392: } else {
3393: $forceedit = 1;
3394: }
3395: $cfile = $resurl;
3396: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
3397: $incourse = 1;
3398: $cfile = $resurl.'/smpedit';
3399: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
3400: $incourse = 1;
3401: if ($env{'form.forceedit'}) {
3402: $forceview = 1;
3403: } else {
3404: $forceedit = 1;
3405: }
3406: $cfile = $resurl;
3407: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
3408: $incourse = 1;
3409: if ($env{'form.forceedit'}) {
3410: $forceview = 1;
3411: } else {
3412: $forceedit = 1;
3413: }
3414: $cfile = $resurl;
3415: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3416: $incourse = 1;
3417: if ($env{'form.forceedit'}) {
3418: $forceview = 1;
3419: } else {
3420: $forceedit = 1;
3421: }
3422: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
3423: }
3424: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3425: my $template = '/res/lib/templates/simpleproblem.problem';
3426: if (&is_on_map($template)) {
3427: $incourse = 1;
3428: $forceview = 1;
3429: $cfile = $template;
3430: }
3431: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3432: $incourse = 1;
3433: if ($env{'form.forceedit'}) {
3434: $forceview = 1;
3435: } else {
3436: $forceedit = 1;
3437: }
3438: $cfile = $resurl;
3439: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3440: $incourse = 1;
3441: if ($env{'form.forceedit'}) {
3442: $forceview = 1;
3443: } else {
3444: $forceedit = 1;
3445: }
3446: $cfile = $resurl;
3447: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3448: $incourse = 1;
3449: $forceview = 1;
3450: if ($symb) {
3451: my ($map,$id,$res)=&decode_symb($symb);
3452: $env{'request.symb'} = $symb;
3453: $cfile = &clutter($res);
3454: } else {
3455: $cfile = $env{'form.suppurl'};
3456: my $escfile = &unescape($cfile);
3457: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
3458: $cfile = '/adm/wrapper'.$escfile;
3459: } else {
3460: $escfile =~ s{^http://}{};
3461: $cfile = &escape("/adm/wrapper/ext/$escfile");
3462: }
3463: }
3464: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3465: if ($env{'form.forceedit'}) {
3466: $forceview = 1;
3467: } else {
3468: $forceedit = 1;
3469: }
3470: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
3471: }
3472: }
3473: if ($uploaded || $incourse) {
3474: $home=&homeserver($cnum,$cdom);
3475: } elsif ($file !~ m{/$}) {
3476: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3477: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3478: # Check that the user has permission to edit this resource
3479: my $setpriv = 1;
3480: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3481: if (defined($cfudom)) {
3482: $home=&homeserver($cfuname,$cfudom);
3483: $cfile=$file;
3484: }
3485: }
3486: if (($cfile ne '') && (!$incourse || $uploaded) &&
3487: (($home ne '') && ($home ne 'no_host'))) {
3488: my @ids=¤t_machine_ids();
3489: unless (grep(/^\Q$home\E$/,@ids)) {
3490: $switchserver=1;
3491: }
3492: }
3493: }
3494: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3495: }
3496:
3497: sub is_course_upload {
3498: my ($file,$cnum,$cdom) = @_;
3499: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3500: $uploadpath =~ s{^\/}{};
3501: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3502: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3503: return 1;
3504: }
3505: return;
3506: }
3507:
3508: sub in_course {
3509: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3510: if ($hideprivileged) {
3511: my $skipuser;
3512: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3513: my @possdoms = ($cdom);
3514: if ($coursehash{'checkforpriv'}) {
3515: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3516: }
3517: if (&privileged($uname,$udom,\@possdoms)) {
3518: $skipuser = 1;
3519: if ($coursehash{'nothideprivileged'}) {
3520: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3521: my $user;
3522: if ($item =~ /:/) {
3523: $user = $item;
3524: } else {
3525: $user = join(':',split(/[\@]/,$item));
3526: }
3527: if ($user eq $uname.':'.$udom) {
3528: undef($skipuser);
3529: last;
3530: }
3531: }
3532: }
3533: if ($skipuser) {
3534: return 0;
3535: }
3536: }
3537: }
3538: $type ||= 'any';
3539: if (!defined($cdom) || !defined($cnum)) {
3540: my $cid = $env{'request.course.id'};
3541: $cdom = $env{'course.'.$cid.'.domain'};
3542: $cnum = $env{'course.'.$cid.'.num'};
3543: }
3544: my $typesref;
3545: if (($type eq 'any') || ($type eq 'all')) {
3546: $typesref = ['active','previous','future'];
3547: } elsif ($type eq 'previous' || $type eq 'future') {
3548: $typesref = [$type];
3549: }
3550: my %roles = &get_my_roles($uname,$udom,'userroles',
3551: $typesref,undef,[$cdom]);
3552: my ($tmp) = keys(%roles);
3553: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3554: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3555: if (@course_roles > 0) {
3556: return 1;
3557: }
3558: return 0;
3559: }
3560:
3561: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
3562: # input: action, courseID, current domain, intended
3563: # path to file, source of file, instruction to parse file for objects,
3564: # ref to hash for embedded objects,
3565: # ref to hash for codebase of java objects.
3566: # reference to scalar to accommodate mime type determined
3567: # from File::MMagic if $parser = parse.
3568: #
3569: # output: url to file (if action was uploaddoc),
3570: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
3571: #
3572: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3573: # course.
3574: #
3575: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3576: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3577: # course's home server.
3578: #
3579: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3580: # be copied from $source (current location) to
3581: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3582: # and will then be copied to
3583: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3584: # course's home server.
3585: #
3586: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3587: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
3588: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3589: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3590: # in course's home server.
3591: #
3592:
3593: sub process_coursefile {
3594: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3595: $mimetype)=@_;
3596: my $fetchresult;
3597: my $home=&homeserver($docuname,$docudom);
3598: if ($action eq 'propagate') {
3599: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3600: $home);
3601: } else {
3602: my $fpath = '';
3603: my $fname = $file;
3604: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3605: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3606: my $filepath = &build_filepath($fpath);
3607: if ($action eq 'copy') {
3608: if ($source eq '') {
3609: $fetchresult = 'no source file';
3610: return $fetchresult;
3611: } else {
3612: my $destination = $filepath.'/'.$fname;
3613: rename($source,$destination);
3614: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3615: $home);
3616: }
3617: } elsif ($action eq 'uploaddoc') {
3618: open(my $fh,'>',$filepath.'/'.$fname);
3619: print $fh $env{'form.'.$source};
3620: close($fh);
3621: if ($parser eq 'parse') {
3622: my $mm = new File::MMagic;
3623: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3624: if ($type eq 'text/html') {
3625: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3626: unless ($parse_result eq 'ok') {
3627: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3628: }
3629: }
3630: if (ref($mimetype)) {
3631: $$mimetype = $type;
3632: }
3633: }
3634: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3635: $home);
3636: if ($fetchresult eq 'ok') {
3637: return '/uploaded/'.$fpath.'/'.$fname;
3638: } else {
3639: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3640: ' to host '.$home.': '.$fetchresult);
3641: return '/adm/notfound.html';
3642: }
3643: }
3644: }
3645: unless ( $fetchresult eq 'ok') {
3646: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3647: ' to host '.$home.': '.$fetchresult);
3648: }
3649: return $fetchresult;
3650: }
3651:
3652: sub build_filepath {
3653: my ($fpath) = @_;
3654: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3655: unless ($fpath eq '') {
3656: my @parts=split('/',$fpath);
3657: foreach my $part (@parts) {
3658: $filepath.= '/'.$part;
3659: if ((-e $filepath)!=1) {
3660: mkdir($filepath,0777);
3661: }
3662: }
3663: }
3664: return $filepath;
3665: }
3666:
3667: sub store_edited_file {
3668: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
3669: my $file = $primary_url;
3670: $file =~ s#^/uploaded/$docudom/$docuname/##;
3671: my $fpath = '';
3672: my $fname = $file;
3673: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3674: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3675: my $filepath = &build_filepath($fpath);
3676: open(my $fh,'>',$filepath.'/'.$fname);
3677: print $fh $content;
3678: close($fh);
3679: my $home=&homeserver($docuname,$docudom);
3680: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3681: $home);
3682: if ($$fetchresult eq 'ok') {
3683: return '/uploaded/'.$fpath.'/'.$fname;
3684: } else {
3685: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3686: ' to host '.$home.': '.$$fetchresult);
3687: return '/adm/notfound.html';
3688: }
3689: }
3690:
3691: sub clean_filename {
3692: my ($fname,$args)=@_;
3693: # Replace Windows backslashes by forward slashes
3694: $fname=~s/\\/\//g;
3695: if (!$args->{'keep_path'}) {
3696: # Get rid of everything but the actual filename
3697: $fname=~s/^.*\/([^\/]+)$/$1/;
3698: }
3699: # Replace spaces by underscores
3700: $fname=~s/\s+/\_/g;
3701: # Replace all other weird characters by nothing
3702: $fname=~s{[^/\w\.\-]}{}g;
3703: # Replace all .\d. sequences with _\d. so they no longer look like version
3704: # numbers
3705: $fname=~s/\.(\d+)(?=\.)/_$1/g;
3706: return $fname;
3707: }
3708: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3709: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3710: # image with the same aspect ratio as the original, but with dimensions which do
3711: # not exceed $resizewidth and $resizeheight.
3712:
3713: sub resizeImage {
3714: my ($img_path,$resizewidth,$resizeheight) = @_;
3715: my $ima = Image::Magick->new;
3716: my $resized;
3717: if (-e $img_path) {
3718: $ima->Read($img_path);
3719: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3720: my $width = $ima->Get('width');
3721: my $height = $ima->Get('height');
3722: if ($width > $resizewidth) {
3723: my $factor = $width/$resizewidth;
3724: my $newheight = $height/$factor;
3725: $ima->Scale(width=>$resizewidth,height=>$newheight);
3726: $resized = 1;
3727: }
3728: }
3729: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3730: my $width = $ima->Get('width');
3731: my $height = $ima->Get('height');
3732: if ($height > $resizeheight) {
3733: my $factor = $height/$resizeheight;
3734: my $newwidth = $width/$factor;
3735: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3736: $resized = 1;
3737: }
3738: }
3739: if ($resized) {
3740: $ima->Write($img_path);
3741: }
3742: }
3743: return;
3744: }
3745:
3746: # --------------- Take an uploaded file and put it into the userfiles directory
3747: # input: $formname - the contents of the file are in $env{"form.$formname"}
3748: # the desired filename is in $env{"form.$formname.filename"}
3749: # $context - possible values: coursedoc, existingfile, overwrite,
3750: # canceloverwrite, or ''.
3751: # if 'coursedoc': upload to the current course
3752: # if 'existingfile': write file to tmp/overwrites directory
3753: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3754: # $context is passed as argument to &finishuserfileupload
3755: # $subdir - directory in userfile to store the file into
3756: # $parser - instruction to parse file for objects ($parser = parse)
3757: # $allfiles - reference to hash for embedded objects
3758: # $codebase - reference to hash for codebase of java objects
3759: # $desuname - username for permanent storage of uploaded file
3760: # $dsetudom - domain for permanaent storage of uploaded file
3761: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3762: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
3763: # $resizewidth - width (pixels) to which to resize uploaded image
3764: # $resizeheight - height (pixels) to which to resize uploaded image
3765: # $mimetype - reference to scalar to accommodate mime type determined
3766: # from File::MMagic.
3767: #
3768: # output: url of file in userspace, or error: <message>
3769: # or /adm/notfound.html if failure to upload occurse
3770:
3771: sub userfileupload {
3772: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
3773: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
3774: if (!defined($subdir)) { $subdir='unknown'; }
3775: my $fname=$env{'form.'.$formname.'.filename'};
3776: $fname=&clean_filename($fname);
3777: # See if there is anything left
3778: unless ($fname) { return 'error: no uploaded file'; }
3779: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3780: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3781: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3782: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3783: my $now = time;
3784: my $filepath;
3785: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
3786: $filepath = 'tmp/helprequests/'.$now;
3787: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3788: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3789: '_'.$env{'user.domain'}.'/pending';
3790: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3791: my ($docuname,$docudom);
3792: if ($destudom =~ /^$match_domain$/) {
3793: $docudom = $destudom;
3794: } else {
3795: $docudom = $env{'user.domain'};
3796: }
3797: if ($destuname =~ /^$match_username$/) {
3798: $docuname = $destuname;
3799: } else {
3800: $docuname = $env{'user.name'};
3801: }
3802: if (exists($env{'form.group'})) {
3803: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3804: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3805: }
3806: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3807: if ($context eq 'canceloverwrite') {
3808: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3809: if (-e $tempfile) {
3810: my @info = stat($tempfile);
3811: if ($info[9] eq $env{'form.timestamp'}) {
3812: unlink($tempfile);
3813: }
3814: }
3815: return;
3816: }
3817: }
3818: # Create the directory if not present
3819: my @parts=split(/\//,$filepath);
3820: my $fullpath = $perlvar{'lonDaemons'};
3821: for (my $i=0;$i<@parts;$i++) {
3822: $fullpath .= '/'.$parts[$i];
3823: if ((-e $fullpath)!=1) {
3824: mkdir($fullpath,0777);
3825: }
3826: }
3827: open(my $fh,'>',$fullpath.'/'.$fname);
3828: print $fh $env{'form.'.$formname};
3829: close($fh);
3830: if ($context eq 'existingfile') {
3831: my @info = stat($fullpath.'/'.$fname);
3832: return ($fullpath.'/'.$fname,$info[9]);
3833: } else {
3834: return $fullpath.'/'.$fname;
3835: }
3836: }
3837: if ($subdir eq 'scantron') {
3838: $fname = 'scantron_orig_'.$fname;
3839: } else {
3840: $fname="$subdir/$fname";
3841: }
3842: if ($context eq 'coursedoc') {
3843: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3844: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3845: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
3846: return &finishuserfileupload($docuname,$docudom,
3847: $formname,$fname,$parser,$allfiles,
3848: $codebase,$thumbwidth,$thumbheight,
3849: $resizewidth,$resizeheight,$context,$mimetype);
3850: } else {
3851: if ($env{'form.folder'}) {
3852: $fname=$env{'form.folder'}.'/'.$fname;
3853: }
3854: return &process_coursefile('uploaddoc',$docuname,$docudom,
3855: $fname,$formname,$parser,
3856: $allfiles,$codebase,$mimetype);
3857: }
3858: } elsif (defined($destuname)) {
3859: my $docuname=$destuname;
3860: my $docudom=$destudom;
3861: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3862: $parser,$allfiles,$codebase,
3863: $thumbwidth,$thumbheight,
3864: $resizewidth,$resizeheight,$context,$mimetype);
3865: } else {
3866: my $docuname=$env{'user.name'};
3867: my $docudom=$env{'user.domain'};
3868: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
3869: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3870: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3871: }
3872: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3873: $parser,$allfiles,$codebase,
3874: $thumbwidth,$thumbheight,
3875: $resizewidth,$resizeheight,$context,$mimetype);
3876: }
3877: }
3878:
3879: sub finishuserfileupload {
3880: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
3881: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
3882: my $path=$docudom.'/'.$docuname.'/';
3883: my $filepath=$perlvar{'lonDocRoot'};
3884:
3885: my ($fnamepath,$file,$fetchthumb);
3886: $file=$fname;
3887: if ($fname=~m|/|) {
3888: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3889: $path.=$fnamepath.'/';
3890: }
3891: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
3892: my $count;
3893: for ($count=4;$count<=$#parts;$count++) {
3894: $filepath.="/$parts[$count]";
3895: if ((-e $filepath)!=1) {
3896: mkdir($filepath,0777);
3897: }
3898: }
3899:
3900: # Save the file
3901: {
3902: if (!open(FH,'>',$filepath.'/'.$file)) {
3903: &logthis('Failed to create '.$filepath.'/'.$file);
3904: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3905: return '/adm/notfound.html';
3906: }
3907: if ($context eq 'overwrite') {
3908: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
3909: my $target = $filepath.'/'.$file;
3910: if (-e $source) {
3911: my @info = stat($source);
3912: if ($info[9] eq $env{'form.timestamp'}) {
3913: unless (&File::Copy::move($source,$target)) {
3914: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3915: return "Moving from $source failed";
3916: }
3917: } else {
3918: return "Temporary file: $source had unexpected date/time for last modification";
3919: }
3920: } else {
3921: return "Temporary file: $source missing";
3922: }
3923: } elsif (!print FH ($env{'form.'.$formname})) {
3924: &logthis('Failed to write to '.$filepath.'/'.$file);
3925: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3926: return '/adm/notfound.html';
3927: }
3928: close(FH);
3929: if ($resizewidth && $resizeheight) {
3930: my $mm = new File::MMagic;
3931: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3932: if ($mime_type =~ m{^image/}) {
3933: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3934: }
3935: }
3936: }
3937: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3938: if (ref($mimetype)) {
3939: if ($$mimetype eq '') {
3940: my $mm = new File::MMagic;
3941: my $type = $mm->checktype_filename($filepath.'/'.$file);
3942: $$mimetype = $type;
3943: }
3944: }
3945: }
3946: if ($parser eq 'parse') {
3947: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
3948: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3949: $allfiles,$codebase);
3950: unless ($parse_result eq 'ok') {
3951: &logthis('Failed to parse '.$filepath.$file.
3952: ' for embedded media: '.$parse_result);
3953: }
3954: }
3955: }
3956: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3957: my $input = $filepath.'/'.$file;
3958: my $output = $filepath.'/'.'tn-'.$file;
3959: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3960: my @args = ('convert','-sample',$thumbsize,$input,$output);
3961: system({$args[0]} @args);
3962: if (-e $filepath.'/'.'tn-'.$file) {
3963: $fetchthumb = 1;
3964: }
3965: }
3966:
3967: # Notify homeserver to grep it
3968: #
3969: my $docuhome=&homeserver($docuname,$docudom);
3970: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
3971: if ($fetchresult eq 'ok') {
3972: if ($fetchthumb) {
3973: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3974: if ($thumbresult ne 'ok') {
3975: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3976: $docuhome.': '.$thumbresult);
3977: }
3978: }
3979: #
3980: # Return the URL to it
3981: return '/uploaded/'.$path.$file;
3982: } else {
3983: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3984: ': '.$fetchresult);
3985: return '/adm/notfound.html';
3986: }
3987: }
3988:
3989: sub extract_embedded_items {
3990: my ($fullpath,$allfiles,$codebase,$content) = @_;
3991: my @state = ();
3992: my (%lastids,%related,%shockwave,%flashvars);
3993: my %javafiles = (
3994: codebase => '',
3995: code => '',
3996: archive => ''
3997: );
3998: my %mediafiles = (
3999: src => '',
4000: movie => '',
4001: );
4002: my $p;
4003: if ($content) {
4004: $p = HTML::LCParser->new($content);
4005: } else {
4006: $p = HTML::LCParser->new($fullpath);
4007: }
4008: while (my $t=$p->get_token()) {
4009: if ($t->[0] eq 'S') {
4010: my ($tagname, $attr) = ($t->[1],$t->[2]);
4011: push(@state, $tagname);
4012: if (lc($tagname) eq 'allow') {
4013: &add_filetype($allfiles,$attr->{'src'},'src');
4014: }
4015: if (lc($tagname) eq 'img') {
4016: &add_filetype($allfiles,$attr->{'src'},'src');
4017: }
4018: if (lc($tagname) eq 'a') {
4019: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
4020: &add_filetype($allfiles,$attr->{'href'},'href');
4021: }
4022: }
4023: if (lc($tagname) eq 'script') {
4024: my $src;
4025: if ($attr->{'archive'} =~ /\.jar$/i) {
4026: &add_filetype($allfiles,$attr->{'archive'},'archive');
4027: } else {
4028: if ($attr->{'src'} ne '') {
4029: $src = $attr->{'src'};
4030: &add_filetype($allfiles,$src,'src');
4031: }
4032: }
4033: my $text = $p->get_trimmed_text();
4034: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4035: my @swfargs = split(/,/,$1);
4036: foreach my $item (@swfargs) {
4037: $item =~ s/["']//g;
4038: $item =~ s/^\s+//;
4039: $item =~ s/\s+$//;
4040: }
4041: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4042: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4043: push(@{$related{$swfargs[0]}},$swfargs[2]);
4044: } else {
4045: $related{$swfargs[0]} = [$swfargs[2]];
4046: }
4047: }
4048: }
4049: }
4050: if (lc($tagname) eq 'link') {
4051: if (lc($attr->{'rel'}) eq 'stylesheet') {
4052: &add_filetype($allfiles,$attr->{'href'},'href');
4053: }
4054: }
4055: if (lc($tagname) eq 'object' ||
4056: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4057: foreach my $item (keys(%javafiles)) {
4058: $javafiles{$item} = '';
4059: }
4060: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4061: $lastids{lc($tagname)} = $attr->{'id'};
4062: }
4063: }
4064: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4065: my $name = lc($attr->{'name'});
4066: foreach my $item (keys(%javafiles)) {
4067: if ($name eq $item) {
4068: $javafiles{$item} = $attr->{'value'};
4069: last;
4070: }
4071: }
4072: my $pathfrom;
4073: foreach my $item (keys(%mediafiles)) {
4074: if ($name eq $item) {
4075: $pathfrom = $attr->{'value'};
4076: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4077: &add_filetype($allfiles,$pathfrom,$name);
4078: last;
4079: }
4080: }
4081: if ($name eq 'flashvars') {
4082: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4083: }
4084: if ($pathfrom ne '') {
4085: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4086: $pathfrom);
4087: }
4088: }
4089: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4090: foreach my $item (keys(%javafiles)) {
4091: if ($attr->{$item}) {
4092: $javafiles{$item} = $attr->{$item};
4093: last;
4094: }
4095: }
4096: foreach my $item (keys(%mediafiles)) {
4097: if ($attr->{$item}) {
4098: &add_filetype($allfiles,$attr->{$item},$item);
4099: last;
4100: }
4101: }
4102: if (lc($tagname) eq 'embed') {
4103: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4104: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4105: $attr->{'src'});
4106: }
4107: }
4108: }
4109: if (lc($tagname) eq 'iframe') {
4110: my $src = $attr->{'src'} ;
4111: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4112: &add_filetype($allfiles,$src,'src');
4113: } elsif ($src =~ m{^/}) {
4114: if ($env{'request.course.id'}) {
4115: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4116: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4117: my $url = &hreflocation('',$fullpath);
4118: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4119: my $relpath = $1;
4120: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4121: &add_filetype($allfiles,$1,'src');
4122: }
4123: }
4124: }
4125: }
4126: }
4127: if ($t->[4] =~ m{/>$}) {
4128: pop(@state);
4129: }
4130: } elsif ($t->[0] eq 'E') {
4131: my ($tagname) = ($t->[1]);
4132: if ($javafiles{'codebase'} ne '') {
4133: $javafiles{'codebase'} .= '/';
4134: }
4135: if (lc($tagname) eq 'applet' ||
4136: lc($tagname) eq 'object' ||
4137: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4138: ) {
4139: foreach my $item (keys(%javafiles)) {
4140: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4141: my $file=$javafiles{'codebase'}.$javafiles{$item};
4142: &add_filetype($allfiles,$file,$item);
4143: }
4144: }
4145: }
4146: pop @state;
4147: }
4148: }
4149: foreach my $id (sort(keys(%flashvars))) {
4150: if ($shockwave{$id} ne '') {
4151: my @pairs = split(/\&/,$flashvars{$id});
4152: foreach my $pair (@pairs) {
4153: my ($key,$value) = split(/\=/,$pair);
4154: if ($key eq 'thumb') {
4155: &add_filetype($allfiles,$value,$key);
4156: } elsif ($key eq 'content') {
4157: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4158: my ($ext) = ($value =~ /\.([^.]+)$/);
4159: if ($ext ne '') {
4160: &add_filetype($allfiles,$path.$value,$ext);
4161: }
4162: }
4163: }
4164: }
4165: }
4166: return 'ok';
4167: }
4168:
4169: sub add_filetype {
4170: my ($allfiles,$file,$type)=@_;
4171: if (exists($allfiles->{$file})) {
4172: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4173: push(@{$allfiles->{$file}}, &escape($type));
4174: }
4175: } else {
4176: @{$allfiles->{$file}} = (&escape($type));
4177: }
4178: }
4179:
4180: sub embedded_dependency {
4181: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4182: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4183: if (($identifier ne '') &&
4184: (ref($related->{$identifier}) eq 'ARRAY') &&
4185: ($pathfrom ne '')) {
4186: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4187: foreach my $dep (@{$related->{$identifier}}) {
4188: &add_filetype($allfiles,$path.$dep,'object');
4189: }
4190: }
4191: }
4192: return;
4193: }
4194:
4195: sub removeuploadedurl {
4196: my ($url)=@_;
4197: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
4198: return &removeuserfile($uname,$udom,$fname);
4199: }
4200:
4201: sub removeuserfile {
4202: my ($docuname,$docudom,$fname)=@_;
4203: my $home=&homeserver($docuname,$docudom);
4204: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
4205: if ($result eq 'ok') {
4206: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4207: my $metafile = $fname.'.meta';
4208: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
4209: my $url = "/uploaded/$docudom/$docuname/$fname";
4210: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
4211: my $sqlresult =
4212: &update_portfolio_table($docuname,$docudom,$file,
4213: 'portfolio_metadata',$group,
4214: 'delete');
4215: }
4216: }
4217: return $result;
4218: }
4219:
4220: sub mkdiruserfile {
4221: my ($docuname,$docudom,$dir)=@_;
4222: my $home=&homeserver($docuname,$docudom);
4223: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4224: }
4225:
4226: sub renameuserfile {
4227: my ($docuname,$docudom,$old,$new)=@_;
4228: my $home=&homeserver($docuname,$docudom);
4229: my $result = &reply("renameuserfile:$docudom:$docuname:".
4230: &escape("$old").':'.&escape("$new"),$home);
4231: if ($result eq 'ok') {
4232: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4233: my $oldmeta = $old.'.meta';
4234: my $newmeta = $new.'.meta';
4235: my $metaresult =
4236: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
4237: my $url = "/uploaded/$docudom/$docuname/$old";
4238: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
4239: my $sqlresult =
4240: &update_portfolio_table($docuname,$docudom,$file,
4241: 'portfolio_metadata',$group,
4242: 'delete');
4243: }
4244: }
4245: return $result;
4246: }
4247:
4248: # ------------------------------------------------------------------------- Log
4249:
4250: sub log {
4251: my ($dom,$nam,$hom,$what)=@_;
4252: return critical("log:$dom:$nam:$what",$hom);
4253: }
4254:
4255: # ------------------------------------------------------------------ Course Log
4256: #
4257: # This routine flushes several buffers of non-mission-critical nature
4258: #
4259:
4260: sub flushcourselogs {
4261: &logthis('Flushing log buffers');
4262: #
4263: # course logs
4264: # This is a log of all transactions in a course, which can be used
4265: # for data mining purposes
4266: #
4267: # It also collects the courseid database, which lists last transaction
4268: # times and course titles for all courseids
4269: #
4270: my %courseidbuffer=();
4271: foreach my $crsid (keys(%courselogs)) {
4272: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
4273: &escape($courselogs{$crsid}),
4274: $coursehombuf{$crsid}) eq 'ok') {
4275: delete $courselogs{$crsid};
4276: } else {
4277: &logthis('Failed to flush log buffer for '.$crsid);
4278: if (length($courselogs{$crsid})>40000) {
4279: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
4280: " exceeded maximum size, deleting.</font>");
4281: delete $courselogs{$crsid};
4282: }
4283: }
4284: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
4285: 'description' => $coursedescrbuf{$crsid},
4286: 'inst_code' => $courseinstcodebuf{$crsid},
4287: 'type' => $coursetypebuf{$crsid},
4288: 'owner' => $courseownerbuf{$crsid},
4289: };
4290: }
4291: #
4292: # Write course id database (reverse lookup) to homeserver of courses
4293: # Is used in pickcourse
4294: #
4295: foreach my $crs_home (keys(%courseidbuffer)) {
4296: my $response = &courseidput(&host_domain($crs_home),
4297: $courseidbuffer{$crs_home},
4298: $crs_home,'timeonly');
4299: }
4300: #
4301: # File accesses
4302: # Writes to the dynamic metadata of resources to get hit counts, etc.
4303: #
4304: foreach my $entry (keys(%accesshash)) {
4305: if ($entry =~ /___count$/) {
4306: my ($dom,$name);
4307: ($dom,$name,undef)=
4308: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
4309: if (! defined($dom) || $dom eq '' ||
4310: ! defined($name) || $name eq '') {
4311: my $cid = $env{'request.course.id'};
4312: $dom = $env{'request.'.$cid.'.domain'};
4313: $name = $env{'request.'.$cid.'.num'};
4314: }
4315: my $value = $accesshash{$entry};
4316: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4317: my %temphash=($url => $value);
4318: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4319: if ($result eq 'ok') {
4320: delete $accesshash{$entry};
4321: }
4322: } else {
4323: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
4324: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
4325: my %temphash=($entry => $accesshash{$entry});
4326: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4327: delete $accesshash{$entry};
4328: }
4329: }
4330: }
4331: #
4332: # Roles
4333: # Reverse lookup of user roles for course faculty/staff and co-authorship
4334: #
4335: foreach my $entry (keys(%userrolehash)) {
4336: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
4337: split(/\:/,$entry);
4338: if (&Apache::lonnet::put('nohist_userroles',
4339: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
4340: $rudom,$runame) eq 'ok') {
4341: delete $userrolehash{$entry};
4342: }
4343: }
4344: #
4345: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
4346: #
4347: my %domrolebuffer = ();
4348: foreach my $entry (keys(%domainrolehash)) {
4349: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
4350: if ($domrolebuffer{$rudom}) {
4351: $domrolebuffer{$rudom}.='&'.&escape($entry).
4352: '='.&escape($domainrolehash{$entry});
4353: } else {
4354: $domrolebuffer{$rudom}.=&escape($entry).
4355: '='.&escape($domainrolehash{$entry});
4356: }
4357: delete $domainrolehash{$entry};
4358: }
4359: foreach my $dom (keys(%domrolebuffer)) {
4360: my %servers;
4361: if (defined(&domain($dom,'primary'))) {
4362: my $primary=&domain($dom,'primary');
4363: my $hostname=&hostname($primary);
4364: $servers{$primary} = $hostname;
4365: } else {
4366: %servers = &get_servers($dom,'library');
4367: }
4368: foreach my $tryserver (keys(%servers)) {
4369: if (&reply('domroleput:'.$dom.':'.
4370: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4371: last;
4372: } else {
4373: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4374: }
4375: }
4376: }
4377: $dumpcount++;
4378: }
4379:
4380: sub courselog {
4381: my $what=shift;
4382: $what=time.':'.$what;
4383: unless ($env{'request.course.id'}) { return ''; }
4384: $coursedombuf{$env{'request.course.id'}}=
4385: $env{'course.'.$env{'request.course.id'}.'.domain'};
4386: $coursenumbuf{$env{'request.course.id'}}=
4387: $env{'course.'.$env{'request.course.id'}.'.num'};
4388: $coursehombuf{$env{'request.course.id'}}=
4389: $env{'course.'.$env{'request.course.id'}.'.home'};
4390: $coursedescrbuf{$env{'request.course.id'}}=
4391: $env{'course.'.$env{'request.course.id'}.'.description'};
4392: $courseinstcodebuf{$env{'request.course.id'}}=
4393: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4394: $courseownerbuf{$env{'request.course.id'}}=
4395: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
4396: $coursetypebuf{$env{'request.course.id'}}=
4397: $env{'course.'.$env{'request.course.id'}.'.type'};
4398: if (defined $courselogs{$env{'request.course.id'}}) {
4399: $courselogs{$env{'request.course.id'}}.='&'.$what;
4400: } else {
4401: $courselogs{$env{'request.course.id'}}.=$what;
4402: }
4403: if (length($courselogs{$env{'request.course.id'}})>4048) {
4404: &flushcourselogs();
4405: }
4406: }
4407:
4408: sub courseacclog {
4409: my $fnsymb=shift;
4410: unless ($env{'request.course.id'}) { return ''; }
4411: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
4412: if ($fnsymb=~/$LONCAPA::assess_re/) {
4413: $what.=':POST';
4414: # FIXME: Probably ought to escape things....
4415: foreach my $key (keys(%env)) {
4416: if ($key=~/^form\.(.*)/) {
4417: my $formitem = $1;
4418: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4419: $what.=':'.$formitem.'='.$env{$key};
4420: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
4421: $what.=':'.$formitem.'='.$env{$key};
4422: }
4423: }
4424: }
4425: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4426: # FIXME: We should not be depending on a form parameter that someone
4427: # editing lonsearchcat.pm might change in the future.
4428: if ($env{'form.phase'} eq 'course_search') {
4429: $what.= ':POST';
4430: # FIXME: Probably ought to escape things....
4431: foreach my $element ('courseexp','crsfulltext','crsrelated',
4432: 'crsdiscuss') {
4433: $what.=':'.$element.'='.$env{'form.'.$element};
4434: }
4435: }
4436: }
4437: &courselog($what);
4438: }
4439:
4440: sub countacc {
4441: my $url=&declutter(shift);
4442: return if (! defined($url) || $url eq '');
4443: unless ($env{'request.course.id'}) { return ''; }
4444: #
4445: # Mark that this url was used in this course
4446: #
4447: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
4448: #
4449: # Increase the access count for this resource in this child process
4450: #
4451: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
4452: $accesshash{$key}++;
4453: }
4454:
4455: sub linklog {
4456: my ($from,$to)=@_;
4457: $from=&declutter($from);
4458: $to=&declutter($to);
4459: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4460: $accesshash{$to.'___'.$from.'___goto'}=1;
4461: }
4462:
4463: sub statslog {
4464: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4465: if ($users<2) { return; }
4466: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4467: 'course' => $env{'request.course.id'},
4468: 'sections' => '"all"',
4469: 'num_students' => $users,
4470: 'part' => $part,
4471: 'symb' => $symb,
4472: 'mean_tries' => $av_attempts,
4473: 'deg_of_diff' => $degdiff});
4474: foreach my $key (keys(%dynstore)) {
4475: $accesshash{$key}=$dynstore{$key};
4476: }
4477: }
4478:
4479: sub userrolelog {
4480: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
4481: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
4482: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4483: $userrolehash
4484: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4485: =$tend.':'.$tstart;
4486: }
4487: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
4488: $userrolehash
4489: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4490: =$tend.':'.$tstart;
4491: }
4492: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
4493: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4494: $domainrolehash
4495: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4496: = $tend.':'.$tstart;
4497: }
4498: }
4499:
4500: sub courserolelog {
4501: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
4502: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4503: my $cdom = $1;
4504: my $cnum = $2;
4505: my $sec = $3;
4506: my $namespace = 'rolelog';
4507: my %storehash = (
4508: role => $trole,
4509: start => $tstart,
4510: end => $tend,
4511: selfenroll => $selfenroll,
4512: context => $context,
4513: );
4514: if ($trole eq 'gr') {
4515: $namespace = 'groupslog';
4516: $storehash{'group'} = $sec;
4517: } else {
4518: $storehash{'section'} = $sec;
4519: }
4520: &write_log('course',$namespace,\%storehash,$delflag,$username,
4521: $domain,$cnum,$cdom);
4522: if (($trole ne 'st') || ($sec ne '')) {
4523: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
4524: }
4525: }
4526: return;
4527: }
4528:
4529: sub domainrolelog {
4530: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4531: if ($area =~ m{^/($match_domain)/$}) {
4532: my $cdom = $1;
4533: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4534: my $namespace = 'rolelog';
4535: my %storehash = (
4536: role => $trole,
4537: start => $tstart,
4538: end => $tend,
4539: context => $context,
4540: );
4541: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4542: $domain,$domconfiguser,$cdom);
4543: }
4544: return;
4545:
4546: }
4547:
4548: sub coauthorrolelog {
4549: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4550: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4551: my $audom = $1;
4552: my $auname = $2;
4553: my $namespace = 'rolelog';
4554: my %storehash = (
4555: role => $trole,
4556: start => $tstart,
4557: end => $tend,
4558: context => $context,
4559: );
4560: &write_log('author',$namespace,\%storehash,$delflag,$username,
4561: $domain,$auname,$audom);
4562: }
4563: return;
4564: }
4565:
4566: sub get_course_adv_roles {
4567: my ($cid,$codes) = @_;
4568: $cid=$env{'request.course.id'} unless (defined($cid));
4569: my %coursehash=&coursedescription($cid);
4570: my $crstype = &Apache::loncommon::course_type($cid);
4571: my %nothide=();
4572: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4573: if ($user !~ /:/) {
4574: $nothide{join(':',split(/[\@]/,$user))}=1;
4575: } else {
4576: $nothide{$user}=1;
4577: }
4578: }
4579: my @possdoms = ($coursehash{'domain'});
4580: if ($coursehash{'checkforpriv'}) {
4581: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4582: }
4583: my %returnhash=();
4584: my %dumphash=
4585: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4586: my $now=time;
4587: my %privileged;
4588: foreach my $entry (keys(%dumphash)) {
4589: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4590: if (($tstart) && ($tstart<0)) { next; }
4591: if (($tend) && ($tend<$now)) { next; }
4592: if (($tstart) && ($now<$tstart)) { next; }
4593: my ($role,$username,$domain,$section)=split(/\:/,$entry);
4594: if ($username eq '' || $domain eq '') { next; }
4595: if ((&privileged($username,$domain,\@possdoms)) &&
4596: (!$nothide{$username.':'.$domain})) { next; }
4597: if ($role eq 'cr') { next; }
4598: if ($codes) {
4599: if ($section) { $role .= ':'.$section; }
4600: if ($returnhash{$role}) {
4601: $returnhash{$role}.=','.$username.':'.$domain;
4602: } else {
4603: $returnhash{$role}=$username.':'.$domain;
4604: }
4605: } else {
4606: my $key=&plaintext($role,$crstype);
4607: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
4608: if ($returnhash{$key}) {
4609: $returnhash{$key}.=','.$username.':'.$domain;
4610: } else {
4611: $returnhash{$key}=$username.':'.$domain;
4612: }
4613: }
4614: }
4615: return %returnhash;
4616: }
4617:
4618: sub get_my_roles {
4619: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
4620: unless (defined($uname)) { $uname=$env{'user.name'}; }
4621: unless (defined($udom)) { $udom=$env{'user.domain'}; }
4622: my (%dumphash,%nothide);
4623: if ($context eq 'userroles') {
4624: %dumphash = &dump('roles',$udom,$uname);
4625: } else {
4626: %dumphash = &dump('nohist_userroles',$udom,$uname);
4627: if ($hidepriv) {
4628: my %coursehash=&coursedescription($udom.'_'.$uname);
4629: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4630: if ($user !~ /:/) {
4631: $nothide{join(':',split(/[\@]/,$user))} = 1;
4632: } else {
4633: $nothide{$user} = 1;
4634: }
4635: }
4636: }
4637: }
4638: my %returnhash=();
4639: my $now=time;
4640: my %privileged;
4641: foreach my $entry (keys(%dumphash)) {
4642: my ($role,$tend,$tstart);
4643: if ($context eq 'userroles') {
4644: next if ($entry =~ /^rolesdef/);
4645: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4646: } else {
4647: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4648: }
4649: if (($tstart) && ($tstart<0)) { next; }
4650: my $status = 'active';
4651: if (($tend) && ($tend<=$now)) {
4652: $status = 'previous';
4653: }
4654: if (($tstart) && ($now<$tstart)) {
4655: $status = 'future';
4656: }
4657: if (ref($types) eq 'ARRAY') {
4658: if (!grep(/^\Q$status\E$/,@{$types})) {
4659: next;
4660: }
4661: } else {
4662: if ($status ne 'active') {
4663: next;
4664: }
4665: }
4666: my ($rolecode,$username,$domain,$section,$area);
4667: if ($context eq 'userroles') {
4668: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
4669: (undef,$domain,$username,$section) = split(/\//,$area);
4670: } else {
4671: ($role,$username,$domain,$section) = split(/\:/,$entry);
4672: }
4673: if (ref($roledoms) eq 'ARRAY') {
4674: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4675: next;
4676: }
4677: }
4678: if (ref($roles) eq 'ARRAY') {
4679: if (!grep(/^\Q$role\E$/,@{$roles})) {
4680: if ($role =~ /^cr\//) {
4681: if (!grep(/^cr$/,@{$roles})) {
4682: next;
4683: }
4684: } elsif ($role =~ /^gr\//) {
4685: if (!grep(/^gr$/,@{$roles})) {
4686: next;
4687: }
4688: } else {
4689: next;
4690: }
4691: }
4692: }
4693: if ($hidepriv) {
4694: my @privroles = ('dc','su');
4695: if ($context eq 'userroles') {
4696: next if (grep(/^\Q$role\E$/,@privroles));
4697: } else {
4698: my $possdoms = [$domain];
4699: if (ref($roledoms) eq 'ARRAY') {
4700: push(@{$possdoms},@{$roledoms});
4701: }
4702: if (&privileged($username,$domain,$possdoms,\@privroles)) {
4703: if (!$nothide{$username.':'.$domain}) {
4704: next;
4705: }
4706: }
4707: }
4708: }
4709: if ($withsec) {
4710: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4711: $tstart.':'.$tend;
4712: } else {
4713: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4714: }
4715: }
4716: return %returnhash;
4717: }
4718:
4719: sub get_all_adhocroles {
4720: my ($dom) = @_;
4721: my @roles_by_num = ();
4722: my %domdefaults = &get_domain_defaults($dom);
4723: my (%description,%access_in_dom,%access_info);
4724: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
4725: my $count = 0;
4726: my %domcurrent = %{$domdefaults{'adhocroles'}};
4727: my %ordered;
4728: foreach my $role (sort(keys(%domcurrent))) {
4729: my ($order,$desc,$access_in_dom);
4730: if (ref($domcurrent{$role}) eq 'HASH') {
4731: $order = $domcurrent{$role}{'order'};
4732: $desc = $domcurrent{$role}{'desc'};
4733: $access_in_dom{$role} = $domcurrent{$role}{'access'};
4734: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
4735: }
4736: if ($order eq '') {
4737: $order = $count;
4738: }
4739: $ordered{$order} = $role;
4740: if ($desc ne '') {
4741: $description{$role} = $desc;
4742: } else {
4743: $description{$role}= $role;
4744: }
4745: $count++;
4746: }
4747: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
4748: push(@roles_by_num,$ordered{$item});
4749: }
4750: }
4751: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
4752: }
4753:
4754: sub get_my_adhocroles {
4755: my ($cid,$checkreg) = @_;
4756: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
4757: if ($env{'request.course.id'} eq $cid) {
4758: $cdom = $env{'course.'.$cid.'.domain'};
4759: $cnum = $env{'course.'.$cid.'.num'};
4760: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
4761: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
4762: $cdom = $1;
4763: $cnum = $2;
4764: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
4765: $cdom,$cnum);
4766: }
4767: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
4768: my $user = $env{'user.name'}.':'.$env{'user.domain'};
4769: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
4770: if ($rosterhash{$user} ne '') {
4771: my $type = (split(/:/,$rosterhash{$user}))[5];
4772: return ([],{}) if ($type eq 'auto');
4773: }
4774: }
4775: if (($cdom ne '') && ($cnum ne '')) {
4776: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
4777: my $then=$env{'user.login.time'};
4778: my $update=$env{'user.update.time'};
4779: if (!$update) {
4780: $update = $then;
4781: }
4782: my @liveroles;
4783: foreach my $role ('dh','da') {
4784: if ($env{"user.role.$role./$cdom/"}) {
4785: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
4786: my $limit = $update;
4787: if ($env{'request.role'} eq "$role./$cdom/") {
4788: $limit = $then;
4789: }
4790: my $activerole = 1;
4791: if ($tstart && $tstart>$limit) { $activerole = 0; }
4792: if ($tend && $tend <$limit) { $activerole = 0; }
4793: if ($activerole) {
4794: push(@liveroles,$role);
4795: }
4796: }
4797: }
4798: if (@liveroles) {
4799: if (&homeserver($cnum,$cdom) ne 'no_host') {
4800: my ($accessref,$accessinfo,%access_in_dom);
4801: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
4802: if (ref($roles_by_num) eq 'ARRAY') {
4803: if (@{$roles_by_num}) {
4804: my %settings;
4805: if ($env{'request.course.id'} eq $cid) {
4806: foreach my $envkey (keys(%env)) {
4807: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
4808: $settings{$1} = $env{$envkey};
4809: }
4810: }
4811: } else {
4812: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
4813: }
4814: my %setincrs;
4815: if ($settings{'internal.adhocaccess'}) {
4816: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
4817: }
4818: my @statuses;
4819: if ($env{'environment.inststatus'}) {
4820: @statuses = split(/,/,$env{'environment.inststatus'});
4821: }
4822: my $user = $env{'user.name'}.':'.$env{'user.domain'};
4823: if (ref($accessref) eq 'HASH') {
4824: %access_in_dom = %{$accessref};
4825: }
4826: foreach my $role (@{$roles_by_num}) {
4827: my ($curraccess,@okstatus,@personnel);
4828: if ($setincrs{$role}) {
4829: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
4830: if ($curraccess eq 'status') {
4831: @okstatus = split(/\&/,$rest);
4832: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4833: @personnel = split(/\&/,$rest);
4834: }
4835: } else {
4836: $curraccess = $access_in_dom{$role};
4837: if (ref($accessinfo) eq 'HASH') {
4838: if ($curraccess eq 'status') {
4839: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4840: @okstatus = @{$accessinfo->{$role}};
4841: }
4842: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4843: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4844: @personnel = @{$accessinfo->{$role}};
4845: }
4846: }
4847: }
4848: }
4849: if ($curraccess eq 'none') {
4850: next;
4851: } elsif ($curraccess eq 'all') {
4852: push(@possroles,$role);
4853: } elsif ($curraccess eq 'dh') {
4854: if (grep(/^dh$/,@liveroles)) {
4855: push(@possroles,$role);
4856: } else {
4857: next;
4858: }
4859: } elsif ($curraccess eq 'da') {
4860: if (grep(/^da$/,@liveroles)) {
4861: push(@possroles,$role);
4862: } else {
4863: next;
4864: }
4865: } elsif ($curraccess eq 'status') {
4866: if (@okstatus) {
4867: if (!@statuses) {
4868: if (grep(/^default$/,@okstatus)) {
4869: push(@possroles,$role);
4870: }
4871: } else {
4872: foreach my $status (@okstatus) {
4873: if (grep(/^\Q$status\E$/,@statuses)) {
4874: push(@possroles,$role);
4875: last;
4876: }
4877: }
4878: }
4879: }
4880: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4881: if (grep(/^\Q$user\E$/,@personnel)) {
4882: if ($curraccess eq 'exc') {
4883: push(@possroles,$role);
4884: }
4885: } elsif ($curraccess eq 'inc') {
4886: push(@possroles,$role);
4887: }
4888: }
4889: }
4890: }
4891: }
4892: }
4893: }
4894: }
4895: }
4896: unless (ref($description) eq 'HASH') {
4897: if (ref($roles_by_num) eq 'ARRAY') {
4898: my %desc;
4899: map { $desc{$_} = $_; } (@{$roles_by_num});
4900: $description = \%desc;
4901: } else {
4902: $description = {};
4903: }
4904: }
4905: return (\@possroles,$description);
4906: }
4907:
4908: # ----------------------------------------------------- Frontpage Announcements
4909: #
4910: #
4911:
4912: sub postannounce {
4913: my ($server,$text)=@_;
4914: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
4915: unless ($text=~/\w/) { $text=''; }
4916: return &reply('setannounce:'.&escape($text),$server);
4917: }
4918:
4919: sub getannounce {
4920:
4921: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
4922: my $announcement='';
4923: while (my $line = <$fh>) { $announcement .= $line; }
4924: close($fh);
4925: if ($announcement=~/\w/) {
4926: return
4927: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
4928: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
4929: } else {
4930: return '';
4931: }
4932: } else {
4933: return '';
4934: }
4935: }
4936:
4937: # ---------------------------------------------------------- Course ID routines
4938: # Deal with domain's nohist_courseid.db files
4939: #
4940:
4941: sub courseidput {
4942: my ($domain,$storehash,$coursehome,$caller) = @_;
4943: return unless (ref($storehash) eq 'HASH');
4944: my $outcome;
4945: if ($caller eq 'timeonly') {
4946: my $cids = '';
4947: foreach my $item (keys(%$storehash)) {
4948: $cids.=&escape($item).'&';
4949: }
4950: $cids=~s/\&$//;
4951: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4952: $coursehome);
4953: } else {
4954: my $items = '';
4955: foreach my $item (keys(%$storehash)) {
4956: $items.= &escape($item).'='.
4957: &freeze_escape($$storehash{$item}).'&';
4958: }
4959: $items=~s/\&$//;
4960: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4961: $coursehome);
4962: }
4963: if ($outcome eq 'unknown_cmd') {
4964: my $what;
4965: foreach my $cid (keys(%$storehash)) {
4966: $what .= &escape($cid).'=';
4967: foreach my $item ('description','inst_code','owner','type') {
4968: $what .= &escape($storehash->{$cid}{$item}).':';
4969: }
4970: $what =~ s/\:$/&/;
4971: }
4972: $what =~ s/\&$//;
4973: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4974: } else {
4975: return $outcome;
4976: }
4977: }
4978:
4979: sub courseiddump {
4980: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
4981: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
4982: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
4983: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
4984: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
4985: my $as_hash = 1;
4986: my %returnhash;
4987: if (!$domfilter) { $domfilter=''; }
4988: my %libserv = &all_library();
4989: foreach my $tryserver (keys(%libserv)) {
4990: if ( ( $hostidflag == 1
4991: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4992: || (!defined($hostidflag)) ) {
4993:
4994: if (($domfilter eq '') ||
4995: (&host_domain($tryserver) eq $domfilter)) {
4996: my $rep;
4997: if (grep { $_ eq $tryserver } current_machine_ids()) {
4998: $rep = LONCAPA::Lond::dump_course_id_handler(
4999: join(":", (&host_domain($tryserver), $sincefilter,
5000: &escape($descfilter), &escape($instcodefilter),
5001: &escape($ownerfilter), &escape($coursefilter),
5002: &escape($typefilter), &escape($regexp_ok),
5003: $as_hash, &escape($selfenrollonly),
5004: &escape($catfilter), $showhidden, $caller,
5005: &escape($cloner), &escape($cc_clone), $cloneonly,
5006: &escape($createdbefore), &escape($createdafter),
5007: &escape($creationcontext),$domcloner,$hasuniquecode,
5008: $reqcrsdom,&escape($reqinstcode))));
5009: } else {
5010: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5011: $sincefilter.':'.&escape($descfilter).':'.
5012: &escape($instcodefilter).':'.&escape($ownerfilter).
5013: ':'.&escape($coursefilter).':'.&escape($typefilter).
5014: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5015: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5016: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5017: &escape($cc_clone).':'.$cloneonly.':'.
5018: &escape($createdbefore).':'.&escape($createdafter).':'.
5019: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5020: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
5021: }
5022:
5023: my @pairs=split(/\&/,$rep);
5024: foreach my $item (@pairs) {
5025: my ($key,$value)=split(/\=/,$item,2);
5026: $key = &unescape($key);
5027: next if ($key =~ /^error: 2 /);
5028: my $result = &thaw_unescape($value);
5029: if (ref($result) eq 'HASH') {
5030: $returnhash{$key}=$result;
5031: } else {
5032: my @responses = split(/:/,$value);
5033: my @items = ('description','inst_code','owner','type');
5034: for (my $i=0; $i<@responses; $i++) {
5035: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
5036: }
5037: }
5038: }
5039: }
5040: }
5041: }
5042: return %returnhash;
5043: }
5044:
5045: sub courselastaccess {
5046: my ($cdom,$cnum,$hostidref) = @_;
5047: my %returnhash;
5048: if ($cdom && $cnum) {
5049: my $chome = &homeserver($cnum,$cdom);
5050: if ($chome ne 'no_host') {
5051: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5052: &extract_lastaccess(\%returnhash,$rep);
5053: }
5054: } else {
5055: if (!$cdom) { $cdom=''; }
5056: my %libserv = &all_library();
5057: foreach my $tryserver (keys(%libserv)) {
5058: if (ref($hostidref) eq 'ARRAY') {
5059: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5060: }
5061: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5062: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5063: &extract_lastaccess(\%returnhash,$rep);
5064: }
5065: }
5066: }
5067: return %returnhash;
5068: }
5069:
5070: sub extract_lastaccess {
5071: my ($returnhash,$rep) = @_;
5072: if (ref($returnhash) eq 'HASH') {
5073: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5074: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5075: $rep eq '') {
5076: my @pairs=split(/\&/,$rep);
5077: foreach my $item (@pairs) {
5078: my ($key,$value)=split(/\=/,$item,2);
5079: $key = &unescape($key);
5080: next if ($key =~ /^error: 2 /);
5081: $returnhash->{$key} = &thaw_unescape($value);
5082: }
5083: }
5084: }
5085: return;
5086: }
5087:
5088: # ---------------------------------------------------------- DC e-mail
5089:
5090: sub dcmailput {
5091: my ($domain,$msgid,$message,$server)=@_;
5092: my $status = &Apache::lonnet::critical(
5093: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5094: &escape($message),$server);
5095: return $status;
5096: }
5097:
5098: sub dcmaildump {
5099: my ($dom,$startdate,$enddate,$senders) = @_;
5100: my %returnhash=();
5101:
5102: if (defined(&domain($dom,'primary'))) {
5103: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5104: &escape($enddate).':';
5105: my @esc_senders=map { &escape($_)} @$senders;
5106: $cmd.=&escape(join('&',@esc_senders));
5107: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
5108: my ($key,$value) = split(/\=/,$line,2);
5109: if (($key) && ($value)) {
5110: $returnhash{&unescape($key)} = &unescape($value);
5111: }
5112: }
5113: }
5114: return %returnhash;
5115: }
5116: # ---------------------------------------------------------- Domain roles
5117:
5118: sub get_domain_roles {
5119: my ($dom,$roles,$startdate,$enddate)=@_;
5120: if ((!defined($startdate)) || ($startdate eq '')) {
5121: $startdate = '.';
5122: }
5123: if ((!defined($enddate)) || ($enddate eq '')) {
5124: $enddate = '.';
5125: }
5126: my $rolelist;
5127: if (ref($roles) eq 'ARRAY') {
5128: $rolelist = join('&',@{$roles});
5129: }
5130: my %personnel = ();
5131:
5132: my %servers = &get_servers($dom,'library');
5133: foreach my $tryserver (keys(%servers)) {
5134: %{$personnel{$tryserver}}=();
5135: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5136: &escape($startdate).':'.
5137: &escape($enddate).':'.
5138: &escape($rolelist), $tryserver))) {
5139: my ($key,$value) = split(/\=/,$line,2);
5140: if (($key) && ($value)) {
5141: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5142: }
5143: }
5144: }
5145: return %personnel;
5146: }
5147:
5148: sub get_active_domroles {
5149: my ($dom,$roles) = @_;
5150: return () unless (ref($roles) eq 'ARRAY');
5151: my $now = time;
5152: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5153: my %domroles;
5154: foreach my $server (keys(%dompersonnel)) {
5155: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5156: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5157: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5158: }
5159: }
5160: return %domroles;
5161: }
5162:
5163: # ----------------------------------------------------------- Interval timing
5164:
5165: {
5166: # Caches needed for speedup of navmaps
5167: # We don't want to cache this for very long at all (5 seconds at most)
5168: #
5169: # The user for whom we cache
5170: my $cachedkey='';
5171: # The cached times for this user
5172: my %cachedtimes=();
5173: # When this was last done
5174: my $cachedtime='';
5175:
5176: sub load_all_first_access {
5177: my ($uname,$udom,$ignorecache)=@_;
5178: if (($cachedkey eq $uname.':'.$udom) &&
5179: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
5180: (!$ignorecache)) {
5181: return;
5182: }
5183: $cachedtime=time;
5184: $cachedkey=$uname.':'.$udom;
5185: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
5186: }
5187:
5188: sub get_first_access {
5189: my ($type,$argsymb,$argmap,$ignorecache)=@_;
5190: my ($symb,$courseid,$udom,$uname)=&whichuser();
5191: if ($argsymb) { $symb=$argsymb; }
5192: my ($map,$id,$res)=&decode_symb($symb);
5193: if ($argmap) { $map = $argmap; }
5194: if ($type eq 'course') {
5195: $res='course';
5196: } elsif ($type eq 'map') {
5197: $res=&symbread($map);
5198: } else {
5199: $res=$symb;
5200: }
5201: &load_all_first_access($uname,$udom,$ignorecache);
5202: return $cachedtimes{"$courseid\0$res"};
5203: }
5204:
5205: sub set_first_access {
5206: my ($type,$interval)=@_;
5207: my ($symb,$courseid,$udom,$uname)=&whichuser();
5208: my ($map,$id,$res)=&decode_symb($symb);
5209: if ($type eq 'course') {
5210: $res='course';
5211: } elsif ($type eq 'map') {
5212: $res=&symbread($map);
5213: } else {
5214: $res=$symb;
5215: }
5216: $cachedkey='';
5217: my $firstaccess=&get_first_access($type,$symb,$map);
5218: if (!$firstaccess) {
5219: my $start = time;
5220: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5221: $udom,$uname);
5222: if ($putres eq 'ok') {
5223: &put('timerinterval',{"$courseid\0$res"=>$interval},
5224: $udom,$uname);
5225: &appenv(
5226: {
5227: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5228: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5229: }
5230: );
5231: }
5232: return $putres;
5233: }
5234: return 'already_set';
5235: }
5236: }
5237:
5238: # --------------------------------------------- Set Expire Date for Spreadsheet
5239:
5240: sub expirespread {
5241: my ($uname,$udom,$stype,$usymb)=@_;
5242: my $cid=$env{'request.course.id'};
5243: if ($cid) {
5244: my $now=time;
5245: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
5246: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5247: $env{'course.'.$cid.'.num'}.
5248: ':nohist_expirationdates:'.
5249: &escape($key).'='.$now,
5250: $env{'course.'.$cid.'.home'})
5251: }
5252: return 'ok';
5253: }
5254:
5255: # ----------------------------------------------------- Devalidate Spreadsheets
5256:
5257: sub devalidate {
5258: my ($symb,$uname,$udom)=@_;
5259: my $cid=$env{'request.course.id'};
5260: if ($cid) {
5261: # delete the stored spreadsheets for
5262: # - the student level sheet of this user in course's homespace
5263: # - the assessment level sheet for this resource
5264: # for this user in user's homespace
5265: # - current conditional state info
5266: my $key=$uname.':'.$udom.':';
5267: my $status=
5268: &del('nohist_calculatedsheets',
5269: [$key.'studentcalc:'],
5270: $env{'course.'.$cid.'.domain'},
5271: $env{'course.'.$cid.'.num'})
5272: .' '.
5273: &del('nohist_calculatedsheets_'.$cid,
5274: [$key.'assesscalc:'.$symb],$udom,$uname);
5275: unless ($status eq 'ok ok') {
5276: &logthis('Could not devalidate spreadsheet '.
5277: $uname.' at '.$udom.' for '.
5278: $symb.': '.$status);
5279: }
5280: &delenv('user.state.'.$cid);
5281: }
5282: }
5283:
5284: sub get_scalar {
5285: my ($string,$end) = @_;
5286: my $value;
5287: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5288: $value = $1;
5289: } elsif ($$string =~ s/^([^&]*?)&//) {
5290: $value = $1;
5291: }
5292: return &unescape($value);
5293: }
5294:
5295: sub array2str {
5296: my (@array) = @_;
5297: my $result=&arrayref2str(\@array);
5298: $result=~s/^__ARRAY_REF__//;
5299: $result=~s/__END_ARRAY_REF__$//;
5300: return $result;
5301: }
5302:
5303: sub arrayref2str {
5304: my ($arrayref) = @_;
5305: my $result='__ARRAY_REF__';
5306: foreach my $elem (@$arrayref) {
5307: if(ref($elem) eq 'ARRAY') {
5308: $result.=&arrayref2str($elem).'&';
5309: } elsif(ref($elem) eq 'HASH') {
5310: $result.=&hashref2str($elem).'&';
5311: } elsif(ref($elem)) {
5312: #print("Got a ref of ".(ref($elem))." skipping.");
5313: } else {
5314: $result.=&escape($elem).'&';
5315: }
5316: }
5317: $result=~s/\&$//;
5318: $result .= '__END_ARRAY_REF__';
5319: return $result;
5320: }
5321:
5322: sub hash2str {
5323: my (%hash) = @_;
5324: my $result=&hashref2str(\%hash);
5325: $result=~s/^__HASH_REF__//;
5326: $result=~s/__END_HASH_REF__$//;
5327: return $result;
5328: }
5329:
5330: sub hashref2str {
5331: my ($hashref)=@_;
5332: my $result='__HASH_REF__';
5333: foreach my $key (sort(keys(%$hashref))) {
5334: if (ref($key) eq 'ARRAY') {
5335: $result.=&arrayref2str($key).'=';
5336: } elsif (ref($key) eq 'HASH') {
5337: $result.=&hashref2str($key).'=';
5338: } elsif (ref($key)) {
5339: $result.='=';
5340: #print("Got a ref of ".(ref($key))." skipping.");
5341: } else {
5342: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
5343: }
5344:
5345: if(ref($hashref->{$key}) eq 'ARRAY') {
5346: $result.=&arrayref2str($hashref->{$key}).'&';
5347: } elsif(ref($hashref->{$key}) eq 'HASH') {
5348: $result.=&hashref2str($hashref->{$key}).'&';
5349: } elsif(ref($hashref->{$key})) {
5350: $result.='&';
5351: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
5352: } else {
5353: $result.=&escape($hashref->{$key}).'&';
5354: }
5355: }
5356: $result=~s/\&$//;
5357: $result .= '__END_HASH_REF__';
5358: return $result;
5359: }
5360:
5361: sub str2hash {
5362: my ($string)=@_;
5363: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5364: return %$hash;
5365: }
5366:
5367: sub str2hashref {
5368: my ($string) = @_;
5369:
5370: my %hash;
5371:
5372: if($string !~ /^__HASH_REF__/) {
5373: if (! ($string eq '' || !defined($string))) {
5374: $hash{'error'}='Not hash reference';
5375: }
5376: return (\%hash, $string);
5377: }
5378:
5379: $string =~ s/^__HASH_REF__//;
5380:
5381: while($string !~ /^__END_HASH_REF__/) {
5382: #key
5383: my $key='';
5384: if($string =~ /^__HASH_REF__/) {
5385: ($key, $string)=&str2hashref($string);
5386: if(defined($key->{'error'})) {
5387: $hash{'error'}='Bad data';
5388: return (\%hash, $string);
5389: }
5390: } elsif($string =~ /^__ARRAY_REF__/) {
5391: ($key, $string)=&str2arrayref($string);
5392: if($key->[0] eq 'Array reference error') {
5393: $hash{'error'}='Bad data';
5394: return (\%hash, $string);
5395: }
5396: } else {
5397: $string =~ s/^(.*?)=//;
5398: $key=&unescape($1);
5399: }
5400: $string =~ s/^=//;
5401:
5402: #value
5403: my $value='';
5404: if($string =~ /^__HASH_REF__/) {
5405: ($value, $string)=&str2hashref($string);
5406: if(defined($value->{'error'})) {
5407: $hash{'error'}='Bad data';
5408: return (\%hash, $string);
5409: }
5410: } elsif($string =~ /^__ARRAY_REF__/) {
5411: ($value, $string)=&str2arrayref($string);
5412: if($value->[0] eq 'Array reference error') {
5413: $hash{'error'}='Bad data';
5414: return (\%hash, $string);
5415: }
5416: } else {
5417: $value=&get_scalar(\$string,'__END_HASH_REF__');
5418: }
5419: $string =~ s/^&//;
5420:
5421: $hash{$key}=$value;
5422: }
5423:
5424: $string =~ s/^__END_HASH_REF__//;
5425:
5426: return (\%hash, $string);
5427: }
5428:
5429: sub str2array {
5430: my ($string)=@_;
5431: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5432: return @$array;
5433: }
5434:
5435: sub str2arrayref {
5436: my ($string) = @_;
5437: my @array;
5438:
5439: if($string !~ /^__ARRAY_REF__/) {
5440: if (! ($string eq '' || !defined($string))) {
5441: $array[0]='Array reference error';
5442: }
5443: return (\@array, $string);
5444: }
5445:
5446: $string =~ s/^__ARRAY_REF__//;
5447:
5448: while($string !~ /^__END_ARRAY_REF__/) {
5449: my $value='';
5450: if($string =~ /^__HASH_REF__/) {
5451: ($value, $string)=&str2hashref($string);
5452: if(defined($value->{'error'})) {
5453: $array[0] ='Array reference error';
5454: return (\@array, $string);
5455: }
5456: } elsif($string =~ /^__ARRAY_REF__/) {
5457: ($value, $string)=&str2arrayref($string);
5458: if($value->[0] eq 'Array reference error') {
5459: $array[0] ='Array reference error';
5460: return (\@array, $string);
5461: }
5462: } else {
5463: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5464: }
5465: $string =~ s/^&//;
5466:
5467: push(@array, $value);
5468: }
5469:
5470: $string =~ s/^__END_ARRAY_REF__//;
5471:
5472: return (\@array, $string);
5473: }
5474:
5475: # -------------------------------------------------------------------Temp Store
5476:
5477: sub tmpreset {
5478: my ($symb,$namespace,$domain,$stuname) = @_;
5479: if (!$symb) {
5480: $symb=&symbread();
5481: if (!$symb) { $symb= $env{'request.url'}; }
5482: }
5483: $symb=escape($symb);
5484:
5485: if (!$namespace) { $namespace=$env{'request.state'}; }
5486: $namespace=~s/\//\_/g;
5487: $namespace=~s/\W//g;
5488:
5489: if (!$domain) { $domain=$env{'user.domain'}; }
5490: if (!$stuname) { $stuname=$env{'user.name'}; }
5491: if ($domain eq 'public' && $stuname eq 'public') {
5492: $stuname=$ENV{'REMOTE_ADDR'};
5493: }
5494: my $path=LONCAPA::tempdir();
5495: my %hash;
5496: if (tie(%hash,'GDBM_File',
5497: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
5498: &GDBM_WRCREAT(),0640)) {
5499: foreach my $key (keys(%hash)) {
5500: if ($key=~ /:$symb/) {
5501: delete($hash{$key});
5502: }
5503: }
5504: }
5505: }
5506:
5507: sub tmpstore {
5508: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5509:
5510: if (!$symb) {
5511: $symb=&symbread();
5512: if (!$symb) { $symb= $env{'request.url'}; }
5513: }
5514: $symb=escape($symb);
5515:
5516: if (!$namespace) {
5517: # I don't think we would ever want to store this for a course.
5518: # it seems this will only be used if we don't have a course.
5519: #$namespace=$env{'request.course.id'};
5520: #if (!$namespace) {
5521: $namespace=$env{'request.state'};
5522: #}
5523: }
5524: $namespace=~s/\//\_/g;
5525: $namespace=~s/\W//g;
5526: if (!$domain) { $domain=$env{'user.domain'}; }
5527: if (!$stuname) { $stuname=$env{'user.name'}; }
5528: if ($domain eq 'public' && $stuname eq 'public') {
5529: $stuname=$ENV{'REMOTE_ADDR'};
5530: }
5531: my $now=time;
5532: my %hash;
5533: my $path=LONCAPA::tempdir();
5534: if (tie(%hash,'GDBM_File',
5535: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
5536: &GDBM_WRCREAT(),0640)) {
5537: $hash{"version:$symb"}++;
5538: my $version=$hash{"version:$symb"};
5539: my $allkeys='';
5540: foreach my $key (keys(%$storehash)) {
5541: $allkeys.=$key.':';
5542: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
5543: }
5544: $hash{"$version:$symb:timestamp"}=$now;
5545: $allkeys.='timestamp';
5546: $hash{"$version:keys:$symb"}=$allkeys;
5547: if (untie(%hash)) {
5548: return 'ok';
5549: } else {
5550: return "error:$!";
5551: }
5552: } else {
5553: return "error:$!";
5554: }
5555: }
5556:
5557: # -----------------------------------------------------------------Temp Restore
5558:
5559: sub tmprestore {
5560: my ($symb,$namespace,$domain,$stuname) = @_;
5561:
5562: if (!$symb) {
5563: $symb=&symbread();
5564: if (!$symb) { $symb= $env{'request.url'}; }
5565: }
5566: $symb=escape($symb);
5567:
5568: if (!$namespace) { $namespace=$env{'request.state'}; }
5569:
5570: if (!$domain) { $domain=$env{'user.domain'}; }
5571: if (!$stuname) { $stuname=$env{'user.name'}; }
5572: if ($domain eq 'public' && $stuname eq 'public') {
5573: $stuname=$ENV{'REMOTE_ADDR'};
5574: }
5575: my %returnhash;
5576: $namespace=~s/\//\_/g;
5577: $namespace=~s/\W//g;
5578: my %hash;
5579: my $path=LONCAPA::tempdir();
5580: if (tie(%hash,'GDBM_File',
5581: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
5582: &GDBM_READER(),0640)) {
5583: my $version=$hash{"version:$symb"};
5584: $returnhash{'version'}=$version;
5585: my $scope;
5586: for ($scope=1;$scope<=$version;$scope++) {
5587: my $vkeys=$hash{"$scope:keys:$symb"};
5588: my @keys=split(/:/,$vkeys);
5589: my $key;
5590: $returnhash{"$scope:keys"}=$vkeys;
5591: foreach $key (@keys) {
5592: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5593: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5594: }
5595: }
5596: if (!(untie(%hash))) {
5597: return "error:$!";
5598: }
5599: } else {
5600: return "error:$!";
5601: }
5602: return %returnhash;
5603: }
5604:
5605: # ----------------------------------------------------------------------- Store
5606:
5607: sub store {
5608: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
5609: my $home='';
5610:
5611: if ($stuname) { $home=&homeserver($stuname,$domain); }
5612:
5613: $symb=&symbclean($symb);
5614: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
5615:
5616: if (!$domain) { $domain=$env{'user.domain'}; }
5617: if (!$stuname) { $stuname=$env{'user.name'}; }
5618:
5619: &devalidate($symb,$stuname,$domain);
5620:
5621: $symb=escape($symb);
5622: if (!$namespace) {
5623: unless ($namespace=$env{'request.course.id'}) {
5624: return '';
5625: }
5626: }
5627: if (!$home) { $home=$env{'user.home'}; }
5628:
5629: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5630: $$storehash{'host'}=$perlvar{'lonHostID'};
5631:
5632: my $namevalue='';
5633: foreach my $key (keys(%$storehash)) {
5634: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5635: }
5636: $namevalue=~s/\&$//;
5637: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
5638: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
5639: }
5640:
5641: # -------------------------------------------------------------- Critical Store
5642:
5643: sub cstore {
5644: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
5645: my $home='';
5646:
5647: if ($stuname) { $home=&homeserver($stuname,$domain); }
5648:
5649: $symb=&symbclean($symb);
5650: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
5651:
5652: if (!$domain) { $domain=$env{'user.domain'}; }
5653: if (!$stuname) { $stuname=$env{'user.name'}; }
5654:
5655: &devalidate($symb,$stuname,$domain);
5656:
5657: $symb=escape($symb);
5658: if (!$namespace) {
5659: unless ($namespace=$env{'request.course.id'}) {
5660: return '';
5661: }
5662: }
5663: if (!$home) { $home=$env{'user.home'}; }
5664:
5665: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5666: $$storehash{'host'}=$perlvar{'lonHostID'};
5667:
5668: my $namevalue='';
5669: foreach my $key (keys(%$storehash)) {
5670: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5671: }
5672: $namevalue=~s/\&$//;
5673: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
5674: return critical
5675: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
5676: }
5677:
5678: # --------------------------------------------------------------------- Restore
5679:
5680: sub restore {
5681: my ($symb,$namespace,$domain,$stuname) = @_;
5682: my $home='';
5683:
5684: if ($stuname) { $home=&homeserver($stuname,$domain); }
5685:
5686: if (!$symb) {
5687: return if ($namespace eq 'courserequests');
5688: unless ($symb=escape(&symbread())) { return ''; }
5689: } else {
5690: unless ($namespace eq 'courserequests') {
5691: $symb=&escape(&symbclean($symb));
5692: }
5693: }
5694: if (!$namespace) {
5695: unless ($namespace=$env{'request.course.id'}) {
5696: return '';
5697: }
5698: }
5699: if (!$domain) { $domain=$env{'user.domain'}; }
5700: if (!$stuname) { $stuname=$env{'user.name'}; }
5701: if (!$home) { $home=$env{'user.home'}; }
5702: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5703:
5704: my %returnhash=();
5705: foreach my $line (split(/\&/,$answer)) {
5706: my ($name,$value)=split(/\=/,$line);
5707: $returnhash{&unescape($name)}=&thaw_unescape($value);
5708: }
5709: my $version;
5710: for ($version=1;$version<=$returnhash{'version'};$version++) {
5711: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5712: $returnhash{$item}=$returnhash{$version.':'.$item};
5713: }
5714: }
5715: return %returnhash;
5716: }
5717:
5718: # ---------------------------------------------------------- Course Description
5719: #
5720: #
5721:
5722: sub coursedescription {
5723: my ($courseid,$args)=@_;
5724: $courseid=~s/^\///;
5725: $courseid=~s/\_/\//g;
5726: my ($cdomain,$cnum)=split(/\//,$courseid);
5727: my $chome=&homeserver($cnum,$cdomain);
5728: my $normalid=$cdomain.'_'.$cnum;
5729: # need to always cache even if we get errors otherwise we keep
5730: # trying and trying and trying to get the course description.
5731: my %envhash=();
5732: my %returnhash=();
5733:
5734: my $expiretime=600;
5735: if ($env{'request.course.id'} eq $normalid) {
5736: $expiretime=120;
5737: }
5738:
5739: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5740: if (!$args->{'freshen_cache'}
5741: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5742: foreach my $key (keys(%env)) {
5743: next if ($key !~ /^\Q$prefix\E(.*)/);
5744: my ($setting) = $1;
5745: $returnhash{$setting} = $env{$key};
5746: }
5747: return %returnhash;
5748: }
5749:
5750: # get the data again
5751:
5752: if (!$args->{'one_time'}) {
5753: $envhash{'course.'.$normalid.'.last_cache'}=time;
5754: }
5755:
5756: if ($chome ne 'no_host') {
5757: %returnhash=&dump('environment',$cdomain,$cnum);
5758: if (!exists($returnhash{'con_lost'})) {
5759: my $username = $env{'user.name'}; # Defult username
5760: if(defined $args->{'user'}) {
5761: $username = $args->{'user'};
5762: }
5763: $returnhash{'home'}= $chome;
5764: $returnhash{'domain'} = $cdomain;
5765: $returnhash{'num'} = $cnum;
5766: if (!defined($returnhash{'type'})) {
5767: $returnhash{'type'} = 'Course';
5768: }
5769: while (my ($name,$value) = each %returnhash) {
5770: $envhash{'course.'.$normalid.'.'.$name}=$value;
5771: }
5772: $returnhash{'url'}=&clutter($returnhash{'url'});
5773: $returnhash{'fn'}=LONCAPA::tempdir() .
5774: $username.'_'.$cdomain.'_'.$cnum;
5775: $envhash{'course.'.$normalid.'.home'}=$chome;
5776: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5777: $envhash{'course.'.$normalid.'.num'}=$cnum;
5778: }
5779: }
5780: if (!$args->{'one_time'}) {
5781: &appenv(\%envhash);
5782: }
5783: return %returnhash;
5784: }
5785:
5786: sub update_released_required {
5787: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5788: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5789: $cid = $env{'request.course.id'};
5790: $cdom = $env{'course.'.$cid.'.domain'};
5791: $cnum = $env{'course.'.$cid.'.num'};
5792: $chome = $env{'course.'.$cid.'.home'};
5793: }
5794: if ($needsrelease) {
5795: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5796: my $needsupdate;
5797: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5798: $needsupdate = 1;
5799: } else {
5800: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5801: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5802: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5803: $needsupdate = 1;
5804: }
5805: }
5806: if ($needsupdate) {
5807: my %needshash = (
5808: 'internal.releaserequired' => $needsrelease,
5809: );
5810: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5811: if ($putresult eq 'ok') {
5812: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5813: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5814: if (ref($crsinfo{$cid}) eq 'HASH') {
5815: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5816: &courseidput($cdom,\%crsinfo,$chome,'notime');
5817: }
5818: }
5819: }
5820: }
5821: return;
5822: }
5823:
5824: # -------------------------------------------------See if a user is privileged
5825:
5826: sub privileged {
5827: my ($username,$domain,$possdomains,$possroles)=@_;
5828: my $now = time;
5829: my $roles;
5830: if (ref($possroles) eq 'ARRAY') {
5831: $roles = $possroles;
5832: } else {
5833: $roles = ['dc','su'];
5834: }
5835: if (ref($possdomains) eq 'ARRAY') {
5836: my %privileged = &privileged_by_domain($possdomains,$roles);
5837: foreach my $dom (@{$possdomains}) {
5838: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5839: (ref($privileged{$dom}) eq 'HASH')) {
5840: foreach my $role (@{$roles}) {
5841: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5842: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5843: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5844: return 1 unless (($end && $end < $now) ||
5845: ($start && $start > $now));
5846: }
5847: }
5848: }
5849: }
5850: }
5851: } else {
5852: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5853: my $now = time;
5854:
5855: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
5856: my ($trole, $tend, $tstart) = split(/_/, $role);
5857: if (grep(/^\Q$trole\E$/,@{$roles})) {
5858: return 1 unless ($tend && $tend < $now)
5859: or ($tstart && $tstart > $now);
5860: }
5861: }
5862: }
5863: return 0;
5864: }
5865:
5866: sub privileged_by_domain {
5867: my ($domains,$roles) = @_;
5868: my %privileged = ();
5869: my $cachetime = 60*60*24;
5870: my $now = time;
5871: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5872: return %privileged;
5873: }
5874: foreach my $dom (@{$domains}) {
5875: next if (ref($privileged{$dom}) eq 'HASH');
5876: my $needroles;
5877: foreach my $role (@{$roles}) {
5878: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5879: if (defined($cached)) {
5880: if (ref($result) eq 'HASH') {
5881: $privileged{$dom}{$role} = $result;
5882: }
5883: } else {
5884: $needroles = 1;
5885: }
5886: }
5887: if ($needroles) {
5888: my %dompersonnel = &get_domain_roles($dom,$roles);
5889: $privileged{$dom} = {};
5890: foreach my $server (keys(%dompersonnel)) {
5891: if (ref($dompersonnel{$server}) eq 'HASH') {
5892: foreach my $item (keys(%{$dompersonnel{$server}})) {
5893: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5894: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5895: next if ($end && $end < $now);
5896: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5897: $dompersonnel{$server}{$item};
5898: }
5899: }
5900: }
5901: if (ref($privileged{$dom}) eq 'HASH') {
5902: foreach my $role (@{$roles}) {
5903: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5904: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5905: } else {
5906: my %hash = ();
5907: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5908: }
5909: }
5910: }
5911: }
5912: }
5913: return %privileged;
5914: }
5915:
5916: # -------------------------------------------------------- Get user privileges
5917:
5918: sub rolesinit {
5919: my ($domain, $username) = @_;
5920: my %userroles = ('user.login.time' => time);
5921: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5922:
5923: # firstaccess and timerinterval are related to timed maps/resources.
5924: # also, blocking can be triggered by an activating timer
5925: # it's saved in the user's %env.
5926: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5927: my %timerinterval = &dump('timerinterval', $domain, $username);
5928: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5929: %timerintchk, %timerintenv);
5930:
5931: foreach my $key (keys(%firstaccess)) {
5932: my ($cid, $rest) = split(/\0/, $key);
5933: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5934: }
5935:
5936: foreach my $key (keys(%timerinterval)) {
5937: my ($cid,$rest) = split(/\0/,$key);
5938: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5939: }
5940:
5941: my %allroles=();
5942: my %allgroups=();
5943:
5944: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
5945: my $role = $rolesdump{$area};
5946: $area =~ s/\_\w\w$//;
5947:
5948: my ($trole, $tend, $tstart, $group_privs);
5949:
5950: if ($role =~ /^cr/) {
5951: # Custom role, defined by a user
5952: # e.g., user.role.cr/msu/smith/mynewrole
5953: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5954: $trole = $1;
5955: ($tend, $tstart) = split('_', $2);
5956: } else {
5957: $trole = $role;
5958: }
5959: } elsif ($role =~ m|^gr/|) {
5960: # Role of member in a group, defined within a course/community
5961: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5962: ($trole, $tend, $tstart) = split(/_/, $role);
5963: next if $tstart eq '-1';
5964: ($trole, $group_privs) = split(/\//, $trole);
5965: $group_privs = &unescape($group_privs);
5966: } else {
5967: # Just a normal role, defined in roles.tab
5968: ($trole, $tend, $tstart) = split(/_/,$role);
5969: }
5970:
5971: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5972: $username);
5973: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5974:
5975: # role expired or not available yet?
5976: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5977: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5978:
5979: next if $area eq '' or $trole eq '';
5980:
5981: my $spec = "$trole.$area";
5982: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5983:
5984: if ($trole =~ /^cr\//) {
5985: # Custom role, defined by a user
5986: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5987: } elsif ($trole eq 'gr') {
5988: # Role of a member in a group, defined within a course/community
5989: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5990: next;
5991: } else {
5992: # Normal role, defined in roles.tab
5993: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5994: }
5995:
5996: my $cid = $tdomain.'_'.$trest;
5997: unless ($firstaccchk{$cid}) {
5998: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5999: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6000: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6001: $coursetimerstarts{$cid}{$item};
6002: }
6003: }
6004: $firstaccchk{$cid} = 1;
6005: }
6006: unless ($timerintchk{$cid}) {
6007: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6008: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6009: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6010: $coursetimerintervals{$cid}{$item};
6011: }
6012: }
6013: $timerintchk{$cid} = 1;
6014: }
6015: }
6016:
6017: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6018: \%allroles, \%allgroups);
6019: $env{'user.adv'} = $userroles{'user.adv'};
6020: $env{'user.rar'} = $userroles{'user.rar'};
6021:
6022: return (\%userroles,\%firstaccenv,\%timerintenv);
6023: }
6024:
6025: sub set_arearole {
6026: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6027: unless ($nolog) {
6028: # log the associated role with the area
6029: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6030: }
6031: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
6032: }
6033:
6034: sub custom_roleprivs {
6035: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6036: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
6037: my $homsvr = &homeserver($rauthor,$rdomain);
6038: if (&hostname($homsvr) ne '') {
6039: my ($rdummy,$roledef)=
6040: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6041: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6042: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6043: if (defined($syspriv)) {
6044: if ($trest =~ /^$match_community$/) {
6045: $syspriv =~ s/bre\&S//;
6046: }
6047: $$allroles{'cm./'}.=':'.$syspriv;
6048: $$allroles{$spec.'./'}.=':'.$syspriv;
6049: }
6050: if ($tdomain ne '') {
6051: if (defined($dompriv)) {
6052: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6053: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6054: }
6055: if (($trest ne '') && (defined($coursepriv))) {
6056: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6057: my $rolename = $1;
6058: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6059: }
6060: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6061: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6062: }
6063: }
6064: }
6065: }
6066: }
6067:
6068: sub course_adhocrole_privs {
6069: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6070: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6071: if ($overrides{"internal.adhocpriv.$rolename"}) {
6072: my (%currprivs,%storeprivs);
6073: foreach my $item (split(/:/,$coursepriv)) {
6074: my ($priv,$restrict) = split(/\&/,$item);
6075: $currprivs{$priv} = $restrict;
6076: }
6077: my (%possadd,%possremove,%full);
6078: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6079: my ($priv,$restrict)=split(/\&/,$item);
6080: $full{$priv} = $restrict;
6081: }
6082: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6083: next if ($item eq '');
6084: my ($rule,$rest) = split(/=/,$item);
6085: next unless (($rule eq 'off') || ($rule eq 'on'));
6086: foreach my $priv (split(/:/,$rest)) {
6087: if ($priv ne '') {
6088: if ($rule eq 'off') {
6089: $possremove{$priv} = 1;
6090: } else {
6091: $possadd{$priv} = 1;
6092: }
6093: }
6094: }
6095: }
6096: foreach my $priv (sort(keys(%full))) {
6097: if (exists($currprivs{$priv})) {
6098: unless (exists($possremove{$priv})) {
6099: $storeprivs{$priv} = $currprivs{$priv};
6100: }
6101: } elsif (exists($possadd{$priv})) {
6102: $storeprivs{$priv} = $full{$priv};
6103: }
6104: }
6105: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6106: }
6107: return $coursepriv;
6108: }
6109:
6110: sub group_roleprivs {
6111: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6112: my $access = 1;
6113: my $now = time;
6114: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6115: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6116: if ($access) {
6117: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
6118: $$allgroups{$course}{$group} .=':'.$group_privs;
6119: }
6120: }
6121:
6122: sub standard_roleprivs {
6123: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6124: if (defined($pr{$trole.':s'})) {
6125: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6126: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6127: }
6128: if ($tdomain ne '') {
6129: if (defined($pr{$trole.':d'})) {
6130: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6131: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6132: }
6133: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6134: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6135: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6136: }
6137: }
6138: }
6139:
6140: sub set_userprivs {
6141: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
6142: my $author=0;
6143: my $adv=0;
6144: my $rar=0;
6145: my %grouproles = ();
6146: if (keys(%{$allgroups}) > 0) {
6147: my @groupkeys;
6148: foreach my $role (keys(%{$allroles})) {
6149: push(@groupkeys,$role);
6150: }
6151: if (ref($groups_roles) eq 'HASH') {
6152: foreach my $key (keys(%{$groups_roles})) {
6153: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6154: push(@groupkeys,$key);
6155: }
6156: }
6157: }
6158: if (@groupkeys > 0) {
6159: foreach my $role (@groupkeys) {
6160: my ($trole,$area,$sec,$extendedarea);
6161: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6162: $trole = $1;
6163: $area = $2;
6164: $sec = $3;
6165: $extendedarea = $area.$sec;
6166: if (exists($$allgroups{$area})) {
6167: foreach my $group (keys(%{$$allgroups{$area}})) {
6168: my $spec = $trole.'.'.$extendedarea;
6169: $grouproles{$spec.'.'.$area.'/'.$group} =
6170: $$allgroups{$area}{$group};
6171: }
6172: }
6173: }
6174: }
6175: }
6176: }
6177: foreach my $group (keys(%grouproles)) {
6178: $$allroles{$group} = $grouproles{$group};
6179: }
6180: foreach my $role (keys(%{$allroles})) {
6181: my %thesepriv;
6182: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
6183: foreach my $item (split(/:/,$$allroles{$role})) {
6184: if ($item ne '') {
6185: my ($privilege,$restrictions)=split(/&/,$item);
6186: if ($restrictions eq '') {
6187: $thesepriv{$privilege}='F';
6188: } elsif ($thesepriv{$privilege} ne 'F') {
6189: $thesepriv{$privilege}.=$restrictions;
6190: }
6191: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
6192: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
6193: }
6194: }
6195: my $thesestr='';
6196: foreach my $priv (sort(keys(%thesepriv))) {
6197: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6198: }
6199: $userroles->{'user.priv.'.$role} = $thesestr;
6200: }
6201: return ($author,$adv,$rar);
6202: }
6203:
6204: sub role_status {
6205: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
6206: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
6207: my ($one,$two) = split(m{\./},$rolekey,2);
6208: (undef,undef,$$role) = split(/\./,$one,3);
6209: unless (!defined($$role) || $$role eq '') {
6210: $$where = '/'.$two;
6211: $$trolecode=$$role.'.'.$$where;
6212: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6213: $$tstatus='is';
6214: if ($$tstart && $$tstart>$update) {
6215: $$tstatus='future';
6216: if ($$tstart<$now) {
6217: if ($$tstart && $$tstart>$refresh) {
6218: if (($$where ne '') && ($$role ne '')) {
6219: my (%allroles,%allgroups,$group_privs,
6220: %groups_roles,@rolecodes);
6221: my %userroles = (
6222: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6223: );
6224: @rolecodes = ('cm');
6225: my $spec=$$role.'.'.$$where;
6226: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6227: if ($$role =~ /^cr\//) {
6228: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
6229: push(@rolecodes,'cr');
6230: } elsif ($$role eq 'gr') {
6231: push(@rolecodes,$$role);
6232: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6233: $env{'user.name'});
6234: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
6235: (undef,my $group_privs) = split(/\//,$trole);
6236: $group_privs = &unescape($group_privs);
6237: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
6238: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
6239: &get_groups_roles($tdomain,$trest,
6240: \%course_roles,\@rolecodes,
6241: \%groups_roles);
6242: } else {
6243: push(@rolecodes,$$role);
6244: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6245: }
6246: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6247: \%groups_roles);
6248: &appenv(\%userroles,\@rolecodes);
6249: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
6250: }
6251: }
6252: $$tstatus = 'is';
6253: }
6254: }
6255: if ($$tend) {
6256: if ($$tend<$update) {
6257: $$tstatus='expired';
6258: } elsif ($$tend<$now) {
6259: $$tstatus='will_not';
6260: }
6261: }
6262: }
6263: }
6264: }
6265:
6266: sub get_groups_roles {
6267: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6268: return unless((ref($cdom_courseroles) eq 'HASH') &&
6269: (ref($rolecodes) eq 'ARRAY') &&
6270: (ref($groups_roles) eq 'HASH'));
6271: if (keys(%{$cdom_courseroles}) > 0) {
6272: my ($cnum) = ($rest =~ /^($match_courseid)/);
6273: if ($cdom ne '' && $cnum ne '') {
6274: foreach my $key (keys(%{$cdom_courseroles})) {
6275: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6276: my $crsrole = $1;
6277: my $crssec = $2;
6278: if ($crsrole =~ /^cr/) {
6279: unless (grep(/^cr$/,@{$rolecodes})) {
6280: push(@{$rolecodes},'cr');
6281: }
6282: } else {
6283: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6284: push(@{$rolecodes},$crsrole);
6285: }
6286: }
6287: my $rolekey = "$crsrole./$cdom/$cnum";
6288: if ($crssec ne '') {
6289: $rolekey .= "/$crssec";
6290: }
6291: $rolekey .= './';
6292: $groups_roles->{$rolekey} = $rolecodes;
6293: }
6294: }
6295: }
6296: }
6297: return;
6298: }
6299:
6300: sub delete_env_groupprivs {
6301: my ($where,$courseroles,$possroles) = @_;
6302: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6303: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6304: unless (ref($courseroles->{$udom}) eq 'HASH') {
6305: %{$courseroles->{$udom}} =
6306: &get_my_roles('','','userroles',['active'],
6307: $possroles,[$udom],1);
6308: }
6309: if (ref($courseroles->{$udom}) eq 'HASH') {
6310: foreach my $item (keys(%{$courseroles->{$udom}})) {
6311: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6312: my $area = '/'.$cdom.'/'.$cnum;
6313: my $privkey = "user.priv.$crsrole.$area";
6314: if ($crssec ne '') {
6315: $privkey .= '/'.$crssec;
6316: }
6317: $privkey .= ".$area/$group";
6318: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6319: }
6320: }
6321: return;
6322: }
6323:
6324: sub check_adhoc_privs {
6325: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
6326: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
6327: if ($sec) {
6328: $cckey .= '/'.$sec;
6329: }
6330: my $setprivs;
6331: if ($env{$cckey}) {
6332: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
6333: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
6334: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
6335: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
6336: $setprivs = 1;
6337: }
6338: } else {
6339: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
6340: $setprivs = 1;
6341: }
6342: return $setprivs;
6343: }
6344:
6345: sub set_adhoc_privileges {
6346: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
6347: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
6348: my $area = '/'.$dcdom.'/'.$pickedcourse;
6349: if ($sec ne '') {
6350: $area .= '/'.$sec;
6351: }
6352: my $spec = $role.'.'.$area;
6353: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
6354: $env{'user.name'},1);
6355: my %rolehash = ();
6356: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6357: my $rolename = $1;
6358: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
6359: my %domdef = &get_domain_defaults($dcdom);
6360: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6361: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6362: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6363: }
6364: }
6365: } else {
6366: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6367: }
6368: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
6369: &appenv(\%userroles,[$role,'cm']);
6370: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
6371: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
6372: &appenv( {'request.role' => $spec,
6373: 'request.role.domain' => $dcdom,
6374: 'request.course.sec' => $sec,
6375: }
6376: );
6377: my $tadv=0;
6378: if (&allowed('adv') eq 'F') { $tadv=1; }
6379: &appenv({'request.role.adv' => $tadv});
6380: }
6381: }
6382:
6383: # --------------------------------------------------------------- get interface
6384:
6385: sub get {
6386: my ($namespace,$storearr,$udomain,$uname)=@_;
6387: my $items='';
6388: foreach my $item (@$storearr) {
6389: $items.=&escape($item).'&';
6390: }
6391: $items=~s/\&$//;
6392: if (!$udomain) { $udomain=$env{'user.domain'}; }
6393: if (!$uname) { $uname=$env{'user.name'}; }
6394: my $uhome=&homeserver($uname,$udomain);
6395:
6396: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
6397: my @pairs=split(/\&/,$rep);
6398: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6399: return @pairs;
6400: }
6401: my %returnhash=();
6402: my $i=0;
6403: foreach my $item (@$storearr) {
6404: $returnhash{$item}=&thaw_unescape($pairs[$i]);
6405: $i++;
6406: }
6407: return %returnhash;
6408: }
6409:
6410: # --------------------------------------------------------------- del interface
6411:
6412: sub del {
6413: my ($namespace,$storearr,$udomain,$uname)=@_;
6414: my $items='';
6415: foreach my $item (@$storearr) {
6416: $items.=&escape($item).'&';
6417: }
6418:
6419: $items=~s/\&$//;
6420: if (!$udomain) { $udomain=$env{'user.domain'}; }
6421: if (!$uname) { $uname=$env{'user.name'}; }
6422: my $uhome=&homeserver($uname,$udomain);
6423: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
6424: }
6425:
6426: # -------------------------------------------------------------- dump interface
6427:
6428: sub unserialize {
6429: my ($rep, $escapedkeys) = @_;
6430:
6431: return {} if $rep =~ /^error/;
6432:
6433: my %returnhash=();
6434: foreach my $item (split(/\&/,$rep)) {
6435: my ($key, $value) = split(/=/, $item, 2);
6436: $key = unescape($key) unless $escapedkeys;
6437: next if $key =~ /^error: 2 /;
6438: $returnhash{$key} = &thaw_unescape($value);
6439: }
6440: #return %returnhash;
6441: return \%returnhash;
6442: }
6443:
6444: # see Lond::dump_with_regexp
6445: # if $escapedkeys hash keys won't get unescaped.
6446: sub dump {
6447: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
6448: if (!$udomain) { $udomain=$env{'user.domain'}; }
6449: if (!$uname) { $uname=$env{'user.name'}; }
6450: my $uhome=&homeserver($uname,$udomain);
6451:
6452: if ($regexp) {
6453: $regexp=&escape($regexp);
6454: } else {
6455: $regexp='.';
6456: }
6457: if (grep { $_ eq $uhome } current_machine_ids()) {
6458: # user is hosted on this machine
6459: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
6460: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
6461: return %{unserialize($reply, $escapedkeys)};
6462: }
6463: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
6464: my @pairs=split(/\&/,$rep);
6465: my %returnhash=();
6466: if (!($rep =~ /^error/ )) {
6467: foreach my $item (@pairs) {
6468: my ($key,$value)=split(/=/,$item,2);
6469: $key = unescape($key) unless $escapedkeys;
6470: #$key = &unescape($key);
6471: next if ($key =~ /^error: 2 /);
6472: $returnhash{$key}=&thaw_unescape($value);
6473: }
6474: }
6475: return %returnhash;
6476: }
6477:
6478:
6479: # --------------------------------------------------------- dumpstore interface
6480:
6481: sub dumpstore {
6482: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
6483: # same as dump but keys must be escaped. They may contain colon separated
6484: # lists of values that may themself contain colons (e.g. symbs).
6485: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
6486: }
6487:
6488: # -------------------------------------------------------------- keys interface
6489:
6490: sub getkeys {
6491: my ($namespace,$udomain,$uname)=@_;
6492: if (!$udomain) { $udomain=$env{'user.domain'}; }
6493: if (!$uname) { $uname=$env{'user.name'}; }
6494: my $uhome=&homeserver($uname,$udomain);
6495: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6496: my @keyarray=();
6497: foreach my $key (split(/\&/,$rep)) {
6498: next if ($key =~ /^error: 2 /);
6499: push(@keyarray,&unescape($key));
6500: }
6501: return @keyarray;
6502: }
6503:
6504: # --------------------------------------------------------------- currentdump
6505: sub currentdump {
6506: my ($courseid,$sdom,$sname)=@_;
6507: $courseid = $env{'request.course.id'} if (! defined($courseid));
6508: $sdom = $env{'user.domain'} if (! defined($sdom));
6509: $sname = $env{'user.name'} if (! defined($sname));
6510: my $uhome = &homeserver($sname,$sdom);
6511: my $rep;
6512:
6513: if (grep { $_ eq $uhome } current_machine_ids()) {
6514: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6515: $courseid)));
6516: } else {
6517: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6518: }
6519:
6520: return if ($rep =~ /^(error:|no_such_host)/);
6521: #
6522: my %returnhash=();
6523: #
6524: if ($rep eq 'unknown_cmd') {
6525: # an old lond will not know currentdump
6526: # Do a dump and make it look like a currentdump
6527: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
6528: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6529: my %hash = @tmp;
6530: @tmp=();
6531: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
6532: } else {
6533: my @pairs=split(/\&/,$rep);
6534: foreach my $pair (@pairs) {
6535: my ($key,$value)=split(/=/,$pair,2);
6536: my ($symb,$param) = split(/:/,$key);
6537: $returnhash{&unescape($symb)}->{&unescape($param)} =
6538: &thaw_unescape($value);
6539: }
6540: }
6541: return %returnhash;
6542: }
6543:
6544: sub convert_dump_to_currentdump{
6545: my %hash = %{shift()};
6546: my %returnhash;
6547: # Code ripped from lond, essentially. The only difference
6548: # here is the unescaping done by lonnet::dump(). Conceivably
6549: # we might run in to problems with parameter names =~ /^v\./
6550: while (my ($key,$value) = each(%hash)) {
6551: my ($v,$symb,$param) = split(/:/,$key);
6552: $symb = &unescape($symb);
6553: $param = &unescape($param);
6554: next if ($v eq 'version' || $symb eq 'keys');
6555: next if (exists($returnhash{$symb}) &&
6556: exists($returnhash{$symb}->{$param}) &&
6557: $returnhash{$symb}->{'v.'.$param} > $v);
6558: $returnhash{$symb}->{$param}=$value;
6559: $returnhash{$symb}->{'v.'.$param}=$v;
6560: }
6561: #
6562: # Remove all of the keys in the hashes which keep track of
6563: # the version of the parameter.
6564: while (my ($symb,$param_hash) = each(%returnhash)) {
6565: # use a foreach because we are going to delete from the hash.
6566: foreach my $key (keys(%$param_hash)) {
6567: delete($param_hash->{$key}) if ($key =~ /^v\./);
6568: }
6569: }
6570: return \%returnhash;
6571: }
6572:
6573: # ------------------------------------------------------ critical inc interface
6574:
6575: sub cinc {
6576: return &inc(@_,'critical');
6577: }
6578:
6579: # --------------------------------------------------------------- inc interface
6580:
6581: sub inc {
6582: my ($namespace,$store,$udomain,$uname,$critical) = @_;
6583: if (!$udomain) { $udomain=$env{'user.domain'}; }
6584: if (!$uname) { $uname=$env{'user.name'}; }
6585: my $uhome=&homeserver($uname,$udomain);
6586: my $items='';
6587: if (! ref($store)) {
6588: # got a single value, so use that instead
6589: $items = &escape($store).'=&';
6590: } elsif (ref($store) eq 'SCALAR') {
6591: $items = &escape($$store).'=&';
6592: } elsif (ref($store) eq 'ARRAY') {
6593: $items = join('=&',map {&escape($_);} @{$store});
6594: } elsif (ref($store) eq 'HASH') {
6595: while (my($key,$value) = each(%{$store})) {
6596: $items.= &escape($key).'='.&escape($value).'&';
6597: }
6598: }
6599: $items=~s/\&$//;
6600: if ($critical) {
6601: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
6602: } else {
6603: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
6604: }
6605: }
6606:
6607: # --------------------------------------------------------------- put interface
6608:
6609: sub put {
6610: my ($namespace,$storehash,$udomain,$uname)=@_;
6611: if (!$udomain) { $udomain=$env{'user.domain'}; }
6612: if (!$uname) { $uname=$env{'user.name'}; }
6613: my $uhome=&homeserver($uname,$udomain);
6614: my $items='';
6615: foreach my $item (keys(%$storehash)) {
6616: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
6617: }
6618: $items=~s/\&$//;
6619: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
6620: }
6621:
6622: # ------------------------------------------------------------ newput interface
6623:
6624: sub newput {
6625: my ($namespace,$storehash,$udomain,$uname)=@_;
6626: if (!$udomain) { $udomain=$env{'user.domain'}; }
6627: if (!$uname) { $uname=$env{'user.name'}; }
6628: my $uhome=&homeserver($uname,$udomain);
6629: my $items='';
6630: foreach my $key (keys(%$storehash)) {
6631: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6632: }
6633: $items=~s/\&$//;
6634: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
6635: }
6636:
6637: # --------------------------------------------------------- putstore interface
6638:
6639: sub putstore {
6640: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
6641: if (!$udomain) { $udomain=$env{'user.domain'}; }
6642: if (!$uname) { $uname=$env{'user.name'}; }
6643: my $uhome=&homeserver($uname,$udomain);
6644: my $items='';
6645: foreach my $key (keys(%$storehash)) {
6646: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6647: }
6648: $items=~s/\&$//;
6649: my $esc_symb=&escape($symb);
6650: my $esc_v=&escape($version);
6651: my $reply =
6652: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
6653: $uhome);
6654: if (($tolog) && ($reply eq 'ok')) {
6655: my $namevalue='';
6656: foreach my $key (keys(%{$storehash})) {
6657: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6658: }
6659: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
6660: '&host='.&escape($perlvar{'lonHostID'}).
6661: '&version='.$esc_v.
6662: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
6663: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
6664: }
6665: if ($reply eq 'unknown_cmd') {
6666: # gfall back to way things use to be done
6667: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
6668: $uname);
6669: }
6670: return $reply;
6671: }
6672:
6673: sub old_putstore {
6674: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
6675: if (!$udomain) { $udomain=$env{'user.domain'}; }
6676: if (!$uname) { $uname=$env{'user.name'}; }
6677: my $uhome=&homeserver($uname,$udomain);
6678: my %newstorehash;
6679: foreach my $item (keys(%$storehash)) {
6680: my $key = $version.':'.&escape($symb).':'.$item;
6681: $newstorehash{$key} = $storehash->{$item};
6682: }
6683: my $items='';
6684: my %allitems = ();
6685: foreach my $item (keys(%newstorehash)) {
6686: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
6687: my $key = $1.':keys:'.$2;
6688: $allitems{$key} .= $3.':';
6689: }
6690: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
6691: }
6692: foreach my $item (keys(%allitems)) {
6693: $allitems{$item} =~ s/\:$//;
6694: $items.= $item.'='.$allitems{$item}.'&';
6695: }
6696: $items=~s/\&$//;
6697: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
6698: }
6699:
6700: # ------------------------------------------------------ critical put interface
6701:
6702: sub cput {
6703: my ($namespace,$storehash,$udomain,$uname)=@_;
6704: if (!$udomain) { $udomain=$env{'user.domain'}; }
6705: if (!$uname) { $uname=$env{'user.name'}; }
6706: my $uhome=&homeserver($uname,$udomain);
6707: my $items='';
6708: foreach my $item (keys(%$storehash)) {
6709: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
6710: }
6711: $items=~s/\&$//;
6712: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
6713: }
6714:
6715: # -------------------------------------------------------------- eget interface
6716:
6717: sub eget {
6718: my ($namespace,$storearr,$udomain,$uname)=@_;
6719: my $items='';
6720: foreach my $item (@$storearr) {
6721: $items.=&escape($item).'&';
6722: }
6723: $items=~s/\&$//;
6724: if (!$udomain) { $udomain=$env{'user.domain'}; }
6725: if (!$uname) { $uname=$env{'user.name'}; }
6726: my $uhome=&homeserver($uname,$udomain);
6727: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
6728: my @pairs=split(/\&/,$rep);
6729: my %returnhash=();
6730: my $i=0;
6731: foreach my $item (@$storearr) {
6732: $returnhash{$item}=&thaw_unescape($pairs[$i]);
6733: $i++;
6734: }
6735: return %returnhash;
6736: }
6737:
6738: # ------------------------------------------------------------ tmpput interface
6739: sub tmpput {
6740: my ($storehash,$server,$context)=@_;
6741: my $items='';
6742: foreach my $item (keys(%$storehash)) {
6743: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
6744: }
6745: $items=~s/\&$//;
6746: if (defined($context)) {
6747: $items .= ':'.&escape($context);
6748: }
6749: return &reply("tmpput:$items",$server);
6750: }
6751:
6752: # ------------------------------------------------------------ tmpget interface
6753: sub tmpget {
6754: my ($token,$server)=@_;
6755: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6756: my $rep=&reply("tmpget:$token",$server);
6757: my %returnhash;
6758: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
6759: return %returnhash;
6760: }
6761: foreach my $item (split(/\&/,$rep)) {
6762: my ($key,$value)=split(/=/,$item);
6763: $returnhash{&unescape($key)}=&thaw_unescape($value);
6764: }
6765: return %returnhash;
6766: }
6767:
6768: # ------------------------------------------------------------ tmpdel interface
6769: sub tmpdel {
6770: my ($token,$server)=@_;
6771: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6772: return &reply("tmpdel:$token",$server);
6773: }
6774:
6775: # ------------------------------------------------------------ get_timebased_id
6776:
6777: sub get_timebased_id {
6778: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6779: $maxtries) = @_;
6780: my ($newid,$error,$dellock);
6781: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6782: return ('','ok','invalid call to get suffix');
6783: }
6784:
6785: # set defaults for any optional args for which values were not supplied
6786: if ($who eq '') {
6787: $who = $env{'user.name'}.':'.$env{'user.domain'};
6788: }
6789: if (!$locktries) {
6790: $locktries = 3;
6791: }
6792: if (!$maxtries) {
6793: $maxtries = 10;
6794: }
6795:
6796: if (($cdom eq '') || ($cnum eq '')) {
6797: if ($env{'request.course.id'}) {
6798: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6799: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6800: }
6801: if (($cdom eq '') || ($cnum eq '')) {
6802: return ('','ok','call to get suffix not in course context');
6803: }
6804: }
6805:
6806: # construct locking item
6807: my $lockhash = {
6808: $prefix."\0".'locked_'.$keyid => $who,
6809: };
6810: my $tries = 0;
6811:
6812: # attempt to get lock on nohist_$namespace file
6813: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6814: while (($gotlock ne 'ok') && $tries <$locktries) {
6815: $tries ++;
6816: sleep 1;
6817: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6818: }
6819:
6820: # attempt to get unique identifier, based on current timestamp
6821: if ($gotlock eq 'ok') {
6822: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6823: my $id = time;
6824: $newid = $id;
6825: if ($idtype eq 'addcode') {
6826: $newid .= &sixnum_code();
6827: }
6828: my $idtries = 0;
6829: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6830: if ($idtype eq 'concat') {
6831: $newid = $id.$idtries;
6832: } elsif ($idtype eq 'addcode') {
6833: $newid = $newid.&sixnum_code();
6834: } else {
6835: $newid ++;
6836: }
6837: $idtries ++;
6838: }
6839: if (!exists($inuse{$prefix."\0".$newid})) {
6840: my %new_item = (
6841: $prefix."\0".$newid => $who,
6842: );
6843: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6844: $cdom,$cnum);
6845: if ($putresult ne 'ok') {
6846: undef($newid);
6847: $error = 'error saving new item: '.$putresult;
6848: }
6849: } else {
6850: undef($newid);
6851: $error = ('error: no unique suffix available for the new item ');
6852: }
6853: # remove lock
6854: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6855: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6856: } else {
6857: $error = "error: could not obtain lockfile\n";
6858: $dellock = 'ok';
6859: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6860: $dellock = 'nolock';
6861: }
6862: }
6863: return ($newid,$dellock,$error);
6864: }
6865:
6866: sub sixnum_code {
6867: my $code;
6868: for (0..6) {
6869: $code .= int( rand(9) );
6870: }
6871: return $code;
6872: }
6873:
6874: # -------------------------------------------------- portfolio access checking
6875:
6876: sub portfolio_access {
6877: my ($requrl,$clientip) = @_;
6878: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
6879: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
6880: if ($result) {
6881: my %setters;
6882: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6883: my ($startblock,$endblock) =
6884: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6885: if ($startblock && $endblock) {
6886: return 'B';
6887: }
6888: } else {
6889: my ($startblock,$endblock) =
6890: &Apache::loncommon::blockcheck(\%setters,'port');
6891: if ($startblock && $endblock) {
6892: return 'B';
6893: }
6894: }
6895: }
6896: if ($result eq 'ok') {
6897: return 'F';
6898: } elsif ($result =~ /^[^:]+:guest_/) {
6899: return 'A';
6900: }
6901: return '';
6902: }
6903:
6904: sub get_portfolio_access {
6905: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
6906:
6907: if (!ref($access_hash)) {
6908: my $current_perms = &get_portfile_permissions($udom,$unum);
6909: my %access_controls = &get_access_controls($current_perms,$group,
6910: $file_name);
6911: $access_hash = $access_controls{$file_name};
6912: }
6913:
6914: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
6915: my $now = time;
6916: if (ref($access_hash) eq 'HASH') {
6917: foreach my $key (keys(%{$access_hash})) {
6918: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6919: if ($start > $now) {
6920: next;
6921: }
6922: if ($end && $end<$now) {
6923: next;
6924: }
6925: if ($scope eq 'public') {
6926: $public = $key;
6927: last;
6928: } elsif ($scope eq 'guest') {
6929: $guest = $key;
6930: } elsif ($scope eq 'domains') {
6931: push(@domains,$key);
6932: } elsif ($scope eq 'users') {
6933: push(@users,$key);
6934: } elsif ($scope eq 'course') {
6935: push(@courses,$key);
6936: } elsif ($scope eq 'group') {
6937: push(@groups,$key);
6938: } elsif ($scope eq 'ip') {
6939: push(@ips,$key);
6940: }
6941: }
6942: if ($public) {
6943: return 'ok';
6944: } elsif (@ips > 0) {
6945: my $allowed;
6946: foreach my $ipkey (@ips) {
6947: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6948: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6949: $allowed = 1;
6950: last;
6951: }
6952: }
6953: }
6954: if ($allowed) {
6955: return 'ok';
6956: }
6957: }
6958: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6959: if ($guest) {
6960: return $guest;
6961: }
6962: } else {
6963: if (@domains > 0) {
6964: foreach my $domkey (@domains) {
6965: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6966: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6967: return 'ok';
6968: }
6969: }
6970: }
6971: }
6972: if (@users > 0) {
6973: foreach my $userkey (@users) {
6974: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6975: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6976: if (ref($item) eq 'HASH') {
6977: if (($item->{'uname'} eq $env{'user.name'}) &&
6978: ($item->{'udom'} eq $env{'user.domain'})) {
6979: return 'ok';
6980: }
6981: }
6982: }
6983: }
6984: }
6985: }
6986: my %roleshash;
6987: my @courses_and_groups = @courses;
6988: push(@courses_and_groups,@groups);
6989: if (@courses_and_groups > 0) {
6990: my (%allgroups,%allroles);
6991: my ($start,$end,$role,$sec,$group);
6992: foreach my $envkey (%env) {
6993: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
6994: my $cid = $2.'_'.$3;
6995: if ($1 eq 'gr') {
6996: $group = $4;
6997: $allgroups{$cid}{$group} = $env{$envkey};
6998: } else {
6999: if ($4 eq '') {
7000: $sec = 'none';
7001: } else {
7002: $sec = $4;
7003: }
7004: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7005: }
7006: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
7007: my $cid = $2.'_'.$3;
7008: if ($4 eq '') {
7009: $sec = 'none';
7010: } else {
7011: $sec = $4;
7012: }
7013: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7014: }
7015: }
7016: if (keys(%allroles) == 0) {
7017: return;
7018: }
7019: foreach my $key (@courses_and_groups) {
7020: my %content = %{$$access_hash{$key}};
7021: my $cnum = $content{'number'};
7022: my $cdom = $content{'domain'};
7023: my $cid = $cdom.'_'.$cnum;
7024: if (!exists($allroles{$cid})) {
7025: next;
7026: }
7027: foreach my $role_id (keys(%{$content{'roles'}})) {
7028: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7029: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7030: my @status = @{$content{'roles'}{$role_id}{'access'}};
7031: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7032: foreach my $role (keys(%{$allroles{$cid}})) {
7033: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7034: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7035: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7036: if (grep/^all$/,@sections) {
7037: return 'ok';
7038: } else {
7039: if (grep/^$sec$/,@sections) {
7040: return 'ok';
7041: }
7042: }
7043: }
7044: }
7045: if (keys(%{$allgroups{$cid}}) == 0) {
7046: if (grep/^none$/,@groups) {
7047: return 'ok';
7048: }
7049: } else {
7050: if (grep/^all$/,@groups) {
7051: return 'ok';
7052: }
7053: foreach my $group (keys(%{$allgroups{$cid}})) {
7054: if (grep/^$group$/,@groups) {
7055: return 'ok';
7056: }
7057: }
7058: }
7059: }
7060: }
7061: }
7062: }
7063: }
7064: if ($guest) {
7065: return $guest;
7066: }
7067: }
7068: }
7069: return;
7070: }
7071:
7072: sub course_group_datechecker {
7073: my ($dates,$now,$status) = @_;
7074: my ($start,$end) = split(/\./,$dates);
7075: if (!$start && !$end) {
7076: return 'ok';
7077: }
7078: if (grep/^active$/,@{$status}) {
7079: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7080: return 'ok';
7081: }
7082: }
7083: if (grep/^previous$/,@{$status}) {
7084: if ($end > $now ) {
7085: return 'ok';
7086: }
7087: }
7088: if (grep/^future$/,@{$status}) {
7089: if ($start > $now) {
7090: return 'ok';
7091: }
7092: }
7093: return;
7094: }
7095:
7096: sub parse_portfolio_url {
7097: my ($url) = @_;
7098:
7099: my ($type,$udom,$unum,$group,$file_name);
7100:
7101: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
7102: $type = 1;
7103: $udom = $1;
7104: $unum = $2;
7105: $file_name = $3;
7106: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
7107: $type = 2;
7108: $udom = $1;
7109: $unum = $2;
7110: $group = $3;
7111: $file_name = $3.'/'.$4;
7112: }
7113: if (wantarray) {
7114: return ($type,$udom,$unum,$file_name,$group);
7115: }
7116: return $type;
7117: }
7118:
7119: sub is_portfolio_url {
7120: my ($url) = @_;
7121: return scalar(&parse_portfolio_url($url));
7122: }
7123:
7124: sub is_portfolio_file {
7125: my ($file) = @_;
7126: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
7127: return 1;
7128: }
7129: return;
7130: }
7131:
7132: sub usertools_access {
7133: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
7134: my ($access,%tools);
7135: if ($context eq '') {
7136: $context = 'tools';
7137: }
7138: if ($context eq 'requestcourses') {
7139: %tools = (
7140: official => 1,
7141: unofficial => 1,
7142: community => 1,
7143: textbook => 1,
7144: placement => 1,
7145: );
7146: } elsif ($context eq 'requestauthor') {
7147: %tools = (
7148: requestauthor => 1,
7149: );
7150: } else {
7151: %tools = (
7152: aboutme => 1,
7153: blog => 1,
7154: webdav => 1,
7155: portfolio => 1,
7156: );
7157: }
7158: return if (!defined($tools{$tool}));
7159:
7160: if (($udom eq '') || ($uname eq '')) {
7161: $udom = $env{'user.domain'};
7162: $uname = $env{'user.name'};
7163: }
7164:
7165: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7166: if ($action ne 'reload') {
7167: if ($context eq 'requestcourses') {
7168: return $env{'environment.canrequest.'.$tool};
7169: } elsif ($context eq 'requestauthor') {
7170: return $env{'environment.canrequest.author'};
7171: } else {
7172: return $env{'environment.availabletools.'.$tool};
7173: }
7174: }
7175: }
7176:
7177: my ($toolstatus,$inststatus,$envkey);
7178: if ($context eq 'requestauthor') {
7179: $envkey = $context;
7180: } else {
7181: $envkey = $context.'.'.$tool;
7182: }
7183:
7184: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7185: ($action ne 'reload')) {
7186: $toolstatus = $env{'environment.'.$envkey};
7187: $inststatus = $env{'environment.inststatus'};
7188: } else {
7189: if (ref($userenvref) eq 'HASH') {
7190: $toolstatus = $userenvref->{$envkey};
7191: $inststatus = $userenvref->{'inststatus'};
7192: } else {
7193: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7194: $toolstatus = $userenv{$envkey};
7195: $inststatus = $userenv{'inststatus'};
7196: }
7197: }
7198:
7199: if ($toolstatus ne '') {
7200: if ($toolstatus) {
7201: $access = 1;
7202: } else {
7203: $access = 0;
7204: }
7205: return $access;
7206: }
7207:
7208: my ($is_adv,%domdef);
7209: if (ref($is_advref) eq 'HASH') {
7210: $is_adv = $is_advref->{'is_adv'};
7211: } else {
7212: $is_adv = &is_advanced_user($udom,$uname);
7213: }
7214: if (ref($domdefref) eq 'HASH') {
7215: %domdef = %{$domdefref};
7216: } else {
7217: %domdef = &get_domain_defaults($udom);
7218: }
7219: if (ref($domdef{$tool}) eq 'HASH') {
7220: if ($is_adv) {
7221: if ($domdef{$tool}{'_LC_adv'} ne '') {
7222: if ($domdef{$tool}{'_LC_adv'}) {
7223: $access = 1;
7224: } else {
7225: $access = 0;
7226: }
7227: return $access;
7228: }
7229: }
7230: if ($inststatus ne '') {
7231: my ($hasaccess,$hasnoaccess);
7232: foreach my $affiliation (split(/:/,$inststatus)) {
7233: if ($domdef{$tool}{$affiliation} ne '') {
7234: if ($domdef{$tool}{$affiliation}) {
7235: $hasaccess = 1;
7236: } else {
7237: $hasnoaccess = 1;
7238: }
7239: }
7240: }
7241: if ($hasaccess || $hasnoaccess) {
7242: if ($hasaccess) {
7243: $access = 1;
7244: } elsif ($hasnoaccess) {
7245: $access = 0;
7246: }
7247: return $access;
7248: }
7249: } else {
7250: if ($domdef{$tool}{'default'} ne '') {
7251: if ($domdef{$tool}{'default'}) {
7252: $access = 1;
7253: } elsif ($domdef{$tool}{'default'} == 0) {
7254: $access = 0;
7255: }
7256: return $access;
7257: }
7258: }
7259: } else {
7260: if (($context eq 'tools') && ($tool ne 'webdav')) {
7261: $access = 1;
7262: } else {
7263: $access = 0;
7264: }
7265: return $access;
7266: }
7267: }
7268:
7269: sub is_course_owner {
7270: my ($cdom,$cnum,$udom,$uname) = @_;
7271: if (($udom eq '') || ($uname eq '')) {
7272: $udom = $env{'user.domain'};
7273: $uname = $env{'user.name'};
7274: }
7275: unless (($udom eq '') || ($uname eq '')) {
7276: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7277: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7278: return 1;
7279: } else {
7280: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7281: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7282: return 1;
7283: }
7284: }
7285: }
7286: }
7287: return;
7288: }
7289:
7290: sub is_advanced_user {
7291: my ($udom,$uname) = @_;
7292: if ($udom ne '' && $uname ne '') {
7293: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7294: if (wantarray) {
7295: return ($env{'user.adv'},$env{'user.author'});
7296: } else {
7297: return $env{'user.adv'};
7298: }
7299: }
7300: }
7301: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7302: my %allroles;
7303: my ($is_adv,$is_author);
7304: foreach my $role (keys(%roleshash)) {
7305: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7306: my $area = '/'.$tdomain.'/'.$trest;
7307: if ($sec ne '') {
7308: $area .= '/'.$sec;
7309: }
7310: if (($area ne '') && ($trole ne '')) {
7311: my $spec=$trole.'.'.$area;
7312: if ($trole =~ /^cr\//) {
7313: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7314: } elsif ($trole ne 'gr') {
7315: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7316: }
7317: if ($trole eq 'au') {
7318: $is_author = 1;
7319: }
7320: }
7321: }
7322: foreach my $role (keys(%allroles)) {
7323: last if ($is_adv);
7324: foreach my $item (split(/:/,$allroles{$role})) {
7325: if ($item ne '') {
7326: my ($privilege,$restrictions)=split(/&/,$item);
7327: if ($privilege eq 'adv') {
7328: $is_adv = 1;
7329: last;
7330: }
7331: }
7332: }
7333: }
7334: if (wantarray) {
7335: return ($is_adv,$is_author);
7336: }
7337: return $is_adv;
7338: }
7339:
7340: sub check_can_request {
7341: my ($dom,$can_request,$request_domains) = @_;
7342: my $canreq = 0;
7343: my ($types,$typename) = &Apache::loncommon::course_types();
7344: my @options = ('approval','validate','autolimit');
7345: my $optregex = join('|',@options);
7346: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7347: foreach my $type (@{$types}) {
7348: if (&usertools_access($env{'user.name'},
7349: $env{'user.domain'},
7350: $type,undef,'requestcourses')) {
7351: $canreq ++;
7352: if (ref($request_domains) eq 'HASH') {
7353: push(@{$request_domains->{$type}},$env{'user.domain'});
7354: }
7355: if ($dom eq $env{'user.domain'}) {
7356: $can_request->{$type} = 1;
7357: }
7358: }
7359: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
7360: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7361: if (@curr > 0) {
7362: foreach my $item (@curr) {
7363: if (ref($request_domains) eq 'HASH') {
7364: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7365: if ($otherdom ne '') {
7366: if (ref($request_domains->{$type}) eq 'ARRAY') {
7367: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7368: push(@{$request_domains->{$type}},$otherdom);
7369: }
7370: } else {
7371: push(@{$request_domains->{$type}},$otherdom);
7372: }
7373: }
7374: }
7375: }
7376: unless($dom eq $env{'user.domain'}) {
7377: $canreq ++;
7378: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7379: $can_request->{$type} = 1;
7380: }
7381: }
7382: }
7383: }
7384: }
7385: }
7386: return $canreq;
7387: }
7388:
7389: # ---------------------------------------------- Custom access rule evaluation
7390:
7391: sub customaccess {
7392: my ($priv,$uri)=@_;
7393: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
7394: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
7395: $udom = &LONCAPA::clean_domain($udom);
7396: $ucrs = &LONCAPA::clean_username($ucrs);
7397: my $access=0;
7398: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
7399: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7400: if ($type eq 'user') {
7401: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7402: my ($tdom,$tuname)=split(m{/},$scope);
7403: if ($tdom) {
7404: if ($tdom ne $env{'user.domain'}) { next; }
7405: }
7406: if ($tuname) {
7407: if ($tuname ne $env{'user.name'}) { next; }
7408: }
7409: $access=($effect eq 'allow');
7410: last;
7411: }
7412: } else {
7413: if ($role) {
7414: if ($role ne $urole) { next; }
7415: }
7416: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7417: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7418: if ($tdom) {
7419: if ($tdom ne $udom) { next; }
7420: }
7421: if ($tcrs) {
7422: if ($tcrs ne $ucrs) { next; }
7423: }
7424: if ($tsec) {
7425: if ($tsec ne $usec) { next; }
7426: }
7427: $access=($effect eq 'allow');
7428: last;
7429: }
7430: if ($realm eq '' && $role eq '') {
7431: $access=($effect eq 'allow');
7432: }
7433: }
7434: }
7435: return $access;
7436: }
7437:
7438: # ------------------------------------------------- Check for a user privilege
7439:
7440: sub allowed {
7441: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
7442: my $ver_orguri=$uri;
7443: $uri=&deversion($uri);
7444: my $orguri=$uri;
7445: $uri=&declutter($uri);
7446:
7447: if ($priv eq 'evb') {
7448: # Evade communication block restrictions for specified role in a course
7449: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7450: return $1;
7451: } else {
7452: return;
7453: }
7454: }
7455:
7456: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
7457: # Free bre access to adm and meta resources
7458: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$}))
7459: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7460: && ($priv eq 'bre')) {
7461: return 'F';
7462: }
7463:
7464: # Free bre access to user's own portfolio contents
7465: my ($space,$domain,$name,@dir)=split('/',$uri);
7466: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
7467: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
7468: my %setters;
7469: my ($startblock,$endblock) =
7470: &Apache::loncommon::blockcheck(\%setters,'port');
7471: if ($startblock && $endblock) {
7472: return 'B';
7473: } else {
7474: return 'F';
7475: }
7476: }
7477:
7478: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
7479: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7480: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7481: if (exists($env{'request.course.id'})) {
7482: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7483: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7484: if (($domain eq $cdom) && ($name eq $cnum)) {
7485: my $courseprivid=$env{'request.course.id'};
7486: $courseprivid=~s/\_/\//;
7487: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7488: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7489: return $1;
7490: } else {
7491: if ($env{'request.course.sec'}) {
7492: $courseprivid.='/'.$env{'request.course.sec'};
7493: }
7494: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7495: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7496: return $2;
7497: }
7498: }
7499: }
7500: }
7501: }
7502:
7503: # Free bre to public access
7504:
7505: if ($priv eq 'bre') {
7506: my $copyright=&metadata($uri,'copyright');
7507: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
7508: return 'F';
7509: }
7510: if ($copyright eq 'priv') {
7511: $uri=~/([^\/]+)\/([^\/]+)\//;
7512: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
7513: return '';
7514: }
7515: }
7516: if ($copyright eq 'domain') {
7517: $uri=~/([^\/]+)\/([^\/]+)\//;
7518: unless (($env{'user.domain'} eq $1) ||
7519: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
7520: return '';
7521: }
7522: }
7523: if ($env{'request.role'}=~ /li\.\//) {
7524: # Library role, so allow browsing of resources in this domain.
7525: return 'F';
7526: }
7527: if ($copyright eq 'custom') {
7528: unless (&customaccess($priv,$uri)) { return ''; }
7529: }
7530: }
7531: # Domain coordinator is trying to create a course
7532: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
7533: # uri is the requested domain in this case.
7534: # comparison to 'request.role.domain' shows if the user has selected
7535: # a role of dc for the domain in question.
7536: return 'F' if ($uri eq $env{'request.role.domain'});
7537: }
7538:
7539: my $thisallowed='';
7540: my $statecond=0;
7541: my $courseprivid='';
7542:
7543: my $ownaccess;
7544: # Community Coordinator or Assistant Co-author browsing resource space.
7545: if (($priv eq 'bro') && ($env{'user.author'})) {
7546: if ($uri eq '') {
7547: $ownaccess = 1;
7548: } else {
7549: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
7550: my $udom = $env{'user.domain'};
7551: my $uname = $env{'user.name'};
7552: if ($uri =~ m{^\Q$udom\E/?$}) {
7553: $ownaccess = 1;
7554: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
7555: unless ($uri =~ m{\.\./}) {
7556: $ownaccess = 1;
7557: }
7558: } elsif (($udom ne 'public') && ($uname ne 'public')) {
7559: my $now = time;
7560: if ($uri =~ m{^([^/]+)/?$}) {
7561: my $adom = $1;
7562: foreach my $key (keys(%env)) {
7563: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
7564: my ($start,$end) = split('.',$env{$key});
7565: if (($now >= $start) && (!$end || $end < $now)) {
7566: $ownaccess = 1;
7567: last;
7568: }
7569: }
7570: }
7571: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
7572: my $adom = $1;
7573: my $aname = $2;
7574: foreach my $role ('ca','aa') {
7575: if ($env{"user.role.$role./$adom/$aname"}) {
7576: my ($start,$end) =
7577: split('.',$env{"user.role.$role./$adom/$aname"});
7578: if (($now >= $start) && (!$end || $end < $now)) {
7579: $ownaccess = 1;
7580: last;
7581: }
7582: }
7583: }
7584: }
7585: }
7586: }
7587: }
7588: }
7589:
7590: # Course
7591:
7592: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
7593: unless (($priv eq 'bro') && (!$ownaccess)) {
7594: $thisallowed.=$1;
7595: }
7596: }
7597:
7598: # Domain
7599:
7600: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
7601: =~/\Q$priv\E\&([^\:]*)/) {
7602: unless (($priv eq 'bro') && (!$ownaccess)) {
7603: $thisallowed.=$1;
7604: }
7605: }
7606:
7607: # User who is not author or co-author might still be able to edit
7608: # resource of an author in the domain (e.g., if Domain Coordinator).
7609: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
7610: (&allowed('mdc',$env{'request.course.id'}))) {
7611: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
7612: $thisallowed.=$1;
7613: }
7614: }
7615:
7616: # Course: uri itself is a course
7617: my $courseuri=$uri;
7618: $courseuri=~s/\_(\d)/\/$1/;
7619: $courseuri=~s/^([^\/])/\/$1/;
7620:
7621: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
7622: =~/\Q$priv\E\&([^\:]*)/) {
7623: unless (($priv eq 'bro') && (!$ownaccess)) {
7624: $thisallowed.=$1;
7625: }
7626: }
7627:
7628: # URI is an uploaded document for this course, default permissions don't matter
7629: # not allowing 'edit' access (editupload) to uploaded course docs
7630: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
7631: $thisallowed='';
7632: my ($match)=&is_on_map($uri);
7633: if ($match) {
7634: if ($env{'user.priv.'.$env{'request.role'}.'./'}
7635: =~/\Q$priv\E\&([^\:]*)/) {
7636: my $value = $1;
7637: if ($noblockcheck) {
7638: $thisallowed.=$value;
7639: } else {
7640: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7641: if (@blockers > 0) {
7642: $thisallowed = 'B';
7643: } else {
7644: $thisallowed.=$value;
7645: }
7646: }
7647: }
7648: } else {
7649: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
7650: if ($refuri) {
7651: if ($refuri =~ m|^/adm/|) {
7652: $thisallowed='F';
7653: } else {
7654: $refuri=&declutter($refuri);
7655: my ($match) = &is_on_map($refuri);
7656: if ($match) {
7657: if ($noblockcheck) {
7658: $thisallowed='F';
7659: } else {
7660: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7661: if (@blockers > 0) {
7662: $thisallowed = 'B';
7663: } else {
7664: $thisallowed='F';
7665: }
7666: }
7667: }
7668: }
7669: }
7670: }
7671: }
7672:
7673: if ($priv eq 'bre'
7674: && $thisallowed ne 'F'
7675: && $thisallowed ne '2'
7676: && &is_portfolio_url($uri)) {
7677: $thisallowed = &portfolio_access($uri,$clientip);
7678: }
7679:
7680: # Full access at system, domain or course-wide level? Exit.
7681: if ($thisallowed=~/F/) {
7682: return 'F';
7683: }
7684:
7685: # If this is generating or modifying users, exit with special codes
7686:
7687: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
7688: if (($priv eq 'cca') || ($priv eq 'caa')) {
7689: my ($audom,$auname)=split('/',$uri);
7690: # no author name given, so this just checks on the general right to make a co-author in this domain
7691: unless ($auname) { return $thisallowed; }
7692: # an author name is given, so we are about to actually make a co-author for a certain account
7693: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
7694: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
7695: ($audom ne $env{'request.role.domain'}))) { return ''; }
7696: }
7697: return $thisallowed;
7698: }
7699: #
7700: # Gathered so far: system, domain and course wide privileges
7701: #
7702: # Course: See if uri or referer is an individual resource that is part of
7703: # the course
7704:
7705: if ($env{'request.course.id'}) {
7706:
7707: $courseprivid=$env{'request.course.id'};
7708: if ($env{'request.course.sec'}) {
7709: $courseprivid.='/'.$env{'request.course.sec'};
7710: }
7711: $courseprivid=~s/\_/\//;
7712: my $checkreferer=1;
7713: my ($match,$cond)=&is_on_map($uri);
7714: if ($match) {
7715: $statecond=$cond;
7716: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
7717: =~/\Q$priv\E\&([^\:]*)/) {
7718: my $value = $1;
7719: if ($priv eq 'bre') {
7720: if ($noblockcheck) {
7721: $thisallowed.=$value;
7722: } else {
7723: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7724: if (@blockers > 0) {
7725: $thisallowed = 'B';
7726: } else {
7727: $thisallowed.=$value;
7728: }
7729: }
7730: } else {
7731: $thisallowed.=$value;
7732: }
7733: $checkreferer=0;
7734: }
7735: }
7736:
7737: if ($checkreferer) {
7738: my $refuri=$env{'httpref.'.$orguri};
7739: unless ($refuri) {
7740: foreach my $key (keys(%env)) {
7741: if ($key=~/^httpref\..*\*/) {
7742: my $pattern=$key;
7743: $pattern=~s/^httpref\.\/res\///;
7744: $pattern=~s/\*/\[\^\/\]\+/g;
7745: $pattern=~s/\//\\\//g;
7746: if ($orguri=~/$pattern/) {
7747: $refuri=$env{$key};
7748: }
7749: }
7750: }
7751: }
7752:
7753: if ($refuri) {
7754: $refuri=&declutter($refuri);
7755: my ($match,$cond)=&is_on_map($refuri);
7756: if ($match) {
7757: my $refstatecond=$cond;
7758: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
7759: =~/\Q$priv\E\&([^\:]*)/) {
7760: my $value = $1;
7761: if ($priv eq 'bre') {
7762: if ($noblockcheck) {
7763: $thisallowed.=$value;
7764: } else {
7765: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7766: if (@blockers > 0) {
7767: $thisallowed = 'B';
7768: } else {
7769: $thisallowed.=$value;
7770: }
7771: }
7772: } else {
7773: $thisallowed.=$value;
7774: }
7775: $uri=$refuri;
7776: $statecond=$refstatecond;
7777: }
7778: }
7779: }
7780: }
7781: }
7782:
7783: #
7784: # Gathered now: all privileges that could apply, and condition number
7785: #
7786: #
7787: # Full or no access?
7788: #
7789:
7790: if ($thisallowed=~/F/) {
7791: return 'F';
7792: }
7793:
7794: unless ($thisallowed) {
7795: return '';
7796: }
7797:
7798: # Restrictions exist, deal with them
7799: #
7800: # C:according to course preferences
7801: # R:according to resource settings
7802: # L:unless locked
7803: # X:according to user session state
7804: #
7805:
7806: # Possibly locked functionality, check all courses
7807: # Locks might take effect only after 10 minutes cache expiration for other
7808: # courses, and 2 minutes for current course
7809:
7810: my $envkey;
7811: if ($thisallowed=~/L/) {
7812: foreach $envkey (keys(%env)) {
7813: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7814: my $courseid=$2;
7815: my $roleid=$1.'.'.$2;
7816: $courseid=~s/^\///;
7817: my $expiretime=600;
7818: if ($env{'request.role'} eq $roleid) {
7819: $expiretime=120;
7820: }
7821: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7822: my $prefix='course.'.$cdom.'_'.$cnum.'.';
7823: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
7824: &coursedescription($courseid,{'freshen_cache' => 1});
7825: }
7826: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7827: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7828: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7829: &log($env{'user.domain'},$env{'user.name'},
7830: $env{'user.home'},
7831: 'Locked by res: '.$priv.' for '.$uri.' due to '.
7832: $cdom.'/'.$cnum.'/'.$csec.' expire '.
7833: $env{$prefix.'priv.'.$priv.'.lock.expire'});
7834: return '';
7835: }
7836: }
7837: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7838: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7839: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7840: &log($env{'user.domain'},$env{'user.name'},
7841: $env{'user.home'},
7842: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
7843: $cdom.'/'.$cnum.'/'.$csec.' expire '.
7844: $env{$prefix.'priv.'.$priv.'.lock.expire'});
7845: return '';
7846: }
7847: }
7848: }
7849: }
7850: }
7851:
7852: #
7853: # Rest of the restrictions depend on selected course
7854: #
7855:
7856: unless ($env{'request.course.id'}) {
7857: if ($thisallowed eq 'A') {
7858: return 'A';
7859: } elsif ($thisallowed eq 'B') {
7860: return 'B';
7861: } else {
7862: return '1';
7863: }
7864: }
7865:
7866: #
7867: # Now user is definitely in a course
7868: #
7869:
7870:
7871: # Course preferences
7872:
7873: if ($thisallowed=~/C/) {
7874: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7875: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7876: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
7877: =~/\Q$rolecode\E/) {
7878: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
7879: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7880: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7881: $env{'request.course.id'});
7882: }
7883: return '';
7884: }
7885:
7886: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
7887: =~/\Q$unamedom\E/) {
7888: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
7889: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7890: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7891: $env{'request.course.id'});
7892: }
7893: return '';
7894: }
7895: }
7896:
7897: # Resource preferences
7898:
7899: if ($thisallowed=~/R/) {
7900: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7901: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
7902: if (($priv ne 'pch') && ($priv ne 'plc')) {
7903: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7904: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7905: }
7906: return '';
7907: }
7908: }
7909:
7910: # Restricted by state or randomout?
7911:
7912: if ($thisallowed=~/X/) {
7913: if ($env{'acc.randomout'}) {
7914: if (!$symb) { $symb=&symbread($uri,1); }
7915: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
7916: return '';
7917: }
7918: }
7919: if (&condval($statecond)) {
7920: return '2';
7921: } else {
7922: return '';
7923: }
7924: }
7925:
7926: if ($thisallowed eq 'A') {
7927: return 'A';
7928: } elsif ($thisallowed eq 'B') {
7929: return 'B';
7930: }
7931: return 'F';
7932: }
7933:
7934: # ------------------------------------------- Check construction space access
7935:
7936: sub constructaccess {
7937: my ($url,$setpriv)=@_;
7938:
7939: # We do not allow editing of previous versions of files
7940: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7941:
7942: # Get username and domain from URL
7943: my ($ownername,$ownerdomain,$ownerhome);
7944:
7945: ($ownerdomain,$ownername) =
7946: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
7947:
7948: # The URL does not really point to any authorspace, forget it
7949: unless (($ownername) && ($ownerdomain)) { return ''; }
7950:
7951: # Now we need to see if the user has access to the authorspace of
7952: # $ownername at $ownerdomain
7953:
7954: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7955: # Real author for this?
7956: $ownerhome = $env{'user.home'};
7957: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7958: return ($ownername,$ownerdomain,$ownerhome);
7959: }
7960: } else {
7961: # Co-author for this?
7962: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7963: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7964: $ownerhome = &homeserver($ownername,$ownerdomain);
7965: return ($ownername,$ownerdomain,$ownerhome);
7966: }
7967: if ($env{'request.course.id'}) {
7968: if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
7969: ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
7970: if (&allowed('mdc',$env{'request.course.id'})) {
7971: $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
7972: return ($ownername,$ownerdomain,$ownerhome);
7973: }
7974: }
7975: }
7976: }
7977:
7978: # We don't have any access right now. If we are not possibly going to do anything about this,
7979: # we might as well leave
7980: unless ($setpriv) { return ''; }
7981:
7982: # Backdoor access?
7983: my $allowed=&allowed('eco',$ownerdomain);
7984: # Nope
7985: unless ($allowed) { return ''; }
7986: # Looks like we may have access, but could be locked by the owner of the construction space
7987: if ($allowed eq 'U') {
7988: my %blocked=&get('environment',['domcoord.author'],
7989: $ownerdomain,$ownername);
7990: # Is blocked by owner
7991: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7992: }
7993: if (($allowed eq 'F') || ($allowed eq 'U')) {
7994: # Grant temporary access
7995: my $then=$env{'user.login.time'};
7996: my $update=$env{'user.update.time'};
7997: if (!$update) { $update = $then; }
7998: my $refresh=$env{'user.refresh.time'};
7999: if (!$refresh) { $refresh = $update; }
8000: my $now = time;
8001: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
8002: $now,'ca','constructaccess');
8003: $ownerhome = &homeserver($ownername,$ownerdomain);
8004: return($ownername,$ownerdomain,$ownerhome);
8005: }
8006: # No business here
8007: return '';
8008: }
8009:
8010: # ----------------------------------------------------------- Content Blocking
8011:
8012: {
8013: # Caches for faster Course Contents display where content blocking
8014: # is in operation (i.e., interval param set) for timed quiz.
8015: #
8016: # User for whom data are being temporarily cached.
8017: my $cacheduser='';
8018: # Cached blockers for this user (a hash of blocking items).
8019: my %cachedblockers=();
8020: # When the data were last cached.
8021: my $cachedlast='';
8022:
8023: sub load_all_blockers {
8024: my ($uname,$udom,$blocks)=@_;
8025: if (($uname ne '') && ($udom ne '')) {
8026: if (($cacheduser eq $uname.':'.$udom) &&
8027: (abs($cachedlast-time)<5)) {
8028: return;
8029: }
8030: }
8031: $cachedlast=time;
8032: $cacheduser=$uname.':'.$udom;
8033: %cachedblockers = &get_commblock_resources($blocks);
8034: }
8035:
8036: sub get_comm_blocks {
8037: my ($cdom,$cnum) = @_;
8038: if ($cdom eq '' || $cnum eq '') {
8039: return unless ($env{'request.course.id'});
8040: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8041: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8042: }
8043: my %commblocks;
8044: my $hashid=$cdom.'_'.$cnum;
8045: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8046: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8047: %commblocks = %{$blocksref};
8048: } else {
8049: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8050: my $cachetime = 600;
8051: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8052: }
8053: return %commblocks;
8054: }
8055:
8056: sub get_commblock_resources {
8057: my ($blocks) = @_;
8058: my %blockers = ();
8059: return %blockers unless ($env{'request.course.id'});
8060: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
8061: my %commblocks;
8062: if (ref($blocks) eq 'HASH') {
8063: %commblocks = %{$blocks};
8064: } else {
8065: %commblocks = &get_comm_blocks();
8066: }
8067: return %blockers unless (keys(%commblocks) > 0);
8068: my $navmap = Apache::lonnavmaps::navmap->new();
8069: return %blockers unless (ref($navmap));
8070: my $now = time;
8071: foreach my $block (keys(%commblocks)) {
8072: if ($block =~ /^(\d+)____(\d+)$/) {
8073: my ($start,$end) = ($1,$2);
8074: if ($start <= $now && $end >= $now) {
8075: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8076: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8077: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8078: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8079: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8080: }
8081: }
8082: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8083: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8084: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
8085: }
8086: }
8087: }
8088: }
8089: }
8090: } elsif ($block =~ /^firstaccess____(.+)$/) {
8091: my $item = $1;
8092: my @to_test;
8093: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8094: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8095: my @interval;
8096: my $type = 'map';
8097: if ($item eq 'course') {
8098: $type = 'course';
8099: @interval=&EXT("resource.0.interval");
8100: } else {
8101: if ($item =~ /___\d+___/) {
8102: $type = 'resource';
8103: @interval=&EXT("resource.0.interval",$item);
8104: if (ref($navmap)) {
8105: my $res = $navmap->getBySymb($item);
8106: push(@to_test,$res);
8107: }
8108: } else {
8109: my $mapsymb = &symbread($item,1);
8110: if ($mapsymb) {
8111: if (ref($navmap)) {
8112: my $mapres = $navmap->getBySymb($mapsymb);
8113: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
8114: foreach my $res (@to_test) {
8115: my $symb = $res->symb();
8116: next if ($symb eq $mapsymb);
8117: if ($symb ne '') {
8118: @interval=&EXT("resource.0.interval",$symb);
8119: if ($interval[1] eq 'map') {
8120: last;
8121: }
8122: }
8123: }
8124: }
8125: }
8126: }
8127: }
8128: if ($interval[0] =~ /^(\d+)/) {
8129: my $timelimit = $1;
8130: my $first_access;
8131: if ($type eq 'resource') {
8132: $first_access=&get_first_access($interval[1],$item);
8133: } elsif ($type eq 'map') {
8134: $first_access=&get_first_access($interval[1],undef,$item);
8135: } else {
8136: $first_access=&get_first_access($interval[1]);
8137: }
8138: if ($first_access) {
8139: my $timesup = $first_access+$timelimit;
8140: if ($timesup > $now) {
8141: my $activeblock;
8142: foreach my $res (@to_test) {
8143: if ($res->answerable()) {
8144: $activeblock = 1;
8145: last;
8146: }
8147: }
8148: if ($activeblock) {
8149: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8150: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8151: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8152: }
8153: }
8154: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8155: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8156: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
8157: }
8158: }
8159: }
8160: }
8161: }
8162: }
8163: }
8164: }
8165: }
8166: }
8167: return %blockers;
8168: }
8169:
8170: sub has_comm_blocking {
8171: my ($priv,$symb,$uri,$blocks) = @_;
8172: my @blockers;
8173: return unless ($env{'request.course.id'});
8174: return unless ($priv eq 'bre');
8175: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
8176: return if ($env{'request.state'} eq 'construct');
8177: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
8178: return unless (keys(%cachedblockers) > 0);
8179: my (%possibles,@symbs);
8180: if (!$symb) {
8181: $symb = &symbread($uri,1,1,1,\%possibles);
8182: }
8183: if ($symb) {
8184: @symbs = ($symb);
8185: } elsif (keys(%possibles)) {
8186: @symbs = keys(%possibles);
8187: }
8188: my $noblock;
8189: foreach my $symb (@symbs) {
8190: last if ($noblock);
8191: my ($map,$resid,$resurl)=&decode_symb($symb);
8192: foreach my $block (keys(%cachedblockers)) {
8193: if ($block =~ /^firstaccess____(.+)$/) {
8194: my $item = $1;
8195: if (($item eq $map) || ($item eq $symb)) {
8196: $noblock = 1;
8197: last;
8198: }
8199: }
8200: if (ref($cachedblockers{$block}) eq 'HASH') {
8201: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
8202: if ($cachedblockers{$block}{'resources'}{$symb}) {
8203: unless (grep(/^\Q$block\E$/,@blockers)) {
8204: push(@blockers,$block);
8205: }
8206: }
8207: }
8208: }
8209: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
8210: if ($cachedblockers{$block}{'maps'}{$map}) {
8211: unless (grep(/^\Q$block\E$/,@blockers)) {
8212: push(@blockers,$block);
8213: }
8214: }
8215: }
8216: }
8217: }
8218: return if ($noblock);
8219: return @blockers;
8220: }
8221: }
8222:
8223: # -------------------------------- Deversion and split uri into path an filename
8224:
8225: #
8226: # Removes the version from a URI and
8227: # splits it in to its filename and path to the filename.
8228: # Seems like File::Basename could have done this more clearly.
8229: # Parameters:
8230: # $uri - input URI
8231: # Returns:
8232: # Two element list consisting of
8233: # $pathname - the URI up to and excluding the trailing /
8234: # $filename - The part of the URI following the last /
8235: # NOTE:
8236: # Another realization of this is simply:
8237: # use File::Basename;
8238: # ...
8239: # $uri = shift;
8240: # $filename = basename($uri);
8241: # $path = dirname($uri);
8242: # return ($filename, $path);
8243: #
8244: # The implementation below is probably faster however.
8245: #
8246: sub split_uri_for_cond {
8247: my $uri=&deversion(&declutter(shift));
8248: my @uriparts=split(/\//,$uri);
8249: my $filename=pop(@uriparts);
8250: my $pathname=join('/',@uriparts);
8251: return ($pathname,$filename);
8252: }
8253: # --------------------------------------------------- Is a resource on the map?
8254:
8255: sub is_on_map {
8256: my ($pathname,$filename) = &split_uri_for_cond(shift);
8257: #Trying to find the conditional for the file
8258: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
8259: /\&\Q$filename\E\:([\d\|]+)\&/);
8260: if ($match) {
8261: return (1,$1);
8262: } else {
8263: return (0,0);
8264: }
8265: }
8266:
8267: # --------------------------------------------------------- Get symb from alias
8268:
8269: sub get_symb_from_alias {
8270: my $symb=shift;
8271: my ($map,$resid,$url)=&decode_symb($symb);
8272: # Already is a symb
8273: if ($url) { return $symb; }
8274: # Must be an alias
8275: my $aliassymb='';
8276: my %bighash;
8277: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8278: &GDBM_READER(),0640)) {
8279: my $rid=$bighash{'mapalias_'.$symb};
8280: if ($rid) {
8281: my ($mapid,$resid)=split(/\./,$rid);
8282: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8283: $resid,$bighash{'src_'.$rid});
8284: }
8285: untie %bighash;
8286: }
8287: return $aliassymb;
8288: }
8289:
8290: # ----------------------------------------------------------------- Define Role
8291:
8292: sub definerole {
8293: if (allowed('mcr','/')) {
8294: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
8295: foreach my $role (split(':',$sysrole)) {
8296: my ($crole,$cqual)=split(/\&/,$role);
8297: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8298: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8299: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
8300: return "refused:s:$crole&$cqual";
8301: }
8302: }
8303: }
8304: foreach my $role (split(':',$domrole)) {
8305: my ($crole,$cqual)=split(/\&/,$role);
8306: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8307: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8308: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
8309: return "refused:d:$crole&$cqual";
8310: }
8311: }
8312: }
8313: foreach my $role (split(':',$courole)) {
8314: my ($crole,$cqual)=split(/\&/,$role);
8315: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8316: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8317: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
8318: return "refused:c:$crole&$cqual";
8319: }
8320: }
8321: }
8322: my $uhome;
8323: if (($uname ne '') && ($udom ne '')) {
8324: $uhome = &homeserver($uname,$udom);
8325: return $uhome if ($uhome eq 'no_host');
8326: } else {
8327: $uname = $env{'user.name'};
8328: $udom = $env{'user.domain'};
8329: $uhome = $env{'user.home'};
8330: }
8331: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
8332: "$udom:$uname:rolesdef_$rolename=".
8333: escape($sysrole.'_'.$domrole.'_'.$courole);
8334: return reply($command,$uhome);
8335: } else {
8336: return 'refused';
8337: }
8338: }
8339:
8340: # ---------------- Make a metadata query against the network of library servers
8341:
8342: sub metadata_query {
8343: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
8344: my %rhash;
8345: my %libserv = &all_library();
8346: my @server_list = (defined($server_array) ? @$server_array
8347: : keys(%libserv) );
8348: for my $server (@server_list) {
8349: my $domains = '';
8350: if (ref($domains_hash) eq 'HASH') {
8351: $domains = $domains_hash->{$server};
8352: }
8353: unless ($custom or $customshow) {
8354: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
8355: $rhash{$server}=$reply;
8356: }
8357: else {
8358: my $reply=&reply("querysend:".&escape($query).':'.
8359: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
8360: $server);
8361: $rhash{$server}=$reply;
8362: }
8363: }
8364: return \%rhash;
8365: }
8366:
8367: # ----------------------------------------- Send log queries and wait for reply
8368:
8369: sub log_query {
8370: my ($uname,$udom,$query,%filters)=@_;
8371: my $uhome=&homeserver($uname,$udom);
8372: if ($uhome eq 'no_host') { return 'error: no_host'; }
8373: my $uhost=&hostname($uhome);
8374: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
8375: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8376: $uhome);
8377: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
8378: return get_query_reply($queryid);
8379: }
8380:
8381: # -------------------------- Update MySQL table for portfolio file
8382:
8383: sub update_portfolio_table {
8384: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
8385: if ($group ne '') {
8386: $file_name =~s /^\Q$group\E//;
8387: }
8388: my $homeserver = &homeserver($uname,$udom);
8389: my $queryid=
8390: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8391: ':'.&escape($file_name).':'.$action,$homeserver);
8392: my $reply = &get_query_reply($queryid);
8393: return $reply;
8394: }
8395:
8396: # -------------------------- Update MySQL allusers table
8397:
8398: sub update_allusers_table {
8399: my ($uname,$udom,$names) = @_;
8400: my $homeserver = &homeserver($uname,$udom);
8401: my $queryid=
8402: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8403: 'lastname='.&escape($names->{'lastname'}).'%%'.
8404: 'firstname='.&escape($names->{'firstname'}).'%%'.
8405: 'middlename='.&escape($names->{'middlename'}).'%%'.
8406: 'generation='.&escape($names->{'generation'}).'%%'.
8407: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8408: 'id='.&escape($names->{'id'}),$homeserver);
8409: return;
8410: }
8411:
8412: # ------- Request retrieval of institutional classlists for course(s)
8413:
8414: sub fetch_enrollment_query {
8415: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
8416: my ($homeserver,$sleep,$loopmax);
8417: my $maxtries = 1;
8418: if ($context eq 'automated') {
8419: $homeserver = $perlvar{'lonHostID'};
8420: $sleep = 2;
8421: $loopmax = 100;
8422: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
8423: } else {
8424: $homeserver = &homeserver($cnum,$dom);
8425: }
8426: my $host=&hostname($homeserver);
8427: my $cmd = '';
8428: foreach my $affiliate (keys(%{$affiliatesref})) {
8429: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
8430: }
8431: $cmd =~ s/%%$//;
8432: $cmd = &escape($cmd);
8433: my $query = 'fetchenrollment';
8434: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
8435: unless ($queryid=~/^\Q$host\E\_/) {
8436: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
8437: return 'error: '.$queryid;
8438: }
8439: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
8440: my $tries = 1;
8441: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8442: $reply = &get_query_reply($queryid,$sleep,$loopmax);
8443: $tries ++;
8444: }
8445: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8446: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8447: } else {
8448: my @responses = split(/:/,$reply);
8449: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
8450: foreach my $line (@responses) {
8451: my ($key,$value) = split(/=/,$line,2);
8452: $$replyref{$key} = $value;
8453: }
8454: } else {
8455: my $pathname = LONCAPA::tempdir();
8456: foreach my $line (@responses) {
8457: my ($key,$value) = split(/=/,$line);
8458: $$replyref{$key} = $value;
8459: if ($value > 0) {
8460: foreach my $item (@{$$affiliatesref{$key}}) {
8461: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
8462: my $destname = $pathname.'/'.$filename;
8463: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
8464: if ($xml_classlist =~ /^error/) {
8465: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
8466: } else {
8467: if ( open(FILE,">",$destname) ) {
8468: print FILE &unescape($xml_classlist);
8469: close(FILE);
8470: } else {
8471: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
8472: }
8473: }
8474: }
8475: }
8476: }
8477: }
8478: return 'ok';
8479: }
8480: return 'error';
8481: }
8482:
8483: sub get_query_reply {
8484: my ($queryid,$sleep,$loopmax) = @_;;
8485: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
8486: $sleep = 0.2;
8487: }
8488: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
8489: $loopmax = 100;
8490: }
8491: my $replyfile=LONCAPA::tempdir().$queryid;
8492: my $reply='';
8493: for (1..$loopmax) {
8494: sleep($sleep);
8495: if (-e $replyfile.'.end') {
8496: if (open(my $fh,"<",$replyfile)) {
8497: $reply = join('',<$fh>);
8498: close($fh);
8499: } else { return 'error: reply_file_error'; }
8500: return &unescape($reply);
8501: }
8502: }
8503: return 'timeout:'.$queryid;
8504: }
8505:
8506: sub courselog_query {
8507: #
8508: # possible filters:
8509: # url: url or symb
8510: # username
8511: # domain
8512: # action: view, submit, grade
8513: # start: timestamp
8514: # end: timestamp
8515: #
8516: my (%filters)=@_;
8517: unless ($env{'request.course.id'}) { return 'no_course'; }
8518: if ($filters{'url'}) {
8519: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
8520: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
8521: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
8522: }
8523: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8524: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
8525: return &log_query($cname,$cdom,'courselog',%filters);
8526: }
8527:
8528: sub userlog_query {
8529: #
8530: # possible filters:
8531: # action: log check role
8532: # start: timestamp
8533: # end: timestamp
8534: #
8535: my ($uname,$udom,%filters)=@_;
8536: return &log_query($uname,$udom,'userlog',%filters);
8537: }
8538:
8539: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
8540:
8541: sub auto_run {
8542: my ($cnum,$cdom) = @_;
8543: my $response = 0;
8544: my $settings;
8545: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
8546: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
8547: $settings = $domconfig{'autoenroll'};
8548: if ($settings->{'run'} eq '1') {
8549: $response = 1;
8550: }
8551: } else {
8552: my $homeserver;
8553: if (&is_course($cdom,$cnum)) {
8554: $homeserver = &homeserver($cnum,$cdom);
8555: } else {
8556: $homeserver = &domain($cdom,'primary');
8557: }
8558: if ($homeserver ne 'no_host') {
8559: $response = &reply('autorun:'.$cdom,$homeserver);
8560: }
8561: }
8562: return $response;
8563: }
8564:
8565: sub auto_get_sections {
8566: my ($cnum,$cdom,$inst_coursecode) = @_;
8567: my $homeserver;
8568: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8569: $homeserver = &homeserver($cnum,$cdom);
8570: }
8571: if (!defined($homeserver)) {
8572: if ($cdom =~ /^$match_domain$/) {
8573: $homeserver = &domain($cdom,'primary');
8574: }
8575: }
8576: my @secs;
8577: if (defined($homeserver)) {
8578: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
8579: unless ($response eq 'refused') {
8580: @secs = split(/:/,$response);
8581: }
8582: }
8583: return @secs;
8584: }
8585:
8586: sub auto_new_course {
8587: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
8588: my $homeserver = &homeserver($cnum,$cdom);
8589: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
8590: return $response;
8591: }
8592:
8593: sub auto_validate_courseID {
8594: my ($cnum,$cdom,$inst_course_id) = @_;
8595: my $homeserver = &homeserver($cnum,$cdom);
8596: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
8597: return $response;
8598: }
8599:
8600: sub auto_validate_instcode {
8601: my ($cnum,$cdom,$instcode,$owner) = @_;
8602: my ($homeserver,$response);
8603: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8604: $homeserver = &homeserver($cnum,$cdom);
8605: }
8606: if (!defined($homeserver)) {
8607: if ($cdom =~ /^$match_domain$/) {
8608: $homeserver = &domain($cdom,'primary');
8609: }
8610: }
8611: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
8612: &escape($instcode).':'.&escape($owner),$homeserver));
8613: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
8614: return ($outcome,$description,$defaultcredits);
8615: }
8616:
8617: sub auto_create_password {
8618: my ($cnum,$cdom,$authparam,$udom) = @_;
8619: my ($homeserver,$response);
8620: my $create_passwd = 0;
8621: my $authchk = '';
8622: if ($udom =~ /^$match_domain$/) {
8623: $homeserver = &domain($udom,'primary');
8624: }
8625: if ($homeserver eq '') {
8626: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8627: $homeserver = &homeserver($cnum,$cdom);
8628: }
8629: }
8630: if ($homeserver eq '') {
8631: $authchk = 'nodomain';
8632: } else {
8633: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
8634: if ($response eq 'refused') {
8635: $authchk = 'refused';
8636: } else {
8637: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
8638: }
8639: }
8640: return ($authparam,$create_passwd,$authchk);
8641: }
8642:
8643: sub auto_photo_permission {
8644: my ($cnum,$cdom,$students) = @_;
8645: my $homeserver = &homeserver($cnum,$cdom);
8646: my ($outcome,$perm_reqd,$conditions) =
8647: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
8648: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8649: return (undef,undef);
8650: }
8651: return ($outcome,$perm_reqd,$conditions);
8652: }
8653:
8654: sub auto_checkphotos {
8655: my ($uname,$udom,$pid) = @_;
8656: my $homeserver = &homeserver($uname,$udom);
8657: my ($result,$resulttype);
8658: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
8659: &escape($uname).':'.&escape($pid),
8660: $homeserver));
8661: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8662: return (undef,undef);
8663: }
8664: if ($outcome) {
8665: ($result,$resulttype) = split(/:/,$outcome);
8666: }
8667: return ($result,$resulttype);
8668: }
8669:
8670: sub auto_photochoice {
8671: my ($cnum,$cdom) = @_;
8672: my $homeserver = &homeserver($cnum,$cdom);
8673: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
8674: &escape($cdom),
8675: $homeserver)));
8676: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8677: return (undef,undef);
8678: }
8679: return ($update,$comment);
8680: }
8681:
8682: sub auto_photoupdate {
8683: my ($affiliatesref,$dom,$cnum,$photo) = @_;
8684: my $homeserver = &homeserver($cnum,$dom);
8685: my $host=&hostname($homeserver);
8686: my $cmd = '';
8687: my $maxtries = 1;
8688: foreach my $affiliate (keys(%{$affiliatesref})) {
8689: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
8690: }
8691: $cmd =~ s/%%$//;
8692: $cmd = &escape($cmd);
8693: my $query = 'institutionalphotos';
8694: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
8695: unless ($queryid=~/^\Q$host\E\_/) {
8696: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
8697: return 'error: '.$queryid;
8698: }
8699: my $reply = &get_query_reply($queryid);
8700: my $tries = 1;
8701: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8702: $reply = &get_query_reply($queryid);
8703: $tries ++;
8704: }
8705: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8706: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8707: } else {
8708: my @responses = split(/:/,$reply);
8709: my $outcome = shift(@responses);
8710: foreach my $item (@responses) {
8711: my ($key,$value) = split(/=/,$item);
8712: $$photo{$key} = $value;
8713: }
8714: return $outcome;
8715: }
8716: return 'error';
8717: }
8718:
8719: sub auto_instcode_format {
8720: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
8721: $cat_order) = @_;
8722: my $courses = '';
8723: my @homeservers;
8724: if ($caller eq 'global') {
8725: my %servers = &get_servers($codedom,'library');
8726: foreach my $tryserver (keys(%servers)) {
8727: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8728: push(@homeservers,$tryserver);
8729: }
8730: }
8731: } elsif ($caller eq 'requests') {
8732: if ($codedom =~ /^$match_domain$/) {
8733: my $chome = &domain($codedom,'primary');
8734: unless ($chome eq 'no_host') {
8735: push(@homeservers,$chome);
8736: }
8737: }
8738: } else {
8739: push(@homeservers,&homeserver($caller,$codedom));
8740: }
8741: foreach my $code (keys(%{$instcodes})) {
8742: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
8743: }
8744: chop($courses);
8745: my $ok_response = 0;
8746: my $response;
8747: while (@homeservers > 0 && $ok_response == 0) {
8748: my $server = shift(@homeservers);
8749: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
8750: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
8751: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
8752: split(/:/,$response);
8753: %{$codes} = (%{$codes},&str2hash($codes_str));
8754: push(@{$codetitles},&str2array($codetitles_str));
8755: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
8756: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
8757: $ok_response = 1;
8758: }
8759: }
8760: if ($ok_response) {
8761: return 'ok';
8762: } else {
8763: return $response;
8764: }
8765: }
8766:
8767: sub auto_instcode_defaults {
8768: my ($domain,$returnhash,$code_order) = @_;
8769: my @homeservers;
8770:
8771: my %servers = &get_servers($domain,'library');
8772: foreach my $tryserver (keys(%servers)) {
8773: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8774: push(@homeservers,$tryserver);
8775: }
8776: }
8777:
8778: my $response;
8779: foreach my $server (@homeservers) {
8780: $response=&reply('autoinstcodedefaults:'.$domain,$server);
8781: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8782:
8783: foreach my $pair (split(/\&/,$response)) {
8784: my ($name,$value)=split(/\=/,$pair);
8785: if ($name eq 'code_order') {
8786: @{$code_order} = split(/\&/,&unescape($value));
8787: } else {
8788: $returnhash->{&unescape($name)}=&unescape($value);
8789: }
8790: }
8791: return 'ok';
8792: }
8793:
8794: return $response;
8795: }
8796:
8797: sub auto_possible_instcodes {
8798: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
8799: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
8800: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8801: return;
8802: }
8803: my (@homeservers,$uhome);
8804: if (defined(&domain($domain,'primary'))) {
8805: $uhome=&domain($domain,'primary');
8806: push(@homeservers,&domain($domain,'primary'));
8807: } else {
8808: my %servers = &get_servers($domain,'library');
8809: foreach my $tryserver (keys(%servers)) {
8810: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8811: push(@homeservers,$tryserver);
8812: }
8813: }
8814: }
8815: my $response;
8816: foreach my $server (@homeservers) {
8817: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8818: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8819: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8820: split(':',$response);
8821: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8822: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
8823: foreach my $item (split('&',$cat_title)) {
8824: my ($name,$value)=split('=',$item);
8825: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
8826: }
8827: foreach my $item (split('&',$cat_order)) {
8828: my ($name,$value)=split('=',$item);
8829: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
8830: }
8831: return 'ok';
8832: }
8833: return $response;
8834: }
8835:
8836: sub auto_courserequest_checks {
8837: my ($dom) = @_;
8838: my ($homeserver,%validations);
8839: if ($dom =~ /^$match_domain$/) {
8840: $homeserver = &domain($dom,'primary');
8841: }
8842: unless ($homeserver eq 'no_host') {
8843: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8844: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8845: my @items = split(/&/,$response);
8846: foreach my $item (@items) {
8847: my ($key,$value) = split('=',$item);
8848: $validations{&unescape($key)} = &thaw_unescape($value);
8849: }
8850: }
8851: }
8852: return %validations;
8853: }
8854:
8855: sub auto_courserequest_validation {
8856: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
8857: my ($homeserver,$response);
8858: if ($dom =~ /^$match_domain$/) {
8859: $homeserver = &domain($dom,'primary');
8860: }
8861: unless ($homeserver eq 'no_host') {
8862: my $customdata;
8863: if (ref($custominfo) eq 'HASH') {
8864: $customdata = &freeze_escape($custominfo);
8865: }
8866: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
8867: ':'.&escape($crstype).':'.&escape($inststatuslist).
8868: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8869: $customdata,$homeserver));
8870: }
8871: return $response;
8872: }
8873:
8874: sub auto_validate_class_sec {
8875: my ($cdom,$cnum,$owners,$inst_class) = @_;
8876: my $homeserver = &homeserver($cnum,$cdom);
8877: my $ownerlist;
8878: if (ref($owners) eq 'ARRAY') {
8879: $ownerlist = join(',',@{$owners});
8880: } else {
8881: $ownerlist = $owners;
8882: }
8883: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
8884: &escape($ownerlist).':'.$cdom,$homeserver);
8885: return $response;
8886: }
8887:
8888: sub auto_crsreq_update {
8889: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
8890: $code,$accessstart,$accessend,$inbound) = @_;
8891: my ($homeserver,%crsreqresponse);
8892: if ($cdom =~ /^$match_domain$/) {
8893: $homeserver = &domain($cdom,'primary');
8894: }
8895: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8896: my $info;
8897: if (ref($inbound) eq 'HASH') {
8898: $info = &freeze_escape($inbound);
8899: }
8900: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8901: ':'.&escape($action).':'.&escape($ownername).':'.
8902: &escape($ownerdomain).':'.&escape($fullname).':'.
8903: &escape($title).':'.&escape($code).':'.
8904: &escape($accessstart).':'.&escape($accessend).':'.$info,
8905: $homeserver);
8906: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8907: my @items = split(/&/,$response);
8908: foreach my $item (@items) {
8909: my ($key,$value) = split('=',$item);
8910: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8911: }
8912: }
8913: }
8914: return \%crsreqresponse;
8915: }
8916:
8917: sub auto_export_grades {
8918: my ($cdom,$cnum,$inforef,$gradesref) = @_;
8919: my ($homeserver,%exportresponse);
8920: if ($cdom =~ /^$match_domain$/) {
8921: $homeserver = &domain($cdom,'primary');
8922: }
8923: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8924: my $info;
8925: if (ref($inforef) eq 'HASH') {
8926: $info = &freeze_escape($inforef);
8927: }
8928: if (ref($gradesref) eq 'HASH') {
8929: my $grades = &freeze_escape($gradesref);
8930: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
8931: $info.':'.$grades,$homeserver);
8932: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
8933: my @items = split(/&/,$response);
8934: foreach my $item (@items) {
8935: my ($key,$value) = split('=',$item);
8936: $exportresponse{&unescape($key)} = &thaw_unescape($value);
8937: }
8938: }
8939: }
8940: }
8941: return \%exportresponse;
8942: }
8943:
8944: sub check_instcode_cloning {
8945: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8946: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8947: return;
8948: }
8949: my $canclone;
8950: if (@{$code_order} > 0) {
8951: my $instcoderegexp ='^';
8952: my @clonecodes = split(/\&/,$cloner);
8953: foreach my $item (@{$code_order}) {
8954: if (grep(/^\Q$item\E=/,@clonecodes)) {
8955: foreach my $pair (@clonecodes) {
8956: my ($key,$val) = split(/\=/,$pair,2);
8957: $val = &unescape($val);
8958: if ($key eq $item) {
8959: $instcoderegexp .= '('.$val.')';
8960: last;
8961: }
8962: }
8963: } else {
8964: $instcoderegexp .= $codedefaults->{$item};
8965: }
8966: }
8967: $instcoderegexp .= '$';
8968: my (@from,@to);
8969: eval {
8970: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8971: (@to) = ($clonetocode =~ /$instcoderegexp/);
8972: };
8973: if ((@from > 0) && (@to > 0)) {
8974: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8975: if (!@diffs) {
8976: $canclone = 1;
8977: }
8978: }
8979: }
8980: return $canclone;
8981: }
8982:
8983: sub default_instcode_cloning {
8984: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8985: my (%codedefaults,@code_order,$canclone);
8986: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8987: %codedefaults = %{$codedefaultsref};
8988: @code_order = @{$codeorderref};
8989: } elsif ($clonedom) {
8990: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8991: }
8992: if (($domdefclone) && (@code_order)) {
8993: my @clonecodes = split(/\+/,$domdefclone);
8994: my $instcoderegexp ='^';
8995: foreach my $item (@code_order) {
8996: if (grep(/^\Q$item\E$/,@clonecodes)) {
8997: $instcoderegexp .= '('.$codedefaults{$item}.')';
8998: } else {
8999: $instcoderegexp .= $codedefaults{$item};
9000: }
9001: }
9002: $instcoderegexp .= '$';
9003: my (@from,@to);
9004: eval {
9005: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9006: (@to) = ($clonetocode =~ /$instcoderegexp/);
9007: };
9008: if ((@from > 0) && (@to > 0)) {
9009: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9010: if (!@diffs) {
9011: $canclone = 1;
9012: }
9013: }
9014: }
9015: return $canclone;
9016: }
9017:
9018: # ------------------------------------------------------- Course Group routines
9019:
9020: sub get_coursegroups {
9021: my ($cdom,$cnum,$group,$namespace) = @_;
9022: return(&dump($namespace,$cdom,$cnum,$group));
9023: }
9024:
9025: sub modify_coursegroup {
9026: my ($cdom,$cnum,$groupsettings) = @_;
9027: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
9028: }
9029:
9030: sub toggle_coursegroup_status {
9031: my ($cdom,$cnum,$group,$action) = @_;
9032: my ($from_namespace,$to_namespace);
9033: if ($action eq 'delete') {
9034: $from_namespace = 'coursegroups';
9035: $to_namespace = 'deleted_groups';
9036: } else {
9037: $from_namespace = 'deleted_groups';
9038: $to_namespace = 'coursegroups';
9039: }
9040: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
9041: if (my $tmp = &error(%curr_group)) {
9042: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
9043: return ('read error',$tmp);
9044: } else {
9045: my %savedsettings = %curr_group;
9046: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
9047: my $deloutcome;
9048: if ($result eq 'ok') {
9049: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
9050: } else {
9051: return ('write error',$result);
9052: }
9053: if ($deloutcome eq 'ok') {
9054: return 'ok';
9055: } else {
9056: return ('delete error',$deloutcome);
9057: }
9058: }
9059: }
9060:
9061: sub modify_group_roles {
9062: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
9063: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
9064: my $role = 'gr/'.&escape($userprivs);
9065: my ($uname,$udom) = split(/:/,$user);
9066: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
9067: if ($result eq 'ok') {
9068: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
9069: }
9070: return $result;
9071: }
9072:
9073: sub modify_coursegroup_membership {
9074: my ($cdom,$cnum,$membership) = @_;
9075: my $result = &put('groupmembership',$membership,$cdom,$cnum);
9076: return $result;
9077: }
9078:
9079: sub get_active_groups {
9080: my ($udom,$uname,$cdom,$cnum) = @_;
9081: my $now = time;
9082: my %groups = ();
9083: foreach my $key (keys(%env)) {
9084: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
9085: my ($start,$end) = split(/\./,$env{$key});
9086: if (($end!=0) && ($end<$now)) { next; }
9087: if (($start!=0) && ($start>$now)) { next; }
9088: if ($1 eq $cdom && $2 eq $cnum) {
9089: $groups{$3} = $env{$key} ;
9090: }
9091: }
9092: }
9093: return %groups;
9094: }
9095:
9096: sub get_group_membership {
9097: my ($cdom,$cnum,$group) = @_;
9098: return(&dump('groupmembership',$cdom,$cnum,$group));
9099: }
9100:
9101: sub get_users_groups {
9102: my ($udom,$uname,$courseid) = @_;
9103: my @usersgroups;
9104: my $cachetime=1800;
9105:
9106: my $hashid="$udom:$uname:$courseid";
9107: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
9108: if (defined($cached)) {
9109: @usersgroups = split(/:/,$grouplist);
9110: } else {
9111: $grouplist = '';
9112: my $courseurl = &courseid_to_courseurl($courseid);
9113: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
9114: my $access_end = $env{'course.'.$courseid.
9115: '.default_enrollment_end_date'};
9116: my $now = time;
9117: foreach my $key (keys(%roleshash)) {
9118: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
9119: my $group = $1;
9120: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
9121: my $start = $2;
9122: my $end = $1;
9123: if ($start == -1) { next; } # deleted from group
9124: if (($start!=0) && ($start>$now)) { next; }
9125: if (($end!=0) && ($end<$now)) {
9126: if ($access_end && $access_end < $now) {
9127: if ($access_end - $end < 86400) {
9128: push(@usersgroups,$group);
9129: }
9130: }
9131: next;
9132: }
9133: push(@usersgroups,$group);
9134: }
9135: }
9136: }
9137: @usersgroups = &sort_course_groups($courseid,@usersgroups);
9138: $grouplist = join(':',@usersgroups);
9139: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
9140: }
9141: return @usersgroups;
9142: }
9143:
9144: sub devalidate_getgroups_cache {
9145: my ($udom,$uname,$cdom,$cnum)=@_;
9146: my $courseid = $cdom.'_'.$cnum;
9147:
9148: my $hashid="$udom:$uname:$courseid";
9149: &devalidate_cache_new('getgroups',$hashid);
9150: }
9151:
9152: # ------------------------------------------------------------------ Plain Text
9153:
9154: sub plaintext {
9155: my ($short,$type,$cid,$forcedefault) = @_;
9156: if ($short =~ m{^cr/}) {
9157: return (split('/',$short))[-1];
9158: }
9159: if (!defined($cid)) {
9160: $cid = $env{'request.course.id'};
9161: }
9162: my %rolenames = (
9163: Course => 'std',
9164: Community => 'alt1',
9165: Placement => 'std',
9166: );
9167: if ($cid ne '') {
9168: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
9169: unless ($forcedefault) {
9170: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
9171: &Apache::lonlocal::mt_escape(\$roletext);
9172: return &Apache::lonlocal::mt($roletext);
9173: }
9174: }
9175: }
9176: if ((defined($type)) && (defined($rolenames{$type})) &&
9177: (defined($rolenames{$type})) &&
9178: (defined($prp{$short}{$rolenames{$type}}))) {
9179: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
9180: } elsif ($cid ne '') {
9181: my $crstype = $env{'course.'.$cid.'.type'};
9182: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
9183: (defined($prp{$short}{$rolenames{$crstype}}))) {
9184: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
9185: }
9186: }
9187: return &Apache::lonlocal::mt($prp{$short}{'std'});
9188: }
9189:
9190: # ----------------------------------------------------------------- Assign Role
9191:
9192: sub assignrole {
9193: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
9194: $context)=@_;
9195: my $mrole;
9196: if ($role =~ /^cr\//) {
9197: my $cwosec=$url;
9198: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
9199: unless (&allowed('ccr',$cwosec)) {
9200: my $refused = 1;
9201: if ($context eq 'requestcourses') {
9202: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
9203: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
9204: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
9205: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9206: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9207: if ($crsenv{'internal.courseowner'} eq
9208: $env{'user.name'}.':'.$env{'user.domain'}) {
9209: $refused = '';
9210: }
9211: }
9212: }
9213: }
9214: }
9215: if ($refused) {
9216: &logthis('Refused custom assignrole: '.
9217: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
9218: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
9219: return 'refused';
9220: }
9221: }
9222: $mrole='cr';
9223: } elsif ($role =~ /^gr\//) {
9224: my $cwogrp=$url;
9225: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
9226: unless (&allowed('mdg',$cwogrp)) {
9227: &logthis('Refused group assignrole: '.
9228: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
9229: $env{'user.name'}.' at '.$env{'user.domain'});
9230: return 'refused';
9231: }
9232: $mrole='gr';
9233: } else {
9234: my $cwosec=$url;
9235: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
9236: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
9237: my $refused;
9238: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
9239: if (!(&allowed('c'.$role,$url))) {
9240: $refused = 1;
9241: }
9242: } else {
9243: $refused = 1;
9244: }
9245: if ($refused) {
9246: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9247: if (!$selfenroll && $context eq 'course') {
9248: my %crsenv;
9249: if ($role eq 'cc' || $role eq 'co') {
9250: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9251: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
9252: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
9253: if ($crsenv{'internal.courseowner'} eq
9254: $env{'user.name'}.':'.$env{'user.domain'}) {
9255: $refused = '';
9256: }
9257: }
9258: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
9259: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
9260: if ($crsenv{'internal.courseowner'} eq
9261: $env{'user.name'}.':'.$env{'user.domain'}) {
9262: $refused = '';
9263: }
9264: }
9265: }
9266: }
9267: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
9268: $refused = '';
9269: } elsif ($context eq 'requestcourses') {
9270: my @possroles = ('st','ta','ep','in','cc','co');
9271: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
9272: my $wrongcc;
9273: if ($cnum =~ /^$match_community$/) {
9274: $wrongcc = 1 if ($role eq 'cc');
9275: } else {
9276: $wrongcc = 1 if ($role eq 'co');
9277: }
9278: unless ($wrongcc) {
9279: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9280: if ($crsenv{'internal.courseowner'} eq
9281: $env{'user.name'}.':'.$env{'user.domain'}) {
9282: $refused = '';
9283: }
9284: }
9285: }
9286: } elsif ($context eq 'requestauthor') {
9287: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
9288: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
9289: if ($env{'environment.requestauthor'} eq 'automatic') {
9290: $refused = '';
9291: } else {
9292: my %domdefaults = &get_domain_defaults($udom);
9293: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
9294: my $checkbystatus;
9295: if ($env{'user.adv'}) {
9296: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9297: if ($disposition eq 'automatic') {
9298: $refused = '';
9299: } elsif ($disposition eq '') {
9300: $checkbystatus = 1;
9301: }
9302: } else {
9303: $checkbystatus = 1;
9304: }
9305: if ($checkbystatus) {
9306: if ($env{'environment.inststatus'}) {
9307: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9308: foreach my $type (@inststatuses) {
9309: if (($type ne '') &&
9310: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9311: $refused = '';
9312: }
9313: }
9314: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9315: $refused = '';
9316: }
9317: }
9318: }
9319: }
9320: }
9321: }
9322: if ($refused) {
9323: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9324: ' '.$role.' '.$end.' '.$start.' by '.
9325: $env{'user.name'}.' at '.$env{'user.domain'});
9326: return 'refused';
9327: }
9328: }
9329: } elsif ($role eq 'au') {
9330: if ($url ne '/'.$udom.'/') {
9331: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9332: ' to assign author role for '.$uname.':'.$udom.
9333: ' in domain: '.$url.' refused (wrong domain).');
9334: return 'refused';
9335: }
9336: }
9337: $mrole=$role;
9338: }
9339: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
9340: "$udom:$uname:$url".'_'."$mrole=$role";
9341: if ($end) { $command.='_'.$end; }
9342: if ($start) {
9343: if ($end) {
9344: $command.='_'.$start;
9345: } else {
9346: $command.='_0_'.$start;
9347: }
9348: }
9349: my $origstart = $start;
9350: my $origend = $end;
9351: my $delflag;
9352: # actually delete
9353: if ($deleteflag) {
9354: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
9355: # modify command to delete the role
9356: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
9357: "$udom:$uname:$url".'_'."$mrole";
9358: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
9359: # set start and finish to negative values for userrolelog
9360: $start=-1;
9361: $end=-1;
9362: $delflag = 1;
9363: }
9364: }
9365: # send command
9366: my $answer=&reply($command,&homeserver($uname,$udom));
9367: # log new user role if status is ok
9368: if ($answer eq 'ok') {
9369: &userrolelog($role,$uname,$udom,$url,$start,$end);
9370: if (($role eq 'cc') || ($role eq 'in') ||
9371: ($role eq 'ep') || ($role eq 'ad') ||
9372: ($role eq 'ta') || ($role eq 'st') ||
9373: ($role=~/^cr/) || ($role eq 'gr') ||
9374: ($role eq 'co')) {
9375: # for course roles, perform group memberships changes triggered by role change.
9376: unless ($role =~ /^gr/) {
9377: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
9378: $origstart,$selfenroll,$context);
9379: }
9380: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9381: $selfenroll,$context);
9382: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
9383: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
9384: ($role eq 'da')) {
9385: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9386: $context);
9387: } elsif (($role eq 'ca') || ($role eq 'aa')) {
9388: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9389: $context);
9390: }
9391: if ($role eq 'cc') {
9392: &autoupdate_coowners($url,$end,$start,$uname,$udom);
9393: }
9394: }
9395: return $answer;
9396: }
9397:
9398: sub autoupdate_coowners {
9399: my ($url,$end,$start,$uname,$udom) = @_;
9400: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
9401: if (($cdom ne '') && ($cnum ne '')) {
9402: my $now = time;
9403: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
9404: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
9405: my %coursehash = &coursedescription($cdom.'_'.$cnum);
9406: my $instcode = $coursehash{'internal.coursecode'};
9407: if ($instcode ne '') {
9408: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
9409: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
9410: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
9411: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
9412: if ($result eq 'valid') {
9413: if ($coursehash{'internal.co-owners'}) {
9414: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9415: push(@newcoowners,$coowner);
9416: }
9417: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
9418: push(@newcoowners,$uname.':'.$udom);
9419: }
9420: @newcoowners = sort(@newcoowners);
9421: } else {
9422: push(@newcoowners,$uname.':'.$udom);
9423: }
9424: } else {
9425: if ($coursehash{'internal.co-owners'}) {
9426: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9427: unless ($coowner eq $uname.':'.$udom) {
9428: push(@newcoowners,$coowner);
9429: }
9430: }
9431: unless (@newcoowners > 0) {
9432: $delcoowners = 1;
9433: $coowners = '';
9434: }
9435: }
9436: }
9437: if (@newcoowners || $delcoowners) {
9438: &store_coowners($cdom,$cnum,$coursehash{'home'},
9439: $delcoowners,@newcoowners);
9440: }
9441: }
9442: }
9443: }
9444: }
9445: }
9446: }
9447:
9448: sub store_coowners {
9449: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
9450: my $cid = $cdom.'_'.$cnum;
9451: my ($coowners,$delresult,$putresult);
9452: if (@newcoowners) {
9453: $coowners = join(',',@newcoowners);
9454: my %coownershash = (
9455: 'internal.co-owners' => $coowners,
9456: );
9457: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
9458: if ($putresult eq 'ok') {
9459: if ($env{'course.'.$cid.'.num'} eq $cnum) {
9460: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
9461: }
9462: }
9463: }
9464: if ($delcoowners) {
9465: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
9466: if ($delresult eq 'ok') {
9467: if ($env{'course.'.$cid.'.internal.co-owners'}) {
9468: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
9469: }
9470: }
9471: }
9472: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
9473: my %crsinfo =
9474: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
9475: if (ref($crsinfo{$cid}) eq 'HASH') {
9476: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
9477: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
9478: }
9479: }
9480: }
9481:
9482: # -------------------------------------------------- Modify user authentication
9483: # Overrides without validation
9484:
9485: sub modifyuserauth {
9486: my ($udom,$uname,$umode,$upass)=@_;
9487: my $uhome=&homeserver($uname,$udom);
9488: unless (&allowed('mau',$udom)) { return 'refused'; }
9489: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
9490: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9491: ' in domain '.$env{'request.role.domain'});
9492: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
9493: &escape($upass),$uhome);
9494: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
9495: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
9496: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
9497: &log($udom,,$uname,$uhome,
9498: 'Authentication changed by '.$env{'user.domain'}.', '.
9499: $env{'user.name'}.', '.$umode.
9500: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
9501: unless ($reply eq 'ok') {
9502: &logthis('Authentication mode error: '.$reply);
9503: return 'error: '.$reply;
9504: }
9505: return 'ok';
9506: }
9507:
9508: # --------------------------------------------------------------- Modify a user
9509:
9510: sub modifyuser {
9511: my ($udom, $uname, $uid,
9512: $umode, $upass, $first,
9513: $middle, $last, $gene,
9514: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
9515: $udom= &LONCAPA::clean_domain($udom);
9516: $uname=&LONCAPA::clean_username($uname);
9517: my $showcandelete = 'none';
9518: if (ref($candelete) eq 'ARRAY') {
9519: if (@{$candelete} > 0) {
9520: $showcandelete = join(', ',@{$candelete});
9521: }
9522: }
9523: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
9524: $umode.', '.$first.', '.$middle.', '.
9525: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
9526: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
9527: ' desiredhome not specified').
9528: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9529: ' in domain '.$env{'request.role.domain'});
9530: my $uhome=&homeserver($uname,$udom,'true');
9531: my $newuser;
9532: if ($uhome eq 'no_host') {
9533: $newuser = 1;
9534: }
9535: # ----------------------------------------------------------------- Create User
9536: if (($uhome eq 'no_host') &&
9537: (($umode && $upass) || ($umode eq 'localauth'))) {
9538: my $unhome='';
9539: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
9540: $unhome = $desiredhome;
9541: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
9542: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
9543: } else { # load balancing routine for determining $unhome
9544: my $loadm=10000000;
9545: my %servers = &get_servers($udom,'library');
9546: foreach my $tryserver (keys(%servers)) {
9547: my $answer=reply('load',$tryserver);
9548: if (($answer=~/\d+/) && ($answer<$loadm)) {
9549: $loadm=$answer;
9550: $unhome=$tryserver;
9551: }
9552: }
9553: }
9554: if (($unhome eq '') || ($unhome eq 'no_host')) {
9555: return 'error: unable to find a home server for '.$uname.
9556: ' in domain '.$udom;
9557: }
9558: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
9559: &escape($upass),$unhome);
9560: unless ($reply eq 'ok') {
9561: return 'error: '.$reply;
9562: }
9563: $uhome=&homeserver($uname,$udom,'true');
9564: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
9565: return 'error: unable verify users home machine.';
9566: }
9567: } # End of creation of new user
9568: # ---------------------------------------------------------------------- Add ID
9569: if ($uid) {
9570: $uid=~tr/A-Z/a-z/;
9571: my %uidhash=&idrget($udom,$uname);
9572: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
9573: && (!$forceid)) {
9574: unless ($uid eq $uidhash{$uname}) {
9575: return 'error: user id "'.$uid.'" does not match '.
9576: 'current user id "'.$uidhash{$uname}.'".';
9577: }
9578: } else {
9579: &idput($udom,{$uname => $uid},$uhome,'ids');
9580: }
9581: }
9582: # -------------------------------------------------------------- Add names, etc
9583: my @tmp=&get('environment',
9584: ['firstname','middlename','lastname','generation','id',
9585: 'permanentemail','inststatus'],
9586: $udom,$uname);
9587: my (%names,%oldnames);
9588: if ($tmp[0] =~ m/^error:.*/) {
9589: %names=();
9590: } else {
9591: %names = @tmp;
9592: %oldnames = %names;
9593: }
9594: #
9595: # If name, email and/or uid are blank (e.g., because an uploaded file
9596: # of users did not contain them), do not overwrite existing values
9597: # unless field is in $candelete array ref.
9598: #
9599:
9600: my @fields = ('firstname','middlename','lastname','generation',
9601: 'permanentemail','id');
9602: my %newvalues;
9603: if (ref($candelete) eq 'ARRAY') {
9604: foreach my $field (@fields) {
9605: if (grep(/^\Q$field\E$/,@{$candelete})) {
9606: if ($field eq 'firstname') {
9607: $names{$field} = $first;
9608: } elsif ($field eq 'middlename') {
9609: $names{$field} = $middle;
9610: } elsif ($field eq 'lastname') {
9611: $names{$field} = $last;
9612: } elsif ($field eq 'generation') {
9613: $names{$field} = $gene;
9614: } elsif ($field eq 'permanentemail') {
9615: $names{$field} = $email;
9616: } elsif ($field eq 'id') {
9617: $names{$field} = $uid;
9618: }
9619: }
9620: }
9621: }
9622: if ($first) { $names{'firstname'} = $first; }
9623: if (defined($middle)) { $names{'middlename'} = $middle; }
9624: if ($last) { $names{'lastname'} = $last; }
9625: if (defined($gene)) { $names{'generation'} = $gene; }
9626: if ($email) {
9627: $email=~s/[^\w\@\.\-\,]//gs;
9628: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
9629: }
9630: if ($uid) { $names{'id'} = $uid; }
9631: if (defined($inststatus)) {
9632: $names{'inststatus'} = '';
9633: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
9634: if (ref($usertypes) eq 'HASH') {
9635: my @okstatuses;
9636: foreach my $item (split(/:/,$inststatus)) {
9637: if (defined($usertypes->{$item})) {
9638: push(@okstatuses,$item);
9639: }
9640: }
9641: if (@okstatuses) {
9642: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
9643: }
9644: }
9645: }
9646: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
9647: $umode.', '.$first.', '.$middle.', '.
9648: $last.', '.$gene.', '.$email.', '.$inststatus;
9649: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
9650: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
9651: } else {
9652: $logmsg .= ' during self creation';
9653: }
9654: my $changed;
9655: if ($newuser) {
9656: $changed = 1;
9657: } else {
9658: foreach my $field (@fields) {
9659: if ($names{$field} ne $oldnames{$field}) {
9660: $changed = 1;
9661: last;
9662: }
9663: }
9664: }
9665: unless ($changed) {
9666: $logmsg = 'No changes in user information needed for: '.$logmsg;
9667: &logthis($logmsg);
9668: return 'ok';
9669: }
9670: my $reply = &put('environment', \%names, $udom,$uname);
9671: if ($reply ne 'ok') {
9672: return 'error: '.$reply;
9673: }
9674: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
9675: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
9676: }
9677: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
9678: &devalidate_cache_new('namescache',$uname.':'.$udom);
9679: $logmsg = 'Success modifying user '.$logmsg;
9680: &logthis($logmsg);
9681: return 'ok';
9682: }
9683:
9684: # -------------------------------------------------------------- Modify student
9685:
9686: sub modifystudent {
9687: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
9688: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
9689: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
9690: if (!$cid) {
9691: unless ($cid=$env{'request.course.id'}) {
9692: return 'not_in_class';
9693: }
9694: }
9695: # --------------------------------------------------------------- Make the user
9696: my $reply=&modifyuser
9697: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
9698: $desiredhome,$email,$inststatus);
9699: unless ($reply eq 'ok') { return $reply; }
9700: # This will cause &modify_student_enrollment to get the uid from the
9701: # student's environment
9702: $uid = undef if (!$forceid);
9703: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
9704: $gene,$usec,$end,$start,$type,$locktype,
9705: $cid,$selfenroll,$context,$credits,$instsec);
9706: return $reply;
9707: }
9708:
9709: sub modify_student_enrollment {
9710: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
9711: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
9712: my ($cdom,$cnum,$chome);
9713: if (!$cid) {
9714: unless ($cid=$env{'request.course.id'}) {
9715: return 'not_in_class';
9716: }
9717: $cdom=$env{'course.'.$cid.'.domain'};
9718: $cnum=$env{'course.'.$cid.'.num'};
9719: } else {
9720: ($cdom,$cnum)=split(/_/,$cid);
9721: }
9722: $chome=$env{'course.'.$cid.'.home'};
9723: if (!$chome) {
9724: $chome=&homeserver($cnum,$cdom);
9725: }
9726: if (!$chome) { return 'unknown_course'; }
9727: # Make sure the user exists
9728: my $uhome=&homeserver($uname,$udom);
9729: if (($uhome eq '') || ($uhome eq 'no_host')) {
9730: return 'error: no such user';
9731: }
9732: # Get student data if we were not given enough information
9733: if (!defined($first) || $first eq '' ||
9734: !defined($last) || $last eq '' ||
9735: !defined($uid) || $uid eq '' ||
9736: !defined($middle) || $middle eq '' ||
9737: !defined($gene) || $gene eq '') {
9738: # They did not supply us with enough data to enroll the student, so
9739: # we need to pick up more information.
9740: my %tmp = &get('environment',
9741: ['firstname','middlename','lastname', 'generation','id']
9742: ,$udom,$uname);
9743:
9744: #foreach my $key (keys(%tmp)) {
9745: # &logthis("key $key = ".$tmp{$key});
9746: #}
9747: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
9748: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
9749: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
9750: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
9751: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
9752: }
9753: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
9754: my $user = "$uname:$udom";
9755: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
9756: my $reply=cput('classlist',
9757: {$user =>
9758: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
9759: $cdom,$cnum);
9760: if (($reply eq 'ok') || ($reply eq 'delayed')) {
9761: &devalidate_getsection_cache($udom,$uname,$cid);
9762: } else {
9763: return 'error: '.$reply;
9764: }
9765: # Add student role to user
9766: my $uurl='/'.$cid;
9767: $uurl=~s/\_/\//g;
9768: if ($usec) {
9769: $uurl.='/'.$usec;
9770: }
9771: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
9772: $selfenroll,$context);
9773: if ($result ne 'ok') {
9774: if ($old_entry{$user} ne '') {
9775: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
9776: } else {
9777: $reply = &del('classlist',[$user],$cdom,$cnum);
9778: }
9779: }
9780: return $result;
9781: }
9782:
9783: sub format_name {
9784: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
9785: my $name;
9786: if ($first ne 'lastname') {
9787: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
9788: } else {
9789: if ($lastname=~/\S/) {
9790: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
9791: $name=~s/\s+,/,/;
9792: } else {
9793: $name.= $firstname.' '.$middlename.' '.$generation;
9794: }
9795: }
9796: $name=~s/^\s+//;
9797: $name=~s/\s+$//;
9798: $name=~s/\s+/ /g;
9799: return $name;
9800: }
9801:
9802: # ------------------------------------------------- Write to course preferences
9803:
9804: sub writecoursepref {
9805: my ($courseid,%prefs)=@_;
9806: $courseid=~s/^\///;
9807: $courseid=~s/\_/\//g;
9808: my ($cdomain,$cnum)=split(/\//,$courseid);
9809: my $chome=homeserver($cnum,$cdomain);
9810: if (($chome eq '') || ($chome eq 'no_host')) {
9811: return 'error: no such course';
9812: }
9813: my $cstring='';
9814: foreach my $pref (keys(%prefs)) {
9815: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
9816: }
9817: $cstring=~s/\&$//;
9818: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
9819: }
9820:
9821: # ---------------------------------------------------------- Make/modify course
9822:
9823: sub createcourse {
9824: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
9825: $course_owner,$crstype,$cnum,$context,$category)=@_;
9826: $url=&declutter($url);
9827: my $cid='';
9828: if ($context eq 'requestcourses') {
9829: my $can_create = 0;
9830: my ($ownername,$ownerdom) = split(':',$course_owner);
9831: if ($udom eq $ownerdom) {
9832: if (&usertools_access($ownername,$ownerdom,$category,undef,
9833: $context)) {
9834: $can_create = 1;
9835: }
9836: } else {
9837: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
9838: $category);
9839: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
9840: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
9841: if (@curr > 0) {
9842: my @options = qw(approval validate autolimit);
9843: my $optregex = join('|',@options);
9844: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9845: $can_create = 1;
9846: }
9847: }
9848: }
9849: }
9850: if ($can_create) {
9851: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9852: unless (&allowed('ccc',$udom)) {
9853: return 'refused';
9854: }
9855: }
9856: } else {
9857: return 'refused';
9858: }
9859: } elsif (!&allowed('ccc',$udom)) {
9860: return 'refused';
9861: }
9862: # --------------------------------------------------------------- Get Unique ID
9863: my $uname;
9864: if ($cnum =~ /^$match_courseid$/) {
9865: my $chome=&homeserver($cnum,$udom,'true');
9866: if (($chome eq '') || ($chome eq 'no_host')) {
9867: $uname = $cnum;
9868: } else {
9869: $uname = &generate_coursenum($udom,$crstype);
9870: }
9871: } else {
9872: $uname = &generate_coursenum($udom,$crstype);
9873: }
9874: return $uname if ($uname =~ /^error/);
9875: # -------------------------------------------------- Check supplied server name
9876: if (!defined($course_server)) {
9877: if (defined(&domain($udom,'primary'))) {
9878: $course_server = &domain($udom,'primary');
9879: } else {
9880: $course_server = $env{'user.home'};
9881: }
9882: }
9883: my %host_servers =
9884: &Apache::lonnet::get_servers($udom,'library');
9885: unless ($host_servers{$course_server}) {
9886: return 'error: invalid home server for course: '.$course_server;
9887: }
9888: # ------------------------------------------------------------- Make the course
9889: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
9890: $course_server);
9891: unless ($reply eq 'ok') { return 'error: '.$reply; }
9892: my $uhome=&homeserver($uname,$udom,'true');
9893: if (($uhome eq '') || ($uhome eq 'no_host')) {
9894: return 'error: no such course';
9895: }
9896: # ----------------------------------------------------------------- Course made
9897: # log existence
9898: my $now = time;
9899: my $newcourse = {
9900: $udom.'_'.$uname => {
9901: description => $description,
9902: inst_code => $inst_code,
9903: owner => $course_owner,
9904: type => $crstype,
9905: creator => $env{'user.name'}.':'.
9906: $env{'user.domain'},
9907: created => $now,
9908: context => $context,
9909: },
9910: };
9911: &courseidput($udom,$newcourse,$uhome,'notime');
9912: # set toplevel url
9913: my $topurl=$url;
9914: unless ($nonstandard) {
9915: # ------------------------------------------ For standard courses, make top url
9916: my $mapurl=&clutter($url);
9917: if ($mapurl eq '/res/') { $mapurl=''; }
9918: $env{'form.initmap'}=(<<ENDINITMAP);
9919: <map>
9920: <resource id="1" type="start"></resource>
9921: <resource id="2" src="$mapurl"></resource>
9922: <resource id="3" type="finish"></resource>
9923: <link index="1" from="1" to="2"></link>
9924: <link index="2" from="2" to="3"></link>
9925: </map>
9926: ENDINITMAP
9927: $topurl=&declutter(
9928: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
9929: );
9930: }
9931: # ----------------------------------------------------------- Write preferences
9932: &writecoursepref($udom.'_'.$uname,
9933: ('description' => $description,
9934: 'url' => $topurl,
9935: 'internal.creator' => $env{'user.name'}.':'.
9936: $env{'user.domain'},
9937: 'internal.created' => $now,
9938: 'internal.creationcontext' => $context)
9939: );
9940: return '/'.$udom.'/'.$uname;
9941: }
9942:
9943: # ------------------------------------------------------------------- Create ID
9944: sub generate_coursenum {
9945: my ($udom,$crstype) = @_;
9946: my $domdesc = &domain($udom);
9947: return 'error: invalid domain' if ($domdesc eq '');
9948: my $first;
9949: if ($crstype eq 'Community') {
9950: $first = '0';
9951: } else {
9952: $first = int(1+rand(9));
9953: }
9954: my $uname=$first.
9955: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9956: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9957: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9958: # ----------------------------------------------- Make sure that does not exist
9959: my $uhome=&homeserver($uname,$udom,'true');
9960: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9961: if ($crstype eq 'Community') {
9962: $first = '0';
9963: } else {
9964: $first = int(1+rand(9));
9965: }
9966: $uname=$first.
9967: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9968: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9969: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9970: $uhome=&homeserver($uname,$udom,'true');
9971: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9972: return 'error: unable to generate unique course-ID';
9973: }
9974: }
9975: return $uname;
9976: }
9977:
9978: sub is_course {
9979: my ($cdom, $cnum) = scalar(@_) == 1 ?
9980: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9981:
9982: return unless $cdom and $cnum;
9983:
9984: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9985: '.');
9986:
9987: return unless(exists($courses{$cdom.'_'.$cnum}));
9988: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
9989: }
9990:
9991: sub store_userdata {
9992: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
9993: my $result;
9994: if ($datakey ne '') {
9995: if (ref($storehash) eq 'HASH') {
9996: if ($udom eq '' || $uname eq '') {
9997: $udom = $env{'user.domain'};
9998: $uname = $env{'user.name'};
9999: }
10000: my $uhome=&homeserver($uname,$udom);
10001: if (($uhome eq '') || ($uhome eq 'no_host')) {
10002: $result = 'error: no_host';
10003: } else {
10004: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10005: $storehash->{'host'} = $perlvar{'lonHostID'};
10006:
10007: my $namevalue='';
10008: foreach my $key (keys(%{$storehash})) {
10009: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10010: }
10011: $namevalue=~s/\&$//;
10012: unless ($namespace eq 'courserequests') {
10013: $datakey = &escape($datakey);
10014: }
10015: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
10016: $namevalue,$uhome);
10017: }
10018: } else {
10019: $result = 'error: data to store was not a hash reference';
10020: }
10021: } else {
10022: $result= 'error: invalid requestkey';
10023: }
10024: return $result;
10025: }
10026:
10027: # ---------------------------------------------------------- Assign Custom Role
10028:
10029: sub assigncustomrole {
10030: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10031: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10032: $end,$start,$deleteflag,$selfenroll,$context);
10033: }
10034:
10035: # ----------------------------------------------------------------- Revoke Role
10036:
10037: sub revokerole {
10038: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10039: my $now=time;
10040: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10041: }
10042:
10043: # ---------------------------------------------------------- Revoke Custom Role
10044:
10045: sub revokecustomrole {
10046: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10047: my $now=time;
10048: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10049: $deleteflag,$selfenroll,$context);
10050: }
10051:
10052: # ------------------------------------------------------------ Disk usage
10053: sub diskusage {
10054: my ($udom,$uname,$directorypath,$getpropath)=@_;
10055: $directorypath =~ s/\/$//;
10056: my $listing=&reply('du2:'.&escape($directorypath).':'
10057: .&escape($getpropath).':'.&escape($uname).':'
10058: .&escape($udom),homeserver($uname,$udom));
10059: if ($listing eq 'unknown_cmd') {
10060: if ($getpropath) {
10061: $directorypath = &propath($udom,$uname).'/'.$directorypath;
10062: }
10063: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10064: }
10065: return $listing;
10066: }
10067:
10068: sub is_locked {
10069: my ($file_name, $domain, $user, $which) = @_;
10070: my @check;
10071: my $is_locked;
10072: push (@check,$file_name);
10073: my %locked = &get('file_permissions',\@check,
10074: $env{'user.domain'},$env{'user.name'});
10075: my ($tmp)=keys(%locked);
10076: if ($tmp=~/^error:/) { undef(%locked); }
10077:
10078: if (ref($locked{$file_name}) eq 'ARRAY') {
10079: $is_locked = 'false';
10080: foreach my $entry (@{$locked{$file_name}}) {
10081: if (ref($entry) eq 'ARRAY') {
10082: $is_locked = 'true';
10083: if (ref($which) eq 'ARRAY') {
10084: push(@{$which},$entry);
10085: } else {
10086: last;
10087: }
10088: }
10089: }
10090: } else {
10091: $is_locked = 'false';
10092: }
10093: return $is_locked;
10094: }
10095:
10096: sub declutter_portfile {
10097: my ($file) = @_;
10098: $file =~ s{^(/portfolio/|portfolio/)}{/};
10099: return $file;
10100: }
10101:
10102: # ------------------------------------------------------------- Mark as Read Only
10103:
10104: sub mark_as_readonly {
10105: my ($domain,$user,$files,$what) = @_;
10106: my %current_permissions = &dump('file_permissions',$domain,$user);
10107: my ($tmp)=keys(%current_permissions);
10108: if ($tmp=~/^error:/) { undef(%current_permissions); }
10109: foreach my $file (@{$files}) {
10110: $file = &declutter_portfile($file);
10111: push(@{$current_permissions{$file}},$what);
10112: }
10113: &put('file_permissions',\%current_permissions,$domain,$user);
10114: return;
10115: }
10116:
10117: # ------------------------------------------------------------Save Selected Files
10118:
10119: sub save_selected_files {
10120: my ($user, $path, @files) = @_;
10121: my $filename = $user."savedfiles";
10122: my @other_files = &files_not_in_path($user, $path);
10123: open (OUT,'>',LONCAPA::tempdir().$filename);
10124: foreach my $file (@files) {
10125: print (OUT $env{'form.currentpath'}.$file."\n");
10126: }
10127: foreach my $file (@other_files) {
10128: print (OUT $file."\n");
10129: }
10130: close (OUT);
10131: return 'ok';
10132: }
10133:
10134: sub clear_selected_files {
10135: my ($user) = @_;
10136: my $filename = $user."savedfiles";
10137: open (OUT,'>',LONCAPA::tempdir().$filename);
10138: print (OUT undef);
10139: close (OUT);
10140: return ("ok");
10141: }
10142:
10143: sub files_in_path {
10144: my ($user, $path) = @_;
10145: my $filename = $user."savedfiles";
10146: my %return_files;
10147: open (IN,'<',LONCAPA::tempdir().$filename);
10148: while (my $line_in = <IN>) {
10149: chomp ($line_in);
10150: my @paths_and_file = split (m!/!, $line_in);
10151: my $file_part = pop (@paths_and_file);
10152: my $path_part = join ('/', @paths_and_file);
10153: $path_part.='/';
10154: my $path_and_file = $path_part.$file_part;
10155: if ($path_part eq $path) {
10156: $return_files{$file_part}= 'selected';
10157: }
10158: }
10159: close (IN);
10160: return (\%return_files);
10161: }
10162:
10163: # called in portfolio select mode, to show files selected NOT in current directory
10164: sub files_not_in_path {
10165: my ($user, $path) = @_;
10166: my $filename = $user."savedfiles";
10167: my @return_files;
10168: my $path_part;
10169: open(IN, '<',LONCAPA::tempdir().$filename);
10170: while (my $line = <IN>) {
10171: #ok, I know it's clunky, but I want it to work
10172: my @paths_and_file = split(m|/|, $line);
10173: my $file_part = pop(@paths_and_file);
10174: chomp($file_part);
10175: my $path_part = join('/', @paths_and_file);
10176: $path_part .= '/';
10177: my $path_and_file = $path_part.$file_part;
10178: if ($path_part ne $path) {
10179: push(@return_files, ($path_and_file));
10180: }
10181: }
10182: close(OUT);
10183: return (@return_files);
10184: }
10185:
10186: #------------------------------Submitted/Handedback Portfolio Files Versioning
10187:
10188: sub portfiles_versioning {
10189: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10190: my $portfolio_root = '/userfiles/portfolio';
10191: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10192: foreach my $file (@{$portfiles}) {
10193: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10194: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10195: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10196: my $getpropath = 1;
10197: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10198: $stu_name,$getpropath);
10199: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10200: my $new_answer =
10201: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10202: if ($new_answer ne 'problem getting file') {
10203: push(@{$versioned_portfiles}, $directory.$new_answer);
10204: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10205: [$symb,$env{'request.course.id'},'graded']);
10206: }
10207: }
10208: }
10209:
10210: sub get_next_version {
10211: my ($answer_name, $answer_ext, $dir_list) = @_;
10212: my $version;
10213: if (ref($dir_list) eq 'ARRAY') {
10214: foreach my $row (@{$dir_list}) {
10215: my ($file) = split(/\&/,$row,2);
10216: my ($file_name,$file_version,$file_ext) =
10217: &file_name_version_ext($file);
10218: if (($file_name eq $answer_name) &&
10219: ($file_ext eq $answer_ext)) {
10220: # gets here if filename and extension match,
10221: # regardless of version
10222: if ($file_version ne '') {
10223: # a versioned file is found so save it for later
10224: if ($file_version > $version) {
10225: $version = $file_version;
10226: }
10227: }
10228: }
10229: }
10230: }
10231: $version ++;
10232: return($version);
10233: }
10234:
10235: sub version_selected_portfile {
10236: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10237: my ($answer_name,$answer_ver,$answer_ext) =
10238: &file_name_version_ext($file_name);
10239: my $new_answer;
10240: $env{'form.copy'} =
10241: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10242: if($env{'form.copy'} eq '-1') {
10243: $new_answer = 'problem getting file';
10244: } else {
10245: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10246: my $copy_result =
10247: &finishuserfileupload($stu_name,$domain,'copy',
10248: '/portfolio'.$directory.$new_answer);
10249: }
10250: undef($env{'form.copy'});
10251: return ($new_answer);
10252: }
10253:
10254: sub file_name_version_ext {
10255: my ($file)=@_;
10256: my @file_parts = split(/\./, $file);
10257: my ($name,$version,$ext);
10258: if (@file_parts > 1) {
10259: $ext=pop(@file_parts);
10260: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10261: $version=pop(@file_parts);
10262: }
10263: $name=join('.',@file_parts);
10264: } else {
10265: $name=join('.',@file_parts);
10266: }
10267: return($name,$version,$ext);
10268: }
10269:
10270: #----------------------------------------------Get portfolio file permissions
10271:
10272: sub get_portfile_permissions {
10273: my ($domain,$user) = @_;
10274: my %current_permissions = &dump('file_permissions',$domain,$user);
10275: my ($tmp)=keys(%current_permissions);
10276: if ($tmp=~/^error:/) { undef(%current_permissions); }
10277: return \%current_permissions;
10278: }
10279:
10280: #---------------------------------------------Get portfolio file access controls
10281:
10282: sub get_access_controls {
10283: my ($current_permissions,$group,$file) = @_;
10284: my %access;
10285: my $real_file = $file;
10286: $file =~ s/\.meta$//;
10287: if (defined($file)) {
10288: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10289: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10290: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10291: }
10292: }
10293: } else {
10294: foreach my $key (keys(%{$current_permissions})) {
10295: if ($key =~ /\0accesscontrol$/) {
10296: if (defined($group)) {
10297: if ($key !~ m-^\Q$group\E/-) {
10298: next;
10299: }
10300: }
10301: my ($fullpath) = split(/\0/,$key);
10302: if (ref($$current_permissions{$key}) eq 'HASH') {
10303: foreach my $control (keys(%{$$current_permissions{$key}})) {
10304: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10305: }
10306: }
10307: }
10308: }
10309: }
10310: return %access;
10311: }
10312:
10313: sub modify_access_controls {
10314: my ($file_name,$changes,$domain,$user)=@_;
10315: my ($outcome,$deloutcome);
10316: my %store_permissions;
10317: my %new_values;
10318: my %new_control;
10319: my %translation;
10320: my @deletions = ();
10321: my $now = time;
10322: if (exists($$changes{'activate'})) {
10323: if (ref($$changes{'activate'}) eq 'HASH') {
10324: my @newitems = sort(keys(%{$$changes{'activate'}}));
10325: my $numnew = scalar(@newitems);
10326: for (my $i=0; $i<$numnew; $i++) {
10327: my $newkey = $newitems[$i];
10328: my $newid = &Apache::loncommon::get_cgi_id();
10329: if ($newkey =~ /^\d+:/) {
10330: $newkey =~ s/^(\d+)/$newid/;
10331: $translation{$1} = $newid;
10332: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10333: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10334: $translation{$1} = $newid;
10335: }
10336: $new_values{$file_name."\0".$newkey} =
10337: $$changes{'activate'}{$newitems[$i]};
10338: $new_control{$newkey} = $now;
10339: }
10340: }
10341: }
10342: my %todelete;
10343: my %changed_items;
10344: foreach my $action ('delete','update') {
10345: if (exists($$changes{$action})) {
10346: if (ref($$changes{$action}) eq 'HASH') {
10347: foreach my $key (keys(%{$$changes{$action}})) {
10348: my ($itemnum) = ($key =~ /^([^:]+):/);
10349: if ($action eq 'delete') {
10350: $todelete{$itemnum} = 1;
10351: } else {
10352: $changed_items{$itemnum} = $key;
10353: }
10354: }
10355: }
10356: }
10357: }
10358: # get lock on access controls for file.
10359: my $lockhash = {
10360: $file_name."\0".'locked_access_records' => $env{'user.name'}.
10361: ':'.$env{'user.domain'},
10362: };
10363: my $tries = 0;
10364: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10365:
10366: while (($gotlock ne 'ok') && $tries < 10) {
10367: $tries ++;
10368: sleep(0.1);
10369: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10370: }
10371: if ($gotlock eq 'ok') {
10372: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10373: my ($tmp)=keys(%curr_permissions);
10374: if ($tmp=~/^error:/) { undef(%curr_permissions); }
10375: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10376: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10377: if (ref($curr_controls) eq 'HASH') {
10378: foreach my $control_item (keys(%{$curr_controls})) {
10379: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10380: if (defined($todelete{$itemnum})) {
10381: push(@deletions,$file_name."\0".$control_item);
10382: } else {
10383: if (defined($changed_items{$itemnum})) {
10384: $new_control{$changed_items{$itemnum}} = $now;
10385: push(@deletions,$file_name."\0".$control_item);
10386: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10387: } else {
10388: $new_control{$control_item} = $$curr_controls{$control_item};
10389: }
10390: }
10391: }
10392: }
10393: }
10394: my ($group);
10395: if (&is_course($domain,$user)) {
10396: ($group,my $file) = split(/\//,$file_name,2);
10397: }
10398: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10399: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10400: $outcome = &put('file_permissions',\%new_values,$domain,$user);
10401: # remove lock
10402: my @del_lock = ($file_name."\0".'locked_access_records');
10403: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10404: my $sqlresult =
10405: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10406: $group);
10407: } else {
10408: $outcome = "error: could not obtain lockfile\n";
10409: }
10410: return ($outcome,$deloutcome,\%new_values,\%translation);
10411: }
10412:
10413: sub make_public_indefinitely {
10414: my (@requrl) = @_;
10415: return &automated_portfile_access('public',\@requrl);
10416: }
10417:
10418: sub automated_portfile_access {
10419: my ($accesstype,$addsref,$delsref,$info) = @_;
10420: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
10421: return 'invalid';
10422: }
10423: my %urls;
10424: if (ref($addsref) eq 'ARRAY') {
10425: foreach my $requrl (@{$addsref}) {
10426: if (&is_portfolio_url($requrl)) {
10427: unless (exists($urls{$requrl})) {
10428: $urls{$requrl} = 'add';
10429: }
10430: }
10431: }
10432: }
10433: if (ref($delsref) eq 'ARRAY') {
10434: foreach my $requrl (@{$delsref}) {
10435: if (&is_portfolio_url($requrl)) {
10436: unless (exists($urls{$requrl})) {
10437: $urls{$requrl} = 'delete';
10438: }
10439: }
10440: }
10441: }
10442: unless (keys(%urls)) {
10443: return 'invalid';
10444: }
10445: my $ip;
10446: if ($accesstype eq 'ip') {
10447: if (ref($info) eq 'HASH') {
10448: if ($info->{'ip'} ne '') {
10449: $ip = $info->{'ip'};
10450: }
10451: }
10452: if ($ip eq '') {
10453: return 'invalid';
10454: }
10455: }
10456: my $errors;
10457: my $now = time;
10458: my %current_perms;
10459: foreach my $requrl (sort(keys(%urls))) {
10460: my $action;
10461: if ($urls{$requrl} eq 'add') {
10462: $action = 'activate';
10463: } else {
10464: $action = 'none';
10465: }
10466: my $aclnum = 0;
10467: my (undef,$udom,$unum,$file_name,$group) =
10468: &parse_portfolio_url($requrl);
10469: unless (exists($current_perms{$unum.':'.$udom})) {
10470: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
10471: }
10472: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
10473: $group,$file_name);
10474: foreach my $key (keys(%{$access_controls{$file_name}})) {
10475: my ($num,$scope,$end,$start) =
10476: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10477: if ($scope eq $accesstype) {
10478: if (($start <= $now) && ($end == 0)) {
10479: if ($accesstype eq 'ip') {
10480: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
10481: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
10482: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
10483: if ($urls{$requrl} eq 'add') {
10484: $action = 'none';
10485: last;
10486: } else {
10487: $action = 'delete';
10488: $aclnum = $num;
10489: last;
10490: }
10491: }
10492: }
10493: }
10494: } elsif ($accesstype eq 'public') {
10495: if ($urls{$requrl} eq 'add') {
10496: $action = 'none';
10497: last;
10498: } else {
10499: $action = 'delete';
10500: $aclnum = $num;
10501: last;
10502: }
10503: }
10504: } elsif ($accesstype eq 'public') {
10505: $action = 'update';
10506: $aclnum = $num;
10507: last;
10508: }
10509: }
10510: }
10511: if ($action eq 'none') {
10512: next;
10513: } else {
10514: my %changes;
10515: my $newend = 0;
10516: my $newstart = $now;
10517: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
10518: $changes{$action}{$newkey} = {
10519: type => $accesstype,
10520: time => {
10521: start => $newstart,
10522: end => $newend,
10523: },
10524: };
10525: if ($accesstype eq 'ip') {
10526: $changes{$action}{$newkey}{'ip'} = [$ip];
10527: }
10528: my ($outcome,$deloutcome,$new_values,$translation) =
10529: &modify_access_controls($file_name,\%changes,$udom,$unum);
10530: unless ($outcome eq 'ok') {
10531: $errors .= $outcome.' ';
10532: }
10533: }
10534: }
10535: if ($errors) {
10536: $errors =~ s/\s$//;
10537: return $errors;
10538: } else {
10539: return 'ok';
10540: }
10541: }
10542:
10543: #------------------------------------------------------Get Marked as Read Only
10544:
10545: sub get_marked_as_readonly {
10546: my ($domain,$user,$what,$group) = @_;
10547: my $current_permissions = &get_portfile_permissions($domain,$user);
10548: my @readonly_files;
10549: my $cmp1=$what;
10550: if (ref($what)) { $cmp1=join('',@{$what}) };
10551: while (my ($file_name,$value) = each(%{$current_permissions})) {
10552: if (defined($group)) {
10553: if ($file_name !~ m-^\Q$group\E/-) {
10554: next;
10555: }
10556: }
10557: if (ref($value) eq "ARRAY"){
10558: foreach my $stored_what (@{$value}) {
10559: my $cmp2=$stored_what;
10560: if (ref($stored_what) eq 'ARRAY') {
10561: $cmp2=join('',@{$stored_what});
10562: }
10563: if ($cmp1 eq $cmp2) {
10564: push(@readonly_files, $file_name);
10565: last;
10566: } elsif (!defined($what)) {
10567: push(@readonly_files, $file_name);
10568: last;
10569: }
10570: }
10571: }
10572: }
10573: return @readonly_files;
10574: }
10575: #-----------------------------------------------------------Get Marked as Read Only Hash
10576:
10577: sub get_marked_as_readonly_hash {
10578: my ($current_permissions,$group,$what) = @_;
10579: my %readonly_files;
10580: while (my ($file_name,$value) = each(%{$current_permissions})) {
10581: if (defined($group)) {
10582: if ($file_name !~ m-^\Q$group\E/-) {
10583: next;
10584: }
10585: }
10586: if (ref($value) eq "ARRAY"){
10587: foreach my $stored_what (@{$value}) {
10588: if (ref($stored_what) eq 'ARRAY') {
10589: foreach my $lock_descriptor(@{$stored_what}) {
10590: if ($lock_descriptor eq 'graded') {
10591: $readonly_files{$file_name} = 'graded';
10592: } elsif ($lock_descriptor eq 'handback') {
10593: $readonly_files{$file_name} = 'handback';
10594: } else {
10595: if (!exists($readonly_files{$file_name})) {
10596: $readonly_files{$file_name} = 'locked';
10597: }
10598: }
10599: }
10600: }
10601: }
10602: }
10603: }
10604: return %readonly_files;
10605: }
10606: # ------------------------------------------------------------ Unmark as Read Only
10607:
10608: sub unmark_as_readonly {
10609: # unmarks $file_name (if $file_name is defined), or all files locked by $what
10610: # for portfolio submissions, $what contains [$symb,$crsid]
10611: my ($domain,$user,$what,$file_name,$group) = @_;
10612: $file_name = &declutter_portfile($file_name);
10613: my $symb_crs = $what;
10614: if (ref($what)) { $symb_crs=join('',@$what); }
10615: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
10616: my ($tmp)=keys(%current_permissions);
10617: if ($tmp=~/^error:/) { undef(%current_permissions); }
10618: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
10619: foreach my $file (@readonly_files) {
10620: my $clean_file = &declutter_portfile($file);
10621: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
10622: my $current_locks = $current_permissions{$file};
10623: my @new_locks;
10624: my @del_keys;
10625: if (ref($current_locks) eq "ARRAY"){
10626: foreach my $locker (@{$current_locks}) {
10627: my $compare=$locker;
10628: if (ref($locker) eq 'ARRAY') {
10629: $compare=join('',@{$locker});
10630: if ($compare ne $symb_crs) {
10631: push(@new_locks, $locker);
10632: }
10633: }
10634: }
10635: if (scalar(@new_locks) > 0) {
10636: $current_permissions{$file} = \@new_locks;
10637: } else {
10638: push(@del_keys, $file);
10639: &del('file_permissions',\@del_keys, $domain, $user);
10640: delete($current_permissions{$file});
10641: }
10642: }
10643: }
10644: &put('file_permissions',\%current_permissions,$domain,$user);
10645: return;
10646: }
10647:
10648: # ------------------------------------------------------------ Directory lister
10649:
10650: sub dirlist {
10651: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
10652: $uri=~s/^\///;
10653: $uri=~s/\/$//;
10654: my ($udom, $uname);
10655: if ($getuserdir) {
10656: $udom = $userdomain;
10657: $uname = $username;
10658: } else {
10659: (undef,$udom,$uname)=split(/\//,$uri);
10660: if(defined($userdomain)) {
10661: $udom = $userdomain;
10662: }
10663: if(defined($username)) {
10664: $uname = $username;
10665: }
10666: }
10667: my ($dirRoot,$listing,@listing_results);
10668:
10669: $dirRoot = $perlvar{'lonDocRoot'};
10670: if (defined($getpropath)) {
10671: $dirRoot = &propath($udom,$uname);
10672: $dirRoot =~ s/\/$//;
10673: } elsif (defined($getuserdir)) {
10674: my $subdir=$uname.'__';
10675: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10676: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10677: ."/$udom/$subdir/$uname";
10678: } elsif (defined($alternateRoot)) {
10679: $dirRoot = $alternateRoot;
10680: }
10681:
10682: if($udom) {
10683: if($uname) {
10684: my $uhome = &homeserver($uname,$udom);
10685: if ($uhome eq 'no_host') {
10686: return ([],'no_host');
10687: }
10688: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
10689: .$getuserdir.':'.&escape($dirRoot)
10690: .':'.&escape($uname).':'.&escape($udom),$uhome);
10691: if ($listing eq 'unknown_cmd') {
10692: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
10693: } else {
10694: @listing_results = map { &unescape($_); } split(/:/,$listing);
10695: }
10696: if ($listing eq 'unknown_cmd') {
10697: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
10698: @listing_results = split(/:/,$listing);
10699: } else {
10700: @listing_results = map { &unescape($_); } split(/:/,$listing);
10701: }
10702: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10703: ($listing eq 'rejected') || ($listing eq 'refused') ||
10704: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10705: return ([],$listing);
10706: } else {
10707: return (\@listing_results);
10708: }
10709: } elsif(!$alternateRoot) {
10710: my (%allusers,%listerror);
10711: my %servers = &get_servers($udom,'library');
10712: foreach my $tryserver (keys(%servers)) {
10713: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10714: &escape($udom),$tryserver);
10715: if ($listing eq 'unknown_cmd') {
10716: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10717: $udom, $tryserver);
10718: } else {
10719: @listing_results = map { &unescape($_); } split(/:/,$listing);
10720: }
10721: if ($listing eq 'unknown_cmd') {
10722: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10723: $udom, $tryserver);
10724: @listing_results = split(/:/,$listing);
10725: } else {
10726: @listing_results =
10727: map { &unescape($_); } split(/:/,$listing);
10728: }
10729: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10730: ($listing eq 'rejected') || ($listing eq 'refused') ||
10731: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10732: $listerror{$tryserver} = $listing;
10733: } else {
10734: foreach my $line (@listing_results) {
10735: my ($entry) = split(/&/,$line,2);
10736: $allusers{$entry} = 1;
10737: }
10738: }
10739: }
10740: my @alluserslist=();
10741: foreach my $user (sort(keys(%allusers))) {
10742: push(@alluserslist,$user.'&user');
10743: }
10744:
10745: if (!%listerror) {
10746: # no errors
10747: return (\@alluserslist);
10748: } elsif (scalar(keys(%servers)) == 1) {
10749: # one library server, one error
10750: my ($key) = keys(%listerror);
10751: return (\@alluserslist, $listerror{$key});
10752: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10753: # con_lost indicates that we might miss data from at least one
10754: # library server
10755: return (\@alluserslist, 'con_lost');
10756: } else {
10757: # multiple library servers and no con_lost -> data should be
10758: # complete.
10759: return (\@alluserslist);
10760: }
10761:
10762: } else {
10763: return ([],'missing username');
10764: }
10765: } elsif(!defined($getpropath)) {
10766: my $path = $perlvar{'lonDocRoot'}.'/res/';
10767: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10768: return (\@all_domains);
10769: } else {
10770: return ([],'missing domain');
10771: }
10772: }
10773:
10774: # --------------------------------------------- GetFileTimestamp
10775: # This function utilizes dirlist and returns the date stamp for
10776: # when it was last modified. It will also return an error of -1
10777: # if an error occurs
10778:
10779: sub GetFileTimestamp {
10780: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
10781: $studentDomain = &LONCAPA::clean_domain($studentDomain);
10782: $studentName = &LONCAPA::clean_username($studentName);
10783: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10784: undef,$getuserdir);
10785: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10786: return -1;
10787: }
10788: if (ref($fileref) eq 'ARRAY') {
10789: my @stats = split('&',$fileref->[0]);
10790: # @stats contains first the filename, then the stat output
10791: return $stats[10]; # so this is 10 instead of 9.
10792: } else {
10793: return -1;
10794: }
10795: }
10796:
10797: sub stat_file {
10798: my ($uri) = @_;
10799: $uri = &clutter_with_no_wrapper($uri);
10800:
10801: my ($udom,$uname,$file);
10802: if ($uri =~ m-^/(uploaded|editupload)/-) {
10803: ($udom,$uname,$file) =
10804: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
10805: $file = 'userfiles/'.$file;
10806: }
10807: if ($uri =~ m-^/res/-) {
10808: ($udom,$uname) =
10809: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
10810: $file = $uri;
10811: }
10812:
10813: if (!$udom || !$uname || !$file) {
10814: # unable to handle the uri
10815: return ();
10816: }
10817: my $getpropath;
10818: if ($file =~ /^userfiles\//) {
10819: $getpropath = 1;
10820: }
10821: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10822: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10823: return ();
10824: } else {
10825: if (ref($listref) eq 'ARRAY') {
10826: my @stats = split('&',$listref->[0]);
10827: shift(@stats); #filename is first
10828: return @stats;
10829: }
10830: }
10831: return ();
10832: }
10833:
10834: # --------------------------------------------------------- recursedirs
10835: # Recursive function to traverse either a specific user's Authoring Space
10836: # or corresponding Published Resource Space, and populate the hash ref:
10837: # $dirhashref with URLs of all directories, and if $filehashref hash
10838: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
10839: # or .rights files in resource space, and .meta, .save, .log, and .bak
10840: # files in Authoring Space.
10841: #
10842: # Inputs:
10843: #
10844: # $is_home - true if current server is home server for user's space
10845: # $context - either: priv, or res respectively for Authoring or Resource Space.
10846: # $docroot - Document root (i.e., /home/httpd/html
10847: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
10848: # $relpath - Current path (relative to top level).
10849: # $dirhashref - reference to hash to populate with URLs of directories (Required)
10850: # $filehashref - reference to hash to populate with URLs of files (Optional)
10851: #
10852: # Returns: nothing
10853: #
10854: # Side Effects: populates $dirhashref, and $filehashref (if provided).
10855: #
10856: # Currently used by interface/londocs.pm to create linked select boxes for
10857: # directory and filename to import a Course "Author" resource into a course, and
10858: # also to create linked select boxes for Authoring Space and Directory to choose
10859: # save location for creation of a new "standard" problem from the Course Editor.
10860: #
10861:
10862: sub recursedirs {
10863: my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
10864: return unless (ref($dirhashref) eq 'HASH');
10865: my $currpath = $docroot.$toppath;
10866: if ($relpath) {
10867: $currpath .= "/$relpath";
10868: }
10869: my $savefile;
10870: if (ref($filehashref)) {
10871: $savefile = 1;
10872: }
10873: if ($is_home) {
10874: if (opendir(my $dirh,$currpath)) {
10875: foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
10876: next if ($item eq '');
10877: if (-d "$currpath/$item") {
10878: my $newpath;
10879: if ($relpath) {
10880: $newpath = "$relpath/$item";
10881: } else {
10882: $newpath = $item;
10883: }
10884: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10885: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10886: } elsif ($savefile) {
10887: if ($context eq 'priv') {
10888: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10889: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10890: }
10891: } else {
10892: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
10893: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10894: }
10895: }
10896: }
10897: }
10898: closedir($dirh);
10899: }
10900: } else {
10901: my ($dirlistref,$listerror) =
10902: &dirlist($toppath.$relpath);
10903: my @dir_lines;
10904: my $dirptr=16384;
10905: if (ref($dirlistref) eq 'ARRAY') {
10906: foreach my $dir_line (sort
10907: {
10908: my ($afile)=split('&',$a,2);
10909: my ($bfile)=split('&',$b,2);
10910: return (lc($afile) cmp lc($bfile));
10911: } (@{$dirlistref})) {
10912: my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
10913: split(/\&/,$dir_line,16);
10914: $item =~ s/\s+$//;
10915: next if (($item =~ /^\.\.?$/) || ($obs));
10916: if ($dirptr&$testdir) {
10917: my $newpath;
10918: if ($relpath) {
10919: $newpath = "$relpath/$item";
10920: } else {
10921: $relpath = '/';
10922: $newpath = $item;
10923: }
10924: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10925: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10926: } elsif ($savefile) {
10927: if ($context eq 'priv') {
10928: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10929: $filehashref->{$relpath}{$item} = 1;
10930: }
10931: } else {
10932: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
10933: $filehashref->{$relpath}{$item} = 1;
10934: }
10935: }
10936: }
10937: }
10938: }
10939: }
10940: return;
10941: }
10942:
10943: # -------------------------------------------------------- Value of a Condition
10944:
10945: # gets the value of a specific preevaluated condition
10946: # stored in the string $env{user.state.<cid>}
10947: # or looks up a condition reference in the bighash and if if hasn't
10948: # already been evaluated recurses into docondval to get the value of
10949: # the condition, then memoizing it to
10950: # $env{user.state.<cid>.<condition>}
10951: sub directcondval {
10952: my $number=shift;
10953: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
10954: &Apache::lonuserstate::evalstate();
10955: }
10956: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10957: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10958: } elsif ($number =~ /^_/) {
10959: my $sub_condition;
10960: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10961: &GDBM_READER(),0640)) {
10962: $sub_condition=$bighash{'conditions'.$number};
10963: untie(%bighash);
10964: }
10965: my $value = &docondval($sub_condition);
10966: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
10967: return $value;
10968: }
10969: if ($env{'user.state.'.$env{'request.course.id'}}) {
10970: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
10971: } else {
10972: return 2;
10973: }
10974: }
10975:
10976: # get the collection of conditions for this resource
10977: sub condval {
10978: my $condidx=shift;
10979: my $allpathcond='';
10980: foreach my $cond (split(/\|/,$condidx)) {
10981: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10982: $allpathcond.=
10983: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10984: }
10985: }
10986: $allpathcond=~s/\|$//;
10987: return &docondval($allpathcond);
10988: }
10989:
10990: #evaluates an expression of conditions
10991: sub docondval {
10992: my ($allpathcond) = @_;
10993: my $result=0;
10994: if ($env{'request.course.id'}
10995: && defined($allpathcond)) {
10996: my $operand='|';
10997: my @stack;
10998: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10999: if ($chunk eq '(') {
11000: push @stack,($operand,$result);
11001: } elsif ($chunk eq ')') {
11002: my $before=pop @stack;
11003: if (pop @stack eq '&') {
11004: $result=$result>$before?$before:$result;
11005: } else {
11006: $result=$result>$before?$result:$before;
11007: }
11008: } elsif (($chunk eq '&') || ($chunk eq '|')) {
11009: $operand=$chunk;
11010: } else {
11011: my $new=directcondval($chunk);
11012: if ($operand eq '&') {
11013: $result=$result>$new?$new:$result;
11014: } else {
11015: $result=$result>$new?$result:$new;
11016: }
11017: }
11018: }
11019: }
11020: return $result;
11021: }
11022:
11023: # ---------------------------------------------------- Devalidate courseresdata
11024:
11025: sub devalidatecourseresdata {
11026: my ($coursenum,$coursedomain)=@_;
11027: my $hashid=$coursenum.':'.$coursedomain;
11028: &devalidate_cache_new('courseres',$hashid);
11029: }
11030:
11031:
11032: # --------------------------------------------------- Course Resourcedata Query
11033: #
11034: # Parameters:
11035: # $coursenum - Number of the course.
11036: # $coursedomain - Domain at which the course was created.
11037: # Returns:
11038: # A hash of the course parameters along (I think) with timestamps
11039: # and version info.
11040:
11041: sub get_courseresdata {
11042: my ($coursenum,$coursedomain)=@_;
11043: my $coursehom=&homeserver($coursenum,$coursedomain);
11044: my $hashid=$coursenum.':'.$coursedomain;
11045: my ($result,$cached)=&is_cached_new('courseres',$hashid);
11046: my %dumpreply;
11047: unless (defined($cached)) {
11048: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11049: $result=\%dumpreply;
11050: my ($tmp) = keys(%dumpreply);
11051: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11052: &do_cache_new('courseres',$hashid,$result,600);
11053: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11054: return $tmp;
11055: } elsif ($tmp =~ /^(error)/) {
11056: $result=undef;
11057: &do_cache_new('courseres',$hashid,$result,600);
11058: }
11059: }
11060: return $result;
11061: }
11062:
11063: sub devalidateuserresdata {
11064: my ($uname,$udom)=@_;
11065: my $hashid="$udom:$uname";
11066: &devalidate_cache_new('userres',$hashid);
11067: }
11068:
11069: sub get_userresdata {
11070: my ($uname,$udom)=@_;
11071: #most student don\'t have any data set, check if there is some data
11072: if (&EXT_cache_status($udom,$uname)) { return undef; }
11073:
11074: my $hashid="$udom:$uname";
11075: my ($result,$cached)=&is_cached_new('userres',$hashid);
11076: if (!defined($cached)) {
11077: my %resourcedata=&dump('resourcedata',$udom,$uname);
11078: $result=\%resourcedata;
11079: &do_cache_new('userres',$hashid,$result,600);
11080: }
11081: my ($tmp)=keys(%$result);
11082: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11083: return $result;
11084: }
11085: #error 2 occurs when the .db doesn't exist
11086: if ($tmp!~/error: 2 /) {
11087: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11088: &logthis("<font color=\"blue\">WARNING:".
11089: " Trying to get resource data for ".
11090: $uname." at ".$udom.": ".
11091: $tmp."</font>");
11092: }
11093: } elsif ($tmp=~/error: 2 /) {
11094: #&EXT_cache_set($udom,$uname);
11095: &do_cache_new('userres',$hashid,undef,600);
11096: undef($tmp); # not really an error so don't send it back
11097: }
11098: return $tmp;
11099: }
11100: #----------------------------------------------- resdata - return resource data
11101: # Purpose:
11102: # Return resource data for either users or for a course.
11103: # Parameters:
11104: # $name - Course/user name.
11105: # $domain - Name of the domain the user/course is registered on.
11106: # $type - Type of thing $name is (must be 'course' or 'user')
11107: # $mapp - decluttered URL of enclosing map
11108: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
11109: # $recurseup - Ref to array of map URLs, starting with map containing
11110: # $mapp up through hierarchy of nested maps to top level map.
11111: # $courseid - CourseID (first part of param identifier).
11112: # $modifier - Middle part of param identifier.
11113: # $what - Last part of param identifier.
11114: # @which - Array of names of resources desired.
11115: # Returns:
11116: # The value of the first reasource in @which that is found in the
11117: # resource hash.
11118: # Exceptional Conditions:
11119: # If the $type passed in is not valid (not the string 'course' or
11120: # 'user', an undefined reference is returned.
11121: # If none of the resources are found, an undef is returned
11122: sub resdata {
11123: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11124: $modifier,$what,@which)=@_;
11125: my $result;
11126: if ($type eq 'course') {
11127: $result=&get_courseresdata($name,$domain);
11128: } elsif ($type eq 'user') {
11129: $result=&get_userresdata($name,$domain);
11130: }
11131: if (!ref($result)) { return $result; }
11132: foreach my $item (@which) {
11133: if ($item->[1] eq 'course') {
11134: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11135: unless ($$recursed) {
11136: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11137: $$recursed = 1;
11138: }
11139: foreach my $item (@${recurseup}) {
11140: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11141: last if (defined($result->{$norecursechk}));
11142: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11143: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11144: }
11145: }
11146: }
11147: if (defined($result->{$item->[0]})) {
11148: return [$result->{$item->[0]},$item->[1]];
11149: }
11150: }
11151: return undef;
11152: }
11153:
11154: sub get_domain_ltitools {
11155: my ($cdom) = @_;
11156: my %ltitools;
11157: my ($result,$cached)=&is_cached_new('ltitools',$cdom);
11158: if (defined($cached)) {
11159: if (ref($result) eq 'HASH') {
11160: %ltitools = %{$result};
11161: }
11162: } else {
11163: my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
11164: if (ref($domconfig{'ltitools'}) eq 'HASH') {
11165: %ltitools = %{$domconfig{'ltitools'}};
11166: my %encdomconfig = &get_dom('encconfig',['ltitools'],$cdom);
11167: if (ref($encdomconfig{'ltitools'}) eq 'HASH') {
11168: foreach my $id (keys(%ltitools)) {
11169: if (ref($encdomconfig{'ltitools'}{$id}) eq 'HASH') {
11170: foreach my $item ('key','secret') {
11171: $ltitools{$id}{$item} = $encdomconfig{'ltitools'}{$id}{$item};
11172: }
11173: }
11174: }
11175: }
11176: }
11177: my $cachetime = 24*60*60;
11178: &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
11179: }
11180: return %ltitools;
11181: }
11182:
11183: sub get_numsuppfiles {
11184: my ($cnum,$cdom,$ignorecache)=@_;
11185: my $hashid=$cnum.':'.$cdom;
11186: my ($suppcount,$cached);
11187: unless ($ignorecache) {
11188: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11189: }
11190: unless (defined($cached)) {
11191: my $chome=&homeserver($cnum,$cdom);
11192: unless ($chome eq 'no_host') {
11193: ($suppcount,my $errors) = (0,0);
11194: my $suppmap = 'supplemental.sequence';
11195: ($suppcount,$errors) =
11196: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11197: }
11198: &do_cache_new('suppcount',$hashid,$suppcount,600);
11199: }
11200: return $suppcount;
11201: }
11202:
11203: #
11204: # EXT resource caching routines
11205: #
11206:
11207: {
11208: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11209: #
11210: # The course for which we cache
11211: my $cachedmapkey='';
11212: # The cached recursive maps for this course
11213: my %cachedmaps=();
11214: # When this was last done
11215: my $cachedmaptime='';
11216:
11217: sub clear_EXT_cache_status {
11218: &delenv('cache.EXT.');
11219: }
11220:
11221: sub EXT_cache_status {
11222: my ($target_domain,$target_user) = @_;
11223: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11224: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11225: # We know already the user has no data
11226: return 1;
11227: } else {
11228: return 0;
11229: }
11230: }
11231:
11232: sub EXT_cache_set {
11233: my ($target_domain,$target_user) = @_;
11234: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11235: #&appenv({$cachename => time});
11236: }
11237:
11238: # --------------------------------------------------------- Value of a Variable
11239: sub EXT {
11240:
11241: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11242: unless ($varname) { return ''; }
11243: #get real user name/domain, courseid and symb
11244: my $courseid;
11245: my $publicuser;
11246: if ($symbparm) {
11247: $symbparm=&get_symb_from_alias($symbparm);
11248: }
11249: if (!($uname && $udom)) {
11250: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11251: if (!$symbparm) { $symbparm=$cursymb; }
11252: } else {
11253: $courseid=$env{'request.course.id'};
11254: }
11255: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11256: my $rest;
11257: if (defined($therest[0])) {
11258: $rest=join('.',@therest);
11259: } else {
11260: $rest='';
11261: }
11262:
11263: my $qualifierrest=$qualifier;
11264: if ($rest) { $qualifierrest.='.'.$rest; }
11265: my $spacequalifierrest=$space;
11266: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11267: if ($realm eq 'user') {
11268: # --------------------------------------------------------------- user.resource
11269: if ($space eq 'resource') {
11270: if ( (defined($Apache::lonhomework::parsing_a_problem)
11271: || defined($Apache::lonhomework::parsing_a_task))
11272: &&
11273: ($symbparm eq &symbread()) ) {
11274: # if we are in the middle of processing the resource the
11275: # get the value we are planning on committing
11276: if (defined($Apache::lonhomework::results{$qualifierrest})) {
11277: return $Apache::lonhomework::results{$qualifierrest};
11278: } else {
11279: return $Apache::lonhomework::history{$qualifierrest};
11280: }
11281: } else {
11282: my %restored;
11283: if ($publicuser || $env{'request.state'} eq 'construct') {
11284: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11285: } else {
11286: %restored=&restore($symbparm,$courseid,$udom,$uname);
11287: }
11288: return $restored{$qualifierrest};
11289: }
11290: # ----------------------------------------------------------------- user.access
11291: } elsif ($space eq 'access') {
11292: # FIXME - not supporting calls for a specific user
11293: return &allowed($qualifier,$rest);
11294: # ------------------------------------------ user.preferences, user.environment
11295: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11296: if (($uname eq $env{'user.name'}) &&
11297: ($udom eq $env{'user.domain'})) {
11298: return $env{join('.',('environment',$qualifierrest))};
11299: } else {
11300: my %returnhash;
11301: if (!$publicuser) {
11302: %returnhash=&userenvironment($udom,$uname,
11303: $qualifierrest);
11304: }
11305: return $returnhash{$qualifierrest};
11306: }
11307: # ----------------------------------------------------------------- user.course
11308: } elsif ($space eq 'course') {
11309: # FIXME - not supporting calls for a specific user
11310: return $env{join('.',('request.course',$qualifier))};
11311: # ------------------------------------------------------------------- user.role
11312: } elsif ($space eq 'role') {
11313: # FIXME - not supporting calls for a specific user
11314: my ($role,$where)=split(/\./,$env{'request.role'});
11315: if ($qualifier eq 'value') {
11316: return $role;
11317: } elsif ($qualifier eq 'extent') {
11318: return $where;
11319: }
11320: # ----------------------------------------------------------------- user.domain
11321: } elsif ($space eq 'domain') {
11322: return $udom;
11323: # ------------------------------------------------------------------- user.name
11324: } elsif ($space eq 'name') {
11325: return $uname;
11326: # ---------------------------------------------------- Any other user namespace
11327: } else {
11328: my %reply;
11329: if (!$publicuser) {
11330: %reply=&get($space,[$qualifierrest],$udom,$uname);
11331: }
11332: return $reply{$qualifierrest};
11333: }
11334: } elsif ($realm eq 'query') {
11335: # ---------------------------------------------- pull stuff out of query string
11336: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11337: [$spacequalifierrest]);
11338: return $env{'form.'.$spacequalifierrest};
11339: } elsif ($realm eq 'request') {
11340: # ------------------------------------------------------------- request.browser
11341: if ($space eq 'browser') {
11342: return $env{'browser.'.$qualifier};
11343: # ------------------------------------------------------------ request.filename
11344: } else {
11345: return $env{'request.'.$spacequalifierrest};
11346: }
11347: } elsif ($realm eq 'course') {
11348: # ---------------------------------------------------------- course.description
11349: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11350: } elsif ($realm eq 'resource') {
11351:
11352: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11353: if (!$symbparm) { $symbparm=&symbread(); }
11354: }
11355:
11356: if ($qualifier eq '') {
11357: if ($space eq 'title') {
11358: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11359: return &gettitle($symbparm);
11360: }
11361:
11362: if ($space eq 'map') {
11363: my ($map) = &decode_symb($symbparm);
11364: return &symbread($map);
11365: }
11366: if ($space eq 'maptitle') {
11367: my ($map) = &decode_symb($symbparm);
11368: return &gettitle($map);
11369: }
11370: if ($space eq 'filename') {
11371: if ($symbparm) {
11372: return &clutter((&decode_symb($symbparm))[2]);
11373: }
11374: return &hreflocation('',$env{'request.filename'});
11375: }
11376:
11377: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11378: if ($space eq 'visibleparts') {
11379: my $navmap = Apache::lonnavmaps::navmap->new();
11380: my $item;
11381: if (ref($navmap)) {
11382: my $res = $navmap->getBySymb($symbparm);
11383: my $parts = $res->parts();
11384: if (ref($parts) eq 'ARRAY') {
11385: $item = join(',',@{$parts});
11386: }
11387: undef($navmap);
11388: }
11389: return $item;
11390: }
11391: }
11392: }
11393:
11394: my ($section, $group, @groups, @recurseup, $recursed);
11395: my ($courselevelm,$courseleveli,$courselevel,$mapp);
11396: if (($courseid eq '') && ($cid)) {
11397: $courseid = $cid;
11398: }
11399: if (($symbparm && $courseid) &&
11400: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
11401:
11402: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11403:
11404: # ----------------------------------------------------- Cascading lookup scheme
11405: my $symbp=$symbparm;
11406: $mapp=&deversion((&decode_symb($symbp))[0]);
11407: my $symbparm=$symbp.'.'.$spacequalifierrest;
11408: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
11409: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11410: if (($env{'user.name'} eq $uname) &&
11411: ($env{'user.domain'} eq $udom)) {
11412: $section=$env{'request.course.sec'};
11413: @groups = split(/:/,$env{'request.course.groups'});
11414: @groups=&sort_course_groups($courseid,@groups);
11415: } else {
11416: if (! defined($usection)) {
11417: $section=&getsection($udom,$uname,$courseid);
11418: } else {
11419: $section = $usection;
11420: }
11421: @groups = &get_users_groups($udom,$uname,$courseid);
11422: }
11423:
11424: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11425: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11426: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
11427: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11428:
11429: $courselevel=$courseid.'.'.$spacequalifierrest;
11430: my $courselevelr=$courseid.'.'.$symbparm;
11431: $courseleveli=$courseid.'.'.$recurseparm;
11432: $courselevelm=$courseid.'.'.$mapparm;
11433:
11434: # ----------------------------------------------------------- first, check user
11435:
11436: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
11437: \@recurseup,$courseid,'.',$spacequalifierrest,
11438: ([$courselevelr,'resource'],
11439: [$courselevelm,'map' ],
11440: [$courseleveli,'map' ],
11441: [$courselevel, 'course' ]));
11442: if (defined($userreply)) { return &get_reply($userreply); }
11443:
11444: # ------------------------------------------------ second, check some of course
11445: my $coursereply;
11446: if (@groups > 0) {
11447: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11448: $recurseparm,$mapparm,$spacequalifierrest,
11449: $mapp,\$recursed,\@recurseup);
11450: if (defined($coursereply)) { return &get_reply($coursereply); }
11451: }
11452:
11453: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11454: $env{'course.'.$courseid.'.domain'},
11455: 'course',$mapp,\$recursed,\@recurseup,
11456: $courseid,'.['.$section.'].',$spacequalifierrest,
11457: ([$seclevelr, 'resource'],
11458: [$seclevelm, 'map' ],
11459: [$secleveli, 'map' ],
11460: [$seclevel, 'course' ],
11461: [$courselevelr,'resource']));
11462: if (defined($coursereply)) { return &get_reply($coursereply); }
11463:
11464: # ------------------------------------------------------ third, check map parms
11465: my %parmhash=();
11466: my $thisparm='';
11467: if (tie(%parmhash,'GDBM_File',
11468: $env{'request.course.fn'}.'_parms.db',
11469: &GDBM_READER(),0640)) {
11470: $thisparm=$parmhash{$symbparm};
11471: untie(%parmhash);
11472: }
11473: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
11474: }
11475: # ------------------------------------------ fourth, look in resource metadata
11476:
11477: my $what = $spacequalifierrest;
11478: $what=~s/\./\_/;
11479: my $filename;
11480: if (!$symbparm) { $symbparm=&symbread(); }
11481: if ($symbparm) {
11482: $filename=(&decode_symb($symbparm))[2];
11483: } else {
11484: $filename=$env{'request.filename'};
11485: }
11486: my $metadata=&metadata($filename,$what);
11487: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11488: $metadata=&metadata($filename,'parameter_'.$what);
11489: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11490:
11491: # ----------------------------------------------- fifth, look in rest of course
11492: if ($symbparm && defined($courseid) &&
11493: $courseid eq $env{'request.course.id'}) {
11494: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11495: $env{'course.'.$courseid.'.domain'},
11496: 'course',$mapp,\$recursed,\@recurseup,
11497: $courseid,'.',$spacequalifierrest,
11498: ([$courselevelm,'map' ],
11499: [$courseleveli,'map' ],
11500: [$courselevel, 'course']));
11501: if (defined($coursereply)) { return &get_reply($coursereply); }
11502: }
11503: # ------------------------------------------------------------------ Cascade up
11504: unless ($space eq '0') {
11505: my @parts=split(/_/,$space);
11506: my $id=pop(@parts);
11507: my $part=join('_',@parts);
11508: if ($part eq '') { $part='0'; }
11509: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
11510: $symbparm,$udom,$uname,$section,1);
11511: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
11512: }
11513: if ($recurse) { return undef; }
11514: my $pack_def=&packages_tab_default($filename,$varname);
11515: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
11516: # ---------------------------------------------------- Any other user namespace
11517: } elsif ($realm eq 'environment') {
11518: # ----------------------------------------------------------------- environment
11519: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11520: return $env{'environment.'.$spacequalifierrest};
11521: } else {
11522: if ($uname eq 'anonymous' && $udom eq '') {
11523: return '';
11524: }
11525: my %returnhash=&userenvironment($udom,$uname,
11526: $spacequalifierrest);
11527: return $returnhash{$spacequalifierrest};
11528: }
11529: } elsif ($realm eq 'system') {
11530: # ----------------------------------------------------------------- system.time
11531: if ($space eq 'time') {
11532: return time;
11533: }
11534: } elsif ($realm eq 'server') {
11535: # ----------------------------------------------------------------- system.time
11536: if ($space eq 'name') {
11537: return $ENV{'SERVER_NAME'};
11538: }
11539: }
11540: return '';
11541: }
11542:
11543: sub get_reply {
11544: my ($reply_value) = @_;
11545: if (ref($reply_value) eq 'ARRAY') {
11546: if (wantarray) {
11547: return @$reply_value;
11548: }
11549: return $reply_value->[0];
11550: } else {
11551: return $reply_value;
11552: }
11553: }
11554:
11555: sub check_group_parms {
11556: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
11557: $recursed,$recurseupref) = @_;
11558: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
11559: [$what,'course']);
11560: my $coursereply;
11561: foreach my $group (@{$groups}) {
11562: my @groupitems = ();
11563: foreach my $level (@levels) {
11564: my $item = $courseid.'.['.$group.'].'.$level->[0];
11565: push(@groupitems,[$item,$level->[1]]);
11566: }
11567: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11568: $env{'course.'.$courseid.'.domain'},
11569: 'course',$mapp,$recursed,$recurseupref,
11570: $courseid,'.['.$group.'].',$what,
11571: @groupitems);
11572: last if (defined($coursereply));
11573: }
11574: return $coursereply;
11575: }
11576:
11577: sub get_map_hierarchy {
11578: my ($mapname,$courseid) = @_;
11579: my @recurseup = ();
11580: if ($mapname) {
11581: if (($cachedmapkey eq $courseid) &&
11582: (abs($cachedmaptime-time)<5)) {
11583: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
11584: return @{$cachedmaps{$mapname}};
11585: }
11586: }
11587: my $navmap = Apache::lonnavmaps::navmap->new();
11588: if (ref($navmap)) {
11589: @recurseup = $navmap->recurseup_maps($mapname);
11590: undef($navmap);
11591: $cachedmaps{$mapname} = \@recurseup;
11592: $cachedmaptime=time;
11593: $cachedmapkey=$courseid;
11594: }
11595: }
11596: return @recurseup;
11597: }
11598:
11599: }
11600:
11601: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
11602: my ($courseid,@groups) = @_;
11603: @groups = sort(@groups);
11604: return @groups;
11605: }
11606:
11607: sub packages_tab_default {
11608: my ($uri,$varname)=@_;
11609: my (undef,$part,$name)=split(/\./,$varname);
11610:
11611: my (@extension,@specifics,$do_default);
11612: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
11613: my ($pack_type,$pack_part)=split(/_/,$package,2);
11614: if ($pack_type eq 'default') {
11615: $do_default=1;
11616: } elsif ($pack_type eq 'extension') {
11617: push(@extension,[$package,$pack_type,$pack_part]);
11618: } elsif ($pack_part eq $part || $pack_type eq 'part') {
11619: # only look at packages defaults for packages that this id is
11620: push(@specifics,[$package,$pack_type,$pack_part]);
11621: }
11622: }
11623: # first look for a package that matches the requested part id
11624: foreach my $package (@specifics) {
11625: my (undef,$pack_type,$pack_part)=@{$package};
11626: next if ($pack_part ne $part);
11627: if (defined($packagetab{"$pack_type&$name&default"})) {
11628: return $packagetab{"$pack_type&$name&default"};
11629: }
11630: }
11631: # look for any possible matching non extension_ package
11632: foreach my $package (@specifics) {
11633: my (undef,$pack_type,$pack_part)=@{$package};
11634: if (defined($packagetab{"$pack_type&$name&default"})) {
11635: return $packagetab{"$pack_type&$name&default"};
11636: }
11637: if ($pack_type eq 'part') { $pack_part='0'; }
11638: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11639: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
11640: }
11641: }
11642: # look for any posible extension_ match
11643: foreach my $package (@extension) {
11644: my ($package,$pack_type)=@{$package};
11645: if (defined($packagetab{"$pack_type&$name&default"})) {
11646: return $packagetab{"$pack_type&$name&default"};
11647: }
11648: if (defined($packagetab{$package."&$name&default"})) {
11649: return $packagetab{$package."&$name&default"};
11650: }
11651: }
11652: # look for a global default setting
11653: if ($do_default && defined($packagetab{"default&$name&default"})) {
11654: return $packagetab{"default&$name&default"};
11655: }
11656: return undef;
11657: }
11658:
11659: sub add_prefix_and_part {
11660: my ($prefix,$part)=@_;
11661: my $keyroot;
11662: if (defined($prefix) && $prefix !~ /^__/) {
11663: # prefix that has a part already
11664: $keyroot=$prefix;
11665: } elsif (defined($prefix)) {
11666: # prefix that is missing a part
11667: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11668: } else {
11669: # no prefix at all
11670: if (defined($part)) { $keyroot='_'.$part; }
11671: }
11672: return $keyroot;
11673: }
11674:
11675: # ---------------------------------------------------------------- Get metadata
11676:
11677: my %metaentry;
11678: my %importedpartids;
11679: sub metadata {
11680: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
11681: $uri=&declutter($uri);
11682: # if it is a non metadata possible uri return quickly
11683: if (($uri eq '') ||
11684: (($uri =~ m|^/*adm/|) &&
11685: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
11686: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
11687: return undef;
11688: }
11689: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
11690: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
11691: return undef;
11692: }
11693: my $filename=$uri;
11694: $uri=~s/\.meta$//;
11695: #
11696: # Is the metadata already cached?
11697: # Look at timestamp of caching
11698: # Everything is cached by the main uri, libraries are never directly cached
11699: #
11700: if (!defined($liburi)) {
11701: my ($result,$cached)=&is_cached_new('meta',$uri);
11702: if (defined($cached)) { return $result->{':'.$what}; }
11703: }
11704: {
11705: # Imported parts would go here
11706: my %importedids=();
11707: my @origfileimportpartids=();
11708: my $importedparts=0;
11709: #
11710: # Is this a recursive call for a library?
11711: #
11712: # if (! exists($metacache{$uri})) {
11713: # $metacache{$uri}={};
11714: # }
11715: my $cachetime = 60*60;
11716: if ($liburi) {
11717: $liburi=&declutter($liburi);
11718: $filename=$liburi;
11719: } else {
11720: &devalidate_cache_new('meta',$uri);
11721: undef(%metaentry);
11722: }
11723: my %metathesekeys=();
11724: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
11725: my $metastring;
11726: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
11727: my $which = &hreflocation('','/'.($liburi || $uri));
11728: $metastring =
11729: &Apache::lonnet::ssi_body($which,
11730: ('grade_target' => 'meta'));
11731: $cachetime = 1; # only want this cached in the child not long term
11732: } elsif (($uri !~ m -^(editupload)/-) &&
11733: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
11734: my $file=&filelocation('',&clutter($filename));
11735: #push(@{$metaentry{$uri.'.file'}},$file);
11736: $metastring=&getfile($file);
11737: }
11738: my $parser=HTML::LCParser->new(\$metastring);
11739: my $token;
11740: undef %metathesekeys;
11741: while ($token=$parser->get_token) {
11742: if ($token->[0] eq 'S') {
11743: if (defined($token->[2]->{'package'})) {
11744: #
11745: # This is a package - get package info
11746: #
11747: my $package=$token->[2]->{'package'};
11748: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11749: if (defined($token->[2]->{'id'})) {
11750: $keyroot.='_'.$token->[2]->{'id'};
11751: }
11752: if ($metaentry{':packages'}) {
11753: $metaentry{':packages'}.=','.$package.$keyroot;
11754: } else {
11755: $metaentry{':packages'}=$package.$keyroot;
11756: }
11757: foreach my $pack_entry (keys(%packagetab)) {
11758: my $part=$keyroot;
11759: $part=~s/^\_//;
11760: if ($pack_entry=~/^\Q$package\E\&/ ||
11761: $pack_entry=~/^\Q$package\E_0\&/) {
11762: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
11763: # ignore package.tab specified default values
11764: # here &package_tab_default() will fetch those
11765: if ($subp eq 'default') { next; }
11766: my $value=$packagetab{$pack_entry};
11767: my $unikey;
11768: if ($pack =~ /_0$/) {
11769: $unikey='parameter_0_'.$name;
11770: $part=0;
11771: } else {
11772: $unikey='parameter'.$keyroot.'_'.$name;
11773: }
11774: if ($subp eq 'display') {
11775: $value.=' [Part: '.$part.']';
11776: }
11777: $metaentry{':'.$unikey.'.part'}=$part;
11778: $metathesekeys{$unikey}=1;
11779: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11780: $metaentry{':'.$unikey.'.'.$subp}=$value;
11781: }
11782: if (defined($metaentry{':'.$unikey.'.default'})) {
11783: $metaentry{':'.$unikey}=
11784: $metaentry{':'.$unikey.'.default'};
11785: }
11786: }
11787: }
11788: } else {
11789: #
11790: # This is not a package - some other kind of start tag
11791: #
11792: my $entry=$token->[1];
11793: my $unikey='';
11794:
11795: if ($entry eq 'import') {
11796: #
11797: # Importing a library here
11798: #
11799: my $location=$parser->get_text('/import');
11800: my $dir=$filename;
11801: $dir=~s|[^/]*$||;
11802: $location=&filelocation($dir,$location);
11803:
11804: my $importmode=$token->[2]->{'importmode'};
11805: if ($importmode eq 'problem') {
11806: # Import as problem/response
11807: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11808: } elsif ($importmode eq 'part') {
11809: # Import as part(s)
11810: $importedparts=1;
11811: # We need to get the original file and the imported file to get the part order correct
11812: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11813: # Load and inspect original file
11814: if ($#origfileimportpartids<0) {
11815: undef(%importedpartids);
11816: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11817: my $origfile=&getfile($origfilelocation);
11818: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11819: }
11820:
11821: # Load and inspect imported file
11822: my $impfile=&getfile($location);
11823: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11824: if ($#impfilepartids>=0) {
11825: # This problem had parts
11826: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
11827: } else {
11828: # Importing by turning a single problem into a problem part
11829: # It gets the import-tags ID as part-ID
11830: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
11831: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
11832: }
11833: } else {
11834: # Normal import
11835: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11836: if (defined($token->[2]->{'id'})) {
11837: $unikey.='_'.$token->[2]->{'id'};
11838: }
11839: }
11840:
11841: if ($depthcount<20) {
11842: my $metadata =
11843: &metadata($uri,'keys', $location,$unikey,
11844: $depthcount+1);
11845: foreach my $meta (split(',',$metadata)) {
11846: $metaentry{':'.$meta}=$metaentry{':'.$meta};
11847: $metathesekeys{$meta}=1;
11848: }
11849:
11850: }
11851: } else {
11852: #
11853: # Not importing, some other kind of non-package, non-library start tag
11854: #
11855: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11856: if (defined($token->[2]->{'id'})) {
11857: $unikey.='_'.$token->[2]->{'id'};
11858: }
11859: if (defined($token->[2]->{'name'})) {
11860: $unikey.='_'.$token->[2]->{'name'};
11861: }
11862: $metathesekeys{$unikey}=1;
11863: foreach my $param (@{$token->[3]}) {
11864: $metaentry{':'.$unikey.'.'.$param} =
11865: $token->[2]->{$param};
11866: }
11867: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
11868: my $default=$metaentry{':'.$unikey.'.default'};
11869: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11870: # only ws inside the tag, and not in default, so use default
11871: # as value
11872: $metaentry{':'.$unikey}=$default;
11873: } elsif ( $internaltext =~ /\S/ ) {
11874: # something interesting inside the tag
11875: $metaentry{':'.$unikey}=$internaltext;
11876: } else {
11877: # no interesting values, don't set a default
11878: }
11879: # end of not-a-package not-a-library import
11880: }
11881: # end of not-a-package start tag
11882: }
11883: # the next is the end of "start tag"
11884: }
11885: }
11886: my ($extension) = ($uri =~ /\.(\w+)$/);
11887: $extension = lc($extension);
11888: if ($extension eq 'htm') { $extension='html'; }
11889:
11890: foreach my $key (keys(%packagetab)) {
11891: #no specific packages #how's our extension
11892: if ($key!~/^extension_\Q$extension\E&/) { next; }
11893: &metadata_create_package_def($uri,$key,'extension_'.$extension,
11894: \%metathesekeys);
11895: }
11896:
11897: if (!exists($metaentry{':packages'})
11898: || $packagetab{"import_defaults&extension_$extension"}) {
11899: foreach my $key (keys(%packagetab)) {
11900: #no specific packages well let's get default then
11901: if ($key!~/^default&/) { next; }
11902: &metadata_create_package_def($uri,$key,'default',
11903: \%metathesekeys);
11904: }
11905: }
11906: # are there custom rights to evaluate
11907: if ($metaentry{':copyright'} eq 'custom') {
11908:
11909: #
11910: # Importing a rights file here
11911: #
11912: unless ($depthcount) {
11913: my $location=$metaentry{':customdistributionfile'};
11914: my $dir=$filename;
11915: $dir=~s|[^/]*$||;
11916: $location=&filelocation($dir,$location);
11917: my $rights_metadata =
11918: &metadata($uri,'keys',$location,'_rights',
11919: $depthcount+1);
11920: foreach my $rights (split(',',$rights_metadata)) {
11921: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11922: $metathesekeys{$rights}=1;
11923: }
11924: }
11925: }
11926: # uniqifiy package listing
11927: my %seen;
11928: my @uniq_packages =
11929: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11930: $metaentry{':packages'} = join(',',@uniq_packages);
11931:
11932: if ($importedparts) {
11933: # We had imported parts and need to rebuild partorder
11934: $metaentry{':partorder'}='';
11935: $metathesekeys{'partorder'}=1;
11936: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
11937: if ($origfileimportpartids[$index] eq 'part') {
11938: # original part, part of the problem
11939: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
11940: } else {
11941: # we have imported parts at this position
11942: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
11943: }
11944: }
11945: $metaentry{':partorder'}=~s/^\,//;
11946: }
11947:
11948: $metaentry{':keys'} = join(',',keys(%metathesekeys));
11949: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
11950: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
11951: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
11952: # this is the end of "was not already recently cached
11953: }
11954: return $metaentry{':'.$what};
11955: }
11956:
11957: sub metadata_create_package_def {
11958: my ($uri,$key,$package,$metathesekeys)=@_;
11959: my ($pack,$name,$subp)=split(/\&/,$key);
11960: if ($subp eq 'default') { next; }
11961:
11962: if (defined($metaentry{':packages'})) {
11963: $metaentry{':packages'}.=','.$package;
11964: } else {
11965: $metaentry{':packages'}=$package;
11966: }
11967: my $value=$packagetab{$key};
11968: my $unikey;
11969: $unikey='parameter_0_'.$name;
11970: $metaentry{':'.$unikey.'.part'}=0;
11971: $$metathesekeys{$unikey}=1;
11972: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11973: $metaentry{':'.$unikey.'.'.$subp}=$value;
11974: }
11975: if (defined($metaentry{':'.$unikey.'.default'})) {
11976: $metaentry{':'.$unikey}=
11977: $metaentry{':'.$unikey.'.default'};
11978: }
11979: }
11980:
11981: sub metadata_generate_part0 {
11982: my ($metadata,$metacache,$uri) = @_;
11983: my %allnames;
11984: foreach my $metakey (keys(%$metadata)) {
11985: if ($metakey=~/^parameter\_(.*)/) {
11986: my $part=$$metacache{':'.$metakey.'.part'};
11987: my $name=$$metacache{':'.$metakey.'.name'};
11988: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
11989: $allnames{$name}=$part;
11990: }
11991: }
11992: }
11993: foreach my $name (keys(%allnames)) {
11994: $$metadata{"parameter_0_$name"}=1;
11995: my $key=":parameter_0_$name";
11996: $$metacache{"$key.part"}='0';
11997: $$metacache{"$key.name"}=$name;
11998: $$metacache{"$key.type"}=$$metacache{':parameter_'.
11999: $allnames{$name}.'_'.$name.
12000: '.type'};
12001: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12002: '.display'};
12003: my $expr='[Part: '.$allnames{$name}.']';
12004: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12005: $$metacache{"$key.display"}=$olddis;
12006: }
12007: }
12008:
12009: # ------------------------------------------------------ Devalidate title cache
12010:
12011: sub devalidate_title_cache {
12012: my ($url)=@_;
12013: if (!$env{'request.course.id'}) { return; }
12014: my $symb=&symbread($url);
12015: if (!$symb) { return; }
12016: my $key=$env{'request.course.id'}."\0".$symb;
12017: &devalidate_cache_new('title',$key);
12018: }
12019:
12020: # ------------------------------------------------- Get the title of a course
12021:
12022: sub current_course_title {
12023: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12024: }
12025: # ------------------------------------------------- Get the title of a resource
12026:
12027: sub gettitle {
12028: my $urlsymb=shift;
12029: my $symb=&symbread($urlsymb);
12030: if ($symb) {
12031: my $key=$env{'request.course.id'}."\0".$symb;
12032: my ($result,$cached)=&is_cached_new('title',$key);
12033: if (defined($cached)) {
12034: return $result;
12035: }
12036: my ($map,$resid,$url)=&decode_symb($symb);
12037: my $title='';
12038: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12039: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12040: } else {
12041: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12042: &GDBM_READER(),0640)) {
12043: my $mapid=$bighash{'map_pc_'.&clutter($map)};
12044: $title=$bighash{'title_'.$mapid.'.'.$resid};
12045: untie(%bighash);
12046: }
12047: }
12048: $title=~s/\&colon\;/\:/gs;
12049: if ($title) {
12050: # Remember both $symb and $title for dynamic metadata
12051: $accesshash{$symb.'___crstitle'}=$title;
12052: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12053: # Cache this title and then return it
12054: return &do_cache_new('title',$key,$title,600);
12055: }
12056: $urlsymb=$url;
12057: }
12058: my $title=&metadata($urlsymb,'title');
12059: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
12060: return $title;
12061: }
12062:
12063: sub get_slot {
12064: my ($which,$cnum,$cdom)=@_;
12065: if (!$cnum || !$cdom) {
12066: (undef,my $courseid)=&whichuser();
12067: $cdom=$env{'course.'.$courseid.'.domain'};
12068: $cnum=$env{'course.'.$courseid.'.num'};
12069: }
12070: my $key=join("\0",'slots',$cdom,$cnum,$which);
12071: my %slotinfo;
12072: if (exists($remembered{$key})) {
12073: $slotinfo{$which} = $remembered{$key};
12074: } else {
12075: %slotinfo=&get('slots',[$which],$cdom,$cnum);
12076: &Apache::lonhomework::showhash(%slotinfo);
12077: my ($tmp)=keys(%slotinfo);
12078: if ($tmp=~/^error:/) { return (); }
12079: $remembered{$key} = $slotinfo{$which};
12080: }
12081: if (ref($slotinfo{$which}) eq 'HASH') {
12082: return %{$slotinfo{$which}};
12083: }
12084: return $slotinfo{$which};
12085: }
12086:
12087: sub get_reservable_slots {
12088: my ($cnum,$cdom,$uname,$udom) = @_;
12089: my $now = time;
12090: my $reservable_info;
12091: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12092: if (exists($remembered{$key})) {
12093: $reservable_info = $remembered{$key};
12094: } else {
12095: my %resv;
12096: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12097: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12098: $reservable_info = \%resv;
12099: $remembered{$key} = $reservable_info;
12100: }
12101: return $reservable_info;
12102: }
12103:
12104: sub get_course_slots {
12105: my ($cnum,$cdom) = @_;
12106: my $hashid=$cnum.':'.$cdom;
12107: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12108: if (defined($cached)) {
12109: if (ref($result) eq 'HASH') {
12110: return %{$result};
12111: }
12112: } else {
12113: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12114: my ($tmp) = keys(%slots);
12115: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12116: &do_cache_new('allslots',$hashid,\%slots,600);
12117: return %slots;
12118: }
12119: }
12120: return;
12121: }
12122:
12123: sub devalidate_slots_cache {
12124: my ($cnum,$cdom)=@_;
12125: my $hashid=$cnum.':'.$cdom;
12126: &devalidate_cache_new('allslots',$hashid);
12127: }
12128:
12129: sub get_coursechange {
12130: my ($cdom,$cnum) = @_;
12131: if ($cdom eq '' || $cnum eq '') {
12132: return unless ($env{'request.course.id'});
12133: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12134: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12135: }
12136: my $hashid=$cdom.'_'.$cnum;
12137: my ($change,$cached)=&is_cached_new('crschange',$hashid);
12138: if ((defined($cached)) && ($change ne '')) {
12139: return $change;
12140: } else {
12141: my %crshash;
12142: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12143: if ($crshash{'internal.contentchange'} eq '') {
12144: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12145: if ($change eq '') {
12146: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12147: $change = $crshash{'internal.created'};
12148: }
12149: } else {
12150: $change = $crshash{'internal.contentchange'};
12151: }
12152: my $cachetime = 600;
12153: &do_cache_new('crschange',$hashid,$change,$cachetime);
12154: }
12155: return $change;
12156: }
12157:
12158: sub devalidate_coursechange_cache {
12159: my ($cnum,$cdom)=@_;
12160: my $hashid=$cnum.':'.$cdom;
12161: &devalidate_cache_new('crschange',$hashid);
12162: }
12163:
12164: # ------------------------------------------------- Update symbolic store links
12165:
12166: sub symblist {
12167: my ($mapname,%newhash)=@_;
12168: $mapname=&deversion(&declutter($mapname));
12169: my %hash;
12170: if (($env{'request.course.fn'}) && (%newhash)) {
12171: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12172: &GDBM_WRCREAT(),0640)) {
12173: foreach my $url (keys(%newhash)) {
12174: next if ($url eq 'last_known'
12175: && $env{'form.no_update_last_known'});
12176: $hash{declutter($url)}=&encode_symb($mapname,
12177: $newhash{$url}->[1],
12178: $newhash{$url}->[0]);
12179: }
12180: if (untie(%hash)) {
12181: return 'ok';
12182: }
12183: }
12184: }
12185: return 'error';
12186: }
12187:
12188: # --------------------------------------------------------------- Verify a symb
12189:
12190: sub symbverify {
12191: my ($symb,$thisurl,$encstate)=@_;
12192: my $thisfn=$thisurl;
12193: $thisfn=&declutter($thisfn);
12194: # direct jump to resource in page or to a sequence - will construct own symbs
12195: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12196: # check URL part
12197: my ($map,$resid,$url)=&decode_symb($symb);
12198:
12199: unless ($url eq $thisfn) { return 0; }
12200:
12201: $symb=&symbclean($symb);
12202: $thisurl=&deversion($thisurl);
12203: $thisfn=&deversion($thisfn);
12204:
12205: my %bighash;
12206: my $okay=0;
12207:
12208: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12209: &GDBM_READER(),0640)) {
12210: my $noclutter;
12211: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12212: $thisurl =~ s/\?.+$//;
12213: if ($map =~ m{^uploaded/.+\.page$}) {
12214: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12215: $thisurl =~ s{^\Qhttp://https://\E}{https://};
12216: $noclutter = 1;
12217: }
12218: }
12219: my $ids;
12220: if ($noclutter) {
12221: $ids=$bighash{'ids_'.$thisurl};
12222: } else {
12223: $ids=$bighash{'ids_'.&clutter($thisurl)};
12224: }
12225: unless ($ids) {
12226: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
12227: $ids=$bighash{$idkey};
12228: }
12229: if ($ids) {
12230: # ------------------------------------------------------------------- Has ID(s)
12231: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12232: $symb =~ s/\?.+$//;
12233: }
12234: foreach my $id (split(/\,/,$ids)) {
12235: my ($mapid,$resid)=split(/\./,$id);
12236: if (
12237: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12238: eq $symb) {
12239: if (ref($encstate)) {
12240: $$encstate = $bighash{'encrypted_'.$id};
12241: }
12242: if (($env{'request.role.adv'}) ||
12243: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12244: ($thisurl eq '/adm/navmaps')) {
12245: $okay=1;
12246: last;
12247: }
12248: }
12249: }
12250: }
12251: untie(%bighash);
12252: }
12253: return $okay;
12254: }
12255:
12256: # --------------------------------------------------------------- Clean-up symb
12257:
12258: sub symbclean {
12259: my $symb=shift;
12260: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12261: # remove version from map
12262: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
12263:
12264: # remove version from URL
12265: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
12266:
12267: # remove wrapper
12268:
12269: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
12270: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
12271: return $symb;
12272: }
12273:
12274: # ---------------------------------------------- Split symb to find map and url
12275:
12276: sub encode_symb {
12277: my ($map,$resid,$url)=@_;
12278: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12279: }
12280:
12281: sub decode_symb {
12282: my $symb=shift;
12283: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12284: my ($map,$resid,$url)=split(/___/,$symb);
12285: return (&fixversion($map),$resid,&fixversion($url));
12286: }
12287:
12288: sub fixversion {
12289: my $fn=shift;
12290: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
12291: my %bighash;
12292: my $uri=&clutter($fn);
12293: my $key=$env{'request.course.id'}.'_'.$uri;
12294: # is this cached?
12295: my ($result,$cached)=&is_cached_new('courseresversion',$key);
12296: if (defined($cached)) { return $result; }
12297: # unfortunately not cached, or expired
12298: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12299: &GDBM_READER(),0640)) {
12300: if ($bighash{'version_'.$uri}) {
12301: my $version=$bighash{'version_'.$uri};
12302: unless (($version eq 'mostrecent') ||
12303: ($version==&getversion($uri))) {
12304: $uri=~s/\.(\w+)$/\.$version\.$1/;
12305: }
12306: }
12307: untie %bighash;
12308: }
12309: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
12310: }
12311:
12312: sub deversion {
12313: my $url=shift;
12314: $url=~s/\.\d+\.(\w+)$/\.$1/;
12315: return $url;
12316: }
12317:
12318: # ------------------------------------------------------ Return symb list entry
12319:
12320: sub symbread {
12321: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
12322: my $cache_str='request.symbread.cached.'.$thisfn;
12323: if (defined($env{$cache_str})) {
12324: if ($ignorecachednull) {
12325: return $env{$cache_str} unless ($env{$cache_str} eq '');
12326: } else {
12327: return $env{$cache_str};
12328: }
12329: }
12330: # no filename provided? try from environment
12331: unless ($thisfn) {
12332: if ($env{'request.symb'}) {
12333: return $env{$cache_str}=&symbclean($env{'request.symb'});
12334: }
12335: $thisfn=$env{'request.filename'};
12336: }
12337: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12338: # is that filename actually a symb? Verify, clean, and return
12339: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
12340: if (&symbverify($thisfn,$1)) {
12341: return $env{$cache_str}=&symbclean($thisfn);
12342: }
12343: }
12344: $thisfn=declutter($thisfn);
12345: my %hash;
12346: my %bighash;
12347: my $syval='';
12348: if (($env{'request.course.fn'}) && ($thisfn)) {
12349: my $targetfn = $thisfn;
12350: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
12351: $targetfn = 'adm/wrapper/'.$thisfn;
12352: }
12353: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12354: $targetfn=$1;
12355: }
12356: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12357: &GDBM_READER(),0640)) {
12358: $syval=$hash{$targetfn};
12359: untie(%hash);
12360: }
12361: # ---------------------------------------------------------- There was an entry
12362: if ($syval) {
12363: #unless ($syval=~/\_\d+$/) {
12364: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
12365: #&appenv({'request.ambiguous' => $thisfn});
12366: #return $env{$cache_str}='';
12367: #}
12368: #$syval.=$1;
12369: #}
12370: } else {
12371: # ------------------------------------------------------- Was not in symb table
12372: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12373: &GDBM_READER(),0640)) {
12374: # ---------------------------------------------- Get ID(s) for current resource
12375: my $ids=$bighash{'ids_'.&clutter($thisfn)};
12376: unless ($ids) {
12377: $ids=$bighash{'ids_/'.$thisfn};
12378: }
12379: unless ($ids) {
12380: # alias?
12381: $ids=$bighash{'mapalias_'.$thisfn};
12382: }
12383: if ($ids) {
12384: # ------------------------------------------------------------------- Has ID(s)
12385: my @possibilities=split(/\,/,$ids);
12386: if ($#possibilities==0) {
12387: # ----------------------------------------------- There is only one possibility
12388: my ($mapid,$resid)=split(/\./,$ids);
12389: $syval=&encode_symb($bighash{'map_id_'.$mapid},
12390: $resid,$thisfn);
12391: if (ref($possibles) eq 'HASH') {
12392: $possibles->{$syval} = 1;
12393: }
12394: if ($checkforblock) {
12395: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
12396: if (@blockers) {
12397: $syval = '';
12398: return;
12399: }
12400: }
12401: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12402: # ------------------------------------------ There is more than one possibility
12403: my $realpossible=0;
12404: foreach my $id (@possibilities) {
12405: my $file=$bighash{'src_'.$id};
12406: my $canaccess;
12407: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12408: $canaccess = 1;
12409: } else {
12410: $canaccess = &allowed('bre',$file);
12411: }
12412: if ($canaccess) {
12413: my ($mapid,$resid)=split(/\./,$id);
12414: if ($bighash{'map_type_'.$mapid} ne 'page') {
12415: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12416: $resid,$thisfn);
12417: if (ref($possibles) eq 'HASH') {
12418: $possibles->{$syval} = 1;
12419: }
12420: if ($checkforblock) {
12421: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
12422: unless (@blockers > 0) {
12423: $syval = $poss_syval;
12424: $realpossible++;
12425: }
12426: } else {
12427: $syval = $poss_syval;
12428: $realpossible++;
12429: }
12430: }
12431: }
12432: }
12433: if ($realpossible!=1) { $syval=''; }
12434: } else {
12435: $syval='';
12436: }
12437: }
12438: untie(%bighash);
12439: }
12440: }
12441: if ($syval) {
12442: return $env{$cache_str}=$syval;
12443: }
12444: }
12445: &appenv({'request.ambiguous' => $thisfn});
12446: return $env{$cache_str}='';
12447: }
12448:
12449: # ---------------------------------------------------------- Return random seed
12450:
12451: sub numval {
12452: my $txt=shift;
12453: $txt=~tr/A-J/0-9/;
12454: $txt=~tr/a-j/0-9/;
12455: $txt=~tr/K-T/0-9/;
12456: $txt=~tr/k-t/0-9/;
12457: $txt=~tr/U-Z/0-5/;
12458: $txt=~tr/u-z/0-5/;
12459: $txt=~s/\D//g;
12460: if ($_64bit) { if ($txt > 2**32) { return -1; } }
12461: return int($txt);
12462: }
12463:
12464: sub numval2 {
12465: my $txt=shift;
12466: $txt=~tr/A-J/0-9/;
12467: $txt=~tr/a-j/0-9/;
12468: $txt=~tr/K-T/0-9/;
12469: $txt=~tr/k-t/0-9/;
12470: $txt=~tr/U-Z/0-5/;
12471: $txt=~tr/u-z/0-5/;
12472: $txt=~s/\D//g;
12473: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12474: my $total;
12475: foreach my $val (@txts) { $total+=$val; }
12476: if ($_64bit) { if ($total > 2**32) { return -1; } }
12477: return int($total);
12478: }
12479:
12480: sub numval3 {
12481: use integer;
12482: my $txt=shift;
12483: $txt=~tr/A-J/0-9/;
12484: $txt=~tr/a-j/0-9/;
12485: $txt=~tr/K-T/0-9/;
12486: $txt=~tr/k-t/0-9/;
12487: $txt=~tr/U-Z/0-5/;
12488: $txt=~tr/u-z/0-5/;
12489: $txt=~s/\D//g;
12490: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12491: my $total;
12492: foreach my $val (@txts) { $total+=$val; }
12493: if ($_64bit) { $total=(($total<<32)>>32); }
12494: return $total;
12495: }
12496:
12497: sub digest {
12498: my ($data)=@_;
12499: my $digest=&Digest::MD5::md5($data);
12500: my ($a,$b,$c,$d)=unpack("iiii",$digest);
12501: my ($e,$f);
12502: {
12503: use integer;
12504: $e=($a+$b);
12505: $f=($c+$d);
12506: if ($_64bit) {
12507: $e=(($e<<32)>>32);
12508: $f=(($f<<32)>>32);
12509: }
12510: }
12511: if (wantarray) {
12512: return ($e,$f);
12513: } else {
12514: my $g;
12515: {
12516: use integer;
12517: $g=($e+$f);
12518: if ($_64bit) {
12519: $g=(($g<<32)>>32);
12520: }
12521: }
12522: return $g;
12523: }
12524: }
12525:
12526: sub latest_rnd_algorithm_id {
12527: return '64bit5';
12528: }
12529:
12530: sub get_rand_alg {
12531: my ($courseid)=@_;
12532: if (!$courseid) { $courseid=(&whichuser())[1]; }
12533: if ($courseid) {
12534: return $env{"course.$courseid.rndseed"};
12535: }
12536: return &latest_rnd_algorithm_id();
12537: }
12538:
12539: sub validCODE {
12540: my ($CODE)=@_;
12541: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12542: return 0;
12543: }
12544:
12545: sub getCODE {
12546: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
12547: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12548: defined($Apache::lonhomework::parsing_a_task) ) &&
12549: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
12550: return $Apache::lonhomework::history{'resource.CODE'};
12551: }
12552: return undef;
12553: }
12554: #
12555: # Determines the random seed for a specific context:
12556: #
12557: # parameters:
12558: # symb - in course context the symb for the seed.
12559: # course_id - The course id of the form domain_coursenum.
12560: # domain - Domain for the user.
12561: # course - Course for the user.
12562: # cenv - environment of the course.
12563: #
12564: # NOTE:
12565: # All parameters are picked out of the environment if missing
12566: # or not defined.
12567: # If a symb cannot be determined the current time is used instead.
12568: #
12569: # For a given well defined symb, courside, domain, username,
12570: # and course environment, the seed is reproducible.
12571: #
12572: sub rndseed {
12573: my ($symb,$courseid,$domain,$username, $cenv)=@_;
12574: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
12575: if (!defined($symb)) {
12576: unless ($symb=$wsymb) { return time; }
12577: }
12578: if (!defined $courseid) {
12579: $courseid=$wcourseid;
12580: }
12581: if (!defined $domain) { $domain=$wdomain; }
12582: if (!defined $username) { $username=$wusername }
12583:
12584: my $which;
12585: if (defined($cenv->{'rndseed'})) {
12586: $which = $cenv->{'rndseed'};
12587: } else {
12588: $which =&get_rand_alg($courseid);
12589: }
12590: if (defined(&getCODE())) {
12591:
12592: if ($which eq '64bit5') {
12593: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12594: } elsif ($which eq '64bit4') {
12595: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12596: } else {
12597: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12598: }
12599: } elsif ($which eq '64bit5') {
12600: return &rndseed_64bit5($symb,$courseid,$domain,$username);
12601: } elsif ($which eq '64bit4') {
12602: return &rndseed_64bit4($symb,$courseid,$domain,$username);
12603: } elsif ($which eq '64bit3') {
12604: return &rndseed_64bit3($symb,$courseid,$domain,$username);
12605: } elsif ($which eq '64bit2') {
12606: return &rndseed_64bit2($symb,$courseid,$domain,$username);
12607: } elsif ($which eq '64bit') {
12608: return &rndseed_64bit($symb,$courseid,$domain,$username);
12609: }
12610: return &rndseed_32bit($symb,$courseid,$domain,$username);
12611: }
12612:
12613: sub rndseed_32bit {
12614: my ($symb,$courseid,$domain,$username)=@_;
12615: {
12616: use integer;
12617: my $symbchck=unpack("%32C*",$symb) << 27;
12618: my $symbseed=numval($symb) << 22;
12619: my $namechck=unpack("%32C*",$username) << 17;
12620: my $nameseed=numval($username) << 12;
12621: my $domainseed=unpack("%32C*",$domain) << 7;
12622: my $courseseed=unpack("%32C*",$courseid);
12623: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
12624: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12625: #&logthis("rndseed :$num:$symb");
12626: if ($_64bit) { $num=(($num<<32)>>32); }
12627: return $num;
12628: }
12629: }
12630:
12631: sub rndseed_64bit {
12632: my ($symb,$courseid,$domain,$username)=@_;
12633: {
12634: use integer;
12635: my $symbchck=unpack("%32S*",$symb) << 21;
12636: my $symbseed=numval($symb) << 10;
12637: my $namechck=unpack("%32S*",$username);
12638:
12639: my $nameseed=numval($username) << 21;
12640: my $domainseed=unpack("%32S*",$domain) << 10;
12641: my $courseseed=unpack("%32S*",$courseid);
12642:
12643: my $num1=$symbchck+$symbseed+$namechck;
12644: my $num2=$nameseed+$domainseed+$courseseed;
12645: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12646: #&logthis("rndseed :$num:$symb");
12647: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12648: return "$num1,$num2";
12649: }
12650: }
12651:
12652: sub rndseed_64bit2 {
12653: my ($symb,$courseid,$domain,$username)=@_;
12654: {
12655: use integer;
12656: # strings need to be an even # of cahracters long, it it is odd the
12657: # last characters gets thrown away
12658: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12659: my $symbseed=numval($symb) << 10;
12660: my $namechck=unpack("%32S*",$username.' ');
12661:
12662: my $nameseed=numval($username) << 21;
12663: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12664: my $courseseed=unpack("%32S*",$courseid.' ');
12665:
12666: my $num1=$symbchck+$symbseed+$namechck;
12667: my $num2=$nameseed+$domainseed+$courseseed;
12668: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12669: #&logthis("rndseed :$num:$symb");
12670: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12671: return "$num1,$num2";
12672: }
12673: }
12674:
12675: sub rndseed_64bit3 {
12676: my ($symb,$courseid,$domain,$username)=@_;
12677: {
12678: use integer;
12679: # strings need to be an even # of cahracters long, it it is odd the
12680: # last characters gets thrown away
12681: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12682: my $symbseed=numval2($symb) << 10;
12683: my $namechck=unpack("%32S*",$username.' ');
12684:
12685: my $nameseed=numval2($username) << 21;
12686: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12687: my $courseseed=unpack("%32S*",$courseid.' ');
12688:
12689: my $num1=$symbchck+$symbseed+$namechck;
12690: my $num2=$nameseed+$domainseed+$courseseed;
12691: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12692: #&logthis("rndseed :$num1:$num2:$_64bit");
12693: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12694:
12695: return "$num1:$num2";
12696: }
12697: }
12698:
12699: sub rndseed_64bit4 {
12700: my ($symb,$courseid,$domain,$username)=@_;
12701: {
12702: use integer;
12703: # strings need to be an even # of cahracters long, it it is odd the
12704: # last characters gets thrown away
12705: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12706: my $symbseed=numval3($symb) << 10;
12707: my $namechck=unpack("%32S*",$username.' ');
12708:
12709: my $nameseed=numval3($username) << 21;
12710: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12711: my $courseseed=unpack("%32S*",$courseid.' ');
12712:
12713: my $num1=$symbchck+$symbseed+$namechck;
12714: my $num2=$nameseed+$domainseed+$courseseed;
12715: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12716: #&logthis("rndseed :$num1:$num2:$_64bit");
12717: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12718:
12719: return "$num1:$num2";
12720: }
12721: }
12722:
12723: sub rndseed_64bit5 {
12724: my ($symb,$courseid,$domain,$username)=@_;
12725: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12726: return "$num1:$num2";
12727: }
12728:
12729: sub rndseed_CODE_64bit {
12730: my ($symb,$courseid,$domain,$username)=@_;
12731: {
12732: use integer;
12733: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12734: my $symbseed=numval2($symb);
12735: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12736: my $CODEseed=numval(&getCODE());
12737: my $courseseed=unpack("%32S*",$courseid.' ');
12738: my $num1=$symbseed+$CODEchck;
12739: my $num2=$CODEseed+$courseseed+$symbchck;
12740: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12741: #&logthis("rndseed :$num1:$num2:$symb");
12742: if ($_64bit) { $num1=(($num1<<32)>>32); }
12743: if ($_64bit) { $num2=(($num2<<32)>>32); }
12744: return "$num1:$num2";
12745: }
12746: }
12747:
12748: sub rndseed_CODE_64bit4 {
12749: my ($symb,$courseid,$domain,$username)=@_;
12750: {
12751: use integer;
12752: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12753: my $symbseed=numval3($symb);
12754: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12755: my $CODEseed=numval3(&getCODE());
12756: my $courseseed=unpack("%32S*",$courseid.' ');
12757: my $num1=$symbseed+$CODEchck;
12758: my $num2=$CODEseed+$courseseed+$symbchck;
12759: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12760: #&logthis("rndseed :$num1:$num2:$symb");
12761: if ($_64bit) { $num1=(($num1<<32)>>32); }
12762: if ($_64bit) { $num2=(($num2<<32)>>32); }
12763: return "$num1:$num2";
12764: }
12765: }
12766:
12767: sub rndseed_CODE_64bit5 {
12768: my ($symb,$courseid,$domain,$username)=@_;
12769: my $code = &getCODE();
12770: my ($num1,$num2)=&digest("$symb,$courseid,$code");
12771: return "$num1:$num2";
12772: }
12773:
12774: sub setup_random_from_rndseed {
12775: my ($rndseed)=@_;
12776: if ($rndseed =~/([,:])/) {
12777: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12778: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12779: &Math::Random::random_set_seed_from_phrase($rndseed);
12780: } else {
12781: &Math::Random::random_set_seed($num1,$num2);
12782: }
12783: } else {
12784: &Math::Random::random_set_seed_from_phrase($rndseed);
12785: }
12786: }
12787:
12788: sub latest_receipt_algorithm_id {
12789: return 'receipt3';
12790: }
12791:
12792: sub recunique {
12793: my $fucourseid=shift;
12794: my $unique;
12795: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12796: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
12797: $unique=$env{"course.$fucourseid.internal.encseed"};
12798: } else {
12799: $unique=$perlvar{'lonReceipt'};
12800: }
12801: return unpack("%32C*",$unique);
12802: }
12803:
12804: sub recprefix {
12805: my $fucourseid=shift;
12806: my $prefix;
12807: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12808: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
12809: $prefix=$env{"course.$fucourseid.internal.encpref"};
12810: } else {
12811: $prefix=$perlvar{'lonHostID'};
12812: }
12813: return unpack("%32C*",$prefix);
12814: }
12815:
12816: sub ireceipt {
12817: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
12818:
12819: my $return =&recprefix($fucourseid).'-';
12820:
12821: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12822: $env{'request.state'} eq 'construct') {
12823: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12824: return $return;
12825: }
12826:
12827: my $cuname=unpack("%32C*",$funame);
12828: my $cudom=unpack("%32C*",$fudom);
12829: my $cucourseid=unpack("%32C*",$fucourseid);
12830: my $cusymb=unpack("%32C*",$fusymb);
12831: my $cunique=&recunique($fucourseid);
12832: my $cpart=unpack("%32S*",$part);
12833: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12834:
12835: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
12836:
12837: $return.= ($cunique%$cuname+
12838: $cunique%$cudom+
12839: $cusymb%$cuname+
12840: $cusymb%$cudom+
12841: $cucourseid%$cuname+
12842: $cucourseid%$cudom+
12843: $cpart%$cuname+
12844: $cpart%$cudom);
12845: } else {
12846: $return.= ($cunique%$cuname+
12847: $cunique%$cudom+
12848: $cusymb%$cuname+
12849: $cusymb%$cudom+
12850: $cucourseid%$cuname+
12851: $cucourseid%$cudom);
12852: }
12853: return $return;
12854: }
12855:
12856: sub receipt {
12857: my ($part)=@_;
12858: my ($symb,$courseid,$domain,$name) = &whichuser();
12859: return &ireceipt($name,$domain,$courseid,$symb,$part);
12860: }
12861:
12862: sub whichuser {
12863: my ($passedsymb)=@_;
12864: my ($symb,$courseid,$domain,$name,$publicuser);
12865: if (defined($env{'form.grade_symb'})) {
12866: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12867: my $allowed=&allowed('vgr',$tmp_courseid);
12868: if (!$allowed &&
12869: exists($env{'request.course.sec'}) &&
12870: $env{'request.course.sec'} !~ /^\s*$/) {
12871: $allowed=&allowed('vgr',$tmp_courseid.
12872: '/'.$env{'request.course.sec'});
12873: }
12874: if ($allowed) {
12875: ($symb)=&get_env_multiple('form.grade_symb');
12876: $courseid=$tmp_courseid;
12877: ($domain)=&get_env_multiple('form.grade_domain');
12878: ($name)=&get_env_multiple('form.grade_username');
12879: return ($symb,$courseid,$domain,$name,$publicuser);
12880: }
12881: }
12882: if (!$passedsymb) {
12883: $symb=&symbread();
12884: } else {
12885: $symb=$passedsymb;
12886: }
12887: $courseid=$env{'request.course.id'};
12888: $domain=$env{'user.domain'};
12889: $name=$env{'user.name'};
12890: if ($name eq 'public' && $domain eq 'public') {
12891: if (!defined($env{'form.username'})) {
12892: $env{'form.username'}.=time.rand(10000000);
12893: }
12894: $name.=$env{'form.username'};
12895: }
12896: return ($symb,$courseid,$domain,$name,$publicuser);
12897:
12898: }
12899:
12900: # ------------------------------------------------------------ Serves up a file
12901: # returns either the contents of the file or
12902: # -1 if the file doesn't exist
12903: #
12904: # if the target is a file that was uploaded via DOCS,
12905: # a check will be made to see if a current copy exists on the local server,
12906: # if it does this will be served, otherwise a copy will be retrieved from
12907: # the home server for the course and stored in /home/httpd/html/userfiles on
12908: # the local server.
12909:
12910: sub getfile {
12911: my ($file) = @_;
12912: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
12913: &repcopy($file);
12914: return &readfile($file);
12915: }
12916:
12917: sub repcopy_userfile {
12918: my ($file)=@_;
12919: my $londocroot = $perlvar{'lonDocRoot'};
12920: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
12921: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
12922: my ($cdom,$cnum,$filename) =
12923: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
12924: my $uri="/uploaded/$cdom/$cnum/$filename";
12925: if (-e "$file") {
12926: # we already have a local copy, check it out
12927: my @fileinfo = stat($file);
12928: my $rtncode;
12929: my $info;
12930: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
12931: if ($lwpresp ne 'ok') {
12932: # there is no such file anymore, even though we had a local copy
12933: if ($rtncode eq '404') {
12934: unlink($file);
12935: }
12936: return -1;
12937: }
12938: if ($info < $fileinfo[9]) {
12939: # nice, the file we have is up-to-date, just say okay
12940: return 'ok';
12941: } else {
12942: # the file is outdated, get rid of it
12943: unlink($file);
12944: }
12945: }
12946: # one way or the other, at this point, we don't have the file
12947: # construct the correct path for the file
12948: my @parts = ($cdom,$cnum);
12949: if ($filename =~ m|^(.+)/[^/]+$|) {
12950: push @parts, split(/\//,$1);
12951: }
12952: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
12953: foreach my $part (@parts) {
12954: $path .= '/'.$part;
12955: if (!-e $path) {
12956: mkdir($path,0770);
12957: }
12958: }
12959: # now the path exists for sure
12960: # get a user agent
12961: my $transferfile=$file.'.in.transfer';
12962: # FIXME: this should flock
12963: if (-e $transferfile) { return 'ok'; }
12964: my $request;
12965: $uri=~s/^\///;
12966: my $homeserver = &homeserver($cnum,$cdom);
12967: my $protocol = $protocol{$homeserver};
12968: $protocol = 'http' if ($protocol ne 'https');
12969: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
12970: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
12971: # did it work?
12972: if ($response->is_error()) {
12973: unlink($transferfile);
12974: &logthis("Userfile repcopy failed for $uri");
12975: return -1;
12976: }
12977: # worked, rename the transfer file
12978: rename($transferfile,$file);
12979: return 'ok';
12980: }
12981:
12982: sub tokenwrapper {
12983: my $uri=shift;
12984: $uri=~s|^https?\://([^/]+)||;
12985: $uri=~s|^/||;
12986: $env{'user.environment'}=~/\/([^\/]+)\.id/;
12987: my $token=$1;
12988: my (undef,$udom,$uname,$file)=split('/',$uri,4);
12989: if ($udom && $uname && $file) {
12990: $file=~s|(\?\.*)*$||;
12991: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
12992: my $homeserver = &homeserver($uname,$udom);
12993: my $protocol = $protocol{$homeserver};
12994: $protocol = 'http' if ($protocol ne 'https');
12995: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
12996: (($uri=~/\?/)?'&':'?').'token='.$token.
12997: '&tokenissued='.$perlvar{'lonHostID'};
12998: } else {
12999: return '/adm/notfound.html';
13000: }
13001: }
13002:
13003: # call with reqtype HEAD: get last modification time
13004: # call with reqtype GET: get the file contents
13005: # Do not call this with reqtype GET for large files! It loads everything into memory
13006: #
13007: sub getuploaded {
13008: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13009: $uri=~s/^\///;
13010: my $homeserver = &homeserver($cnum,$cdom);
13011: my $protocol = $protocol{$homeserver};
13012: $protocol = 'http' if ($protocol ne 'https');
13013: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
13014: my $request=new HTTP::Request($reqtype,$uri);
13015: my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
13016: $$rtncode = $response->code;
13017: if (! $response->is_success()) {
13018: return 'failed';
13019: }
13020: if ($reqtype eq 'HEAD') {
13021: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13022: } elsif ($reqtype eq 'GET') {
13023: $$info = $response->content;
13024: }
13025: return 'ok';
13026: }
13027:
13028: sub readfile {
13029: my $file = shift;
13030: if ( (! -e $file ) || ($file eq '') ) { return -1; };
13031: my $fh;
13032: open($fh,"<",$file);
13033: my $a='';
13034: while (my $line = <$fh>) { $a .= $line; }
13035: return $a;
13036: }
13037:
13038: sub filelocation {
13039: my ($dir,$file) = @_;
13040: my $location;
13041: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13042:
13043: if ($file =~ m-^/adm/-) {
13044: $file=~s-^/adm/wrapper/-/-;
13045: $file=~s-^/adm/coursedocs/showdoc/-/-;
13046: }
13047:
13048: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13049: $location = $file;
13050: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13051: my ($udom,$uname,$filename)=
13052: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13053: my $home=&homeserver($uname,$udom);
13054: my $is_me=0;
13055: my @ids=¤t_machine_ids();
13056: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13057: if ($is_me) {
13058: $location=propath($udom,$uname).'/userfiles/'.$filename;
13059: } else {
13060: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13061: $udom.'/'.$uname.'/'.$filename;
13062: }
13063: } elsif ($file =~ m-^/adm/-) {
13064: $location = $perlvar{'lonDocRoot'}.'/'.$file;
13065: } else {
13066: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13067: $file=~s:^/(res|priv)/:/:;
13068: my $space=$1;
13069: if ( !( $file =~ m:^/:) ) {
13070: $location = $dir. '/'.$file;
13071: } else {
13072: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13073: }
13074: }
13075: $location=~s://+:/:g; # remove duplicate /
13076: while ($location=~m{/\.\./}) {
13077: if ($location =~ m{/[^/]+/\.\./}) {
13078: $location=~ s{/[^/]+/\.\./}{/}g;
13079: } else {
13080: $location=~ s{/\.\./}{/}g;
13081: }
13082: } #remove dir/..
13083: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13084: return $location;
13085: }
13086:
13087: sub hreflocation {
13088: my ($dir,$file)=@_;
13089: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13090: $file=filelocation($dir,$file);
13091: } elsif ($file=~m-^/adm/-) {
13092: $file=~s-^/adm/wrapper/-/-;
13093: $file=~s-^/adm/coursedocs/showdoc/-/-;
13094: }
13095: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13096: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13097: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13098: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13099: {/uploaded/$1/$2/}x;
13100: }
13101: if ($file=~ m{^/userfiles/}) {
13102: $file =~ s{^/userfiles/}{/uploaded/};
13103: }
13104: return $file;
13105: }
13106:
13107:
13108:
13109:
13110:
13111: sub current_machine_domains {
13112: return &machine_domains(&hostname($perlvar{'lonHostID'}));
13113: }
13114:
13115: sub machine_domains {
13116: my ($hostname) = @_;
13117: my @domains;
13118: my %hostname = &all_hostnames();
13119: while( my($id, $name) = each(%hostname)) {
13120: # &logthis("-$id-$name-$hostname-");
13121: if ($hostname eq $name) {
13122: push(@domains,&host_domain($id));
13123: }
13124: }
13125: return @domains;
13126: }
13127:
13128: sub current_machine_ids {
13129: return &machine_ids(&hostname($perlvar{'lonHostID'}));
13130: }
13131:
13132: sub machine_ids {
13133: my ($hostname) = @_;
13134: $hostname ||= &hostname($perlvar{'lonHostID'});
13135: my @ids;
13136: my %name_to_host = &all_names();
13137: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13138: return @{ $name_to_host{$hostname} };
13139: }
13140: return;
13141: }
13142:
13143: sub additional_machine_domains {
13144: my @domains;
13145: open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
13146: while( my $line = <$fh>) {
13147: $line =~ s/\s//g;
13148: push(@domains,$line);
13149: }
13150: return @domains;
13151: }
13152:
13153: sub default_login_domain {
13154: my $domain = $perlvar{'lonDefDomain'};
13155: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13156: foreach my $posdom (¤t_machine_domains(),
13157: &additional_machine_domains()) {
13158: if (lc($posdom) eq lc($testdomain)) {
13159: $domain=$posdom;
13160: last;
13161: }
13162: }
13163: return $domain;
13164: }
13165:
13166: # ------------------------------------------------------------- Declutters URLs
13167:
13168: sub declutter {
13169: my $thisfn=shift;
13170: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13171: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13172: $thisfn=~s{^/home/httpd/html}{};
13173: }
13174: $thisfn=~s/^\///;
13175: $thisfn=~s|^adm/wrapper/||;
13176: $thisfn=~s|^adm/coursedocs/showdoc/||;
13177: $thisfn=~s/^res\///;
13178: $thisfn=~s/^priv\///;
13179: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13180: $thisfn=~s/\?.+$//;
13181: }
13182: return $thisfn;
13183: }
13184:
13185: # ------------------------------------------------------------- Clutter up URLs
13186:
13187: sub clutter {
13188: my $thisfn='/'.&declutter(shift);
13189: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
13190: || $thisfn =~ m{^/adm/(includes|pages)} ) {
13191: $thisfn='/res'.$thisfn;
13192: }
13193: if ($thisfn !~m|^/adm|) {
13194: if ($thisfn =~ m|^/ext/|) {
13195: $thisfn='/adm/wrapper'.$thisfn;
13196: } else {
13197: my ($ext) = ($thisfn =~ /\.(\w+)$/);
13198: my $embstyle=&Apache::loncommon::fileembstyle($ext);
13199: if ($embstyle eq 'ssi'
13200: || ($embstyle eq 'hdn')
13201: || ($embstyle eq 'rat')
13202: || ($embstyle eq 'prv')
13203: || ($embstyle eq 'ign')) {
13204: #do nothing with these
13205: } elsif (($embstyle eq 'img')
13206: || ($embstyle eq 'emb')
13207: || ($embstyle eq 'wrp')) {
13208: $thisfn='/adm/wrapper'.$thisfn;
13209: } elsif ($embstyle eq 'unk'
13210: && $thisfn!~/\.(sequence|page)$/) {
13211: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
13212: } else {
13213: # &logthis("Got a blank emb style");
13214: }
13215: }
13216: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
13217: $thisfn='/adm/wrapper'.$thisfn;
13218: }
13219: return $thisfn;
13220: }
13221:
13222: sub clutter_with_no_wrapper {
13223: my $uri = &clutter(shift);
13224: if ($uri =~ m-^/adm/-) {
13225: $uri =~ s-^/adm/wrapper/-/-;
13226: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
13227: }
13228: return $uri;
13229: }
13230:
13231: sub freeze_escape {
13232: my ($value)=@_;
13233: if (ref($value)) {
13234: $value=&nfreeze($value);
13235: return '__FROZEN__'.&escape($value);
13236: }
13237: return &escape($value);
13238: }
13239:
13240:
13241: sub thaw_unescape {
13242: my ($value)=@_;
13243: if ($value =~ /^__FROZEN__/) {
13244: substr($value,0,10,undef);
13245: $value=&unescape($value);
13246: return &thaw($value);
13247: }
13248: return &unescape($value);
13249: }
13250:
13251: sub correct_line_ends {
13252: my ($result)=@_;
13253: $$result =~s/\r\n/\n/mg;
13254: $$result =~s/\r/\n/mg;
13255: }
13256: # ================================================================ Main Program
13257:
13258: sub goodbye {
13259: &logthis("Starting Shut down");
13260: #not converted to using infrastruture and probably shouldn't be
13261: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
13262: #converted
13263: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
13264: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13265: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13266: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
13267: #1.1 only
13268: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13269: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13270: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13271: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13272: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
13273: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13274: &logthis(sprintf("%-20s is %s",'hits',$hits));
13275: &flushcourselogs();
13276: &logthis("Shutting down");
13277: }
13278:
13279: sub get_dns {
13280: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
13281: if (!$ignore_cache) {
13282: my ($content,$cached)=
13283: &Apache::lonnet::is_cached_new('dns',$url);
13284: if ($cached) {
13285: &$func($content,$hashref);
13286: return;
13287: }
13288: }
13289:
13290: my %alldns;
13291: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
13292: foreach my $dns (<$config>) {
13293: next if ($dns !~ /^\^(\S*)/x);
13294: my $line = $1;
13295: my ($host,$protocol) = split(/:/,$line);
13296: if ($protocol ne 'https') {
13297: $protocol = 'http';
13298: }
13299: $alldns{$host} = $protocol;
13300: }
13301: while (%alldns) {
13302: my ($dns) = sort { $b cmp $a } keys(%alldns);
13303: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13304: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
13305: delete($alldns{$dns});
13306: next if ($response->is_error());
13307: my @content = split("\n",$response->content);
13308: unless ($nocache) {
13309: &do_cache_new('dns',$url,\@content,30*24*60*60);
13310: }
13311: &$func(\@content,$hashref);
13312: return;
13313: }
13314: close($config);
13315: my $which = (split('/',$url))[3];
13316: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13317: open($config,"<","$perlvar{'lonTabDir'}/dns_$which.tab");
13318: my @content = <$config>;
13319: &$func(\@content,$hashref);
13320: return;
13321: }
13322:
13323: # ------------------------------------------------------Get DNS checksums file
13324: sub parse_dns_checksums_tab {
13325: my ($lines,$hashref) = @_;
13326: my $lonhost = $perlvar{'lonHostID'};
13327: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
13328: my $loncaparev = &get_server_loncaparev($machine_dom);
13329: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13330: my $webconfdir = '/etc/httpd/conf';
13331: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13332: $webconfdir = '/etc/apache2';
13333: } elsif ($distro =~ /^sles(\d+)$/) {
13334: if ($1 >= 10) {
13335: $webconfdir = '/etc/apache2';
13336: }
13337: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13338: if ($1 >= 10.0) {
13339: $webconfdir = '/etc/apache2';
13340: }
13341: }
13342: my ($release,$timestamp) = split(/\-/,$loncaparev);
13343: my (%chksum,%revnum);
13344: if (ref($lines) eq 'ARRAY') {
13345: chomp(@{$lines});
13346: my $version = shift(@{$lines});
13347: if ($version eq $release) {
13348: foreach my $line (@{$lines}) {
13349: my ($file,$version,$shasum) = split(/,/,$line);
13350: if ($file =~ m{^/etc/httpd/conf}) {
13351: if ($webconfdir eq '/etc/apache2') {
13352: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13353: }
13354: }
13355: $chksum{$file} = $shasum;
13356: $revnum{$file} = $version;
13357: }
13358: if (ref($hashref) eq 'HASH') {
13359: %{$hashref} = (
13360: sums => \%chksum,
13361: versions => \%revnum,
13362: );
13363: }
13364: }
13365: }
13366: return;
13367: }
13368:
13369: sub fetch_dns_checksums {
13370: my %checksums;
13371: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
13372: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
13373: my ($release,$timestamp) = split(/\-/,$loncaparev);
13374: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
13375: \%checksums);
13376: return \%checksums;
13377: }
13378:
13379: # ------------------------------------------------------------ Read domain file
13380: {
13381: my $loaded;
13382: my %domain;
13383:
13384: sub parse_domain_tab {
13385: my ($lines) = @_;
13386: foreach my $line (@$lines) {
13387: next if ($line =~ /^(\#|\s*$ )/x);
13388:
13389: chomp($line);
13390: my ($name,@elements) = split(/:/,$line,9);
13391: my %this_domain;
13392: foreach my $field ('description', 'auth_def', 'auth_arg_def',
13393: 'lang_def', 'city', 'longi', 'lati',
13394: 'primary') {
13395: $this_domain{$field} = shift(@elements);
13396: }
13397: $domain{$name} = \%this_domain;
13398: }
13399: }
13400:
13401: sub reset_domain_info {
13402: undef($loaded);
13403: undef(%domain);
13404: }
13405:
13406: sub load_domain_tab {
13407: my ($ignore_cache,$nocache) = @_;
13408: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
13409: my $fh;
13410: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
13411: my @lines = <$fh>;
13412: &parse_domain_tab(\@lines);
13413: }
13414: close($fh);
13415: $loaded = 1;
13416: }
13417:
13418: sub domain {
13419: &load_domain_tab() if (!$loaded);
13420:
13421: my ($name,$what) = @_;
13422: return if ( !exists($domain{$name}) );
13423:
13424: if (!$what) {
13425: return $domain{$name}{'description'};
13426: }
13427: return $domain{$name}{$what};
13428: }
13429:
13430: sub domain_info {
13431: &load_domain_tab() if (!$loaded);
13432: return %domain;
13433: }
13434:
13435: }
13436:
13437:
13438: # ------------------------------------------------------------- Read hosts file
13439: {
13440: my %hostname;
13441: my %hostdom;
13442: my %libserv;
13443: my $loaded;
13444: my %name_to_host;
13445: my %internetdom;
13446: my %LC_dns_serv;
13447:
13448: sub parse_hosts_tab {
13449: my ($file) = @_;
13450: foreach my $configline (@$file) {
13451: next if ($configline =~ /^(\#|\s*$ )/x);
13452: chomp($configline);
13453: if ($configline =~ /^\^/) {
13454: if ($configline =~ /^\^([\w.\-]+)/) {
13455: $LC_dns_serv{$1} = 1;
13456: }
13457: next;
13458: }
13459: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
13460: $name=~s/\s//g;
13461: if ($id && $domain && $role && $name) {
13462: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13463: my $curr = $hostname{$id};
13464: my $skip;
13465: if (ref($name_to_host{$curr}) eq 'ARRAY') {
13466: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13467: $skip = 1;
13468: } else {
13469: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13470: }
13471: }
13472: unless ($skip) {
13473: push(@{$name_to_host{$name}},$id);
13474: }
13475: } else {
13476: push(@{$name_to_host{$name}},$id);
13477: }
13478: $hostname{$id}=$name;
13479: $hostdom{$id}=$domain;
13480: if ($role eq 'library') { $libserv{$id}=$name; }
13481: if (defined($protocol)) {
13482: if ($protocol eq 'https') {
13483: $protocol{$id} = $protocol;
13484: } else {
13485: $protocol{$id} = 'http';
13486: }
13487: } else {
13488: $protocol{$id} = 'http';
13489: }
13490: if (defined($intdom)) {
13491: $internetdom{$id} = $intdom;
13492: }
13493: }
13494: }
13495: }
13496:
13497: sub reset_hosts_info {
13498: &purge_remembered();
13499: &reset_domain_info();
13500: &reset_hosts_ip_info();
13501: undef(%internetdom);
13502: undef(%name_to_host);
13503: undef(%hostname);
13504: undef(%hostdom);
13505: undef(%libserv);
13506: undef($loaded);
13507: }
13508:
13509: sub load_hosts_tab {
13510: my ($ignore_cache,$nocache) = @_;
13511: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
13512: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
13513: my @config = <$config>;
13514: &parse_hosts_tab(\@config);
13515: close($config);
13516: $loaded=1;
13517: }
13518:
13519: sub hostname {
13520: &load_hosts_tab() if (!$loaded);
13521:
13522: my ($lonid) = @_;
13523: return $hostname{$lonid};
13524: }
13525:
13526: sub all_hostnames {
13527: &load_hosts_tab() if (!$loaded);
13528:
13529: return %hostname;
13530: }
13531:
13532: sub all_names {
13533: my ($ignore_cache,$nocache) = @_;
13534: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
13535:
13536: return %name_to_host;
13537: }
13538:
13539: sub all_host_domain {
13540: &load_hosts_tab() if (!$loaded);
13541: return %hostdom;
13542: }
13543:
13544: sub all_host_intdom {
13545: &load_hosts_tab() if (!$loaded);
13546: return %internetdom;
13547: }
13548:
13549: sub is_library {
13550: &load_hosts_tab() if (!$loaded);
13551:
13552: return exists($libserv{$_[0]});
13553: }
13554:
13555: sub all_library {
13556: &load_hosts_tab() if (!$loaded);
13557:
13558: return %libserv;
13559: }
13560:
13561: sub unique_library {
13562: #2x reverse removes all hostnames that appear more than once
13563: my %unique = reverse &all_library();
13564: return reverse %unique;
13565: }
13566:
13567: sub get_servers {
13568: &load_hosts_tab() if (!$loaded);
13569:
13570: my ($domain,$type) = @_;
13571: my %possible_hosts = ($type eq 'library') ? %libserv
13572: : %hostname;
13573: my %result;
13574: if (ref($domain) eq 'ARRAY') {
13575: while ( my ($host,$hostname) = each(%possible_hosts)) {
13576: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
13577: $result{$host} = $hostname;
13578: }
13579: }
13580: } else {
13581: while ( my ($host,$hostname) = each(%possible_hosts)) {
13582: if ($hostdom{$host} eq $domain) {
13583: $result{$host} = $hostname;
13584: }
13585: }
13586: }
13587: return %result;
13588: }
13589:
13590: sub get_unique_servers {
13591: my %unique = reverse &get_servers(@_);
13592: return reverse %unique;
13593: }
13594:
13595: sub host_domain {
13596: &load_hosts_tab() if (!$loaded);
13597:
13598: my ($lonid) = @_;
13599: return $hostdom{$lonid};
13600: }
13601:
13602: sub all_domains {
13603: &load_hosts_tab() if (!$loaded);
13604:
13605: my %seen;
13606: my @uniq = grep(!$seen{$_}++, values(%hostdom));
13607: return @uniq;
13608: }
13609:
13610: sub internet_dom {
13611: &load_hosts_tab() if (!$loaded);
13612:
13613: my ($lonid) = @_;
13614: return $internetdom{$lonid};
13615: }
13616:
13617: sub is_LC_dns {
13618: &load_hosts_tab() if (!$loaded);
13619:
13620: my ($hostname) = @_;
13621: return exists($LC_dns_serv{$hostname});
13622: }
13623:
13624: }
13625:
13626: {
13627: my %iphost;
13628: my %name_to_ip;
13629: my %lonid_to_ip;
13630:
13631: sub get_hosts_from_ip {
13632: my ($ip) = @_;
13633: my %iphosts = &get_iphost();
13634: if (ref($iphosts{$ip})) {
13635: return @{$iphosts{$ip}};
13636: }
13637: return;
13638: }
13639:
13640: sub reset_hosts_ip_info {
13641: undef(%iphost);
13642: undef(%name_to_ip);
13643: undef(%lonid_to_ip);
13644: }
13645:
13646: sub get_host_ip {
13647: my ($lonid) = @_;
13648: if (exists($lonid_to_ip{$lonid})) {
13649: return $lonid_to_ip{$lonid};
13650: }
13651: my $name=&hostname($lonid);
13652: my $ip = gethostbyname($name);
13653: return if (!$ip || length($ip) ne 4);
13654: $ip=inet_ntoa($ip);
13655: $name_to_ip{$name} = $ip;
13656: $lonid_to_ip{$lonid} = $ip;
13657: return $ip;
13658: }
13659:
13660: sub get_iphost {
13661: my ($ignore_cache,$nocache) = @_;
13662:
13663: if (!$ignore_cache) {
13664: if (%iphost) {
13665: return %iphost;
13666: }
13667: my ($ip_info,$cached)=
13668: &Apache::lonnet::is_cached_new('iphost','iphost');
13669: if ($cached) {
13670: %iphost = %{$ip_info->[0]};
13671: %name_to_ip = %{$ip_info->[1]};
13672: %lonid_to_ip = %{$ip_info->[2]};
13673: return %iphost;
13674: }
13675: }
13676:
13677: # get yesterday's info for fallback
13678: my %old_name_to_ip;
13679: my ($ip_info,$cached)=
13680: &Apache::lonnet::is_cached_new('iphost','iphost');
13681: if ($cached) {
13682: %old_name_to_ip = %{$ip_info->[1]};
13683: }
13684:
13685: my %name_to_host = &all_names($ignore_cache,$nocache);
13686: foreach my $name (keys(%name_to_host)) {
13687: my $ip;
13688: if (!exists($name_to_ip{$name})) {
13689: $ip = gethostbyname($name);
13690: if (!$ip || length($ip) ne 4) {
13691: if (defined($old_name_to_ip{$name})) {
13692: $ip = $old_name_to_ip{$name};
13693: &logthis("Can't find $name defaulting to old $ip");
13694: } else {
13695: &logthis("Name $name no IP found");
13696: next;
13697: }
13698: } else {
13699: $ip=inet_ntoa($ip);
13700: }
13701: $name_to_ip{$name} = $ip;
13702: } else {
13703: $ip = $name_to_ip{$name};
13704: }
13705: foreach my $id (@{ $name_to_host{$name} }) {
13706: $lonid_to_ip{$id} = $ip;
13707: }
13708: push(@{$iphost{$ip}},@{$name_to_host{$name}});
13709: }
13710: unless ($nocache) {
13711: &do_cache_new('iphost','iphost',
13712: [\%iphost,\%name_to_ip,\%lonid_to_ip],
13713: 48*60*60);
13714: }
13715:
13716: return %iphost;
13717: }
13718:
13719: #
13720: # Given a DNS returns the loncapa host name for that DNS
13721: #
13722: sub host_from_dns {
13723: my ($dns) = @_;
13724: my @hosts;
13725: my $ip;
13726:
13727: if (exists($name_to_ip{$dns})) {
13728: $ip = $name_to_ip{$dns};
13729: }
13730: if (!$ip) {
13731: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13732: if (length($ip) == 4) {
13733: $ip = &IO::Socket::inet_ntoa($ip);
13734: }
13735: }
13736: if ($ip) {
13737: @hosts = get_hosts_from_ip($ip);
13738: return $hosts[0];
13739: }
13740: return undef;
13741: }
13742:
13743: sub get_internet_names {
13744: my ($lonid) = @_;
13745: return if ($lonid eq '');
13746: my ($idnref,$cached)=
13747: &Apache::lonnet::is_cached_new('internetnames',$lonid);
13748: if ($cached) {
13749: return $idnref;
13750: }
13751: my $ip = &get_host_ip($lonid);
13752: my @hosts = &get_hosts_from_ip($ip);
13753: my %iphost = &get_iphost();
13754: my (@idns,%seen);
13755: foreach my $id (@hosts) {
13756: my $dom = &host_domain($id);
13757: my $prim_id = &domain($dom,'primary');
13758: my $prim_ip = &get_host_ip($prim_id);
13759: next if ($seen{$prim_ip});
13760: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
13761: foreach my $id (@{$iphost{$prim_ip}}) {
13762: my $intdom = &internet_dom($id);
13763: unless (grep(/^\Q$intdom\E$/,@idns)) {
13764: push(@idns,$intdom);
13765: }
13766: }
13767: }
13768: $seen{$prim_ip} = 1;
13769: }
13770: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
13771: }
13772:
13773: }
13774:
13775: sub all_loncaparevs {
13776: return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10 2.11);
13777: }
13778:
13779: # ---------------------------------------------------------- Read loncaparev table
13780: {
13781: sub load_loncaparevs {
13782: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
13783: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
13784: while (my $configline=<$config>) {
13785: chomp($configline);
13786: my ($hostid,$loncaparev)=split(/:/,$configline);
13787: $loncaparevs{$hostid}=$loncaparev;
13788: }
13789: close($config);
13790: }
13791: }
13792: }
13793: }
13794:
13795: # ---------------------------------------------------------- Read serverhostID table
13796: {
13797: sub load_serverhomeIDs {
13798: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
13799: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
13800: while (my $configline=<$config>) {
13801: chomp($configline);
13802: my ($name,$id)=split(/:/,$configline);
13803: $serverhomeIDs{$name}=$id;
13804: }
13805: close($config);
13806: }
13807: }
13808: }
13809: }
13810:
13811:
13812: BEGIN {
13813:
13814: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13815: unless ($readit) {
13816: {
13817: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13818: %perlvar = (%perlvar,%{$configvars});
13819: }
13820:
13821:
13822: # ------------------------------------------------------ Read spare server file
13823: {
13824: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
13825:
13826: while (my $configline=<$config>) {
13827: chomp($configline);
13828: if ($configline) {
13829: my ($host,$type) = split(':',$configline,2);
13830: if (!defined($type) || $type eq '') { $type = 'default' };
13831: push(@{ $spareid{$type} }, $host);
13832: }
13833: }
13834: close($config);
13835: }
13836: # ------------------------------------------------------------ Read permissions
13837: {
13838: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
13839:
13840: while (my $configline=<$config>) {
13841: chomp($configline);
13842: if ($configline) {
13843: my ($role,$perm)=split(/ /,$configline);
13844: if ($perm ne '') { $pr{$role}=$perm; }
13845: }
13846: }
13847: close($config);
13848: }
13849:
13850: # -------------------------------------------- Read plain texts for permissions
13851: {
13852: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
13853:
13854: while (my $configline=<$config>) {
13855: chomp($configline);
13856: if ($configline) {
13857: my ($short,@plain)=split(/:/,$configline);
13858: %{$prp{$short}} = ();
13859: if (@plain > 0) {
13860: $prp{$short}{'std'} = $plain[0];
13861: for (my $i=1; $i<@plain; $i++) {
13862: $prp{$short}{'alt'.$i} = $plain[$i];
13863: }
13864: }
13865: }
13866: }
13867: close($config);
13868: }
13869:
13870: # ---------------------------------------------------------- Read package table
13871: {
13872: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
13873:
13874: while (my $configline=<$config>) {
13875: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
13876: chomp($configline);
13877: my ($short,$plain)=split(/:/,$configline);
13878: my ($pack,$name)=split(/\&/,$short);
13879: if ($plain ne '') {
13880: $packagetab{$pack.'&'.$name.'&name'}=$name;
13881: $packagetab{$short}=$plain;
13882: }
13883: }
13884: close($config);
13885: }
13886:
13887: # ---------------------------------------------------------- Read loncaparev table
13888:
13889: &load_loncaparevs();
13890:
13891: # ---------------------------------------------------------- Read serverhostID table
13892:
13893: &load_serverhomeIDs();
13894:
13895: # ---------------------------------------------------------- Read releaseslist XML
13896: {
13897: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
13898: if (-e $file) {
13899: my $parser = HTML::LCParser->new($file);
13900: while (my $token = $parser->get_token()) {
13901: if ($token->[0] eq 'S') {
13902: my $item = $token->[1];
13903: my $name = $token->[2]{'name'};
13904: my $value = $token->[2]{'value'};
13905: my $valuematch = $token->[2]{'valuematch'};
13906: my $namematch = $token->[2]{'namematch'};
13907: if ($item eq 'parameter') {
13908: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
13909: my $release = $parser->get_text();
13910: $release =~ s/(^\s*|\s*$ )//gx;
13911: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
13912: }
13913: } elsif ($item ne '' && $name ne '') {
13914: my $release = $parser->get_text();
13915: $release =~ s/(^\s*|\s*$ )//gx;
13916: $needsrelease{$item.':'.$name.':'.$value} = $release;
13917: }
13918: }
13919: }
13920: }
13921: }
13922:
13923: # ---------------------------------------------------------- Read managers table
13924: {
13925: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
13926: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
13927: while (my $configline=<$config>) {
13928: chomp($configline);
13929: next if ($configline =~ /^\#/);
13930: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
13931: $managerstab{$configline} = 1;
13932: }
13933: }
13934: close($config);
13935: }
13936: }
13937: }
13938:
13939: # ------------- set up temporary directory
13940: {
13941: $tmpdir = LONCAPA::tempdir();
13942:
13943: }
13944:
13945: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
13946: 'compress_threshold'=> 20_000,
13947: });
13948:
13949: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
13950: $dumpcount=0;
13951: $locknum=0;
13952:
13953: &logtouch();
13954: &logthis('<font color="yellow">INFO: Read configuration</font>');
13955: $readit=1;
13956: {
13957: use integer;
13958: my $test=(2**32)+1;
13959: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
13960: &logthis(" Detected 64bit platform ($_64bit)");
13961: }
13962: }
13963: }
13964:
13965: 1;
13966: __END__
13967:
13968: =pod
13969:
13970: =head1 NAME
13971:
13972: Apache::lonnet - Subroutines to ask questions about things in the network.
13973:
13974: =head1 SYNOPSIS
13975:
13976: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
13977:
13978: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
13979:
13980: Common parameters:
13981:
13982: =over 4
13983:
13984: =item *
13985:
13986: $uname : an internal username (if $cname expecting a course Id specifically)
13987:
13988: =item *
13989:
13990: $udom : a domain (if $cdom expecting a course's domain specifically)
13991:
13992: =item *
13993:
13994: $symb : a resource instance identifier
13995:
13996: =item *
13997:
13998: $namespace : the name of a .db file that contains the data needed or
13999: being set.
14000:
14001: =back
14002:
14003: =head1 OVERVIEW
14004:
14005: lonnet provides subroutines which interact with the
14006: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14007: about classes, users, and resources.
14008:
14009: For many of these objects you can also use this to store data about
14010: them or modify them in various ways.
14011:
14012: =head2 Symbs
14013:
14014: To identify a specific instance of a resource, LON-CAPA uses symbols
14015: or "symbs"X<symb>. These identifiers are built from the URL of the
14016: map, the resource number of the resource in the map, and the URL of
14017: the resource itself. The latter is somewhat redundant, but might help
14018: if maps change.
14019:
14020: An example is
14021:
14022: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14023:
14024: The respective map entry is
14025:
14026: <resource id="19" src="/res/msu/korte/tests/part12.problem"
14027: title="Problem 2">
14028: </resource>
14029:
14030: Symbs are used by the random number generator, as well as to store and
14031: restore data specific to a certain instance of for example a problem.
14032:
14033: =head2 Storing And Retrieving Data
14034:
14035: X<store()>X<cstore()>X<restore()>Three of the most important functions
14036: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14037: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14038: is is the non-critical message twin of cstore. These functions are for
14039: handlers to store a perl hash to a user's permanent data space in an
14040: easy manner, and to retrieve it again on another call. It is expected
14041: that a handler would use this once at the beginning to retrieve data,
14042: and then again once at the end to send only the new data back.
14043:
14044: The data is stored in the user's data directory on the user's
14045: homeserver under the ID of the course.
14046:
14047: The hash that is returned by restore will have all of the previous
14048: value for all of the elements of the hash.
14049:
14050: Example:
14051:
14052: #creating a hash
14053: my %hash;
14054: $hash{'foo'}='bar';
14055:
14056: #storing it
14057: &Apache::lonnet::cstore(\%hash);
14058:
14059: #changing a value
14060: $hash{'foo'}='notbar';
14061:
14062: #adding a new value
14063: $hash{'bar'}='foo';
14064: &Apache::lonnet::cstore(\%hash);
14065:
14066: #retrieving the hash
14067: my %history=&Apache::lonnet::restore();
14068:
14069: #print the hash
14070: foreach my $key (sort(keys(%history))) {
14071: print("\%history{$key} = $history{$key}");
14072: }
14073:
14074: Will print out:
14075:
14076: %history{1:foo} = bar
14077: %history{1:keys} = foo:timestamp
14078: %history{1:timestamp} = 990455579
14079: %history{2:bar} = foo
14080: %history{2:foo} = notbar
14081: %history{2:keys} = foo:bar:timestamp
14082: %history{2:timestamp} = 990455580
14083: %history{bar} = foo
14084: %history{foo} = notbar
14085: %history{timestamp} = 990455580
14086: %history{version} = 2
14087:
14088: Note that the special hash entries C<keys>, C<version> and
14089: C<timestamp> were added to the hash. C<version> will be equal to the
14090: total number of versions of the data that have been stored. The
14091: C<timestamp> attribute will be the UNIX time the hash was
14092: stored. C<keys> is available in every historical section to list which
14093: keys were added or changed at a specific historical revision of a
14094: hash.
14095:
14096: B<Warning>: do not store the hash that restore returns directly. This
14097: will cause a mess since it will restore the historical keys as if the
14098: were new keys. I.E. 1:foo will become 1:1:foo etc.
14099:
14100: Calling convention:
14101:
14102: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
14103: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
14104:
14105: For more detailed information, see lonnet specific documentation.
14106:
14107: =head1 RETURN MESSAGES
14108:
14109: =over 4
14110:
14111: =item * B<con_lost>: unable to contact remote host
14112:
14113: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14114: when the connection is brought back up
14115:
14116: =item * B<con_failed>: unable to contact remote host and unable to save message
14117: for later delivery
14118:
14119: =item * B<error:>: an error a occurred, a description of the error follows the :
14120:
14121: =item * B<no_such_host>: unable to fund a host associated with the user/domain
14122: that was requested
14123:
14124: =back
14125:
14126: =head1 PUBLIC SUBROUTINES
14127:
14128: =head2 Session Environment Functions
14129:
14130: =over 4
14131:
14132: =item *
14133: X<appenv()>
14134: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
14135: the user envirnoment file, and will be restored for each access this
14136: user makes during this session, also modifies the %env for the current
14137: process. Optional rolesarrayref - if defined contains a reference to an array
14138: of roles which are exempt from the restriction on modifying user.role entries
14139: in the user's environment.db and in %env.
14140:
14141: =item *
14142: X<delenv()>
14143: B<delenv($delthis,$regexp)>: removes all items from the session
14144: environment file that begin with $delthis. If the
14145: optional second arg - $regexp - is true, $delthis is treated as a
14146: regular expression, otherwise \Q$delthis\E is used.
14147: The values are also deleted from the current processes %env.
14148:
14149: =item * get_env_multiple($name)
14150:
14151: gets $name from the %env hash, it seemlessly handles the cases where multiple
14152: values may be defined and end up as an array ref.
14153:
14154: returns an array of values
14155:
14156: =back
14157:
14158: =head2 User Information
14159:
14160: =over 4
14161:
14162: =item *
14163: X<queryauthenticate()>
14164: B<queryauthenticate($uname,$udom)>: try to determine user's current
14165: authentication scheme
14166:
14167: =item *
14168: X<authenticate()>
14169: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
14170: authenticate user from domain's lib servers (first use the current
14171: one). C<$upass> should be the users password.
14172: $checkdefauth is optional (value is 1 if a check should be made to
14173: authenticate user using default authentication method, and allow
14174: account creation if username does not have account in the domain).
14175: $clientcancheckhost is optional (value is 1 if checking whether the
14176: server can host will occur on the client side in lonauth.pm).
14177:
14178: =item *
14179: X<homeserver()>
14180: B<homeserver($uname,$udom)>: find the server which has
14181: the user's directory and files (there must be only one), this caches
14182: the answer, and also caches if there is a borken connection.
14183:
14184: =item *
14185: X<idget()>
14186: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
14187: a list of student/employee IDs or clicker IDs
14188: (student/employee IDs are a unique resource in a domain, there must be
14189: only 1 ID per username, and only 1 username per ID in a specific domain).
14190: clickerIDs are not necessarily unique, as students might share clickers.
14191: (returns hash: id=>name,id=>name)
14192:
14193: =item *
14194: X<idrget()>
14195: B<idrget($udom,@unames)>: find the IDs behind a list of
14196: usernames (returns hash: name=>id,name=>id)
14197:
14198: =item *
14199: X<idput()>
14200: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
14201: names and associated student/employee IDs or clicker IDs.
14202:
14203: =item *
14204: X<iddel()>
14205: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
14206: student/employee ID or clicker ID username look-ups from domain.
14207: The homeserver ($uhome) and namespace ($namespace) are optional.
14208: If no $uhome is provided, it will be determined usig &homeserver()
14209: for each user. If no $namespace is provided, the default is ids.
14210:
14211: =item *
14212: X<updateclickers()>
14213: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
14214: clicker ID-to-username look-ups in clickers.db on library server.
14215: Permitted actions are add or del (i.e., add or delete). The
14216: clickers.db contains clickerID as keys (escaped), and each corresponding
14217: value is an escaped comma-separated list of usernames (for whom the
14218: library server is the homeserver), who registered that particular ID.
14219: If $critical is true, the update will be sent via &critical, otherwise
14220: &reply() will be used.
14221:
14222: =item *
14223: X<rolesinit()>
14224: B<rolesinit($udom,$username)>: get user privileges.
14225: returns user role, first access and timer interval hashes
14226:
14227: =item *
14228: X<privileged()>
14229: B<privileged($username,$domain)>: returns a true if user has a
14230: privileged and active role (i.e. su or dc), false otherwise.
14231:
14232: =item *
14233: X<getsection()>
14234: B<getsection($udom,$uname,$cname)>: finds the section of student in the
14235: course $cname, return section name/number or '' for "not in course"
14236: and '-1' for "no section"
14237:
14238: =item *
14239: X<userenvironment()>
14240: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
14241: passed in @what from the requested user's environment, returns a hash
14242:
14243: =item *
14244: X<userlog_query()>
14245: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14246: activity.log file. %filters defines filters applied when parsing the
14247: log file. These can be start or end timestamps, or the type of action
14248: - log to look for Login or Logout events, check for Checkin or
14249: Checkout, role for role selection. The response is in the form
14250: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
14251: escaped strings of the action recorded in the activity.log file.
14252:
14253: =back
14254:
14255: =head2 User Roles
14256:
14257: =over 4
14258:
14259: =item *
14260:
14261: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
14262: returns codes for allowed actions.
14263:
14264: The first argument is required, all others are optional.
14265:
14266: $priv is the privilege being checked.
14267: $uri contains additional information about what is being checked for access (e.g.,
14268: URL, course ID etc.).
14269: $symb is the unique resource instance identifier in a course; if needed,
14270: but not provided, it will be retrieved via a call to &symbread().
14271: $role is the role for which a priv is being checked (only used if priv is evb).
14272: $clientip is the user's IP address (only used when checking for access to portfolio
14273: files).
14274: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
14275: prevents recursive calls to &allowed.
14276:
14277: F: full access
14278: U,I,K: authentication modes (cxx only)
14279: '': forbidden
14280: 1: user needs to choose course
14281: 2: browse allowed
14282: A: passphrase authentication needed
14283: B: access temporarily blocked because of a blocking event in a course.
14284:
14285: =item *
14286:
14287: constructaccess($url,$setpriv) : check for access to construction space URL
14288:
14289: See if the owner domain and name in the URL match those in the
14290: expected environment. If so, return three element list
14291: ($ownername,$ownerdomain,$ownerhome).
14292:
14293: Otherwise return the null string.
14294:
14295: If second argument 'setpriv' is true, it assigns the privileges,
14296: and returns the same three element list, unless the owner has
14297: blocked "ad hoc" Domain Coordinator access to the Author Space,
14298: in which case the null string is returned.
14299:
14300: =item *
14301:
14302: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14303: define a custom role rolename set privileges in format of lonTabs/roles.tab
14304: for system, domain, and course level. $uname and $udom are optional (current
14305: user's username and domain will be used when either of $uname or $udom are absent.
14306:
14307: =item *
14308:
14309: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
14310: (rolesplain.tab); plain text explanation of a user role term.
14311: $type is Course (default) or Community.
14312: If $forcedefault evaluates to true, text returned will be default
14313: text for $type. Otherwise, if this is a course, the text returned
14314: will be a custom name for the role (if defined in the course's
14315: environment). If no custom name is defined the default is returned.
14316:
14317: =item *
14318:
14319: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
14320: All arguments are optional. Returns a hash of a roles, either for
14321: co-author/assistant author roles for a user's Construction Space
14322: (default), or if $context is 'userroles', roles for the user himself,
14323: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14324: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14325: For each key, value is set to colon-separated start and end times for
14326: the role. If no username and domain are specified, will default to
14327: current user/domain. Types, roles, and roledoms are references to arrays
14328: of role statuses (active, future or previous), roles
14329: (e.g., cc,in, st etc.) and domains of the roles which can be used
14330: to restrict the list of roles reported. If no array ref is
14331: provided for types, will default to return only active roles.
14332:
14333: =item *
14334:
14335: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14336: user: $uname:$udom has a role in the course: $cdom_$cnum.
14337:
14338: Additional optional arguments are: $type (if role checking is to be restricted
14339: to certain user status types -- previous (expired roles), active (currently
14340: available roles) or future (roles available in the future), and
14341: $hideprivileged -- if true will not report course roles for users who
14342: have active Domain Coordinator role in course's domain or in additional
14343: domains (specified in 'Domains to check for privileged users' in course
14344: environment -- set via: Course Settings -> Classlists and staff listing).
14345:
14346: =item *
14347:
14348: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14349: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14350: $possdomains and $possroles are optional array refs -- to domains to check and
14351: roles to check. If $possdomains is not specified, a dump will be done of the
14352: users' roles.db to check for a dc or su role in any domain. This can be
14353: time consuming if &privileged is called repeatedly (e.g., when displaying a
14354: classlist), so in such cases, supplying a $possdomains array is preferred, as
14355: this then allows &privileged_by_domain() to be used, which caches the identity
14356: of privileged users, eliminating the need for repeated calls to &dump().
14357:
14358: =item *
14359:
14360: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14361: where the outer hash keys are domains specified in the $possdomains array ref,
14362: next inner hash keys are privileged roles specified in the $roles array ref,
14363: and the innermost hash contains key = value pairs for username:domain = end:start
14364: for active or future "privileged" users with that role in that domain. To avoid
14365: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14366: innerhash are cached using priv_$role and $dom as the identifiers.
14367:
14368: =back
14369:
14370: =head2 User Modification
14371:
14372: =over 4
14373:
14374: =item *
14375:
14376: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
14377: user for the level given by URL. Optional start and end dates (leave empty
14378: string or zero for "no date")
14379:
14380: =item *
14381:
14382: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14383: change a users, password, possible return values are: ok,
14384: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14385: refused
14386:
14387: =item *
14388:
14389: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
14390:
14391: =item *
14392:
14393: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14394: $forceid,$desiredhome,$email,$inststatus,$candelete) :
14395:
14396: will update user information (firstname,middlename,lastname,generation,
14397: permanentemail), and if forceid is true, student/employee ID also.
14398: A user's institutional affiliation(s) can also be updated.
14399: User information fields will not be overwritten with empty entries
14400: unless the field is included in the $candelete array reference.
14401: This array is included when a single user is modified via "Manage Users",
14402: or when Autoupdate.pl is run by cron in a domain.
14403:
14404: =item *
14405:
14406: modifystudent
14407:
14408: modify a student's enrollment and identification information.
14409: The course id is resolved based on the current user's environment.
14410: This means the invoking user must be a course coordinator or otherwise
14411: associated with a course.
14412:
14413: This call is essentially a wrapper for lonnet::modifyuser and
14414: lonnet::modify_student_enrollment
14415:
14416: Inputs:
14417:
14418: =over 4
14419:
14420: =item B<$udom> Student's loncapa domain
14421:
14422: =item B<$uname> Student's loncapa login name
14423:
14424: =item B<$uid> Student/Employee ID
14425:
14426: =item B<$umode> Student's authentication mode
14427:
14428: =item B<$upass> Student's password
14429:
14430: =item B<$first> Student's first name
14431:
14432: =item B<$middle> Student's middle name
14433:
14434: =item B<$last> Student's last name
14435:
14436: =item B<$gene> Student's generation
14437:
14438: =item B<$usec> Student's section in course
14439:
14440: =item B<$end> Unix time of the roles expiration
14441:
14442: =item B<$start> Unix time of the roles start date
14443:
14444: =item B<$forceid> If defined, allow $uid to be changed
14445:
14446: =item B<$desiredhome> server to use as home server for student
14447:
14448: =item B<$email> Student's permanent e-mail address
14449:
14450: =item B<$type> Type of enrollment (auto or manual)
14451:
14452: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
14453:
14454: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
14455:
14456: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
14457:
14458: =item B<$context> role change context (shown in User Management Logs display in a course)
14459:
14460: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14461:
14462: =item B<$credits> Number of credits student will earn from this class - only needs to be supplied if value needs to be different from default credits for class.
14463:
14464: =back
14465:
14466: =item *
14467:
14468: modify_student_enrollment
14469:
14470: Change a student's enrollment status in a class. The environment variable
14471: 'role.request.course' must be defined for this function to proceed.
14472:
14473: Inputs:
14474:
14475: =over 4
14476:
14477: =item $udom, student's domain
14478:
14479: =item $uname, student's name
14480:
14481: =item $uid, student's user id
14482:
14483: =item $first, student's first name
14484:
14485: =item $middle
14486:
14487: =item $last
14488:
14489: =item $gene
14490:
14491: =item $usec
14492:
14493: =item $end
14494:
14495: =item $start
14496:
14497: =item $type
14498:
14499: =item $locktype
14500:
14501: =item $cid
14502:
14503: =item $selfenroll
14504:
14505: =item $context
14506:
14507: =item $credits, number of credits student will earn from this class
14508:
14509: =item $instsec, institutional course section code for student
14510:
14511: =back
14512:
14513:
14514: =item *
14515:
14516: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14517: custom role; give a custom role to a user for the level given by URL. Specify
14518: name and domain of role author, and role name
14519:
14520: =item *
14521:
14522: revokerole($udom,$uname,$url,$role) : revoke a role for url
14523:
14524: =item *
14525:
14526: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14527:
14528: =back
14529:
14530: =head2 Course Infomation
14531:
14532: =over 4
14533:
14534: =item *
14535:
14536: coursedescription($courseid,$options) : returns a hash of information about the
14537: specified course id, including all environment settings for the
14538: course, the description of the course will be in the hash under the
14539: key 'description'
14540:
14541: $options is an optional parameter that if supplied is a hash reference that controls
14542: what how this function works. It has the following key/values:
14543:
14544: =over 4
14545:
14546: =item freshen_cache
14547:
14548: If defined, and the environment cache for the course is valid, it is
14549: returned in the returned hash.
14550:
14551: =item one_time
14552:
14553: If defined, the last cache time is set to _now_
14554:
14555: =item user
14556:
14557: If defined, the supplied username is used instead of the current user.
14558:
14559:
14560: =back
14561:
14562: =item *
14563:
14564: resdata($name,$domain,$type,@which) : request for current parameter
14565: setting for a specific $type, where $type is either 'course' or 'user',
14566: @what should be a list of parameters to ask about. This routine caches
14567: answers for 10 minutes.
14568:
14569: =item *
14570:
14571: get_courseresdata($courseid, $domain) : dump the entire course resource
14572: data base, returning a hash that is keyed by the resource name and has
14573: values that are the resource value. I believe that the timestamps and
14574: versions are also returned.
14575:
14576: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14577: supplemental content area. This routine caches the number of files for
14578: 10 minutes.
14579:
14580: =back
14581:
14582: =head2 Course Modification
14583:
14584: =over 4
14585:
14586: =item *
14587:
14588: writecoursepref($courseid,%prefs) : write preferences (environment
14589: database) for a course
14590:
14591: =item *
14592:
14593: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14594:
14595: =item *
14596:
14597: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
14598:
14599: =item *
14600:
14601: is_course($courseid), is_course($cdom, $cnum)
14602:
14603: Accepts either a combined $courseid (in the form of domain_courseid) or the
14604: two component version $cdom, $cnum. It checks if the specified course exists.
14605:
14606: Returns:
14607: undef if the course doesn't exist, otherwise
14608: in scalar context the combined courseid.
14609: in list context the two components of the course identifier, domain and
14610: courseid.
14611:
14612: =back
14613:
14614: =head2 Resource Subroutines
14615:
14616: =over 4
14617:
14618: =item *
14619:
14620: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
14621:
14622: =item *
14623:
14624: repcopy($filename) : subscribes to the requested file, and attempts to
14625: replicate from the owning library server, Might return
14626: 'unavailable', 'not_found', 'forbidden', 'ok', or
14627: 'bad_request', also attempts to grab the metadata for the
14628: resource. Expects the local filesystem pathname
14629: (/home/httpd/html/res/....)
14630:
14631: =back
14632:
14633: =head2 Resource Information
14634:
14635: =over 4
14636:
14637: =item *
14638:
14639: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
14640: and returns the value of a variety of different possible values,
14641: $varname should be a request string, and the other parameters can be
14642: used to specify who and what one is asking about. Ordinarily, $cid
14643: does not need to be specified, as it is retrived from
14644: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14645: within lonuserstate::loadmap() when initializing a course, before
14646: $env{'request.course.id'} has been set, so it needs to be provided
14647: in that one case.
14648:
14649: Possible values for $varname are environment.lastname (or other item
14650: from the envirnment hash), user.name (or someother aspect about the
14651: user), resource.0.maxtries (or some other part and parameter of a
14652: resource)
14653:
14654: =item *
14655:
14656: directcondval($number) : get current value of a condition; reads from a state
14657: string
14658:
14659: =item *
14660:
14661: condval($condidx) : value of condition index based on state
14662:
14663: =item *
14664:
14665: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14666: resource's metadata, $what should be either a specific key, or either
14667: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14668: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
14669:
14670: this function automatically caches all requests
14671:
14672: =item *
14673:
14674: metadata_query($query,$custom,$customshow) : make a metadata query against the
14675: network of library servers; returns file handle of where SQL and regex results
14676: will be stored for query
14677:
14678: =item *
14679:
14680: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
14681: return symbolic list entry (all arguments optional).
14682:
14683: Args: filename is the filename (including path) for the file for which a symb
14684: is required; donotrecurse, if true will prevent calls to allowed() being made
14685: to check access status if more than one resource was found in the bighash
14686: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
14687: a randompick); ignorecachednull, if true will prevent a symb of '' being
14688: returned if $env{$cache_str} is defined as ''; checkforblock if true will
14689: cause possible symbs to be checked to determine if they are subject to content
14690: blocking, if so they will not be included as possible symbs; possibles is a
14691: ref to a hash, which, as a side effect, will be populated with all possible
14692: symbs (content blocking not tested).
14693:
14694: returns the data handle
14695:
14696: =item *
14697:
14698: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
14699: and is a possible symb for the URL in $thisfn, and if is an encrypted
14700: resource that the user accessed using /enc/ returns a 1 on success, 0
14701: on failure, user must be in a course, as it assumes the existence of
14702: the course initial hash, and uses $env('request.course.id'}. The third
14703: arg is an optional reference to a scalar. If this arg is passed in the
14704: call to symbverify, it will be set to 1 if the symb has been set to be
14705: encrypted; otherwise it will be null.
14706:
14707: =item *
14708:
14709: symbclean($symb) : removes versions numbers from a symb, returns the
14710: cleaned symb
14711:
14712: =item *
14713:
14714: is_on_map($uri) : checks if the $uri is somewhere on the current
14715: course map, user must be in a course for it to work.
14716:
14717: =item *
14718:
14719: numval($salt) : return random seed value (addend for rndseed)
14720:
14721: =item *
14722:
14723: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
14724: a random seed, all arguments are optional, if they aren't sent it uses the
14725: environment to derive them. Note: if symb isn't sent and it can't get one
14726: from &symbread it will use the current time as its return value
14727:
14728: =item *
14729:
14730: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
14731: unfakeable, receipt
14732:
14733: =item *
14734:
14735: receipt() : API to ireceipt working off of env values; given out to users
14736:
14737: =item *
14738:
14739: countacc($url) : count the number of accesses to a given URL
14740:
14741: =item *
14742:
14743: 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
14744:
14745: =item *
14746:
14747: 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)
14748:
14749: =item *
14750:
14751: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
14752:
14753: =item *
14754:
14755: devalidate($symb) : devalidate temporary spreadsheet calculations,
14756: forcing spreadsheet to reevaluate the resource scores next time.
14757:
14758: =item *
14759:
14760: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
14761: when viewing in course context.
14762:
14763: input: six args -- filename (decluttered), course number, course domain,
14764: url, symb (if registered) and group (if this is a
14765: group item -- e.g., bulletin board, group page etc.).
14766:
14767: output: array of five scalars --
14768: $cfile -- url for file editing if editable on current server
14769: $home -- homeserver of resource (i.e., for author if published,
14770: or course if uploaded.).
14771: $switchserver -- 1 if server switch will be needed.
14772: $forceedit -- 1 if icon/link should be to go to edit mode
14773: $forceview -- 1 if icon/link should be to go to view mode
14774:
14775: =item *
14776:
14777: is_course_upload($file,$cnum,$cdom)
14778:
14779: Used in course context to determine if current file was uploaded to
14780: the course (i.e., would be found in /userfiles/docs on the course's
14781: homeserver.
14782:
14783: input: 3 args -- filename (decluttered), course number and course domain.
14784: output: boolean -- 1 if file was uploaded.
14785:
14786: =back
14787:
14788: =head2 Storing/Retreiving Data
14789:
14790: =over 4
14791:
14792: =item *
14793:
14794: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
14795: permanently for this url; hashref needs to be given and should be a \%hashname;
14796: the remaining args aren't required and if they aren't passed or are '' they will
14797: be derived from the env (with the exception of $laststore, which is an
14798: optional arg used when a user's submission is stored in grading).
14799: $laststore is $version=$timestamp, where $version is the most recent version
14800: number retrieved for the corresponding $symb in the $namespace db file, and
14801: $timestamp is the timestamp for that transaction (UNIX time).
14802: $laststore is currently only passed when cstore() is called by
14803: structuretags::finalize_storage().
14804:
14805: =item *
14806:
14807: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
14808: but uses critical subroutine
14809:
14810: =item *
14811:
14812: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
14813: all args are optional
14814:
14815: =item *
14816:
14817: dumpstore($namespace,$udom,$uname,$regexp,$range) :
14818: dumps the complete (or key matching regexp) namespace into a hash
14819: ($udom, $uname, $regexp, $range are optional) for a namespace that is
14820: normally &store()ed into
14821:
14822: $range should be either an integer '100' (give me the first 100
14823: matching records)
14824: or be two integers sperated by a - with no spaces
14825: '30-50' (give me the 30th through the 50th matching
14826: records)
14827:
14828:
14829: =item *
14830:
14831: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
14832: replaces a &store() version of data with a replacement set of data
14833: for a particular resource in a namespace passed in the $storehash hash
14834: reference. If $tolog is true, the transaction is logged in the courselog
14835: with an action=PUTSTORE.
14836:
14837: =item *
14838:
14839: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
14840: works very similar to store/cstore, but all data is stored in a
14841: temporary location and can be reset using tmpreset, $storehash should
14842: be a hash reference, returns nothing on success
14843:
14844: =item *
14845:
14846: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
14847: similar to restore, but all data is stored in a temporary location and
14848: can be reset using tmpreset. Returns a hash of values on success,
14849: error string otherwise.
14850:
14851: =item *
14852:
14853: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
14854: deltes all keys for $symb form the temporary storage hash.
14855:
14856: =item *
14857:
14858: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14859: reference filled in from namesp ($udom and $uname are optional)
14860:
14861: =item *
14862:
14863: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
14864: namesp ($udom and $uname are optional)
14865:
14866: =item *
14867:
14868: dump($namespace,$udom,$uname,$regexp,$range) :
14869: dumps the complete (or key matching regexp) namespace into a hash
14870: ($udom, $uname, $regexp, $range are optional)
14871:
14872: $range should be either an integer '100' (give me the first 100
14873: matching records)
14874: or be two integers sperated by a - with no spaces
14875: '30-50' (give me the 30th through the 50th matching
14876: records)
14877: =item *
14878:
14879: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
14880: $store can be a scalar, an array reference, or if the amount to be
14881: incremented is > 1, a hash reference.
14882:
14883: ($udom and $uname are optional)
14884:
14885: =item *
14886:
14887: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
14888: ($udom and $uname are optional)
14889:
14890: =item *
14891:
14892: cput($namespace,$storehash,$udom,$uname) : critical put
14893: ($udom and $uname are optional)
14894:
14895: =item *
14896:
14897: newput($namespace,$storehash,$udom,$uname) :
14898:
14899: Attempts to store the items in the $storehash, but only if they don't
14900: currently exist, if this succeeds you can be certain that you have
14901: successfully created a new key value pair in the $namespace db.
14902:
14903:
14904: Args:
14905: $namespace: name of database to store values to
14906: $storehash: hashref to store to the db
14907: $udom: (optional) domain of user containing the db
14908: $uname: (optional) name of user caontaining the db
14909:
14910: Returns:
14911: 'ok' -> succeeded in storing all keys of $storehash
14912: 'key_exists: <key>' -> failed to anything out of $storehash, as at
14913: least <key> already existed in the db (other
14914: requested keys may also already exist)
14915: 'error: <msg>' -> unable to tie the DB or other error occurred
14916: 'con_lost' -> unable to contact request server
14917: 'refused' -> action was not allowed by remote machine
14918:
14919:
14920: =item *
14921:
14922: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14923: reference filled in from namesp (encrypts the return communication)
14924: ($udom and $uname are optional)
14925:
14926: =item *
14927:
14928: log($udom,$name,$home,$message) : write to permanent log for user; use
14929: critical subroutine
14930:
14931: =item *
14932:
14933: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
14934: array reference filled in from namespace found in domain level on either
14935: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
14936:
14937: =item *
14938:
14939: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
14940: domain level either on specified domain server ($uhome) or primary domain
14941: server ($udom and $uhome are optional)
14942:
14943: =item *
14944:
14945: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
14946: for: authentication, language, quotas, timezone, date locale, and portal URL in
14947: the target domain.
14948:
14949: May also include additional key => value pairs for the following groups:
14950:
14951: =over
14952:
14953: =item
14954: disk quotas (MB allocated by default to portfolios and authoring spaces).
14955:
14956: =over
14957:
14958: =item defaultquota, authorquota
14959:
14960: =back
14961:
14962: =item
14963: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
14964: portfolio for users).
14965:
14966: =over
14967:
14968: =item
14969: aboutme, blog, webdav, portfolio
14970:
14971: =back
14972:
14973: =item
14974: requestcourses: ability to request courses, and how requests are processed.
14975:
14976: =over
14977:
14978: =item
14979: official, unofficial, community, textbook, placement
14980:
14981: =back
14982:
14983: =item
14984: inststatus: types of institutional affiliation, and order in which they are displayed.
14985:
14986: =over
14987:
14988: =item
14989: inststatustypes, inststatusorder, inststatusguest
14990:
14991: =back
14992:
14993: =item
14994: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
14995: for course's uploaded content.
14996:
14997: =over
14998:
14999: =item
15000: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
15001: communityquota, textbookquota, placementquota
15002:
15003: =back
15004:
15005: =item
15006: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15007: on your servers.
15008:
15009: =over
15010:
15011: =item
15012: remotesessions, hostedsessions
15013:
15014: =back
15015:
15016: =back
15017:
15018: In cases where a domain coordinator has never used the "Set Domain Configuration"
15019: utility to create a configuration.db file on a domain's primary library server
15020: only the following domain defaults: auth_def, auth_arg_def, lang_def
15021: -- corresponding values are authentication type (internal, krb4, krb5,
15022: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
15023: will be available. Values are retrieved from cache (if current), unless the
15024: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15025: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15026:
15027: Typical usage:
15028:
15029: %domdefaults = &get_domain_defaults($target_domain);
15030:
15031: =back
15032:
15033: =head2 Network Status Functions
15034:
15035: =over 4
15036:
15037: =item *
15038:
15039: dirlist() : return directory list based on URI (first arg).
15040:
15041: Inputs: 1 required, 5 optional.
15042:
15043: =over
15044:
15045: =item
15046: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15047:
15048: =item
15049: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
15050:
15051: =item
15052: $username - username of user/course to be listed. Extracted from $uri if absent.
15053:
15054: =item
15055: $getpropath - boolean: 1 if prepend path using &propath().
15056:
15057: =item
15058: $getuserdir - boolean: 1 if prepend path for "userfiles".
15059:
15060: =item
15061: $alternateRoot - path to prepend in place of path from $uri.
15062:
15063: =back
15064:
15065: Returns: Array of up to two items.
15066:
15067: =over
15068:
15069: a reference to an array of files/subdirectories
15070:
15071: =over
15072:
15073: Each element in the array of files/subdirectories is a & separated list of
15074: item name and the result of running stat on the item. If dirlist was requested
15075: for a file instead of a directory, the item name will be ''. For a directory
15076: listing, if the item is a metadata file, the element will end &N&M
15077: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15078: default copyright set (1).
15079:
15080: =back
15081:
15082: a scalar containing error condition (if encountered).
15083:
15084: =over
15085:
15086: =item
15087: no_host (no homeserver identified for $username:$domain).
15088:
15089: =item
15090: no_such_host (server contacted for listing not identified as valid host).
15091:
15092: =item
15093: con_lost (connection to remote server failed).
15094:
15095: =item
15096: refused (invalid $username:$domain received on lond side).
15097:
15098: =item
15099: no_such_dir (directory at specified path on lond side does not exist).
15100:
15101: =item
15102: empty (directory at specified path on lond side is empty).
15103:
15104: =over
15105:
15106: This is currently not encountered because the &ls3, &ls2,
15107: &ls (_handler) routines on the lond side do not filter out
15108: . and .. from a directory listing.
15109:
15110: =back
15111:
15112: =back
15113:
15114: =back
15115:
15116: =item *
15117:
15118: spareserver() : find server with least workload from spare.tab
15119:
15120:
15121: =item *
15122:
15123: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15124: if there is no corresponding loncapa host.
15125:
15126: =back
15127:
15128:
15129: =head2 Apache Request
15130:
15131: =over 4
15132:
15133: =item *
15134:
15135: ssi($url,%hash) : server side include, does a complete request cycle on url to
15136: localhost, posts hash
15137:
15138: =back
15139:
15140: =head2 Data to String to Data
15141:
15142: =over 4
15143:
15144: =item *
15145:
15146: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15147: and '&' separators, supports elements that are arrayrefs and hashrefs
15148:
15149: =item *
15150:
15151: hashref2str($hashref) : convert a hashref into a string complete with
15152: escaping and '=' and '&' separators, supports elements that are
15153: arrayrefs and hashrefs
15154:
15155: =item *
15156:
15157: arrayref2str($arrayref) : convert an arrayref into a string complete
15158: with escaping and '&' separators, supports elements that are arrayrefs
15159: and hashrefs
15160:
15161: =item *
15162:
15163: str2hash($string) : convert string to hash using unescaping and
15164: splitting on '=' and '&', supports elements that are arrayrefs and
15165: hashrefs
15166:
15167: =item *
15168:
15169: str2array($string) : convert string to hash using unescaping and
15170: splitting on '&', supports elements that are arrayrefs and hashrefs
15171:
15172: =back
15173:
15174: =head2 Logging Routines
15175:
15176:
15177: These routines allow one to make log messages in the lonnet.log and
15178: lonnet.perm logfiles.
15179:
15180: =over 4
15181:
15182: =item *
15183:
15184: logtouch() : make sure the logfile, lonnet.log, exists
15185:
15186: =item *
15187:
15188: logthis() : append message to the normal lonnet.log file, it gets
15189: preiodically rolled over and deleted.
15190:
15191: =item *
15192:
15193: logperm() : append a permanent message to lonnet.perm.log, this log
15194: file never gets deleted by any automated portion of the system, only
15195: messages of critical importance should go in here.
15196:
15197:
15198: =back
15199:
15200: =head2 General File Helper Routines
15201:
15202: =over 4
15203:
15204: =item *
15205:
15206: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15207: (a) files in /uploaded
15208: (i) If a local copy of the file exists -
15209: compares modification date of local copy with last-modified date for
15210: definitive version stored on home server for course. If local copy is
15211: stale, requests a new version from the home server and stores it.
15212: If the original has been removed from the home server, then local copy
15213: is unlinked.
15214: (ii) If local copy does not exist -
15215: requests the file from the home server and stores it.
15216:
15217: If $caller is 'uploadrep':
15218: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15219: for request for files originally uploaded via DOCS.
15220: - returns 'ok' if fresh local copy now available, -1 otherwise.
15221:
15222: Otherwise:
15223: This indicates a call from the content generation phase of the request.
15224: - returns the entire contents of the file or -1.
15225:
15226: (b) files in /res
15227: - returns the entire contents of a file or -1;
15228: it properly subscribes to and replicates the file if neccessary.
15229:
15230:
15231: =item *
15232:
15233: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15234: reference
15235:
15236: returns either a stat() list of data about the file or an empty list
15237: if the file doesn't exist or couldn't find out about it (connection
15238: problems or user unknown)
15239:
15240: =item *
15241:
15242: filelocation($dir,$file) : returns file system location of a file
15243: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15244: directory that relative $file lookups are to looked in ($dir of /a/dir
15245: and a file of ../bob will become /a/bob)
15246:
15247: =item *
15248:
15249: hreflocation($dir,$file) : returns file system location or a URL; same as
15250: filelocation except for hrefs
15251:
15252: =item *
15253:
15254: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15255: also removes beginning /home/httpd/html unless /priv/ follows it.
15256:
15257: =back
15258:
15259: =head2 Usererfile file routines (/uploaded*)
15260:
15261: =over 4
15262:
15263: =item *
15264:
15265: userfileupload(): main rotine for putting a file in a user or course's
15266: filespace, arguments are,
15267:
15268: formname - required - this is the name of the element in $env where the
15269: filename, and the contents of the file to create/modifed exist
15270: the filename is in $env{'form.'.$formname.'.filename'} and the
15271: contents of the file is located in $env{'form.'.$formname}
15272: context - if coursedoc, store the file in the course of the active role
15273: of the current user;
15274: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15275: if 'canceloverwrite': delete file in tmp/overwrites directory
15276: subdir - required - subdirectory to put the file in under ../userfiles/
15277: if undefined, it will be placed in "unknown"
15278:
15279: (This routine calls clean_filename() to remove any dangerous
15280: characters from the filename, and then calls finuserfileupload() to
15281: complete the transaction)
15282:
15283: returns either the url of the uploaded file (/uploaded/....) if successful
15284: and /adm/notfound.html if unsuccessful
15285:
15286: =item *
15287:
15288: clean_filename(): routine for cleaing a filename up for storage in
15289: userfile space, argument is:
15290:
15291: filename - proposed filename
15292:
15293: returns: the new clean filename
15294:
15295: =item *
15296:
15297: finishuserfileupload(): routine that creates and sends the file to
15298: userspace, probably shouldn't be called directly
15299:
15300: docuname: username or courseid of destination for the file
15301: docudom: domain of user/course of destination for the file
15302: formname: same as for userfileupload()
15303: fname: filename (including subdirectories) for the file
15304: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15305: allfiles: reference to hash used to store objects found by parser
15306: codebase: reference to hash used for codebases of java objects found by parser
15307: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15308: thumbheight: height (pixels) of thumbnail to be created for uploaded image
15309: resizewidth: width to be used to resize image using resizeImage from ImageMagick
15310: resizeheight: height to be used to resize image using resizeImage from ImageMagick
15311: context: if 'overwrite', will move the uploaded file from its temporary location to
15312: userfiles to facilitate overwriting a previously uploaded file with same name.
15313: mimetype: reference to scalar to accommodate mime type determined
15314: from File::MMagic if $parser = parse.
15315:
15316: returns either the url of the uploaded file (/uploaded/....) if successful
15317: and /adm/notfound.html if unsuccessful (or an error message if context
15318: was 'overwrite').
15319:
15320:
15321: =item *
15322:
15323: renameuserfile(): renames an existing userfile to a new name
15324:
15325: Args:
15326: docuname: username or courseid of destination for the file
15327: docudom: domain of user/course of destination for the file
15328: old: current file name (including any subdirs under userfiles)
15329: new: desired file name (including any subdirs under userfiles)
15330:
15331: =item *
15332:
15333: mkdiruserfile(): creates a directory is a userfiles dir
15334:
15335: Args:
15336: docuname: username or courseid of destination for the file
15337: docudom: domain of user/course of destination for the file
15338: dir: dir to create (including any subdirs under userfiles)
15339:
15340: =item *
15341:
15342: removeuserfile(): removes a file that exists in userfiles
15343:
15344: Args:
15345: docuname: username or courseid of destination for the file
15346: docudom: domain of user/course of destination for the file
15347: fname: filname to delete (including any subdirs under userfiles)
15348:
15349: =item *
15350:
15351: removeuploadedurl(): convience function for removeuserfile()
15352:
15353: Args:
15354: url: a full /uploaded/... url to delete
15355:
15356: =item *
15357:
15358: get_portfile_permissions():
15359: Args:
15360: domain: domain of user or course contain the portfolio files
15361: user: name of user or num of course contain the portfolio files
15362: Returns:
15363: hashref of a dump of the proper file_permissions.db
15364:
15365:
15366: =item *
15367:
15368: get_access_controls():
15369:
15370: Args:
15371: current_permissions: the hash ref returned from get_portfile_permissions()
15372: group: (optional) the group you want the files associated with
15373: file: (optional) the file you want access info on
15374:
15375: Returns:
15376: a hash (keys are file names) of hashes containing
15377: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15378: values are XML containing access control settings (see below)
15379:
15380: Internal notes:
15381:
15382: access controls are stored in file_permissions.db as key=value pairs.
15383: key -> path to file/file_name\0uniqueID:scope_end_start
15384: where scope -> public,guest,course,group,domains or users.
15385: end -> UNIX time for end of access (0 -> no end date)
15386: start -> UNIX time for start of access
15387:
15388: value -> XML description of access control
15389: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15390: <start></start>
15391: <end></end>
15392:
15393: <password></password> for scope type = guest
15394:
15395: <domain></domain> for scope type = course or group
15396: <number></number>
15397: <roles id="">
15398: <role></role>
15399: <access></access>
15400: <section></section>
15401: <group></group>
15402: </roles>
15403:
15404: <dom></dom> for scope type = domains
15405:
15406: <users> for scope type = users
15407: <user>
15408: <uname></uname>
15409: <udom></udom>
15410: </user>
15411: </users>
15412: </scope>
15413:
15414: Access data is also aggregated for each file in an additional key=value pair:
15415: key -> path to file/file_name\0accesscontrol
15416: value -> reference to hash
15417: hash contains key = value pairs
15418: where key = uniqueID:scope_end_start
15419: value = UNIX time record was last updated
15420:
15421: Used to improve speed of look-ups of access controls for each file.
15422:
15423: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15424:
15425: =item *
15426:
15427: modify_access_controls():
15428:
15429: Modifies access controls for a portfolio file
15430: Args
15431: 1. file name
15432: 2. reference to hash of required changes,
15433: 3. domain
15434: 4. username
15435: where domain,username are the domain of the portfolio owner
15436: (either a user or a course)
15437:
15438: Returns:
15439: 1. result of additions or updates ('ok' or 'error', with error message).
15440: 2. result of deletions ('ok' or 'error', with error message).
15441: 3. reference to hash of any new or updated access controls.
15442: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15443: key = integer (inbound ID)
15444: value = uniqueID
15445:
15446: =item *
15447:
15448: get_timebased_id():
15449:
15450: Attempts to get a unique timestamp-based suffix for use with items added to a
15451: course via the Course Editor (e.g., folders, composite pages,
15452: group bulletin boards).
15453:
15454: Args: (first three required; six others optional)
15455:
15456: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15457: docssequence, or name of group
15458:
15459: 2. keyid (alphanumeric): name of temporary locking key in hash,
15460: e.g., num, boardids
15461:
15462: 3. namespace: name of gdbm file used to store suffixes already assigned;
15463: file will be named nohist_namespace.db
15464:
15465: 4. cdom: domain of course; default is current course domain from %env
15466:
15467: 5. cnum: course number; default is current course number from %env
15468:
15469: 6. idtype: set to concat if an additional digit is to be appended to the
15470: unix timestamp to form the suffix, if the plain timestamp is already
15471: in use. Default is to not do this, but simply increment the unix
15472: timestamp by 1 until a unique key is obtained.
15473:
15474: 7. who: holder of locking key; defaults to user:domain for user.
15475:
15476: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
15477: retrying); default is 3.
15478:
15479: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
15480:
15481: Returns:
15482:
15483: 1. suffix obtained (numeric)
15484:
15485: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15486:
15487: 3. error: contains (localized) error message if an error occurred.
15488:
15489:
15490: =back
15491:
15492: =head2 HTTP Helper Routines
15493:
15494: =over 4
15495:
15496: =item *
15497:
15498: escape() : unpack non-word characters into CGI-compatible hex codes
15499:
15500: =item *
15501:
15502: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15503:
15504: =back
15505:
15506: =head1 PRIVATE SUBROUTINES
15507:
15508: =head2 Underlying communication routines (Shouldn't call)
15509:
15510: =over 4
15511:
15512: =item *
15513:
15514: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15515:
15516: =item *
15517:
15518: reply() : uses subreply to send a message to remote machine, logs all failures
15519:
15520: =item *
15521:
15522: critical() : passes a critical message to another server; if cannot
15523: get through then place message in connection buffer directory and
15524: returns con_delayed, if incapable of saving message, returns
15525: con_failed
15526:
15527: =item *
15528:
15529: reconlonc() : tries to reconnect lonc client processes.
15530:
15531: =back
15532:
15533: =head2 Resource Access Logging
15534:
15535: =over 4
15536:
15537: =item *
15538:
15539: flushcourselogs() : flush (save) buffer logs and access logs
15540:
15541: =item *
15542:
15543: courselog($what) : save message for course in hash
15544:
15545: =item *
15546:
15547: courseacclog($what) : save message for course using &courselog(). Perform
15548: special processing for specific resource types (problems, exams, quizzes, etc).
15549:
15550: =item *
15551:
15552: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15553: as a PerlChildExitHandler
15554:
15555: =back
15556:
15557: =head2 Other
15558:
15559: =over 4
15560:
15561: =item *
15562:
15563: symblist($mapname,%newhash) : update symbolic storage links
15564:
15565: =back
15566:
15567: =cut
15568:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>