1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.1354 2017/08/27 17:49:49 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) = @_;
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: return undef if (!-e "$lonidsdir/$handle.id");
682:
683: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
684: return undef if (!$opened);
685:
686: flock($idf,LOCK_SH);
687: my %disk_env;
688: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
689: &GDBM_READER(),0640)) {
690: return undef;
691: }
692:
693: if (!defined($disk_env{'user.name'})
694: || !defined($disk_env{'user.domain'})) {
695: return undef;
696: }
697:
698: if (ref($userhashref) eq 'HASH') {
699: $userhashref->{'name'} = $disk_env{'user.name'};
700: $userhashref->{'domain'} = $disk_env{'user.domain'};
701: }
702:
703: return $handle;
704: }
705:
706: sub timed_flock {
707: my ($file,$lock_type) = @_;
708: my $failed=0;
709: eval {
710: local $SIG{__DIE__}='DEFAULT';
711: local $SIG{ALRM}=sub {
712: $failed=1;
713: die("failed lock");
714: };
715: alarm(13);
716: flock($file,$lock_type);
717: alarm(0);
718: };
719: if ($failed) {
720: return undef;
721: } else {
722: return 1;
723: }
724: }
725:
726: # ---------------------------------------------------------- Append Environment
727:
728: sub appenv {
729: my ($newenv,$roles) = @_;
730: if (ref($newenv) eq 'HASH') {
731: foreach my $key (keys(%{$newenv})) {
732: my $refused = 0;
733: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
734: $refused = 1;
735: if (ref($roles) eq 'ARRAY') {
736: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
737: if (grep(/^\Q$role\E$/,@{$roles})) {
738: $refused = 0;
739: }
740: }
741: }
742: if ($refused) {
743: &logthis("<font color=\"blue\">WARNING: ".
744: "Attempt to modify environment ".$key." to ".$newenv->{$key}
745: .'</font>');
746: delete($newenv->{$key});
747: } else {
748: $env{$key}=$newenv->{$key};
749: }
750: }
751: my $opened = open(my $env_file,'+<',$env{'user.environment'});
752: if ($opened
753: && &timed_flock($env_file,LOCK_EX)
754: &&
755: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
756: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
757: while (my ($key,$value) = each(%{$newenv})) {
758: $disk_env{$key} = $value;
759: }
760: untie(%disk_env);
761: }
762: }
763: return 'ok';
764: }
765: # ----------------------------------------------------- Delete from Environment
766:
767: sub delenv {
768: my ($delthis,$regexp,$roles) = @_;
769: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
770: my $refused = 1;
771: if (ref($roles) eq 'ARRAY') {
772: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
773: if (grep(/^\Q$role\E$/,@{$roles})) {
774: $refused = 0;
775: }
776: }
777: if ($refused) {
778: &logthis("<font color=\"blue\">WARNING: ".
779: "Attempt to delete from environment ".$delthis);
780: return 'error';
781: }
782: }
783: my $opened = open(my $env_file,'+<',$env{'user.environment'});
784: if ($opened
785: && &timed_flock($env_file,LOCK_EX)
786: &&
787: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
788: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
789: foreach my $key (keys(%disk_env)) {
790: if ($regexp) {
791: if ($key=~/^$delthis/) {
792: delete($env{$key});
793: delete($disk_env{$key});
794: }
795: } else {
796: if ($key=~/^\Q$delthis\E/) {
797: delete($env{$key});
798: delete($disk_env{$key});
799: }
800: }
801: }
802: untie(%disk_env);
803: }
804: return 'ok';
805: }
806:
807: sub get_env_multiple {
808: my ($name) = @_;
809: my @values;
810: if (defined($env{$name})) {
811: # exists is it an array
812: if (ref($env{$name})) {
813: @values=@{ $env{$name} };
814: } else {
815: $values[0]=$env{$name};
816: }
817: }
818: return(@values);
819: }
820:
821: # ------------------------------------------------------------------- Locking
822:
823: sub set_lock {
824: my ($text)=@_;
825: $locknum++;
826: my $id=$$.'-'.$locknum;
827: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
828: 'session.lock.'.$id => $text});
829: return $id;
830: }
831:
832: sub get_locks {
833: my $num=0;
834: my %texts=();
835: foreach my $lock (split(/\,/,$env{'session.locks'})) {
836: if ($lock=~/\w/) {
837: $num++;
838: $texts{$lock}=$env{'session.lock.'.$lock};
839: }
840: }
841: return ($num,%texts);
842: }
843:
844: sub remove_lock {
845: my ($id)=@_;
846: my $newlocks='';
847: foreach my $lock (split(/\,/,$env{'session.locks'})) {
848: if (($lock=~/\w/) && ($lock ne $id)) {
849: $newlocks.=','.$lock;
850: }
851: }
852: &appenv({'session.locks' => $newlocks});
853: &delenv('session.lock.'.$id);
854: }
855:
856: sub remove_all_locks {
857: my $activelocks=$env{'session.locks'};
858: foreach my $lock (split(/\,/,$env{'session.locks'})) {
859: if ($lock=~/\w/) {
860: &remove_lock($lock);
861: }
862: }
863: }
864:
865:
866: # ------------------------------------------ Find out current server userload
867: sub userload {
868: my $numusers=0;
869: {
870: opendir(LONIDS,$perlvar{'lonIDsDir'});
871: my $filename;
872: my $curtime=time;
873: while ($filename=readdir(LONIDS)) {
874: next if ($filename eq '.' || $filename eq '..');
875: next if ($filename =~ /publicuser_\d+\.id/);
876: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
877: if ($curtime-$mtime < 1800) { $numusers++; }
878: }
879: closedir(LONIDS);
880: }
881: my $userloadpercent=0;
882: my $maxuserload=$perlvar{'lonUserLoadLim'};
883: if ($maxuserload) {
884: $userloadpercent=100*$numusers/$maxuserload;
885: }
886: $userloadpercent=sprintf("%.2f",$userloadpercent);
887: return $userloadpercent;
888: }
889:
890: # ------------------------------ Find server with least workload from spare.tab
891:
892: sub spareserver {
893: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
894: my $spare_server;
895: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
896: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
897: : $userloadpercent;
898: my ($uint_dom,$remotesessions);
899: if (($udom ne '') && (&domain($udom) ne '')) {
900: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
901: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
902: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
903: $remotesessions = $udomdefaults{'remotesessions'};
904: }
905: my $spareshash = &this_host_spares($udom);
906: if (ref($spareshash) eq 'HASH') {
907: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
908: foreach my $try_server (@{ $spareshash->{'primary'} }) {
909: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
910: $try_server));
911: ($spare_server, $lowest_load) =
912: &compare_server_load($try_server, $spare_server, $lowest_load);
913: }
914: }
915:
916: my $found_server = ($spare_server ne '' && $lowest_load < 100);
917:
918: if (!$found_server) {
919: if (ref($spareshash->{'default'}) eq 'ARRAY') {
920: foreach my $try_server (@{ $spareshash->{'default'} }) {
921: next unless (&spare_can_host($udom,$uint_dom,
922: $remotesessions,$try_server));
923: ($spare_server, $lowest_load) =
924: &compare_server_load($try_server, $spare_server, $lowest_load);
925: }
926: }
927: }
928: }
929:
930: if (!$want_server_name) {
931: my $protocol = 'http';
932: if ($protocol{$spare_server} eq 'https') {
933: $protocol = $protocol{$spare_server};
934: }
935: if (defined($spare_server)) {
936: my $hostname = &hostname($spare_server);
937: if (defined($hostname)) {
938: $spare_server = $protocol.'://'.$hostname;
939: }
940: }
941: }
942: return $spare_server;
943: }
944:
945: sub compare_server_load {
946: my ($try_server, $spare_server, $lowest_load, $required) = @_;
947:
948: if ($required) {
949: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
950: my $remoterev = &get_server_loncaparev(undef,$try_server);
951: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
952: if (($major eq '' && $minor eq '') ||
953: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
954: return ($spare_server,$lowest_load);
955: }
956: }
957:
958: my $loadans = &reply('load', $try_server);
959: my $userloadans = &reply('userload',$try_server);
960:
961: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
962: return ($spare_server, $lowest_load); #didn't get a number from the server
963: }
964:
965: my $load;
966: if ($loadans =~ /\d/) {
967: if ($userloadans =~ /\d/) {
968: #both are numbers, pick the bigger one
969: $load = ($loadans > $userloadans) ? $loadans
970: : $userloadans;
971: } else {
972: $load = $loadans;
973: }
974: } else {
975: $load = $userloadans;
976: }
977:
978: if (($load =~ /\d/) && ($load < $lowest_load)) {
979: $spare_server = $try_server;
980: $lowest_load = $load;
981: }
982: return ($spare_server,$lowest_load);
983: }
984:
985: # --------------------------- ask offload servers if user already has a session
986: sub find_existing_session {
987: my ($udom,$uname) = @_;
988: my $spareshash = &this_host_spares($udom);
989: if (ref($spareshash) eq 'HASH') {
990: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
991: foreach my $try_server (@{ $spareshash->{'primary'} }) {
992: return $try_server if (&has_user_session($try_server, $udom, $uname));
993: }
994: }
995: if (ref($spareshash->{'default'}) eq 'ARRAY') {
996: foreach my $try_server (@{ $spareshash->{'default'} }) {
997: return $try_server if (&has_user_session($try_server, $udom, $uname));
998: }
999: }
1000: }
1001: return;
1002: }
1003:
1004: # -------------------------------- ask if server already has a session for user
1005: sub has_user_session {
1006: my ($lonid,$udom,$uname) = @_;
1007: my $result = &reply(join(':','userhassession',
1008: map {&escape($_)} ($udom,$uname)),$lonid);
1009: return 1 if ($result eq 'ok');
1010:
1011: return 0;
1012: }
1013:
1014: # --------- determine least loaded server in a user's domain which allows login
1015:
1016: sub choose_server {
1017: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1018: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1019: my %servers = &get_servers($udom);
1020: my $lowest_load = 30000;
1021: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1022: if ($skiploadbal) {
1023: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1024: unless (defined($cached)) {
1025: my $cachetime = 60*60*24;
1026: my %domconfig =
1027: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1028: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1029: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1030: $cachetime);
1031: }
1032: }
1033: }
1034: foreach my $lonhost (keys(%servers)) {
1035: if ($skiploadbal) {
1036: if (ref($balancers) eq 'HASH') {
1037: next if (exists($balancers->{$lonhost}));
1038: }
1039: }
1040: my $loginvia;
1041: if ($checkloginvia) {
1042: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1043: if ($loginvia) {
1044: my ($server,$path) = split(/:/,$loginvia);
1045: ($login_host, $lowest_load) =
1046: &compare_server_load($server, $login_host, $lowest_load, $required);
1047: if ($login_host eq $server) {
1048: $portal_path = $path;
1049: $isredirect = 1;
1050: }
1051: } else {
1052: ($login_host, $lowest_load) =
1053: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1054: if ($login_host eq $lonhost) {
1055: $portal_path = '';
1056: $isredirect = '';
1057: }
1058: }
1059: } else {
1060: ($login_host, $lowest_load) =
1061: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1062: }
1063: }
1064: if ($login_host ne '') {
1065: $hostname = &hostname($login_host);
1066: }
1067: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1068: }
1069:
1070: # --------------------------------------------- Try to change a user's password
1071:
1072: sub changepass {
1073: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1074: $currentpass = &escape($currentpass);
1075: $newpass = &escape($newpass);
1076: my $lonhost = $perlvar{'lonHostID'};
1077: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1078: $server);
1079: if (! $answer) {
1080: &logthis("No reply on password change request to $server ".
1081: "by $uname in domain $udom.");
1082: } elsif ($answer =~ "^ok") {
1083: &logthis("$uname in $udom successfully changed their password ".
1084: "on $server.");
1085: } elsif ($answer =~ "^pwchange_failure") {
1086: &logthis("$uname in $udom was unable to change their password ".
1087: "on $server. The action was blocked by either lcpasswd ".
1088: "or pwchange");
1089: } elsif ($answer =~ "^non_authorized") {
1090: &logthis("$uname in $udom did not get their password correct when ".
1091: "attempting to change it on $server.");
1092: } elsif ($answer =~ "^auth_mode_error") {
1093: &logthis("$uname in $udom attempted to change their password despite ".
1094: "not being locally or internally authenticated on $server.");
1095: } elsif ($answer =~ "^unknown_user") {
1096: &logthis("$uname in $udom attempted to change their password ".
1097: "on $server but were unable to because $server is not ".
1098: "their home server.");
1099: } elsif ($answer =~ "^refused") {
1100: &logthis("$server refused to change $uname in $udom password because ".
1101: "it was sent an unencrypted request to change the password.");
1102: } elsif ($answer =~ "invalid_client") {
1103: &logthis("$server refused to change $uname in $udom password because ".
1104: "it was a reset by e-mail originating from an invalid server.");
1105: }
1106: return $answer;
1107: }
1108:
1109: # ----------------------- Try to determine user's current authentication scheme
1110:
1111: sub queryauthenticate {
1112: my ($uname,$udom)=@_;
1113: my $uhome=&homeserver($uname,$udom);
1114: if (!$uhome) {
1115: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1116: return 'no_host';
1117: }
1118: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1119: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1120: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1121: }
1122: return $answer;
1123: }
1124:
1125: # --------- Try to authenticate user from domain's lib servers (first this one)
1126:
1127: sub authenticate {
1128: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1129: $upass=&escape($upass);
1130: $uname= &LONCAPA::clean_username($uname);
1131: my $uhome=&homeserver($uname,$udom,1);
1132: my $newhome;
1133: if ((!$uhome) || ($uhome eq 'no_host')) {
1134: # Maybe the machine was offline and only re-appeared again recently?
1135: &reconlonc();
1136: # One more
1137: $uhome=&homeserver($uname,$udom,1);
1138: if (($uhome eq 'no_host') && $checkdefauth) {
1139: if (defined(&domain($udom,'primary'))) {
1140: $newhome=&domain($udom,'primary');
1141: }
1142: if ($newhome ne '') {
1143: $uhome = $newhome;
1144: }
1145: }
1146: if ((!$uhome) || ($uhome eq 'no_host')) {
1147: &logthis("User $uname at $udom is unknown in authenticate");
1148: return 'no_host';
1149: }
1150: }
1151: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1152: if ($answer eq 'authorized') {
1153: if ($newhome) {
1154: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1155: return 'no_account_on_host';
1156: } else {
1157: &logthis("User $uname at $udom authorized by $uhome");
1158: return $uhome;
1159: }
1160: }
1161: if ($answer eq 'non_authorized') {
1162: &logthis("User $uname at $udom rejected by $uhome");
1163: return 'no_host';
1164: }
1165: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1166: return 'no_host';
1167: }
1168:
1169: sub can_host_session {
1170: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1171: my $canhost = 1;
1172: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1173: if (ref($remotesessions) eq 'HASH') {
1174: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1175: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1176: $canhost = 0;
1177: } else {
1178: $canhost = 1;
1179: }
1180: }
1181: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1182: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1183: $canhost = 1;
1184: } else {
1185: $canhost = 0;
1186: }
1187: }
1188: if ($canhost) {
1189: if ($remotesessions->{'version'} ne '') {
1190: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1191: if ($reqmajor ne '' && $reqminor ne '') {
1192: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1193: my $major = $1;
1194: my $minor = $2;
1195: if (($major < $reqmajor ) ||
1196: (($major == $reqmajor) && ($minor < $reqminor))) {
1197: $canhost = 0;
1198: }
1199: } else {
1200: $canhost = 0;
1201: }
1202: }
1203: }
1204: }
1205: }
1206: if ($canhost) {
1207: if (ref($hostedsessions) eq 'HASH') {
1208: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1209: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1210: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1211: if (($uint_dom ne '') &&
1212: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1213: $canhost = 0;
1214: } else {
1215: $canhost = 1;
1216: }
1217: }
1218: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1219: if (($uint_dom ne '') &&
1220: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1221: $canhost = 1;
1222: } else {
1223: $canhost = 0;
1224: }
1225: }
1226: }
1227: }
1228: return $canhost;
1229: }
1230:
1231: sub spare_can_host {
1232: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1233: my $canhost=1;
1234: my $try_server_hostname = &hostname($try_server);
1235: my $serverhomeID = &get_server_homeID($try_server_hostname);
1236: my $serverhomedom = &host_domain($serverhomeID);
1237: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1238: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1239: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1240: $canhost = 0;
1241: }
1242: }
1243: if (($canhost) && ($uint_dom)) {
1244: my @intdoms;
1245: my $internet_names = &get_internet_names($try_server);
1246: if (ref($internet_names) eq 'ARRAY') {
1247: @intdoms = @{$internet_names};
1248: }
1249: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1250: my $remoterev = &get_server_loncaparev(undef,$try_server);
1251: $canhost = &can_host_session($udom,$try_server,$remoterev,
1252: $remotesessions,
1253: $defdomdefaults{'hostedsessions'});
1254: }
1255: }
1256: return $canhost;
1257: }
1258:
1259: sub this_host_spares {
1260: my ($dom) = @_;
1261: my ($dom_in_use,$lonhost_in_use,$result);
1262: my @hosts = ¤t_machine_ids();
1263: foreach my $lonhost (@hosts) {
1264: if (&host_domain($lonhost) eq $dom) {
1265: $dom_in_use = $dom;
1266: $lonhost_in_use = $lonhost;
1267: last;
1268: }
1269: }
1270: if ($dom_in_use ne '') {
1271: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1272: }
1273: if (ref($result) ne 'HASH') {
1274: $lonhost_in_use = $perlvar{'lonHostID'};
1275: $dom_in_use = &host_domain($lonhost_in_use);
1276: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1277: if (ref($result) ne 'HASH') {
1278: $result = \%spareid;
1279: }
1280: }
1281: return $result;
1282: }
1283:
1284: sub spares_for_offload {
1285: my ($dom_in_use,$lonhost_in_use) = @_;
1286: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1287: if (defined($cached)) {
1288: return $result;
1289: } else {
1290: my $cachetime = 60*60*24;
1291: my %domconfig =
1292: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1293: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1294: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1295: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1296: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1297: }
1298: }
1299: }
1300: }
1301: return;
1302: }
1303:
1304: sub get_lonbalancer_config {
1305: my ($servers) = @_;
1306: my ($currbalancer,$currtargets);
1307: if (ref($servers) eq 'HASH') {
1308: foreach my $server (keys(%{$servers})) {
1309: my %what = (
1310: spareid => 1,
1311: perlvar => 1,
1312: );
1313: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1314: if ($result eq 'ok') {
1315: if (ref($returnhash) eq 'HASH') {
1316: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1317: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1318: $currbalancer = $server;
1319: $currtargets = {};
1320: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1321: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1322: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1323: }
1324: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1325: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1326: }
1327: }
1328: last;
1329: }
1330: }
1331: }
1332: }
1333: }
1334: }
1335: return ($currbalancer,$currtargets);
1336: }
1337:
1338: sub check_loadbalancing {
1339: my ($uname,$udom,$caller) = @_;
1340: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1341: $rule_in_effect,$offloadto,$otherserver);
1342: my $lonhost = $perlvar{'lonHostID'};
1343: my @hosts = ¤t_machine_ids();
1344: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1345: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1346: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1347: my $serverhomedom = &host_domain($lonhost);
1348: my $domneedscache;
1349: my $cachetime = 60*60*24;
1350:
1351: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1352: $dom_in_use = $udom;
1353: $homeintdom = 1;
1354: } else {
1355: $dom_in_use = $serverhomedom;
1356: }
1357: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1358: unless (defined($cached)) {
1359: my %domconfig =
1360: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1361: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1362: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1363: } else {
1364: $domneedscache = $dom_in_use;
1365: }
1366: }
1367: if (ref($result) eq 'HASH') {
1368: ($is_balancer,$currtargets,$currrules) =
1369: &check_balancer_result($result,@hosts);
1370: if ($is_balancer) {
1371: if (ref($currrules) eq 'HASH') {
1372: if ($homeintdom) {
1373: if ($uname ne '') {
1374: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1375: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1376: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1377: $rule_in_effect = $currrules->{'_LC_author'};
1378: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1379: $rule_in_effect = $currrules->{'_LC_adv'}
1380: }
1381: }
1382: if ($rule_in_effect eq '') {
1383: my %userenv = &userenvironment($udom,$uname,'inststatus');
1384: if ($userenv{'inststatus'} ne '') {
1385: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1386: my ($othertitle,$usertypes,$types) =
1387: &Apache::loncommon::sorted_inst_types($udom);
1388: if (ref($types) eq 'ARRAY') {
1389: foreach my $type (@{$types}) {
1390: if (grep(/^\Q$type\E$/,@statuses)) {
1391: if (exists($currrules->{$type})) {
1392: $rule_in_effect = $currrules->{$type};
1393: }
1394: }
1395: }
1396: }
1397: } else {
1398: if (exists($currrules->{'default'})) {
1399: $rule_in_effect = $currrules->{'default'};
1400: }
1401: }
1402: }
1403: } else {
1404: if (exists($currrules->{'default'})) {
1405: $rule_in_effect = $currrules->{'default'};
1406: }
1407: }
1408: } else {
1409: if ($currrules->{'_LC_external'} ne '') {
1410: $rule_in_effect = $currrules->{'_LC_external'};
1411: }
1412: }
1413: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1414: $uname,$udom);
1415: }
1416: }
1417: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1418: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1419: unless (defined($cached)) {
1420: my %domconfig =
1421: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1422: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1423: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1424: } else {
1425: $domneedscache = $serverhomedom;
1426: }
1427: }
1428: if (ref($result) eq 'HASH') {
1429: ($is_balancer,$currtargets,$currrules) =
1430: &check_balancer_result($result,@hosts);
1431: if ($is_balancer) {
1432: if (ref($currrules) eq 'HASH') {
1433: if ($currrules->{'_LC_internetdom'} ne '') {
1434: $rule_in_effect = $currrules->{'_LC_internetdom'};
1435: }
1436: }
1437: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1438: $uname,$udom);
1439: }
1440: } else {
1441: if ($perlvar{'lonBalancer'} eq 'yes') {
1442: $is_balancer = 1;
1443: $offloadto = &this_host_spares($dom_in_use);
1444: }
1445: unless (defined($cached)) {
1446: $domneedscache = $serverhomedom;
1447: }
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: if ($domneedscache) {
1459: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1460: }
1461: if ($is_balancer) {
1462: my $lowest_load = 30000;
1463: if (ref($offloadto) eq 'HASH') {
1464: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1465: foreach my $try_server (@{$offloadto->{'primary'}}) {
1466: ($otherserver,$lowest_load) =
1467: &compare_server_load($try_server,$otherserver,$lowest_load);
1468: }
1469: }
1470: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1471:
1472: if (!$found_server) {
1473: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1474: foreach my $try_server (@{$offloadto->{'default'}}) {
1475: ($otherserver,$lowest_load) =
1476: &compare_server_load($try_server,$otherserver,$lowest_load);
1477: }
1478: }
1479: }
1480: } elsif (ref($offloadto) eq 'ARRAY') {
1481: if (@{$offloadto} == 1) {
1482: $otherserver = $offloadto->[0];
1483: } elsif (@{$offloadto} > 1) {
1484: foreach my $try_server (@{$offloadto}) {
1485: ($otherserver,$lowest_load) =
1486: &compare_server_load($try_server,$otherserver,$lowest_load);
1487: }
1488: }
1489: }
1490: unless ($caller eq 'login') {
1491: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1492: $is_balancer = 0;
1493: if ($uname ne '' && $udom ne '') {
1494: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1495:
1496: &appenv({'user.loadbalexempt' => $lonhost,
1497: 'user.loadbalcheck.time' => time});
1498: }
1499: }
1500: }
1501: }
1502: }
1503: return ($is_balancer,$otherserver);
1504: }
1505:
1506: sub check_balancer_result {
1507: my ($result,@hosts) = @_;
1508: my ($is_balancer,$currtargets,$currrules);
1509: if (ref($result) eq 'HASH') {
1510: if ($result->{'lonhost'} ne '') {
1511: my $currbalancer = $result->{'lonhost'};
1512: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1513: $is_balancer = 1;
1514: $currtargets = $result->{'targets'};
1515: $currrules = $result->{'rules'};
1516: }
1517: } else {
1518: foreach my $key (keys(%{$result})) {
1519: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1520: (ref($result->{$key}) eq 'HASH')) {
1521: $is_balancer = 1;
1522: $currrules = $result->{$key}{'rules'};
1523: $currtargets = $result->{$key}{'targets'};
1524: last;
1525: }
1526: }
1527: }
1528: }
1529: return ($is_balancer,$currtargets,$currrules);
1530: }
1531:
1532: sub get_loadbalancer_targets {
1533: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1534: my $offloadto;
1535: if ($rule_in_effect eq 'none') {
1536: return [$perlvar{'lonHostID'}];
1537: } elsif ($rule_in_effect eq '') {
1538: $offloadto = $currtargets;
1539: } else {
1540: if ($rule_in_effect eq 'homeserver') {
1541: my $homeserver = &homeserver($uname,$udom);
1542: if ($homeserver ne 'no_host') {
1543: $offloadto = [$homeserver];
1544: }
1545: } elsif ($rule_in_effect eq 'externalbalancer') {
1546: my %domconfig =
1547: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1548: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1549: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1550: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1551: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1552: }
1553: }
1554: } else {
1555: my %servers = &internet_dom_servers($udom);
1556: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1557: if (&hostname($remotebalancer) ne '') {
1558: $offloadto = [$remotebalancer];
1559: }
1560: }
1561: } elsif (&hostname($rule_in_effect) ne '') {
1562: $offloadto = [$rule_in_effect];
1563: }
1564: }
1565: return $offloadto;
1566: }
1567:
1568: sub internet_dom_servers {
1569: my ($dom) = @_;
1570: my (%uniqservers,%servers);
1571: my $primaryserver = &hostname(&domain($dom,'primary'));
1572: my @machinedoms = &machine_domains($primaryserver);
1573: foreach my $mdom (@machinedoms) {
1574: my %currservers = %servers;
1575: my %server = &get_servers($mdom);
1576: %servers = (%currservers,%server);
1577: }
1578: my %by_hostname;
1579: foreach my $id (keys(%servers)) {
1580: push(@{$by_hostname{$servers{$id}}},$id);
1581: }
1582: foreach my $hostname (sort(keys(%by_hostname))) {
1583: if (@{$by_hostname{$hostname}} > 1) {
1584: my $match = 0;
1585: foreach my $id (@{$by_hostname{$hostname}}) {
1586: if (&host_domain($id) eq $dom) {
1587: $uniqservers{$id} = $hostname;
1588: $match = 1;
1589: }
1590: }
1591: unless ($match) {
1592: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1593: }
1594: } else {
1595: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1596: }
1597: }
1598: return %uniqservers;
1599: }
1600:
1601: sub trusted_domains {
1602: my ($cmdtype,$calldom) = @_;
1603: my ($trusted,$untrusted);
1604: if (&domain($calldom) eq '') {
1605: return ($trusted,$untrusted);
1606: }
1607: unless ($cmdtype =~ /^(content|shared|enroll|coaurem|domroles|catalog|reqcrs|msg)$/) {
1608: return ($trusted,$untrusted);
1609: }
1610: my $callprimary = &domain($calldom,'primary');
1611: my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
1612: if ($intcalldom eq '') {
1613: return ($trusted,$untrusted);
1614: }
1615:
1616: my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
1617: unless (defined($cached)) {
1618: my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
1619: &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
1620: $trustconfig = $domconfig{'trust'};
1621: }
1622: if (ref($trustconfig)) {
1623: my (%possexc,%possinc,@allexc,@allinc);
1624: if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
1625: if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
1626: map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}};
1627: }
1628: if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1629: map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
1630: }
1631: }
1632: if (keys(%possexc)) {
1633: if (keys(%possinc)) {
1634: foreach my $key (sort(keys(%possexc))) {
1635: next if ($key eq $intcalldom);
1636: unless ($possinc{$key}) {
1637: push(@allexc,$key);
1638: }
1639: }
1640: } else {
1641: @allexc = sort(keys(%possexc));
1642: }
1643: }
1644: if (keys(%possinc)) {
1645: $possinc{$intcalldom} = 1;
1646: @allinc = sort(keys(%possinc));
1647: }
1648: if ((@allexc > 0) || (@allinc > 0)) {
1649: my %doms_by_intdom;
1650: my %allintdoms = &all_host_intdom();
1651: my %alldoms = &all_host_domain();
1652: foreach my $key (%allintdoms) {
1653: if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
1654: unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
1655: push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
1656: }
1657: } else {
1658: $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}];
1659: }
1660: }
1661: foreach my $exc (@allexc) {
1662: if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1663: $untrusted = $doms_by_intdom{$exc};
1664: }
1665: }
1666: foreach my $inc (@allinc) {
1667: if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1668: $trusted = $doms_by_intdom{$inc};
1669: }
1670: }
1671: }
1672: }
1673: return ($trusted,$untrusted);
1674: }
1675:
1676: sub will_trust {
1677: my ($cmdtype,$domain,$possdom) = @_;
1678: return 1 if ($domain eq $possdom);
1679: my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
1680: my $willtrust;
1681: if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
1682: if (grep(/^\Q$domain\E$/,@{$trustedref})) {
1683: $willtrust = 1;
1684: }
1685: } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
1686: unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
1687: $willtrust = 1;
1688: }
1689: } else {
1690: $willtrust = 1;
1691: }
1692: return $willtrust;
1693: }
1694:
1695: # ---------------------- Find the homebase for a user from domain's lib servers
1696:
1697: my %homecache;
1698: sub homeserver {
1699: my ($uname,$udom,$ignoreBadCache)=@_;
1700: my $index="$uname:$udom";
1701:
1702: if (exists($homecache{$index})) { return $homecache{$index}; }
1703:
1704: my %servers = &get_servers($udom,'library');
1705: foreach my $tryserver (keys(%servers)) {
1706: next if ($ignoreBadCache ne 'true' &&
1707: exists($badServerCache{$tryserver}));
1708:
1709: my $answer=reply("home:$udom:$uname",$tryserver);
1710: if ($answer eq 'found') {
1711: delete($badServerCache{$tryserver});
1712: return $homecache{$index}=$tryserver;
1713: } elsif ($answer eq 'no_host') {
1714: $badServerCache{$tryserver}=1;
1715: }
1716: }
1717: return 'no_host';
1718: }
1719:
1720: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1721:
1722: sub idget {
1723: my ($udom,$idsref,$namespace)=@_;
1724: my %returnhash=();
1725: my @ids=();
1726: if (ref($idsref) eq 'ARRAY') {
1727: @ids = @{$idsref};
1728: } else {
1729: return %returnhash;
1730: }
1731: if ($namespace eq '') {
1732: $namespace = 'ids';
1733: }
1734:
1735: my %servers = &get_servers($udom,'library');
1736: foreach my $tryserver (keys(%servers)) {
1737: my $idlist=join('&', map { &escape($_); } @ids);
1738: if ($namespace eq 'ids') {
1739: $idlist=~tr/A-Z/a-z/;
1740: }
1741: my $reply;
1742: if ($namespace eq 'ids') {
1743: $reply=&reply("idget:$udom:".$idlist,$tryserver);
1744: } else {
1745: $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
1746: }
1747: my @answer=();
1748: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1749: @answer=split(/\&/,$reply);
1750: } ;
1751: my $i;
1752: for ($i=0;$i<=$#ids;$i++) {
1753: if ($answer[$i]) {
1754: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1755: }
1756: }
1757: }
1758: return %returnhash;
1759: }
1760:
1761: # ------------------------------------- Find the IDs behind a list of usernames
1762:
1763: sub idrget {
1764: my ($udom,@unames)=@_;
1765: my %returnhash=();
1766: foreach my $uname (@unames) {
1767: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1768: }
1769: return %returnhash;
1770: }
1771:
1772: # Store away a list of names and associated student/employee IDs or clicker IDs
1773:
1774: sub idput {
1775: my ($udom,$idsref,$uhom,$namespace)=@_;
1776: my %servers=();
1777: my %ids=();
1778: my %byid = ();
1779: if (ref($idsref) eq 'HASH') {
1780: %ids=%{$idsref};
1781: }
1782: if ($namespace eq '') {
1783: $namespace = 'ids';
1784: }
1785: foreach my $uname (keys(%ids)) {
1786: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1787: if ($uhom eq '') {
1788: $uhom=&homeserver($uname,$udom);
1789: }
1790: if ($uhom ne 'no_host') {
1791: my $esc_unam=&escape($uname);
1792: if ($namespace eq 'ids') {
1793: my $id=&escape($ids{$uname});
1794: $id=~tr/A-Z/a-z/;
1795: my $esc_unam=&escape($uname);
1796: $servers{$uhom}.=$id.'='.$esc_unam.'&';
1797: } else {
1798: my @currids = split(/,/,$ids{$uname});
1799: foreach my $id (@currids) {
1800: $byid{$uhom}{$id} .= $uname.',';
1801: }
1802: }
1803: }
1804: }
1805: if ($namespace eq 'clickers') {
1806: foreach my $server (keys(%byid)) {
1807: if (ref($byid{$server}) eq 'HASH') {
1808: foreach my $id (keys(%{$byid{$server}})) {
1809: $byid{$server} =~ s/,$//;
1810: $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&';
1811: }
1812: }
1813: }
1814: }
1815: foreach my $server (keys(%servers)) {
1816: $servers{$server} =~ s/\&$//;
1817: if ($namespace eq 'ids') {
1818: &critical('idput:'.$udom.':'.$servers{$server},$server);
1819: } else {
1820: &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
1821: }
1822: }
1823: }
1824:
1825: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1826:
1827: sub iddel {
1828: my ($udom,$idshashref,$uhome,$namespace)=@_;
1829: my %result=();
1830: my %ids=();
1831: my %byid = ();
1832: if (ref($idshashref) eq 'HASH') {
1833: %ids=%{$idshashref};
1834: } else {
1835: return %result;
1836: }
1837: if ($namespace eq '') {
1838: $namespace = 'ids';
1839: }
1840: my %servers=();
1841: while (my ($id,$unamestr) = each(%ids)) {
1842: if ($namespace eq 'ids') {
1843: my $uhom = $uhome;
1844: if ($uhom eq '') {
1845: $uhom=&homeserver($unamestr,$udom);
1846: }
1847: if ($uhom ne 'no_host') {
1848: $servers{$uhom}.='&'.&escape($id);
1849: }
1850: } else {
1851: my @curritems = split(/,/,$ids{$id});
1852: foreach my $uname (@curritems) {
1853: my $uhom = $uhome;
1854: if ($uhom eq '') {
1855: $uhom=&homeserver($uname,$udom);
1856: }
1857: if ($uhom ne 'no_host') {
1858: $byid{$uhom}{$id} .= $uname.',';
1859: }
1860: }
1861: }
1862: }
1863: if ($namespace eq 'clickers') {
1864: foreach my $server (keys(%byid)) {
1865: if (ref($byid{$server}) eq 'HASH') {
1866: foreach my $id (keys(%{$byid{$server}})) {
1867: $byid{$server}{$id} =~ s/,$//;
1868: $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
1869: }
1870: }
1871: }
1872: }
1873: foreach my $server (keys(%servers)) {
1874: $servers{$server} =~ s/\&$//;
1875: if ($namespace eq 'ids') {
1876: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1877: } elsif ($namespace eq 'clickers') {
1878: $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
1879: }
1880: }
1881: return %result;
1882: }
1883:
1884: # ----- Update clicker ID-to-username look-ups in clickers.db on library server
1885:
1886: sub updateclickers {
1887: my ($udom,$action,$idshashref,$uhome,$critical) = @_;
1888: my %clickers;
1889: if (ref($idshashref) eq 'HASH') {
1890: %clickers=%{$idshashref};
1891: } else {
1892: return;
1893: }
1894: my $items='';
1895: foreach my $item (keys(%clickers)) {
1896: $items.=&escape($item).'='.&escape($clickers{$item}).'&';
1897: }
1898: $items=~s/\&$//;
1899: my $request = "updateclickers:$udom:$action:$items";
1900: if ($critical) {
1901: return &critical($request,$uhome);
1902: } else {
1903: return &reply($request,$uhome);
1904: }
1905: }
1906:
1907: # ------------------------------dump from db file owned by domainconfig user
1908: sub dump_dom {
1909: my ($namespace, $udom, $regexp) = @_;
1910:
1911: $udom ||= $env{'user.domain'};
1912:
1913: return () unless $udom;
1914:
1915: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1916: }
1917:
1918: # ------------------------------------------ get items from domain db files
1919:
1920: sub get_dom {
1921: my ($namespace,$storearr,$udom,$uhome)=@_;
1922: return if ($udom eq 'public');
1923: my $items='';
1924: foreach my $item (@$storearr) {
1925: $items.=&escape($item).'&';
1926: }
1927: $items=~s/\&$//;
1928: if (!$udom) {
1929: $udom=$env{'user.domain'};
1930: return if ($udom eq 'public');
1931: if (defined(&domain($udom,'primary'))) {
1932: $uhome=&domain($udom,'primary');
1933: } else {
1934: undef($uhome);
1935: }
1936: } else {
1937: if (!$uhome) {
1938: if (defined(&domain($udom,'primary'))) {
1939: $uhome=&domain($udom,'primary');
1940: }
1941: }
1942: }
1943: if ($udom && $uhome && ($uhome ne 'no_host')) {
1944: my $rep;
1945: if ($namespace =~ /^enc/) {
1946: $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
1947: } else {
1948: $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1949: }
1950: my %returnhash;
1951: if ($rep eq '' || $rep =~ /^error: 2 /) {
1952: return %returnhash;
1953: }
1954: my @pairs=split(/\&/,$rep);
1955: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1956: return @pairs;
1957: }
1958: my $i=0;
1959: foreach my $item (@$storearr) {
1960: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1961: $i++;
1962: }
1963: return %returnhash;
1964: } else {
1965: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1966: }
1967: }
1968:
1969: # -------------------------------------------- put items in domain db files
1970:
1971: sub put_dom {
1972: my ($namespace,$storehash,$udom,$uhome)=@_;
1973: if (!$udom) {
1974: $udom=$env{'user.domain'};
1975: if (defined(&domain($udom,'primary'))) {
1976: $uhome=&domain($udom,'primary');
1977: } else {
1978: undef($uhome);
1979: }
1980: } else {
1981: if (!$uhome) {
1982: if (defined(&domain($udom,'primary'))) {
1983: $uhome=&domain($udom,'primary');
1984: }
1985: }
1986: }
1987: if ($udom && $uhome && ($uhome ne 'no_host')) {
1988: my $items='';
1989: foreach my $item (keys(%$storehash)) {
1990: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1991: }
1992: $items=~s/\&$//;
1993: if ($namespace =~ /^enc/) {
1994: return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
1995: } else {
1996: return &reply("putdom:$udom:$namespace:$items",$uhome);
1997: }
1998: } else {
1999: &logthis("put_dom failed - no homeserver and/or domain");
2000: }
2001: }
2002:
2003: # --------------------- newput for items in db file owned by domainconfig user
2004: sub newput_dom {
2005: my ($namespace,$storehash,$udom) = @_;
2006: my $result;
2007: if (!$udom) {
2008: $udom=$env{'user.domain'};
2009: }
2010: if ($udom) {
2011: my $uname = &get_domainconfiguser($udom);
2012: $result = &newput($namespace,$storehash,$udom,$uname);
2013: }
2014: return $result;
2015: }
2016:
2017: # --------------------- delete for items in db file owned by domainconfig user
2018: sub del_dom {
2019: my ($namespace,$storearr,$udom)=@_;
2020: if (ref($storearr) eq 'ARRAY') {
2021: if (!$udom) {
2022: $udom=$env{'user.domain'};
2023: }
2024: if ($udom) {
2025: my $uname = &get_domainconfiguser($udom);
2026: return &del($namespace,$storearr,$udom,$uname);
2027: }
2028: }
2029: }
2030:
2031: # ----------------------------------construct domainconfig user for a domain
2032: sub get_domainconfiguser {
2033: my ($udom) = @_;
2034: return $udom.'-domainconfig';
2035: }
2036:
2037: sub retrieve_inst_usertypes {
2038: my ($udom) = @_;
2039: my (%returnhash,@order);
2040: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
2041: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
2042: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
2043: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
2044: } else {
2045: if (defined(&domain($udom,'primary'))) {
2046: my $uhome=&domain($udom,'primary');
2047: my $rep=&reply("inst_usertypes:$udom",$uhome);
2048: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
2049: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
2050: return (\%returnhash,\@order);
2051: }
2052: my ($hashitems,$orderitems) = split(/:/,$rep);
2053: my @pairs=split(/\&/,$hashitems);
2054: foreach my $item (@pairs) {
2055: my ($key,$value)=split(/=/,$item,2);
2056: $key = &unescape($key);
2057: next if ($key =~ /^error: 2 /);
2058: $returnhash{$key}=&thaw_unescape($value);
2059: }
2060: my @esc_order = split(/\&/,$orderitems);
2061: foreach my $item (@esc_order) {
2062: push(@order,&unescape($item));
2063: }
2064: } else {
2065: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
2066: }
2067: return (\%returnhash,\@order);
2068: }
2069: }
2070:
2071: sub is_domainimage {
2072: my ($url) = @_;
2073: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
2074: if (&domain($1) ne '') {
2075: return '1';
2076: }
2077: }
2078: return;
2079: }
2080:
2081: sub inst_directory_query {
2082: my ($srch) = @_;
2083: my $udom = $srch->{'srchdomain'};
2084: my %results;
2085: my $homeserver = &domain($udom,'primary');
2086: my $outcome;
2087: if ($homeserver ne '') {
2088: my $queryid=&reply("querysend:instdirsearch:".
2089: &escape($srch->{'srchby'}).':'.
2090: &escape($srch->{'srchterm'}).':'.
2091: &escape($srch->{'srchtype'}),$homeserver);
2092: my $host=&hostname($homeserver);
2093: if ($queryid !~/^\Q$host\E\_/) {
2094: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
2095: return;
2096: }
2097: my $response = &get_query_reply($queryid);
2098: my $maxtries = 5;
2099: my $tries = 1;
2100: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2101: $response = &get_query_reply($queryid);
2102: $tries ++;
2103: }
2104:
2105: if (!&error($response) && $response ne 'refused') {
2106: if ($response eq 'unavailable') {
2107: $outcome = $response;
2108: } else {
2109: $outcome = 'ok';
2110: my @matches = split(/\n/,$response);
2111: foreach my $match (@matches) {
2112: my ($key,$value) = split(/=/,$match);
2113: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2114: }
2115: }
2116: }
2117: }
2118: return ($outcome,%results);
2119: }
2120:
2121: sub usersearch {
2122: my ($srch) = @_;
2123: my $dom = $srch->{'srchdomain'};
2124: my %results;
2125: my %libserv = &all_library();
2126: my $query = 'usersearch';
2127: foreach my $tryserver (keys(%libserv)) {
2128: if (&host_domain($tryserver) eq $dom) {
2129: my $host=&hostname($tryserver);
2130: my $queryid=
2131: &reply("querysend:".&escape($query).':'.
2132: &escape($srch->{'srchby'}).':'.
2133: &escape($srch->{'srchtype'}).':'.
2134: &escape($srch->{'srchterm'}),$tryserver);
2135: if ($queryid !~/^\Q$host\E\_/) {
2136: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
2137: next;
2138: }
2139: my $reply = &get_query_reply($queryid);
2140: my $maxtries = 1;
2141: my $tries = 1;
2142: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2143: $reply = &get_query_reply($queryid);
2144: $tries ++;
2145: }
2146: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2147: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2148: } else {
2149: my @matches;
2150: if ($reply =~ /\n/) {
2151: @matches = split(/\n/,$reply);
2152: } else {
2153: @matches = split(/\&/,$reply);
2154: }
2155: foreach my $match (@matches) {
2156: my ($uname,$udom,%userhash);
2157: foreach my $entry (split(/:/,$match)) {
2158: my ($key,$value) =
2159: map {&unescape($_);} split(/=/,$entry);
2160: $userhash{$key} = $value;
2161: if ($key eq 'username') {
2162: $uname = $value;
2163: } elsif ($key eq 'domain') {
2164: $udom = $value;
2165: }
2166: }
2167: $results{$uname.':'.$udom} = \%userhash;
2168: }
2169: }
2170: }
2171: }
2172: return %results;
2173: }
2174:
2175: sub get_instuser {
2176: my ($udom,$uname,$id) = @_;
2177: my $homeserver = &domain($udom,'primary');
2178: my ($outcome,%results);
2179: if ($homeserver ne '') {
2180: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2181: &escape($id).':'.&escape($udom),$homeserver);
2182: my $host=&hostname($homeserver);
2183: if ($queryid !~/^\Q$host\E\_/) {
2184: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2185: return;
2186: }
2187: my $response = &get_query_reply($queryid);
2188: my $maxtries = 5;
2189: my $tries = 1;
2190: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2191: $response = &get_query_reply($queryid);
2192: $tries ++;
2193: }
2194: if (!&error($response) && $response ne 'refused') {
2195: if ($response eq 'unavailable') {
2196: $outcome = $response;
2197: } else {
2198: $outcome = 'ok';
2199: my @matches = split(/\n/,$response);
2200: foreach my $match (@matches) {
2201: my ($key,$value) = split(/=/,$match);
2202: $results{&unescape($key)} = &thaw_unescape($value);
2203: }
2204: }
2205: }
2206: }
2207: my %userinfo;
2208: if (ref($results{$uname}) eq 'HASH') {
2209: %userinfo = %{$results{$uname}};
2210: }
2211: return ($outcome,%userinfo);
2212: }
2213:
2214: sub get_multiple_instusers {
2215: my ($udom,$users,$caller) = @_;
2216: my ($outcome,$results);
2217: if (ref($users) eq 'HASH') {
2218: my $count = keys(%{$users});
2219: my $requested = &freeze_escape($users);
2220: my $homeserver = &domain($udom,'primary');
2221: if ($homeserver ne '') {
2222: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2223: my $host=&hostname($homeserver);
2224: if ($queryid !~/^\Q$host\E\_/) {
2225: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2226: ' for host: '.$homeserver.'in domain '.$udom);
2227: return ($outcome,$results);
2228: }
2229: my $response = &get_query_reply($queryid);
2230: my $maxtries = 5;
2231: if ($count > 100) {
2232: $maxtries = 1+int($count/20);
2233: }
2234: my $tries = 1;
2235: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2236: $response = &get_query_reply($queryid);
2237: $tries ++;
2238: }
2239: if ($response eq '') {
2240: $results = {};
2241: foreach my $key (keys(%{$users})) {
2242: my ($uname,$id);
2243: if ($caller eq 'id') {
2244: $id = $key;
2245: } else {
2246: $uname = $key;
2247: }
2248: my ($resp,%info) = &get_instuser($udom,$uname,$id);
2249: $outcome = $resp;
2250: if ($resp eq 'ok') {
2251: %{$results} = (%{$results}, %info);
2252: } else {
2253: last;
2254: }
2255: }
2256: } elsif(!&error($response) && ($response ne 'refused')) {
2257: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2258: $outcome = $response;
2259: } else {
2260: ($outcome,my $userdata) = split(/=/,$response,2);
2261: if ($outcome eq 'ok') {
2262: $results = &thaw_unescape($userdata);
2263: }
2264: }
2265: }
2266: }
2267: }
2268: return ($outcome,$results);
2269: }
2270:
2271: sub inst_rulecheck {
2272: my ($udom,$uname,$id,$item,$rules) = @_;
2273: my %returnhash;
2274: if ($udom ne '') {
2275: if (ref($rules) eq 'ARRAY') {
2276: @{$rules} = map {&escape($_);} (@{$rules});
2277: my $rulestr = join(':',@{$rules});
2278: my $homeserver=&domain($udom,'primary');
2279: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
2280: my $response;
2281: if ($item eq 'username') {
2282: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2283: ':'.&escape($uname).':'.$rulestr,
2284: $homeserver));
2285: } elsif ($item eq 'id') {
2286: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2287: ':'.&escape($id).':'.$rulestr,
2288: $homeserver));
2289: } elsif ($item eq 'selfcreate') {
2290: $response=&unescape(&reply('instselfcreatecheck:'.
2291: &escape($udom).':'.&escape($uname).
2292: ':'.$rulestr,$homeserver));
2293: }
2294: if ($response ne 'refused') {
2295: my @pairs=split(/\&/,$response);
2296: foreach my $item (@pairs) {
2297: my ($key,$value)=split(/=/,$item,2);
2298: $key = &unescape($key);
2299: next if ($key =~ /^error: 2 /);
2300: $returnhash{$key}=&thaw_unescape($value);
2301: }
2302: }
2303: }
2304: }
2305: }
2306: return %returnhash;
2307: }
2308:
2309: sub inst_userrules {
2310: my ($udom,$check) = @_;
2311: my (%ruleshash,@ruleorder);
2312: if ($udom ne '') {
2313: my $homeserver=&domain($udom,'primary');
2314: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
2315: my $response;
2316: if ($check eq 'id') {
2317: $response=&reply('instidrules:'.&escape($udom),
2318: $homeserver);
2319: } elsif ($check eq 'email') {
2320: $response=&reply('instemailrules:'.&escape($udom),
2321: $homeserver);
2322: } else {
2323: $response=&reply('instuserrules:'.&escape($udom),
2324: $homeserver);
2325: }
2326: if (($response ne 'refused') && ($response ne 'error') &&
2327: ($response ne 'unknown_cmd') &&
2328: ($response ne 'no_such_host')) {
2329: my ($hashitems,$orderitems) = split(/:/,$response);
2330: my @pairs=split(/\&/,$hashitems);
2331: foreach my $item (@pairs) {
2332: my ($key,$value)=split(/=/,$item,2);
2333: $key = &unescape($key);
2334: next if ($key =~ /^error: 2 /);
2335: $ruleshash{$key}=&thaw_unescape($value);
2336: }
2337: my @esc_order = split(/\&/,$orderitems);
2338: foreach my $item (@esc_order) {
2339: push(@ruleorder,&unescape($item));
2340: }
2341: }
2342: }
2343: }
2344: return (\%ruleshash,\@ruleorder);
2345: }
2346:
2347: # ------------- Get Authentication, Language and User Tools Defaults for Domain
2348:
2349: sub get_domain_defaults {
2350: my ($domain,$ignore_cache) = @_;
2351: return if (($domain eq '') || ($domain eq 'public'));
2352: my $cachetime = 60*60*24;
2353: unless ($ignore_cache) {
2354: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2355: if (defined($cached)) {
2356: if (ref($result) eq 'HASH') {
2357: return %{$result};
2358: }
2359: }
2360: }
2361: my %domdefaults;
2362: my %domconfig =
2363: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
2364: 'requestcourses','inststatus',
2365: 'coursedefaults','usersessions',
2366: 'requestauthor','selfenrollment',
2367: 'coursecategories','ssl','autoenroll',
2368: 'trust','helpsettings'],$domain);
2369: my @coursetypes = ('official','unofficial','community','textbook','placement');
2370: if (ref($domconfig{'defaults'}) eq 'HASH') {
2371: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2372: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2373: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
2374: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
2375: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
2376: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
2377: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2378: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2379: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
2380: } else {
2381: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2382: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2383: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2384: }
2385: if (ref($domconfig{'quotas'}) eq 'HASH') {
2386: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2387: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2388: } else {
2389: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
2390: }
2391: my @usertools = ('aboutme','blog','webdav','portfolio');
2392: foreach my $item (@usertools) {
2393: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2394: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2395: }
2396: }
2397: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2398: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2399: }
2400: }
2401: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
2402: foreach my $item ('official','unofficial','community','textbook','placement') {
2403: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2404: }
2405: }
2406: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2407: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2408: }
2409: if (ref($domconfig{'inststatus'}) eq 'HASH') {
2410: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
2411: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2412: }
2413: }
2414: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
2415: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
2416: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2417: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2418: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2419: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2420: }
2421: foreach my $type (@coursetypes) {
2422: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2423: unless ($type eq 'community') {
2424: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2425: }
2426: }
2427: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2428: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2429: }
2430: if ($domdefaults{'postsubmit'} eq 'on') {
2431: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2432: $domdefaults{$type.'postsubtimeout'} =
2433: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2434: }
2435: }
2436: }
2437: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2438: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2439: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2440: if (@clonecodes) {
2441: $domdefaults{'canclone'} = join('+',@clonecodes);
2442: }
2443: }
2444: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2445: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2446: }
2447: }
2448: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2449: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2450: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2451: }
2452: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2453: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2454: }
2455: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2456: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2457: }
2458: }
2459: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2460: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2461: my @settings = ('types','registered','enroll_dates','access_dates','section',
2462: 'approval','limit');
2463: foreach my $type (@coursetypes) {
2464: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2465: my @mgrdc = ();
2466: foreach my $item (@settings) {
2467: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2468: push(@mgrdc,$item);
2469: }
2470: }
2471: if (@mgrdc) {
2472: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2473: }
2474: }
2475: }
2476: }
2477: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2478: foreach my $type (@coursetypes) {
2479: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2480: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2481: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2482: }
2483: }
2484: }
2485: }
2486: }
2487: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2488: $domdefaults{'catauth'} = 'std';
2489: $domdefaults{'catunauth'} = 'std';
2490: if ($domconfig{'coursecategories'}{'auth'}) {
2491: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2492: }
2493: if ($domconfig{'coursecategories'}{'unauth'}) {
2494: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2495: }
2496: }
2497: if (ref($domconfig{'ssl'}) eq 'HASH') {
2498: if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
2499: $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
2500: }
2501: if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
2502: $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
2503: }
2504: if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
2505: $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
2506: }
2507: }
2508: if (ref($domconfig{'trust'}) eq 'HASH') {
2509: my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
2510: foreach my $prefix (@prefixes) {
2511: if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
2512: $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
2513: }
2514: }
2515: }
2516: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2517: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2518: }
2519: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2520: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2521: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2522: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2523: }
2524: }
2525: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
2526: return %domdefaults;
2527: }
2528:
2529: sub course_portal_url {
2530: my ($cnum,$cdom) = @_;
2531: my $chome = &homeserver($cnum,$cdom);
2532: my $hostname = &hostname($chome);
2533: my $protocol = $protocol{$chome};
2534: $protocol = 'http' if ($protocol ne 'https');
2535: my %domdefaults = &get_domain_defaults($cdom);
2536: my $firsturl;
2537: if ($domdefaults{'portal_def'}) {
2538: $firsturl = $domdefaults{'portal_def'};
2539: } else {
2540: $firsturl = $protocol.'://'.$hostname;
2541: }
2542: return $firsturl;
2543: }
2544:
2545: # --------------------------------------------------- Assign a key to a student
2546:
2547: sub assign_access_key {
2548: #
2549: # a valid key looks like uname:udom#comments
2550: # comments are being appended
2551: #
2552: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2553: $kdom=
2554: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
2555: $knum=
2556: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
2557: $cdom=
2558: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2559: $cnum=
2560: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2561: $udom=$env{'user.name'} unless (defined($udom));
2562: $uname=$env{'user.domain'} unless (defined($uname));
2563: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
2564: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
2565: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
2566: # assigned to this person
2567: # - this should not happen,
2568: # unless something went wrong
2569: # the first time around
2570: # ready to assign
2571: $logentry=$1.'; '.$logentry;
2572: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
2573: $kdom,$knum) eq 'ok') {
2574: # key now belongs to user
2575: my $envkey='key.'.$cdom.'_'.$cnum;
2576: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
2577: &appenv({'environment.'.$envkey => $ckey});
2578: return 'ok';
2579: } else {
2580: return
2581: 'error: Count not permanently assign key, will need to be re-entered later.';
2582: }
2583: } else {
2584: return 'error: Could not assign key, try again later.';
2585: }
2586: } elsif (!$existing{$ckey}) {
2587: # the key does not exist
2588: return 'error: The key does not exist';
2589: } else {
2590: # the key is somebody else's
2591: return 'error: The key is already in use';
2592: }
2593: }
2594:
2595: # ------------------------------------------ put an additional comment on a key
2596:
2597: sub comment_access_key {
2598: #
2599: # a valid key looks like uname:udom#comments
2600: # comments are being appended
2601: #
2602: my ($ckey,$cdom,$cnum,$logentry)=@_;
2603: $cdom=
2604: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2605: $cnum=
2606: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2607: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2608: if ($existing{$ckey}) {
2609: $existing{$ckey}.='; '.$logentry;
2610: # ready to assign
2611: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
2612: $cdom,$cnum) eq 'ok') {
2613: return 'ok';
2614: } else {
2615: return 'error: Count not store comment.';
2616: }
2617: } else {
2618: # the key does not exist
2619: return 'error: The key does not exist';
2620: }
2621: }
2622:
2623: # ------------------------------------------------------ Generate a set of keys
2624:
2625: sub generate_access_keys {
2626: my ($number,$cdom,$cnum,$logentry)=@_;
2627: $cdom=
2628: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2629: $cnum=
2630: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2631: unless (&allowed('mky',$cdom)) { return 0; }
2632: unless (($cdom) && ($cnum)) { return 0; }
2633: if ($number>10000) { return 0; }
2634: sleep(2); # make sure don't get same seed twice
2635: srand(time()^($$+($$<<15))); # from "Programming Perl"
2636: my $total=0;
2637: for (my $i=1;$i<=$number;$i++) {
2638: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2639: sprintf("%lx",int(100000*rand)).'-'.
2640: sprintf("%lx",int(100000*rand));
2641: $newkey=~s/1/g/g; # folks mix up 1 and l
2642: $newkey=~s/0/h/g; # and also 0 and O
2643: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2644: if ($existing{$newkey}) {
2645: $i--;
2646: } else {
2647: if (&put('accesskeys',
2648: { $newkey => '# generated '.localtime().
2649: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
2650: '; '.$logentry },
2651: $cdom,$cnum) eq 'ok') {
2652: $total++;
2653: }
2654: }
2655: }
2656: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
2657: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2658: return $total;
2659: }
2660:
2661: # ------------------------------------------------------- Validate an accesskey
2662:
2663: sub validate_access_key {
2664: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2665: $cdom=
2666: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2667: $cnum=
2668: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2669: $udom=$env{'user.domain'} unless (defined($udom));
2670: $uname=$env{'user.name'} unless (defined($uname));
2671: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2672: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
2673: }
2674:
2675: # ------------------------------------- Find the section of student in a course
2676: sub devalidate_getsection_cache {
2677: my ($udom,$unam,$courseid)=@_;
2678: my $hashid="$udom:$unam:$courseid";
2679: &devalidate_cache_new('getsection',$hashid);
2680: }
2681:
2682: sub courseid_to_courseurl {
2683: my ($courseid) = @_;
2684: #already url style courseid
2685: return $courseid if ($courseid =~ m{^/});
2686:
2687: if (exists($env{'course.'.$courseid.'.num'})) {
2688: my $cnum = $env{'course.'.$courseid.'.num'};
2689: my $cdom = $env{'course.'.$courseid.'.domain'};
2690: return "/$cdom/$cnum";
2691: }
2692:
2693: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2694: if (exists($courseinfo{'num'})) {
2695: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2696: }
2697:
2698: return undef;
2699: }
2700:
2701: sub getsection {
2702: my ($udom,$unam,$courseid)=@_;
2703: my $cachetime=1800;
2704:
2705: my $hashid="$udom:$unam:$courseid";
2706: my ($result,$cached)=&is_cached_new('getsection',$hashid);
2707: if (defined($cached)) { return $result; }
2708:
2709: my %Pending;
2710: my %Expired;
2711: #
2712: # Each role can either have not started yet (pending), be active,
2713: # or have expired.
2714: #
2715: # If there is an active role, we are done.
2716: #
2717: # If there is more than one role which has not started yet,
2718: # choose the one which will start sooner
2719: # If there is one role which has not started yet, return it.
2720: #
2721: # If there is more than one expired role, choose the one which ended last.
2722: # If there is a role which has expired, return it.
2723: #
2724: $courseid = &courseid_to_courseurl($courseid);
2725: my %roleshash = &dump('roles',$udom,$unam,$courseid);
2726: foreach my $key (keys(%roleshash)) {
2727: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
2728: my $section=$1;
2729: if ($key eq $courseid.'_st') { $section=''; }
2730: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
2731: my $now=time;
2732: if (defined($end) && $end && ($now > $end)) {
2733: $Expired{$end}=$section;
2734: next;
2735: }
2736: if (defined($start) && $start && ($now < $start)) {
2737: $Pending{$start}=$section;
2738: next;
2739: }
2740: return &do_cache_new('getsection',$hashid,$section,$cachetime);
2741: }
2742: #
2743: # Presumedly there will be few matching roles from the above
2744: # loop and the sorting time will be negligible.
2745: if (scalar(keys(%Pending))) {
2746: my ($time) = sort {$a <=> $b} keys(%Pending);
2747: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
2748: }
2749: if (scalar(keys(%Expired))) {
2750: my @sorted = sort {$a <=> $b} keys(%Expired);
2751: my $time = pop(@sorted);
2752: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
2753: }
2754: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
2755: }
2756:
2757: sub save_cache {
2758: &purge_remembered();
2759: #&Apache::loncommon::validate_page();
2760: undef(%env);
2761: undef($env_loaded);
2762: }
2763:
2764: my $to_remember=-1;
2765: my %remembered;
2766: my %accessed;
2767: my $kicks=0;
2768: my $hits=0;
2769: sub make_key {
2770: my ($name,$id) = @_;
2771: if (length($id) > 65
2772: && length(&escape($id)) > 200) {
2773: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2774: }
2775: return &escape($name.':'.$id);
2776: }
2777:
2778: sub devalidate_cache_new {
2779: my ($name,$id,$debug) = @_;
2780: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
2781: my $remembered_id=$name.':'.$id;
2782: $id=&make_key($name,$id);
2783: $memcache->delete($id);
2784: delete($remembered{$remembered_id});
2785: delete($accessed{$remembered_id});
2786: }
2787:
2788: sub is_cached_new {
2789: my ($name,$id,$debug) = @_;
2790: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
2791: if (exists($remembered{$remembered_id})) {
2792: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2793: $accessed{$remembered_id}=[&gettimeofday()];
2794: $hits++;
2795: return ($remembered{$remembered_id},1);
2796: }
2797: $id=&make_key($name,$id);
2798: my $value = $memcache->get($id);
2799: if (!(defined($value))) {
2800: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
2801: return (undef,undef);
2802: }
2803: if ($value eq '__undef__') {
2804: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2805: $value=undef;
2806: }
2807: &make_room($remembered_id,$value,$debug);
2808: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2809: return ($value,1);
2810: }
2811:
2812: sub do_cache_new {
2813: my ($name,$id,$value,$time,$debug) = @_;
2814: my $remembered_id=$name.':'.$id;
2815: $id=&make_key($name,$id);
2816: my $setvalue=$value;
2817: if (!defined($setvalue)) {
2818: $setvalue='__undef__';
2819: }
2820: if (!defined($time) ) {
2821: $time=600;
2822: }
2823: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
2824: my $result = $memcache->set($id,$setvalue,$time);
2825: if (! $result) {
2826: &logthis("caching of id -> $id failed");
2827: $memcache->disconnect_all();
2828: }
2829: # need to make a copy of $value
2830: &make_room($remembered_id,$value,$debug);
2831: return $value;
2832: }
2833:
2834: sub make_room {
2835: my ($remembered_id,$value,$debug)=@_;
2836:
2837: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
2838: : $value;
2839: if ($to_remember<0) { return; }
2840: $accessed{$remembered_id}=[&gettimeofday()];
2841: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2842: my $to_kick;
2843: my $max_time=0;
2844: foreach my $other (keys(%accessed)) {
2845: if (&tv_interval($accessed{$other}) > $max_time) {
2846: $to_kick=$other;
2847: $max_time=&tv_interval($accessed{$other});
2848: }
2849: }
2850: delete($remembered{$to_kick});
2851: delete($accessed{$to_kick});
2852: $kicks++;
2853: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
2854: return;
2855: }
2856:
2857: sub purge_remembered {
2858: #&logthis("Tossing ".scalar(keys(%remembered)));
2859: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
2860: undef(%remembered);
2861: undef(%accessed);
2862: }
2863: # ------------------------------------- Read an entry from a user's environment
2864:
2865: sub userenvironment {
2866: my ($udom,$unam,@what)=@_;
2867: my $items;
2868: foreach my $item (@what) {
2869: $items.=&escape($item).'&';
2870: }
2871: $items=~s/\&$//;
2872: my %returnhash=();
2873: my $uhome = &homeserver($unam,$udom);
2874: unless ($uhome eq 'no_host') {
2875: my @answer=split(/\&/,
2876: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
2877: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2878: return %returnhash;
2879: }
2880: my $i;
2881: for ($i=0;$i<=$#what;$i++) {
2882: $returnhash{$what[$i]}=&unescape($answer[$i]);
2883: }
2884: }
2885: return %returnhash;
2886: }
2887:
2888: # ---------------------------------------------------------- Get a studentphoto
2889: sub studentphoto {
2890: my ($udom,$unam,$ext) = @_;
2891: my $home=&Apache::lonnet::homeserver($unam,$udom);
2892: if (defined($env{'request.course.id'})) {
2893: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
2894: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2895: return(&retrievestudentphoto($udom,$unam,$ext));
2896: } else {
2897: my ($result,$perm_reqd)=
2898: &Apache::lonnet::auto_photo_permission($unam,$udom);
2899: if ($result eq 'ok') {
2900: if (!($perm_reqd eq 'yes')) {
2901: return(&retrievestudentphoto($udom,$unam,$ext));
2902: }
2903: }
2904: }
2905: }
2906: } else {
2907: my ($result,$perm_reqd) =
2908: &Apache::lonnet::auto_photo_permission($unam,$udom);
2909: if ($result eq 'ok') {
2910: if (!($perm_reqd eq 'yes')) {
2911: return(&retrievestudentphoto($udom,$unam,$ext));
2912: }
2913: }
2914: }
2915: return '/adm/lonKaputt/lonlogo_broken.gif';
2916: }
2917:
2918: sub retrievestudentphoto {
2919: my ($udom,$unam,$ext,$type) = @_;
2920: my $home=&Apache::lonnet::homeserver($unam,$udom);
2921: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2922: if ($ret eq 'ok') {
2923: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2924: if ($type eq 'thumbnail') {
2925: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2926: }
2927: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2928: return $tokenurl;
2929: } else {
2930: if ($type eq 'thumbnail') {
2931: return '/adm/lonKaputt/genericstudent_tn.gif';
2932: } else {
2933: return '/adm/lonKaputt/lonlogo_broken.gif';
2934: }
2935: }
2936: }
2937:
2938: # -------------------------------------------------------------------- New chat
2939:
2940: sub chatsend {
2941: my ($newentry,$anon,$group)=@_;
2942: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2943: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2944: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
2945: &reply('chatsend:'.$cdom.':'.$cnum.':'.
2946: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
2947: &escape($newentry)).':'.$group,$chome);
2948: }
2949:
2950: # ------------------------------------------ Find current version of a resource
2951:
2952: sub getversion {
2953: my $fname=&clutter(shift);
2954: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
2955: return ¤tversion(&filelocation('',$fname));
2956: }
2957:
2958: sub currentversion {
2959: my $fname=shift;
2960: my $author=$fname;
2961: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2962: my ($udom,$uname)=split(/\//,$author);
2963: my $home=&homeserver($uname,$udom);
2964: if ($home eq 'no_host') {
2965: return -1;
2966: }
2967: my $answer=&reply("currentversion:$fname",$home);
2968: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2969: return -1;
2970: }
2971: return $answer;
2972: }
2973:
2974: #
2975: # Return special version number of resource if set by override, empty otherwise
2976: #
2977: sub usedversion {
2978: my $fname=shift;
2979: unless ($fname) { $fname=$env{'request.uri'}; }
2980: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2981: if ($urlversion) { return $urlversion; }
2982: return '';
2983: }
2984:
2985: # ----------------------------- Subscribe to a resource, return URL if possible
2986:
2987: sub subscribe {
2988: my $fname=shift;
2989: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
2990: $fname=~s/[\n\r]//g;
2991: my $author=$fname;
2992: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2993: my ($udom,$uname)=split(/\//,$author);
2994: my $home=homeserver($uname,$udom);
2995: if ($home eq 'no_host') {
2996: return 'not_found';
2997: }
2998: my $answer=reply("sub:$fname",$home);
2999: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3000: $answer.=' by '.$home;
3001: }
3002: return $answer;
3003: }
3004:
3005: # -------------------------------------------------------------- Replicate file
3006:
3007: sub repcopy {
3008: my $filename=shift;
3009: $filename=~s/\/+/\//g;
3010: my $londocroot = $perlvar{'lonDocRoot'};
3011: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
3012: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
3013: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3014: $filename=~m{^/*(uploaded|editupload)/}) {
3015: return &repcopy_userfile($filename);
3016: }
3017: $filename=~s/[\n\r]//g;
3018: my $transname="$filename.in.transfer";
3019: # FIXME: this should flock
3020: if ((-e $filename) || (-e $transname)) { return 'ok'; }
3021: my $remoteurl=subscribe($filename);
3022: if ($remoteurl =~ /^con_lost by/) {
3023: &logthis("Subscribe returned $remoteurl: $filename");
3024: return 'unavailable';
3025: } elsif ($remoteurl eq 'not_found') {
3026: #&logthis("Subscribe returned not_found: $filename");
3027: return 'not_found';
3028: } elsif ($remoteurl =~ /^rejected by/) {
3029: &logthis("Subscribe returned $remoteurl: $filename");
3030: return 'forbidden';
3031: } elsif ($remoteurl eq 'directory') {
3032: return 'ok';
3033: } else {
3034: my $author=$filename;
3035: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3036: my ($udom,$uname)=split(/\//,$author);
3037: my $home=homeserver($uname,$udom);
3038: unless ($home eq $perlvar{'lonHostID'}) {
3039: my @parts=split(/\//,$filename);
3040: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
3041: if ($path ne "$londocroot/res") {
3042: &logthis("Malconfiguration for replication: $filename");
3043: return 'bad_request';
3044: }
3045: my $count;
3046: for ($count=5;$count<$#parts;$count++) {
3047: $path.="/$parts[$count]";
3048: if ((-e $path)!=1) {
3049: mkdir($path,0777);
3050: }
3051: }
3052: my $request=new HTTP::Request('GET',"$remoteurl");
3053: my $response;
3054: if ($remoteurl =~ m{/raw/}) {
3055: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
3056: } else {
3057: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
3058: }
3059: if ($response->is_error()) {
3060: unlink($transname);
3061: my $message=$response->status_line;
3062: &logthis("<font color=\"blue\">WARNING:"
3063: ." LWP get: $message: $filename</font>");
3064: return 'unavailable';
3065: } else {
3066: if ($remoteurl!~/\.meta$/) {
3067: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
3068: my $mresponse;
3069: if ($remoteurl =~ m{/raw/}) {
3070: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
3071: } else {
3072: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
3073: }
3074: if ($mresponse->is_error()) {
3075: unlink($filename.'.meta');
3076: &logthis(
3077: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
3078: }
3079: }
3080: rename($transname,$filename);
3081: return 'ok';
3082: }
3083: }
3084: }
3085: }
3086:
3087: # ------------------------------------------------ Get server side include body
3088: sub ssi_body {
3089: my ($filelink,%form)=@_;
3090: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3091: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3092: }
3093: my $output='';
3094: my $response;
3095: if ($filelink=~/^https?\:/) {
3096: ($output,$response)=&externalssi($filelink);
3097: } else {
3098: $filelink .= $filelink=~/\?/ ? '&' : '?';
3099: $filelink .= 'inhibitmenu=yes';
3100: ($output,$response)=&ssi($filelink,%form);
3101: }
3102: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
3103: $output=~s/^.*?\<body[^\>]*\>//si;
3104: $output=~s/\<\/body\s*\>.*?$//si;
3105: if (wantarray) {
3106: return ($output, $response);
3107: } else {
3108: return $output;
3109: }
3110: }
3111:
3112: # --------------------------------------------------------- Server Side Include
3113:
3114: sub absolute_url {
3115: my ($host_name) = @_;
3116: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3117: if ($host_name eq '') {
3118: $host_name = $ENV{'SERVER_NAME'};
3119: }
3120: return $protocol.$host_name;
3121: }
3122:
3123: #
3124: # Server side include.
3125: # Parameters:
3126: # fn Possibly encrypted resource name/id.
3127: # form Hash that describes how the rendering should be done
3128: # and other things.
3129: # Returns:
3130: # Scalar context: The content of the response.
3131: # Array context: 2 element list of the content and the full response object.
3132: #
3133: sub ssi {
3134:
3135: my ($fn,%form)=@_;
3136: my $request;
3137:
3138: $form{'no_update_last_known'}=1;
3139: &Apache::lonenc::check_encrypt(\$fn);
3140: if (%form) {
3141: $request=new HTTP::Request('POST',&absolute_url().$fn);
3142: $request->content(join('&',map {
3143: my $name = escape($_);
3144: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3145: ? join("&$name=", map {escape($_) } @{$form{$_}})
3146: : &escape($form{$_}) );
3147: } keys(%form)));
3148: } else {
3149: $request=new HTTP::Request('GET',&absolute_url().$fn);
3150: }
3151:
3152: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
3153: my $lonhost = $perlvar{'lonHostID'};
3154: my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar);
3155:
3156: if (wantarray) {
3157: return ($response->content, $response);
3158: } else {
3159: return $response->content;
3160: }
3161: }
3162:
3163: sub externalssi {
3164: my ($url)=@_;
3165: my $request=new HTTP::Request('GET',$url);
3166: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
3167: if (wantarray) {
3168: return ($response->content, $response);
3169: } else {
3170: return $response->content;
3171: }
3172: }
3173:
3174:
3175: # If the local copy of a replicated resource is outdated, trigger a
3176: # connection from the homeserver to flush the delayed queue. If no update
3177: # happens, remove local copies of outdated resource (and corresponding
3178: # metadata file).
3179:
3180: sub remove_stale_resfile {
3181: my ($url) = @_;
3182: my $removed;
3183: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3184: my $audom = $1;
3185: my $auname = $2;
3186: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
3187: my $homeserver = &homeserver($auname,$audom);
3188: unless (($homeserver eq 'no_host') ||
3189: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3190: my $fname = &filelocation('',$url);
3191: if (-e $fname) {
3192: my $protocol = $protocol{$homeserver};
3193: $protocol = 'http' if ($protocol ne 'https');
3194: my $hostname = &hostname($homeserver);
3195: if ($hostname) {
3196: my $uri = &declutter($url);
3197: my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
3198: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
3199: if ($response->is_success()) {
3200: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3201: my $locmodtime = (stat($fname))[9];
3202: if ($locmodtime < $remmodtime) {
3203: my $stale;
3204: my $answer = &reply('pong',$homeserver);
3205: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3206: sleep(0.2);
3207: $locmodtime = (stat($fname))[9];
3208: if ($locmodtime < $remmodtime) {
3209: my $posstransfer = $fname.'.in.transfer';
3210: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3211: $removed = 1;
3212: } else {
3213: $stale = 1;
3214: }
3215: } else {
3216: $removed = 1;
3217: }
3218: } else {
3219: $stale = 1;
3220: }
3221: if ($stale) {
3222: unlink($fname);
3223: if ($uri!~/\.meta$/) {
3224: unlink($fname.'.meta');
3225: }
3226: &reply("unsub:$fname",$homeserver);
3227: $removed = 1;
3228: }
3229: }
3230: }
3231: }
3232: }
3233: }
3234: }
3235: }
3236: return $removed;
3237: }
3238:
3239: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3240:
3241: sub allowuploaded {
3242: my ($srcurl,$url)=@_;
3243: $url=&clutter(&declutter($url));
3244: my $dir=$url;
3245: $dir=~s/\/[^\/]+$//;
3246: my %httpref=();
3247: my $httpurl=&hreflocation('',$url);
3248: $httpref{'httpref.'.$httpurl}=$srcurl;
3249: &Apache::lonnet::appenv(\%httpref);
3250: }
3251:
3252: #
3253: # Determine if the current user should be able to edit a particular resource,
3254: # when viewing in course context.
3255: # (a) When viewing resource used to determine if "Edit" item is included in
3256: # Functions.
3257: # (b) When displaying folder contents in course editor, used to determine if
3258: # "Edit" link will be displayed alongside resource.
3259: #
3260: # input: six args -- filename (decluttered), course number, course domain,
3261: # url, symb (if registered) and group (if this is a group
3262: # item -- e.g., bulletin board, group page etc.).
3263: # output: array of five scalars --
3264: # $cfile -- url for file editing if editable on current server
3265: # $home -- homeserver of resource (i.e., for author if published,
3266: # or course if uploaded.).
3267: # $switchserver -- 1 if server switch will be needed.
3268: # $forceedit -- 1 if icon/link should be to go to edit mode
3269: # $forceview -- 1 if icon/link should be to go to view mode
3270: #
3271:
3272: sub can_edit_resource {
3273: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3274: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3275: #
3276: # For aboutme pages user can only edit his/her own.
3277: #
3278: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
3279: my ($sdom,$sname) = ($1,$2);
3280: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3281: $home = $env{'user.home'};
3282: $cfile = $resurl;
3283: if ($env{'form.forceedit'}) {
3284: $forceview = 1;
3285: } else {
3286: $forceedit = 1;
3287: }
3288: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3289: } else {
3290: return;
3291: }
3292: }
3293:
3294: if ($env{'request.course.id'}) {
3295: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3296: if ($group ne '') {
3297: # if this is a group homepage or group bulletin board, check group privs
3298: my $allowed = 0;
3299: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3300: if ((&allowed('mdg',$env{'request.course.id'}.
3301: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3302: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3303: $allowed = 1;
3304: }
3305: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3306: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3307: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3308: $allowed = 1;
3309: }
3310: }
3311: if ($allowed) {
3312: $home=&homeserver($cnum,$cdom);
3313: if ($env{'form.forceedit'}) {
3314: $forceview = 1;
3315: } else {
3316: $forceedit = 1;
3317: }
3318: $cfile = $resurl;
3319: } else {
3320: return;
3321: }
3322: } else {
3323: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3324: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3325: return;
3326: }
3327: } elsif (!$crsedit) {
3328: #
3329: # No edit allowed where CC has switched to student role.
3330: #
3331: return;
3332: }
3333: }
3334: }
3335:
3336: if ($file ne '') {
3337: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
3338: if (&is_course_upload($file,$cnum,$cdom)) {
3339: $uploaded = 1;
3340: $incourse = 1;
3341: if ($file =~/\.(htm|html|css|js|txt)$/) {
3342: $cfile = &hreflocation('',$file);
3343: if ($env{'form.forceedit'}) {
3344: $forceview = 1;
3345: } else {
3346: $forceedit = 1;
3347: }
3348: }
3349: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3350: $incourse = 1;
3351: if ($env{'form.forceedit'}) {
3352: $forceview = 1;
3353: } else {
3354: $forceedit = 1;
3355: }
3356: $cfile = $resurl;
3357: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3358: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3359: $incourse = 1;
3360: if ($env{'form.forceedit'}) {
3361: $forceview = 1;
3362: } else {
3363: $forceedit = 1;
3364: }
3365: $cfile = $resurl;
3366: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
3367: $incourse = 1;
3368: $cfile = $resurl.'/smpedit';
3369: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
3370: $incourse = 1;
3371: if ($env{'form.forceedit'}) {
3372: $forceview = 1;
3373: } else {
3374: $forceedit = 1;
3375: }
3376: $cfile = $resurl;
3377: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
3378: $incourse = 1;
3379: if ($env{'form.forceedit'}) {
3380: $forceview = 1;
3381: } else {
3382: $forceedit = 1;
3383: }
3384: $cfile = $resurl;
3385: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3386: $incourse = 1;
3387: if ($env{'form.forceedit'}) {
3388: $forceview = 1;
3389: } else {
3390: $forceedit = 1;
3391: }
3392: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
3393: }
3394: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3395: my $template = '/res/lib/templates/simpleproblem.problem';
3396: if (&is_on_map($template)) {
3397: $incourse = 1;
3398: $forceview = 1;
3399: $cfile = $template;
3400: }
3401: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3402: $incourse = 1;
3403: if ($env{'form.forceedit'}) {
3404: $forceview = 1;
3405: } else {
3406: $forceedit = 1;
3407: }
3408: $cfile = $resurl;
3409: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3410: $incourse = 1;
3411: if ($env{'form.forceedit'}) {
3412: $forceview = 1;
3413: } else {
3414: $forceedit = 1;
3415: }
3416: $cfile = $resurl;
3417: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3418: $incourse = 1;
3419: $forceview = 1;
3420: if ($symb) {
3421: my ($map,$id,$res)=&decode_symb($symb);
3422: $env{'request.symb'} = $symb;
3423: $cfile = &clutter($res);
3424: } else {
3425: $cfile = $env{'form.suppurl'};
3426: my $escfile = &unescape($cfile);
3427: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
3428: $cfile = '/adm/wrapper'.$escfile;
3429: } else {
3430: $escfile =~ s{^http://}{};
3431: $cfile = &escape("/adm/wrapper/ext/$escfile");
3432: }
3433: }
3434: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3435: if ($env{'form.forceedit'}) {
3436: $forceview = 1;
3437: } else {
3438: $forceedit = 1;
3439: }
3440: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
3441: }
3442: }
3443: if ($uploaded || $incourse) {
3444: $home=&homeserver($cnum,$cdom);
3445: } elsif ($file !~ m{/$}) {
3446: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3447: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3448: # Check that the user has permission to edit this resource
3449: my $setpriv = 1;
3450: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3451: if (defined($cfudom)) {
3452: $home=&homeserver($cfuname,$cfudom);
3453: $cfile=$file;
3454: }
3455: }
3456: if (($cfile ne '') && (!$incourse || $uploaded) &&
3457: (($home ne '') && ($home ne 'no_host'))) {
3458: my @ids=¤t_machine_ids();
3459: unless (grep(/^\Q$home\E$/,@ids)) {
3460: $switchserver=1;
3461: }
3462: }
3463: }
3464: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3465: }
3466:
3467: sub is_course_upload {
3468: my ($file,$cnum,$cdom) = @_;
3469: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3470: $uploadpath =~ s{^\/}{};
3471: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3472: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3473: return 1;
3474: }
3475: return;
3476: }
3477:
3478: sub in_course {
3479: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3480: if ($hideprivileged) {
3481: my $skipuser;
3482: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3483: my @possdoms = ($cdom);
3484: if ($coursehash{'checkforpriv'}) {
3485: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3486: }
3487: if (&privileged($uname,$udom,\@possdoms)) {
3488: $skipuser = 1;
3489: if ($coursehash{'nothideprivileged'}) {
3490: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3491: my $user;
3492: if ($item =~ /:/) {
3493: $user = $item;
3494: } else {
3495: $user = join(':',split(/[\@]/,$item));
3496: }
3497: if ($user eq $uname.':'.$udom) {
3498: undef($skipuser);
3499: last;
3500: }
3501: }
3502: }
3503: if ($skipuser) {
3504: return 0;
3505: }
3506: }
3507: }
3508: $type ||= 'any';
3509: if (!defined($cdom) || !defined($cnum)) {
3510: my $cid = $env{'request.course.id'};
3511: $cdom = $env{'course.'.$cid.'.domain'};
3512: $cnum = $env{'course.'.$cid.'.num'};
3513: }
3514: my $typesref;
3515: if (($type eq 'any') || ($type eq 'all')) {
3516: $typesref = ['active','previous','future'];
3517: } elsif ($type eq 'previous' || $type eq 'future') {
3518: $typesref = [$type];
3519: }
3520: my %roles = &get_my_roles($uname,$udom,'userroles',
3521: $typesref,undef,[$cdom]);
3522: my ($tmp) = keys(%roles);
3523: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3524: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3525: if (@course_roles > 0) {
3526: return 1;
3527: }
3528: return 0;
3529: }
3530:
3531: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
3532: # input: action, courseID, current domain, intended
3533: # path to file, source of file, instruction to parse file for objects,
3534: # ref to hash for embedded objects,
3535: # ref to hash for codebase of java objects.
3536: # reference to scalar to accommodate mime type determined
3537: # from File::MMagic if $parser = parse.
3538: #
3539: # output: url to file (if action was uploaddoc),
3540: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
3541: #
3542: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3543: # course.
3544: #
3545: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3546: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3547: # course's home server.
3548: #
3549: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3550: # be copied from $source (current location) to
3551: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3552: # and will then be copied to
3553: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3554: # course's home server.
3555: #
3556: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3557: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
3558: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3559: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3560: # in course's home server.
3561: #
3562:
3563: sub process_coursefile {
3564: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3565: $mimetype)=@_;
3566: my $fetchresult;
3567: my $home=&homeserver($docuname,$docudom);
3568: if ($action eq 'propagate') {
3569: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3570: $home);
3571: } else {
3572: my $fpath = '';
3573: my $fname = $file;
3574: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3575: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3576: my $filepath = &build_filepath($fpath);
3577: if ($action eq 'copy') {
3578: if ($source eq '') {
3579: $fetchresult = 'no source file';
3580: return $fetchresult;
3581: } else {
3582: my $destination = $filepath.'/'.$fname;
3583: rename($source,$destination);
3584: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3585: $home);
3586: }
3587: } elsif ($action eq 'uploaddoc') {
3588: open(my $fh,'>'.$filepath.'/'.$fname);
3589: print $fh $env{'form.'.$source};
3590: close($fh);
3591: if ($parser eq 'parse') {
3592: my $mm = new File::MMagic;
3593: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3594: if ($type eq 'text/html') {
3595: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3596: unless ($parse_result eq 'ok') {
3597: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3598: }
3599: }
3600: if (ref($mimetype)) {
3601: $$mimetype = $type;
3602: }
3603: }
3604: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3605: $home);
3606: if ($fetchresult eq 'ok') {
3607: return '/uploaded/'.$fpath.'/'.$fname;
3608: } else {
3609: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3610: ' to host '.$home.': '.$fetchresult);
3611: return '/adm/notfound.html';
3612: }
3613: }
3614: }
3615: unless ( $fetchresult eq 'ok') {
3616: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3617: ' to host '.$home.': '.$fetchresult);
3618: }
3619: return $fetchresult;
3620: }
3621:
3622: sub build_filepath {
3623: my ($fpath) = @_;
3624: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3625: unless ($fpath eq '') {
3626: my @parts=split('/',$fpath);
3627: foreach my $part (@parts) {
3628: $filepath.= '/'.$part;
3629: if ((-e $filepath)!=1) {
3630: mkdir($filepath,0777);
3631: }
3632: }
3633: }
3634: return $filepath;
3635: }
3636:
3637: sub store_edited_file {
3638: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
3639: my $file = $primary_url;
3640: $file =~ s#^/uploaded/$docudom/$docuname/##;
3641: my $fpath = '';
3642: my $fname = $file;
3643: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3644: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3645: my $filepath = &build_filepath($fpath);
3646: open(my $fh,'>'.$filepath.'/'.$fname);
3647: print $fh $content;
3648: close($fh);
3649: my $home=&homeserver($docuname,$docudom);
3650: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3651: $home);
3652: if ($$fetchresult eq 'ok') {
3653: return '/uploaded/'.$fpath.'/'.$fname;
3654: } else {
3655: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3656: ' to host '.$home.': '.$$fetchresult);
3657: return '/adm/notfound.html';
3658: }
3659: }
3660:
3661: sub clean_filename {
3662: my ($fname,$args)=@_;
3663: # Replace Windows backslashes by forward slashes
3664: $fname=~s/\\/\//g;
3665: if (!$args->{'keep_path'}) {
3666: # Get rid of everything but the actual filename
3667: $fname=~s/^.*\/([^\/]+)$/$1/;
3668: }
3669: # Replace spaces by underscores
3670: $fname=~s/\s+/\_/g;
3671: # Replace all other weird characters by nothing
3672: $fname=~s{[^/\w\.\-]}{}g;
3673: # Replace all .\d. sequences with _\d. so they no longer look like version
3674: # numbers
3675: $fname=~s/\.(\d+)(?=\.)/_$1/g;
3676: return $fname;
3677: }
3678: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3679: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3680: # image with the same aspect ratio as the original, but with dimensions which do
3681: # not exceed $resizewidth and $resizeheight.
3682:
3683: sub resizeImage {
3684: my ($img_path,$resizewidth,$resizeheight) = @_;
3685: my $ima = Image::Magick->new;
3686: my $resized;
3687: if (-e $img_path) {
3688: $ima->Read($img_path);
3689: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3690: my $width = $ima->Get('width');
3691: my $height = $ima->Get('height');
3692: if ($width > $resizewidth) {
3693: my $factor = $width/$resizewidth;
3694: my $newheight = $height/$factor;
3695: $ima->Scale(width=>$resizewidth,height=>$newheight);
3696: $resized = 1;
3697: }
3698: }
3699: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3700: my $width = $ima->Get('width');
3701: my $height = $ima->Get('height');
3702: if ($height > $resizeheight) {
3703: my $factor = $height/$resizeheight;
3704: my $newwidth = $width/$factor;
3705: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3706: $resized = 1;
3707: }
3708: }
3709: if ($resized) {
3710: $ima->Write($img_path);
3711: }
3712: }
3713: return;
3714: }
3715:
3716: # --------------- Take an uploaded file and put it into the userfiles directory
3717: # input: $formname - the contents of the file are in $env{"form.$formname"}
3718: # the desired filename is in $env{"form.$formname.filename"}
3719: # $context - possible values: coursedoc, existingfile, overwrite,
3720: # canceloverwrite, or ''.
3721: # if 'coursedoc': upload to the current course
3722: # if 'existingfile': write file to tmp/overwrites directory
3723: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3724: # $context is passed as argument to &finishuserfileupload
3725: # $subdir - directory in userfile to store the file into
3726: # $parser - instruction to parse file for objects ($parser = parse)
3727: # $allfiles - reference to hash for embedded objects
3728: # $codebase - reference to hash for codebase of java objects
3729: # $desuname - username for permanent storage of uploaded file
3730: # $dsetudom - domain for permanaent storage of uploaded file
3731: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3732: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
3733: # $resizewidth - width (pixels) to which to resize uploaded image
3734: # $resizeheight - height (pixels) to which to resize uploaded image
3735: # $mimetype - reference to scalar to accommodate mime type determined
3736: # from File::MMagic.
3737: #
3738: # output: url of file in userspace, or error: <message>
3739: # or /adm/notfound.html if failure to upload occurse
3740:
3741: sub userfileupload {
3742: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
3743: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
3744: if (!defined($subdir)) { $subdir='unknown'; }
3745: my $fname=$env{'form.'.$formname.'.filename'};
3746: $fname=&clean_filename($fname);
3747: # See if there is anything left
3748: unless ($fname) { return 'error: no uploaded file'; }
3749: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3750: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3751: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3752: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3753: my $now = time;
3754: my $filepath;
3755: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
3756: $filepath = 'tmp/helprequests/'.$now;
3757: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3758: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3759: '_'.$env{'user.domain'}.'/pending';
3760: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3761: my ($docuname,$docudom);
3762: if ($destudom =~ /^$match_domain$/) {
3763: $docudom = $destudom;
3764: } else {
3765: $docudom = $env{'user.domain'};
3766: }
3767: if ($destuname =~ /^$match_username$/) {
3768: $docuname = $destuname;
3769: } else {
3770: $docuname = $env{'user.name'};
3771: }
3772: if (exists($env{'form.group'})) {
3773: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3774: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3775: }
3776: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3777: if ($context eq 'canceloverwrite') {
3778: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3779: if (-e $tempfile) {
3780: my @info = stat($tempfile);
3781: if ($info[9] eq $env{'form.timestamp'}) {
3782: unlink($tempfile);
3783: }
3784: }
3785: return;
3786: }
3787: }
3788: # Create the directory if not present
3789: my @parts=split(/\//,$filepath);
3790: my $fullpath = $perlvar{'lonDaemons'};
3791: for (my $i=0;$i<@parts;$i++) {
3792: $fullpath .= '/'.$parts[$i];
3793: if ((-e $fullpath)!=1) {
3794: mkdir($fullpath,0777);
3795: }
3796: }
3797: open(my $fh,'>'.$fullpath.'/'.$fname);
3798: print $fh $env{'form.'.$formname};
3799: close($fh);
3800: if ($context eq 'existingfile') {
3801: my @info = stat($fullpath.'/'.$fname);
3802: return ($fullpath.'/'.$fname,$info[9]);
3803: } else {
3804: return $fullpath.'/'.$fname;
3805: }
3806: }
3807: if ($subdir eq 'scantron') {
3808: $fname = 'scantron_orig_'.$fname;
3809: } else {
3810: $fname="$subdir/$fname";
3811: }
3812: if ($context eq 'coursedoc') {
3813: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3814: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3815: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
3816: return &finishuserfileupload($docuname,$docudom,
3817: $formname,$fname,$parser,$allfiles,
3818: $codebase,$thumbwidth,$thumbheight,
3819: $resizewidth,$resizeheight,$context,$mimetype);
3820: } else {
3821: if ($env{'form.folder'}) {
3822: $fname=$env{'form.folder'}.'/'.$fname;
3823: }
3824: return &process_coursefile('uploaddoc',$docuname,$docudom,
3825: $fname,$formname,$parser,
3826: $allfiles,$codebase,$mimetype);
3827: }
3828: } elsif (defined($destuname)) {
3829: my $docuname=$destuname;
3830: my $docudom=$destudom;
3831: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3832: $parser,$allfiles,$codebase,
3833: $thumbwidth,$thumbheight,
3834: $resizewidth,$resizeheight,$context,$mimetype);
3835: } else {
3836: my $docuname=$env{'user.name'};
3837: my $docudom=$env{'user.domain'};
3838: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
3839: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3840: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3841: }
3842: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3843: $parser,$allfiles,$codebase,
3844: $thumbwidth,$thumbheight,
3845: $resizewidth,$resizeheight,$context,$mimetype);
3846: }
3847: }
3848:
3849: sub finishuserfileupload {
3850: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
3851: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
3852: my $path=$docudom.'/'.$docuname.'/';
3853: my $filepath=$perlvar{'lonDocRoot'};
3854:
3855: my ($fnamepath,$file,$fetchthumb);
3856: $file=$fname;
3857: if ($fname=~m|/|) {
3858: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3859: $path.=$fnamepath.'/';
3860: }
3861: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
3862: my $count;
3863: for ($count=4;$count<=$#parts;$count++) {
3864: $filepath.="/$parts[$count]";
3865: if ((-e $filepath)!=1) {
3866: mkdir($filepath,0777);
3867: }
3868: }
3869:
3870: # Save the file
3871: {
3872: if (!open(FH,'>'.$filepath.'/'.$file)) {
3873: &logthis('Failed to create '.$filepath.'/'.$file);
3874: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3875: return '/adm/notfound.html';
3876: }
3877: if ($context eq 'overwrite') {
3878: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
3879: my $target = $filepath.'/'.$file;
3880: if (-e $source) {
3881: my @info = stat($source);
3882: if ($info[9] eq $env{'form.timestamp'}) {
3883: unless (&File::Copy::move($source,$target)) {
3884: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3885: return "Moving from $source failed";
3886: }
3887: } else {
3888: return "Temporary file: $source had unexpected date/time for last modification";
3889: }
3890: } else {
3891: return "Temporary file: $source missing";
3892: }
3893: } elsif (!print FH ($env{'form.'.$formname})) {
3894: &logthis('Failed to write to '.$filepath.'/'.$file);
3895: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3896: return '/adm/notfound.html';
3897: }
3898: close(FH);
3899: if ($resizewidth && $resizeheight) {
3900: my $mm = new File::MMagic;
3901: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3902: if ($mime_type =~ m{^image/}) {
3903: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3904: }
3905: }
3906: }
3907: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3908: if (ref($mimetype)) {
3909: if ($$mimetype eq '') {
3910: my $mm = new File::MMagic;
3911: my $type = $mm->checktype_filename($filepath.'/'.$file);
3912: $$mimetype = $type;
3913: }
3914: }
3915: }
3916: if ($parser eq 'parse') {
3917: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
3918: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3919: $allfiles,$codebase);
3920: unless ($parse_result eq 'ok') {
3921: &logthis('Failed to parse '.$filepath.$file.
3922: ' for embedded media: '.$parse_result);
3923: }
3924: }
3925: }
3926: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3927: my $input = $filepath.'/'.$file;
3928: my $output = $filepath.'/'.'tn-'.$file;
3929: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3930: system("convert -sample $thumbsize $input $output");
3931: if (-e $filepath.'/'.'tn-'.$file) {
3932: $fetchthumb = 1;
3933: }
3934: }
3935:
3936: # Notify homeserver to grep it
3937: #
3938: my $docuhome=&homeserver($docuname,$docudom);
3939: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
3940: if ($fetchresult eq 'ok') {
3941: if ($fetchthumb) {
3942: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3943: if ($thumbresult ne 'ok') {
3944: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3945: $docuhome.': '.$thumbresult);
3946: }
3947: }
3948: #
3949: # Return the URL to it
3950: return '/uploaded/'.$path.$file;
3951: } else {
3952: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3953: ': '.$fetchresult);
3954: return '/adm/notfound.html';
3955: }
3956: }
3957:
3958: sub extract_embedded_items {
3959: my ($fullpath,$allfiles,$codebase,$content) = @_;
3960: my @state = ();
3961: my (%lastids,%related,%shockwave,%flashvars);
3962: my %javafiles = (
3963: codebase => '',
3964: code => '',
3965: archive => ''
3966: );
3967: my %mediafiles = (
3968: src => '',
3969: movie => '',
3970: );
3971: my $p;
3972: if ($content) {
3973: $p = HTML::LCParser->new($content);
3974: } else {
3975: $p = HTML::LCParser->new($fullpath);
3976: }
3977: while (my $t=$p->get_token()) {
3978: if ($t->[0] eq 'S') {
3979: my ($tagname, $attr) = ($t->[1],$t->[2]);
3980: push(@state, $tagname);
3981: if (lc($tagname) eq 'allow') {
3982: &add_filetype($allfiles,$attr->{'src'},'src');
3983: }
3984: if (lc($tagname) eq 'img') {
3985: &add_filetype($allfiles,$attr->{'src'},'src');
3986: }
3987: if (lc($tagname) eq 'a') {
3988: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3989: &add_filetype($allfiles,$attr->{'href'},'href');
3990: }
3991: }
3992: if (lc($tagname) eq 'script') {
3993: my $src;
3994: if ($attr->{'archive'} =~ /\.jar$/i) {
3995: &add_filetype($allfiles,$attr->{'archive'},'archive');
3996: } else {
3997: if ($attr->{'src'} ne '') {
3998: $src = $attr->{'src'};
3999: &add_filetype($allfiles,$src,'src');
4000: }
4001: }
4002: my $text = $p->get_trimmed_text();
4003: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4004: my @swfargs = split(/,/,$1);
4005: foreach my $item (@swfargs) {
4006: $item =~ s/["']//g;
4007: $item =~ s/^\s+//;
4008: $item =~ s/\s+$//;
4009: }
4010: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4011: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4012: push(@{$related{$swfargs[0]}},$swfargs[2]);
4013: } else {
4014: $related{$swfargs[0]} = [$swfargs[2]];
4015: }
4016: }
4017: }
4018: }
4019: if (lc($tagname) eq 'link') {
4020: if (lc($attr->{'rel'}) eq 'stylesheet') {
4021: &add_filetype($allfiles,$attr->{'href'},'href');
4022: }
4023: }
4024: if (lc($tagname) eq 'object' ||
4025: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4026: foreach my $item (keys(%javafiles)) {
4027: $javafiles{$item} = '';
4028: }
4029: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4030: $lastids{lc($tagname)} = $attr->{'id'};
4031: }
4032: }
4033: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4034: my $name = lc($attr->{'name'});
4035: foreach my $item (keys(%javafiles)) {
4036: if ($name eq $item) {
4037: $javafiles{$item} = $attr->{'value'};
4038: last;
4039: }
4040: }
4041: my $pathfrom;
4042: foreach my $item (keys(%mediafiles)) {
4043: if ($name eq $item) {
4044: $pathfrom = $attr->{'value'};
4045: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4046: &add_filetype($allfiles,$pathfrom,$name);
4047: last;
4048: }
4049: }
4050: if ($name eq 'flashvars') {
4051: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4052: }
4053: if ($pathfrom ne '') {
4054: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4055: $pathfrom);
4056: }
4057: }
4058: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4059: foreach my $item (keys(%javafiles)) {
4060: if ($attr->{$item}) {
4061: $javafiles{$item} = $attr->{$item};
4062: last;
4063: }
4064: }
4065: foreach my $item (keys(%mediafiles)) {
4066: if ($attr->{$item}) {
4067: &add_filetype($allfiles,$attr->{$item},$item);
4068: last;
4069: }
4070: }
4071: if (lc($tagname) eq 'embed') {
4072: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4073: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4074: $attr->{'src'});
4075: }
4076: }
4077: }
4078: if (lc($tagname) eq 'iframe') {
4079: my $src = $attr->{'src'} ;
4080: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4081: &add_filetype($allfiles,$src,'src');
4082: } elsif ($src =~ m{^/}) {
4083: if ($env{'request.course.id'}) {
4084: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4085: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4086: my $url = &hreflocation('',$fullpath);
4087: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4088: my $relpath = $1;
4089: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4090: &add_filetype($allfiles,$1,'src');
4091: }
4092: }
4093: }
4094: }
4095: }
4096: if ($t->[4] =~ m{/>$}) {
4097: pop(@state);
4098: }
4099: } elsif ($t->[0] eq 'E') {
4100: my ($tagname) = ($t->[1]);
4101: if ($javafiles{'codebase'} ne '') {
4102: $javafiles{'codebase'} .= '/';
4103: }
4104: if (lc($tagname) eq 'applet' ||
4105: lc($tagname) eq 'object' ||
4106: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4107: ) {
4108: foreach my $item (keys(%javafiles)) {
4109: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4110: my $file=$javafiles{'codebase'}.$javafiles{$item};
4111: &add_filetype($allfiles,$file,$item);
4112: }
4113: }
4114: }
4115: pop @state;
4116: }
4117: }
4118: foreach my $id (sort(keys(%flashvars))) {
4119: if ($shockwave{$id} ne '') {
4120: my @pairs = split(/\&/,$flashvars{$id});
4121: foreach my $pair (@pairs) {
4122: my ($key,$value) = split(/\=/,$pair);
4123: if ($key eq 'thumb') {
4124: &add_filetype($allfiles,$value,$key);
4125: } elsif ($key eq 'content') {
4126: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4127: my ($ext) = ($value =~ /\.([^.]+)$/);
4128: if ($ext ne '') {
4129: &add_filetype($allfiles,$path.$value,$ext);
4130: }
4131: }
4132: }
4133: }
4134: }
4135: return 'ok';
4136: }
4137:
4138: sub add_filetype {
4139: my ($allfiles,$file,$type)=@_;
4140: if (exists($allfiles->{$file})) {
4141: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4142: push(@{$allfiles->{$file}}, &escape($type));
4143: }
4144: } else {
4145: @{$allfiles->{$file}} = (&escape($type));
4146: }
4147: }
4148:
4149: sub embedded_dependency {
4150: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4151: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4152: if (($identifier ne '') &&
4153: (ref($related->{$identifier}) eq 'ARRAY') &&
4154: ($pathfrom ne '')) {
4155: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4156: foreach my $dep (@{$related->{$identifier}}) {
4157: &add_filetype($allfiles,$path.$dep,'object');
4158: }
4159: }
4160: }
4161: return;
4162: }
4163:
4164: sub removeuploadedurl {
4165: my ($url)=@_;
4166: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
4167: return &removeuserfile($uname,$udom,$fname);
4168: }
4169:
4170: sub removeuserfile {
4171: my ($docuname,$docudom,$fname)=@_;
4172: my $home=&homeserver($docuname,$docudom);
4173: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
4174: if ($result eq 'ok') {
4175: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4176: my $metafile = $fname.'.meta';
4177: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
4178: my $url = "/uploaded/$docudom/$docuname/$fname";
4179: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
4180: my $sqlresult =
4181: &update_portfolio_table($docuname,$docudom,$file,
4182: 'portfolio_metadata',$group,
4183: 'delete');
4184: }
4185: }
4186: return $result;
4187: }
4188:
4189: sub mkdiruserfile {
4190: my ($docuname,$docudom,$dir)=@_;
4191: my $home=&homeserver($docuname,$docudom);
4192: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4193: }
4194:
4195: sub renameuserfile {
4196: my ($docuname,$docudom,$old,$new)=@_;
4197: my $home=&homeserver($docuname,$docudom);
4198: my $result = &reply("renameuserfile:$docudom:$docuname:".
4199: &escape("$old").':'.&escape("$new"),$home);
4200: if ($result eq 'ok') {
4201: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4202: my $oldmeta = $old.'.meta';
4203: my $newmeta = $new.'.meta';
4204: my $metaresult =
4205: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
4206: my $url = "/uploaded/$docudom/$docuname/$old";
4207: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
4208: my $sqlresult =
4209: &update_portfolio_table($docuname,$docudom,$file,
4210: 'portfolio_metadata',$group,
4211: 'delete');
4212: }
4213: }
4214: return $result;
4215: }
4216:
4217: # ------------------------------------------------------------------------- Log
4218:
4219: sub log {
4220: my ($dom,$nam,$hom,$what)=@_;
4221: return critical("log:$dom:$nam:$what",$hom);
4222: }
4223:
4224: # ------------------------------------------------------------------ Course Log
4225: #
4226: # This routine flushes several buffers of non-mission-critical nature
4227: #
4228:
4229: sub flushcourselogs {
4230: &logthis('Flushing log buffers');
4231: #
4232: # course logs
4233: # This is a log of all transactions in a course, which can be used
4234: # for data mining purposes
4235: #
4236: # It also collects the courseid database, which lists last transaction
4237: # times and course titles for all courseids
4238: #
4239: my %courseidbuffer=();
4240: foreach my $crsid (keys(%courselogs)) {
4241: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
4242: &escape($courselogs{$crsid}),
4243: $coursehombuf{$crsid}) eq 'ok') {
4244: delete $courselogs{$crsid};
4245: } else {
4246: &logthis('Failed to flush log buffer for '.$crsid);
4247: if (length($courselogs{$crsid})>40000) {
4248: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
4249: " exceeded maximum size, deleting.</font>");
4250: delete $courselogs{$crsid};
4251: }
4252: }
4253: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
4254: 'description' => $coursedescrbuf{$crsid},
4255: 'inst_code' => $courseinstcodebuf{$crsid},
4256: 'type' => $coursetypebuf{$crsid},
4257: 'owner' => $courseownerbuf{$crsid},
4258: };
4259: }
4260: #
4261: # Write course id database (reverse lookup) to homeserver of courses
4262: # Is used in pickcourse
4263: #
4264: foreach my $crs_home (keys(%courseidbuffer)) {
4265: my $response = &courseidput(&host_domain($crs_home),
4266: $courseidbuffer{$crs_home},
4267: $crs_home,'timeonly');
4268: }
4269: #
4270: # File accesses
4271: # Writes to the dynamic metadata of resources to get hit counts, etc.
4272: #
4273: foreach my $entry (keys(%accesshash)) {
4274: if ($entry =~ /___count$/) {
4275: my ($dom,$name);
4276: ($dom,$name,undef)=
4277: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
4278: if (! defined($dom) || $dom eq '' ||
4279: ! defined($name) || $name eq '') {
4280: my $cid = $env{'request.course.id'};
4281: $dom = $env{'request.'.$cid.'.domain'};
4282: $name = $env{'request.'.$cid.'.num'};
4283: }
4284: my $value = $accesshash{$entry};
4285: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4286: my %temphash=($url => $value);
4287: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4288: if ($result eq 'ok') {
4289: delete $accesshash{$entry};
4290: }
4291: } else {
4292: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
4293: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
4294: my %temphash=($entry => $accesshash{$entry});
4295: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4296: delete $accesshash{$entry};
4297: }
4298: }
4299: }
4300: #
4301: # Roles
4302: # Reverse lookup of user roles for course faculty/staff and co-authorship
4303: #
4304: foreach my $entry (keys(%userrolehash)) {
4305: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
4306: split(/\:/,$entry);
4307: if (&Apache::lonnet::put('nohist_userroles',
4308: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
4309: $rudom,$runame) eq 'ok') {
4310: delete $userrolehash{$entry};
4311: }
4312: }
4313: #
4314: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
4315: #
4316: my %domrolebuffer = ();
4317: foreach my $entry (keys(%domainrolehash)) {
4318: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
4319: if ($domrolebuffer{$rudom}) {
4320: $domrolebuffer{$rudom}.='&'.&escape($entry).
4321: '='.&escape($domainrolehash{$entry});
4322: } else {
4323: $domrolebuffer{$rudom}.=&escape($entry).
4324: '='.&escape($domainrolehash{$entry});
4325: }
4326: delete $domainrolehash{$entry};
4327: }
4328: foreach my $dom (keys(%domrolebuffer)) {
4329: my %servers;
4330: if (defined(&domain($dom,'primary'))) {
4331: my $primary=&domain($dom,'primary');
4332: my $hostname=&hostname($primary);
4333: $servers{$primary} = $hostname;
4334: } else {
4335: %servers = &get_servers($dom,'library');
4336: }
4337: foreach my $tryserver (keys(%servers)) {
4338: if (&reply('domroleput:'.$dom.':'.
4339: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4340: last;
4341: } else {
4342: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4343: }
4344: }
4345: }
4346: $dumpcount++;
4347: }
4348:
4349: sub courselog {
4350: my $what=shift;
4351: $what=time.':'.$what;
4352: unless ($env{'request.course.id'}) { return ''; }
4353: $coursedombuf{$env{'request.course.id'}}=
4354: $env{'course.'.$env{'request.course.id'}.'.domain'};
4355: $coursenumbuf{$env{'request.course.id'}}=
4356: $env{'course.'.$env{'request.course.id'}.'.num'};
4357: $coursehombuf{$env{'request.course.id'}}=
4358: $env{'course.'.$env{'request.course.id'}.'.home'};
4359: $coursedescrbuf{$env{'request.course.id'}}=
4360: $env{'course.'.$env{'request.course.id'}.'.description'};
4361: $courseinstcodebuf{$env{'request.course.id'}}=
4362: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4363: $courseownerbuf{$env{'request.course.id'}}=
4364: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
4365: $coursetypebuf{$env{'request.course.id'}}=
4366: $env{'course.'.$env{'request.course.id'}.'.type'};
4367: if (defined $courselogs{$env{'request.course.id'}}) {
4368: $courselogs{$env{'request.course.id'}}.='&'.$what;
4369: } else {
4370: $courselogs{$env{'request.course.id'}}.=$what;
4371: }
4372: if (length($courselogs{$env{'request.course.id'}})>4048) {
4373: &flushcourselogs();
4374: }
4375: }
4376:
4377: sub courseacclog {
4378: my $fnsymb=shift;
4379: unless ($env{'request.course.id'}) { return ''; }
4380: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
4381: if ($fnsymb=~/$LONCAPA::assess_re/) {
4382: $what.=':POST';
4383: # FIXME: Probably ought to escape things....
4384: foreach my $key (keys(%env)) {
4385: if ($key=~/^form\.(.*)/) {
4386: my $formitem = $1;
4387: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4388: $what.=':'.$formitem.'='.$env{$key};
4389: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
4390: $what.=':'.$formitem.'='.$env{$key};
4391: }
4392: }
4393: }
4394: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4395: # FIXME: We should not be depending on a form parameter that someone
4396: # editing lonsearchcat.pm might change in the future.
4397: if ($env{'form.phase'} eq 'course_search') {
4398: $what.= ':POST';
4399: # FIXME: Probably ought to escape things....
4400: foreach my $element ('courseexp','crsfulltext','crsrelated',
4401: 'crsdiscuss') {
4402: $what.=':'.$element.'='.$env{'form.'.$element};
4403: }
4404: }
4405: }
4406: &courselog($what);
4407: }
4408:
4409: sub countacc {
4410: my $url=&declutter(shift);
4411: return if (! defined($url) || $url eq '');
4412: unless ($env{'request.course.id'}) { return ''; }
4413: #
4414: # Mark that this url was used in this course
4415: #
4416: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
4417: #
4418: # Increase the access count for this resource in this child process
4419: #
4420: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
4421: $accesshash{$key}++;
4422: }
4423:
4424: sub linklog {
4425: my ($from,$to)=@_;
4426: $from=&declutter($from);
4427: $to=&declutter($to);
4428: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4429: $accesshash{$to.'___'.$from.'___goto'}=1;
4430: }
4431:
4432: sub statslog {
4433: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4434: if ($users<2) { return; }
4435: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4436: 'course' => $env{'request.course.id'},
4437: 'sections' => '"all"',
4438: 'num_students' => $users,
4439: 'part' => $part,
4440: 'symb' => $symb,
4441: 'mean_tries' => $av_attempts,
4442: 'deg_of_diff' => $degdiff});
4443: foreach my $key (keys(%dynstore)) {
4444: $accesshash{$key}=$dynstore{$key};
4445: }
4446: }
4447:
4448: sub userrolelog {
4449: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
4450: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
4451: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4452: $userrolehash
4453: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4454: =$tend.':'.$tstart;
4455: }
4456: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
4457: $userrolehash
4458: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4459: =$tend.':'.$tstart;
4460: }
4461: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
4462: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4463: $domainrolehash
4464: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4465: = $tend.':'.$tstart;
4466: }
4467: }
4468:
4469: sub courserolelog {
4470: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
4471: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4472: my $cdom = $1;
4473: my $cnum = $2;
4474: my $sec = $3;
4475: my $namespace = 'rolelog';
4476: my %storehash = (
4477: role => $trole,
4478: start => $tstart,
4479: end => $tend,
4480: selfenroll => $selfenroll,
4481: context => $context,
4482: );
4483: if ($trole eq 'gr') {
4484: $namespace = 'groupslog';
4485: $storehash{'group'} = $sec;
4486: } else {
4487: $storehash{'section'} = $sec;
4488: }
4489: &write_log('course',$namespace,\%storehash,$delflag,$username,
4490: $domain,$cnum,$cdom);
4491: if (($trole ne 'st') || ($sec ne '')) {
4492: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
4493: }
4494: }
4495: return;
4496: }
4497:
4498: sub domainrolelog {
4499: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4500: if ($area =~ m{^/($match_domain)/$}) {
4501: my $cdom = $1;
4502: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4503: my $namespace = 'rolelog';
4504: my %storehash = (
4505: role => $trole,
4506: start => $tstart,
4507: end => $tend,
4508: context => $context,
4509: );
4510: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4511: $domain,$domconfiguser,$cdom);
4512: }
4513: return;
4514:
4515: }
4516:
4517: sub coauthorrolelog {
4518: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4519: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4520: my $audom = $1;
4521: my $auname = $2;
4522: my $namespace = 'rolelog';
4523: my %storehash = (
4524: role => $trole,
4525: start => $tstart,
4526: end => $tend,
4527: context => $context,
4528: );
4529: &write_log('author',$namespace,\%storehash,$delflag,$username,
4530: $domain,$auname,$audom);
4531: }
4532: return;
4533: }
4534:
4535: sub get_course_adv_roles {
4536: my ($cid,$codes) = @_;
4537: $cid=$env{'request.course.id'} unless (defined($cid));
4538: my %coursehash=&coursedescription($cid);
4539: my $crstype = &Apache::loncommon::course_type($cid);
4540: my %nothide=();
4541: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4542: if ($user !~ /:/) {
4543: $nothide{join(':',split(/[\@]/,$user))}=1;
4544: } else {
4545: $nothide{$user}=1;
4546: }
4547: }
4548: my @possdoms = ($coursehash{'domain'});
4549: if ($coursehash{'checkforpriv'}) {
4550: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4551: }
4552: my %returnhash=();
4553: my %dumphash=
4554: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4555: my $now=time;
4556: my %privileged;
4557: foreach my $entry (keys(%dumphash)) {
4558: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4559: if (($tstart) && ($tstart<0)) { next; }
4560: if (($tend) && ($tend<$now)) { next; }
4561: if (($tstart) && ($now<$tstart)) { next; }
4562: my ($role,$username,$domain,$section)=split(/\:/,$entry);
4563: if ($username eq '' || $domain eq '') { next; }
4564: if ((&privileged($username,$domain,\@possdoms)) &&
4565: (!$nothide{$username.':'.$domain})) { next; }
4566: if ($role eq 'cr') { next; }
4567: if ($codes) {
4568: if ($section) { $role .= ':'.$section; }
4569: if ($returnhash{$role}) {
4570: $returnhash{$role}.=','.$username.':'.$domain;
4571: } else {
4572: $returnhash{$role}=$username.':'.$domain;
4573: }
4574: } else {
4575: my $key=&plaintext($role,$crstype);
4576: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
4577: if ($returnhash{$key}) {
4578: $returnhash{$key}.=','.$username.':'.$domain;
4579: } else {
4580: $returnhash{$key}=$username.':'.$domain;
4581: }
4582: }
4583: }
4584: return %returnhash;
4585: }
4586:
4587: sub get_my_roles {
4588: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
4589: unless (defined($uname)) { $uname=$env{'user.name'}; }
4590: unless (defined($udom)) { $udom=$env{'user.domain'}; }
4591: my (%dumphash,%nothide);
4592: if ($context eq 'userroles') {
4593: %dumphash = &dump('roles',$udom,$uname);
4594: } else {
4595: %dumphash = &dump('nohist_userroles',$udom,$uname);
4596: if ($hidepriv) {
4597: my %coursehash=&coursedescription($udom.'_'.$uname);
4598: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4599: if ($user !~ /:/) {
4600: $nothide{join(':',split(/[\@]/,$user))} = 1;
4601: } else {
4602: $nothide{$user} = 1;
4603: }
4604: }
4605: }
4606: }
4607: my %returnhash=();
4608: my $now=time;
4609: my %privileged;
4610: foreach my $entry (keys(%dumphash)) {
4611: my ($role,$tend,$tstart);
4612: if ($context eq 'userroles') {
4613: next if ($entry =~ /^rolesdef/);
4614: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4615: } else {
4616: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4617: }
4618: if (($tstart) && ($tstart<0)) { next; }
4619: my $status = 'active';
4620: if (($tend) && ($tend<=$now)) {
4621: $status = 'previous';
4622: }
4623: if (($tstart) && ($now<$tstart)) {
4624: $status = 'future';
4625: }
4626: if (ref($types) eq 'ARRAY') {
4627: if (!grep(/^\Q$status\E$/,@{$types})) {
4628: next;
4629: }
4630: } else {
4631: if ($status ne 'active') {
4632: next;
4633: }
4634: }
4635: my ($rolecode,$username,$domain,$section,$area);
4636: if ($context eq 'userroles') {
4637: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
4638: (undef,$domain,$username,$section) = split(/\//,$area);
4639: } else {
4640: ($role,$username,$domain,$section) = split(/\:/,$entry);
4641: }
4642: if (ref($roledoms) eq 'ARRAY') {
4643: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4644: next;
4645: }
4646: }
4647: if (ref($roles) eq 'ARRAY') {
4648: if (!grep(/^\Q$role\E$/,@{$roles})) {
4649: if ($role =~ /^cr\//) {
4650: if (!grep(/^cr$/,@{$roles})) {
4651: next;
4652: }
4653: } elsif ($role =~ /^gr\//) {
4654: if (!grep(/^gr$/,@{$roles})) {
4655: next;
4656: }
4657: } else {
4658: next;
4659: }
4660: }
4661: }
4662: if ($hidepriv) {
4663: my @privroles = ('dc','su');
4664: if ($context eq 'userroles') {
4665: next if (grep(/^\Q$role\E$/,@privroles));
4666: } else {
4667: my $possdoms = [$domain];
4668: if (ref($roledoms) eq 'ARRAY') {
4669: push(@{$possdoms},@{$roledoms});
4670: }
4671: if (&privileged($username,$domain,$possdoms,\@privroles)) {
4672: if (!$nothide{$username.':'.$domain}) {
4673: next;
4674: }
4675: }
4676: }
4677: }
4678: if ($withsec) {
4679: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4680: $tstart.':'.$tend;
4681: } else {
4682: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4683: }
4684: }
4685: return %returnhash;
4686: }
4687:
4688: sub get_all_adhocroles {
4689: my ($dom) = @_;
4690: my @roles_by_num = ();
4691: my %domdefaults = &get_domain_defaults($dom);
4692: my (%description,%access_in_dom,%access_info);
4693: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
4694: my $count = 0;
4695: my %domcurrent = %{$domdefaults{'adhocroles'}};
4696: my %ordered;
4697: foreach my $role (sort(keys(%domcurrent))) {
4698: my ($order,$desc,$access_in_dom);
4699: if (ref($domcurrent{$role}) eq 'HASH') {
4700: $order = $domcurrent{$role}{'order'};
4701: $desc = $domcurrent{$role}{'desc'};
4702: $access_in_dom{$role} = $domcurrent{$role}{'access'};
4703: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
4704: }
4705: if ($order eq '') {
4706: $order = $count;
4707: }
4708: $ordered{$order} = $role;
4709: if ($desc ne '') {
4710: $description{$role} = $desc;
4711: } else {
4712: $description{$role}= $role;
4713: }
4714: $count++;
4715: }
4716: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
4717: push(@roles_by_num,$ordered{$item});
4718: }
4719: }
4720: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
4721: }
4722:
4723: sub get_my_adhocroles {
4724: my ($cid,$checkreg) = @_;
4725: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
4726: if ($env{'request.course.id'} eq $cid) {
4727: $cdom = $env{'course.'.$cid.'.domain'};
4728: $cnum = $env{'course.'.$cid.'.num'};
4729: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
4730: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
4731: $cdom = $1;
4732: $cnum = $2;
4733: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
4734: $cdom,$cnum);
4735: }
4736: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
4737: my $user = $env{'user.name'}.':'.$env{'user.domain'};
4738: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
4739: if ($rosterhash{$user} ne '') {
4740: my $type = (split(/:/,$rosterhash{$user}))[5];
4741: return ([],{}) if ($type eq 'auto');
4742: }
4743: }
4744: if (($cdom ne '') && ($cnum ne '')) {
4745: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
4746: my $then=$env{'user.login.time'};
4747: my $update=$env{'user.update.time'};
4748: if (!$update) {
4749: $update = $then;
4750: }
4751: my @liveroles;
4752: foreach my $role ('dh','da') {
4753: if ($env{"user.role.$role./$cdom/"}) {
4754: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
4755: my $limit = $update;
4756: if ($env{'request.role'} eq "$role./$cdom/") {
4757: $limit = $then;
4758: }
4759: my $activerole = 1;
4760: if ($tstart && $tstart>$limit) { $activerole = 0; }
4761: if ($tend && $tend <$limit) { $activerole = 0; }
4762: if ($activerole) {
4763: push(@liveroles,$role);
4764: }
4765: }
4766: }
4767: if (@liveroles) {
4768: if (&homeserver($cnum,$cdom) ne 'no_host') {
4769: my ($accessref,$accessinfo,%access_in_dom);
4770: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
4771: if (ref($roles_by_num) eq 'ARRAY') {
4772: if (@{$roles_by_num}) {
4773: my %settings;
4774: if ($env{'request.course.id'} eq $cid) {
4775: foreach my $envkey (keys(%env)) {
4776: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
4777: $settings{$1} = $env{$envkey};
4778: }
4779: }
4780: } else {
4781: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
4782: }
4783: my %setincrs;
4784: if ($settings{'internal.adhocaccess'}) {
4785: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
4786: }
4787: my @statuses;
4788: if ($env{'environment.inststatus'}) {
4789: @statuses = split(/,/,$env{'environment.inststatus'});
4790: }
4791: my $user = $env{'user.name'}.':'.$env{'user.domain'};
4792: if (ref($accessref) eq 'HASH') {
4793: %access_in_dom = %{$accessref};
4794: }
4795: foreach my $role (@{$roles_by_num}) {
4796: my ($curraccess,@okstatus,@personnel);
4797: if ($setincrs{$role}) {
4798: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
4799: if ($curraccess eq 'status') {
4800: @okstatus = split(/\&/,$rest);
4801: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4802: @personnel = split(/\&/,$rest);
4803: }
4804: } else {
4805: $curraccess = $access_in_dom{$role};
4806: if (ref($accessinfo) eq 'HASH') {
4807: if ($curraccess eq 'status') {
4808: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4809: @okstatus = @{$accessinfo->{$role}};
4810: }
4811: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4812: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4813: @personnel = @{$accessinfo->{$role}};
4814: }
4815: }
4816: }
4817: }
4818: if ($curraccess eq 'none') {
4819: next;
4820: } elsif ($curraccess eq 'all') {
4821: push(@possroles,$role);
4822: } elsif ($curraccess eq 'dh') {
4823: if (grep(/^dh$/,@liveroles)) {
4824: push(@possroles,$role);
4825: } else {
4826: next;
4827: }
4828: } elsif ($curraccess eq 'da') {
4829: if (grep(/^da$/,@liveroles)) {
4830: push(@possroles,$role);
4831: } else {
4832: next;
4833: }
4834: } elsif ($curraccess eq 'status') {
4835: if (@okstatus) {
4836: if (!@statuses) {
4837: if (grep(/^default$/,@okstatus)) {
4838: push(@possroles,$role);
4839: }
4840: } else {
4841: foreach my $status (@okstatus) {
4842: if (grep(/^\Q$status\E$/,@statuses)) {
4843: push(@possroles,$role);
4844: last;
4845: }
4846: }
4847: }
4848: }
4849: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4850: if (grep(/^\Q$user\E$/,@personnel)) {
4851: if ($curraccess eq 'exc') {
4852: push(@possroles,$role);
4853: }
4854: } elsif ($curraccess eq 'inc') {
4855: push(@possroles,$role);
4856: }
4857: }
4858: }
4859: }
4860: }
4861: }
4862: }
4863: }
4864: }
4865: unless (ref($description) eq 'HASH') {
4866: if (ref($roles_by_num) eq 'ARRAY') {
4867: my %desc;
4868: map { $desc{$_} = $_; } (@{$roles_by_num});
4869: $description = \%desc;
4870: } else {
4871: $description = {};
4872: }
4873: }
4874: return (\@possroles,$description);
4875: }
4876:
4877: # ----------------------------------------------------- Frontpage Announcements
4878: #
4879: #
4880:
4881: sub postannounce {
4882: my ($server,$text)=@_;
4883: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
4884: unless ($text=~/\w/) { $text=''; }
4885: return &reply('setannounce:'.&escape($text),$server);
4886: }
4887:
4888: sub getannounce {
4889:
4890: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
4891: my $announcement='';
4892: while (my $line = <$fh>) { $announcement .= $line; }
4893: close($fh);
4894: if ($announcement=~/\w/) {
4895: return
4896: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
4897: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
4898: } else {
4899: return '';
4900: }
4901: } else {
4902: return '';
4903: }
4904: }
4905:
4906: # ---------------------------------------------------------- Course ID routines
4907: # Deal with domain's nohist_courseid.db files
4908: #
4909:
4910: sub courseidput {
4911: my ($domain,$storehash,$coursehome,$caller) = @_;
4912: return unless (ref($storehash) eq 'HASH');
4913: my $outcome;
4914: if ($caller eq 'timeonly') {
4915: my $cids = '';
4916: foreach my $item (keys(%$storehash)) {
4917: $cids.=&escape($item).'&';
4918: }
4919: $cids=~s/\&$//;
4920: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4921: $coursehome);
4922: } else {
4923: my $items = '';
4924: foreach my $item (keys(%$storehash)) {
4925: $items.= &escape($item).'='.
4926: &freeze_escape($$storehash{$item}).'&';
4927: }
4928: $items=~s/\&$//;
4929: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4930: $coursehome);
4931: }
4932: if ($outcome eq 'unknown_cmd') {
4933: my $what;
4934: foreach my $cid (keys(%$storehash)) {
4935: $what .= &escape($cid).'=';
4936: foreach my $item ('description','inst_code','owner','type') {
4937: $what .= &escape($storehash->{$cid}{$item}).':';
4938: }
4939: $what =~ s/\:$/&/;
4940: }
4941: $what =~ s/\&$//;
4942: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4943: } else {
4944: return $outcome;
4945: }
4946: }
4947:
4948: sub courseiddump {
4949: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
4950: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
4951: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
4952: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
4953: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
4954: my $as_hash = 1;
4955: my %returnhash;
4956: if (!$domfilter) { $domfilter=''; }
4957: my %libserv = &all_library();
4958: foreach my $tryserver (keys(%libserv)) {
4959: if ( ( $hostidflag == 1
4960: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4961: || (!defined($hostidflag)) ) {
4962:
4963: if (($domfilter eq '') ||
4964: (&host_domain($tryserver) eq $domfilter)) {
4965: my $rep;
4966: if (grep { $_ eq $tryserver } current_machine_ids()) {
4967: $rep = LONCAPA::Lond::dump_course_id_handler(
4968: join(":", (&host_domain($tryserver), $sincefilter,
4969: &escape($descfilter), &escape($instcodefilter),
4970: &escape($ownerfilter), &escape($coursefilter),
4971: &escape($typefilter), &escape($regexp_ok),
4972: $as_hash, &escape($selfenrollonly),
4973: &escape($catfilter), $showhidden, $caller,
4974: &escape($cloner), &escape($cc_clone), $cloneonly,
4975: &escape($createdbefore), &escape($createdafter),
4976: &escape($creationcontext),$domcloner,$hasuniquecode,
4977: $reqcrsdom,&escape($reqinstcode))));
4978: } else {
4979: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4980: $sincefilter.':'.&escape($descfilter).':'.
4981: &escape($instcodefilter).':'.&escape($ownerfilter).
4982: ':'.&escape($coursefilter).':'.&escape($typefilter).
4983: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4984: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4985: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4986: &escape($cc_clone).':'.$cloneonly.':'.
4987: &escape($createdbefore).':'.&escape($createdafter).':'.
4988: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
4989: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
4990: }
4991:
4992: my @pairs=split(/\&/,$rep);
4993: foreach my $item (@pairs) {
4994: my ($key,$value)=split(/\=/,$item,2);
4995: $key = &unescape($key);
4996: next if ($key =~ /^error: 2 /);
4997: my $result = &thaw_unescape($value);
4998: if (ref($result) eq 'HASH') {
4999: $returnhash{$key}=$result;
5000: } else {
5001: my @responses = split(/:/,$value);
5002: my @items = ('description','inst_code','owner','type');
5003: for (my $i=0; $i<@responses; $i++) {
5004: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
5005: }
5006: }
5007: }
5008: }
5009: }
5010: }
5011: return %returnhash;
5012: }
5013:
5014: sub courselastaccess {
5015: my ($cdom,$cnum,$hostidref) = @_;
5016: my %returnhash;
5017: if ($cdom && $cnum) {
5018: my $chome = &homeserver($cnum,$cdom);
5019: if ($chome ne 'no_host') {
5020: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5021: &extract_lastaccess(\%returnhash,$rep);
5022: }
5023: } else {
5024: if (!$cdom) { $cdom=''; }
5025: my %libserv = &all_library();
5026: foreach my $tryserver (keys(%libserv)) {
5027: if (ref($hostidref) eq 'ARRAY') {
5028: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5029: }
5030: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5031: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5032: &extract_lastaccess(\%returnhash,$rep);
5033: }
5034: }
5035: }
5036: return %returnhash;
5037: }
5038:
5039: sub extract_lastaccess {
5040: my ($returnhash,$rep) = @_;
5041: if (ref($returnhash) eq 'HASH') {
5042: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5043: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5044: $rep eq '') {
5045: my @pairs=split(/\&/,$rep);
5046: foreach my $item (@pairs) {
5047: my ($key,$value)=split(/\=/,$item,2);
5048: $key = &unescape($key);
5049: next if ($key =~ /^error: 2 /);
5050: $returnhash->{$key} = &thaw_unescape($value);
5051: }
5052: }
5053: }
5054: return;
5055: }
5056:
5057: # ---------------------------------------------------------- DC e-mail
5058:
5059: sub dcmailput {
5060: my ($domain,$msgid,$message,$server)=@_;
5061: my $status = &Apache::lonnet::critical(
5062: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5063: &escape($message),$server);
5064: return $status;
5065: }
5066:
5067: sub dcmaildump {
5068: my ($dom,$startdate,$enddate,$senders) = @_;
5069: my %returnhash=();
5070:
5071: if (defined(&domain($dom,'primary'))) {
5072: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5073: &escape($enddate).':';
5074: my @esc_senders=map { &escape($_)} @$senders;
5075: $cmd.=&escape(join('&',@esc_senders));
5076: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
5077: my ($key,$value) = split(/\=/,$line,2);
5078: if (($key) && ($value)) {
5079: $returnhash{&unescape($key)} = &unescape($value);
5080: }
5081: }
5082: }
5083: return %returnhash;
5084: }
5085: # ---------------------------------------------------------- Domain roles
5086:
5087: sub get_domain_roles {
5088: my ($dom,$roles,$startdate,$enddate)=@_;
5089: if ((!defined($startdate)) || ($startdate eq '')) {
5090: $startdate = '.';
5091: }
5092: if ((!defined($enddate)) || ($enddate eq '')) {
5093: $enddate = '.';
5094: }
5095: my $rolelist;
5096: if (ref($roles) eq 'ARRAY') {
5097: $rolelist = join('&',@{$roles});
5098: }
5099: my %personnel = ();
5100:
5101: my %servers = &get_servers($dom,'library');
5102: foreach my $tryserver (keys(%servers)) {
5103: %{$personnel{$tryserver}}=();
5104: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5105: &escape($startdate).':'.
5106: &escape($enddate).':'.
5107: &escape($rolelist), $tryserver))) {
5108: my ($key,$value) = split(/\=/,$line,2);
5109: if (($key) && ($value)) {
5110: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5111: }
5112: }
5113: }
5114: return %personnel;
5115: }
5116:
5117: sub get_active_domroles {
5118: my ($dom,$roles) = @_;
5119: return () unless (ref($roles) eq 'ARRAY');
5120: my $now = time;
5121: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5122: my %domroles;
5123: foreach my $server (keys(%dompersonnel)) {
5124: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5125: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5126: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5127: }
5128: }
5129: return %domroles;
5130: }
5131:
5132: # ----------------------------------------------------------- Interval timing
5133:
5134: {
5135: # Caches needed for speedup of navmaps
5136: # We don't want to cache this for very long at all (5 seconds at most)
5137: #
5138: # The user for whom we cache
5139: my $cachedkey='';
5140: # The cached times for this user
5141: my %cachedtimes=();
5142: # When this was last done
5143: my $cachedtime='';
5144:
5145: sub load_all_first_access {
5146: my ($uname,$udom,$ignorecache)=@_;
5147: if (($cachedkey eq $uname.':'.$udom) &&
5148: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
5149: (!$ignorecache)) {
5150: return;
5151: }
5152: $cachedtime=time;
5153: $cachedkey=$uname.':'.$udom;
5154: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
5155: }
5156:
5157: sub get_first_access {
5158: my ($type,$argsymb,$argmap,$ignorecache)=@_;
5159: my ($symb,$courseid,$udom,$uname)=&whichuser();
5160: if ($argsymb) { $symb=$argsymb; }
5161: my ($map,$id,$res)=&decode_symb($symb);
5162: if ($argmap) { $map = $argmap; }
5163: if ($type eq 'course') {
5164: $res='course';
5165: } elsif ($type eq 'map') {
5166: $res=&symbread($map);
5167: } else {
5168: $res=$symb;
5169: }
5170: &load_all_first_access($uname,$udom,$ignorecache);
5171: return $cachedtimes{"$courseid\0$res"};
5172: }
5173:
5174: sub set_first_access {
5175: my ($type,$interval)=@_;
5176: my ($symb,$courseid,$udom,$uname)=&whichuser();
5177: my ($map,$id,$res)=&decode_symb($symb);
5178: if ($type eq 'course') {
5179: $res='course';
5180: } elsif ($type eq 'map') {
5181: $res=&symbread($map);
5182: } else {
5183: $res=$symb;
5184: }
5185: $cachedkey='';
5186: my $firstaccess=&get_first_access($type,$symb,$map);
5187: if (!$firstaccess) {
5188: my $start = time;
5189: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5190: $udom,$uname);
5191: if ($putres eq 'ok') {
5192: &put('timerinterval',{"$courseid\0$res"=>$interval},
5193: $udom,$uname);
5194: &appenv(
5195: {
5196: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5197: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5198: }
5199: );
5200: }
5201: return $putres;
5202: }
5203: return 'already_set';
5204: }
5205: }
5206:
5207: # --------------------------------------------- Set Expire Date for Spreadsheet
5208:
5209: sub expirespread {
5210: my ($uname,$udom,$stype,$usymb)=@_;
5211: my $cid=$env{'request.course.id'};
5212: if ($cid) {
5213: my $now=time;
5214: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
5215: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5216: $env{'course.'.$cid.'.num'}.
5217: ':nohist_expirationdates:'.
5218: &escape($key).'='.$now,
5219: $env{'course.'.$cid.'.home'})
5220: }
5221: return 'ok';
5222: }
5223:
5224: # ----------------------------------------------------- Devalidate Spreadsheets
5225:
5226: sub devalidate {
5227: my ($symb,$uname,$udom)=@_;
5228: my $cid=$env{'request.course.id'};
5229: if ($cid) {
5230: # delete the stored spreadsheets for
5231: # - the student level sheet of this user in course's homespace
5232: # - the assessment level sheet for this resource
5233: # for this user in user's homespace
5234: # - current conditional state info
5235: my $key=$uname.':'.$udom.':';
5236: my $status=
5237: &del('nohist_calculatedsheets',
5238: [$key.'studentcalc:'],
5239: $env{'course.'.$cid.'.domain'},
5240: $env{'course.'.$cid.'.num'})
5241: .' '.
5242: &del('nohist_calculatedsheets_'.$cid,
5243: [$key.'assesscalc:'.$symb],$udom,$uname);
5244: unless ($status eq 'ok ok') {
5245: &logthis('Could not devalidate spreadsheet '.
5246: $uname.' at '.$udom.' for '.
5247: $symb.': '.$status);
5248: }
5249: &delenv('user.state.'.$cid);
5250: }
5251: }
5252:
5253: sub get_scalar {
5254: my ($string,$end) = @_;
5255: my $value;
5256: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5257: $value = $1;
5258: } elsif ($$string =~ s/^([^&]*?)&//) {
5259: $value = $1;
5260: }
5261: return &unescape($value);
5262: }
5263:
5264: sub array2str {
5265: my (@array) = @_;
5266: my $result=&arrayref2str(\@array);
5267: $result=~s/^__ARRAY_REF__//;
5268: $result=~s/__END_ARRAY_REF__$//;
5269: return $result;
5270: }
5271:
5272: sub arrayref2str {
5273: my ($arrayref) = @_;
5274: my $result='__ARRAY_REF__';
5275: foreach my $elem (@$arrayref) {
5276: if(ref($elem) eq 'ARRAY') {
5277: $result.=&arrayref2str($elem).'&';
5278: } elsif(ref($elem) eq 'HASH') {
5279: $result.=&hashref2str($elem).'&';
5280: } elsif(ref($elem)) {
5281: #print("Got a ref of ".(ref($elem))." skipping.");
5282: } else {
5283: $result.=&escape($elem).'&';
5284: }
5285: }
5286: $result=~s/\&$//;
5287: $result .= '__END_ARRAY_REF__';
5288: return $result;
5289: }
5290:
5291: sub hash2str {
5292: my (%hash) = @_;
5293: my $result=&hashref2str(\%hash);
5294: $result=~s/^__HASH_REF__//;
5295: $result=~s/__END_HASH_REF__$//;
5296: return $result;
5297: }
5298:
5299: sub hashref2str {
5300: my ($hashref)=@_;
5301: my $result='__HASH_REF__';
5302: foreach my $key (sort(keys(%$hashref))) {
5303: if (ref($key) eq 'ARRAY') {
5304: $result.=&arrayref2str($key).'=';
5305: } elsif (ref($key) eq 'HASH') {
5306: $result.=&hashref2str($key).'=';
5307: } elsif (ref($key)) {
5308: $result.='=';
5309: #print("Got a ref of ".(ref($key))." skipping.");
5310: } else {
5311: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
5312: }
5313:
5314: if(ref($hashref->{$key}) eq 'ARRAY') {
5315: $result.=&arrayref2str($hashref->{$key}).'&';
5316: } elsif(ref($hashref->{$key}) eq 'HASH') {
5317: $result.=&hashref2str($hashref->{$key}).'&';
5318: } elsif(ref($hashref->{$key})) {
5319: $result.='&';
5320: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
5321: } else {
5322: $result.=&escape($hashref->{$key}).'&';
5323: }
5324: }
5325: $result=~s/\&$//;
5326: $result .= '__END_HASH_REF__';
5327: return $result;
5328: }
5329:
5330: sub str2hash {
5331: my ($string)=@_;
5332: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5333: return %$hash;
5334: }
5335:
5336: sub str2hashref {
5337: my ($string) = @_;
5338:
5339: my %hash;
5340:
5341: if($string !~ /^__HASH_REF__/) {
5342: if (! ($string eq '' || !defined($string))) {
5343: $hash{'error'}='Not hash reference';
5344: }
5345: return (\%hash, $string);
5346: }
5347:
5348: $string =~ s/^__HASH_REF__//;
5349:
5350: while($string !~ /^__END_HASH_REF__/) {
5351: #key
5352: my $key='';
5353: if($string =~ /^__HASH_REF__/) {
5354: ($key, $string)=&str2hashref($string);
5355: if(defined($key->{'error'})) {
5356: $hash{'error'}='Bad data';
5357: return (\%hash, $string);
5358: }
5359: } elsif($string =~ /^__ARRAY_REF__/) {
5360: ($key, $string)=&str2arrayref($string);
5361: if($key->[0] eq 'Array reference error') {
5362: $hash{'error'}='Bad data';
5363: return (\%hash, $string);
5364: }
5365: } else {
5366: $string =~ s/^(.*?)=//;
5367: $key=&unescape($1);
5368: }
5369: $string =~ s/^=//;
5370:
5371: #value
5372: my $value='';
5373: if($string =~ /^__HASH_REF__/) {
5374: ($value, $string)=&str2hashref($string);
5375: if(defined($value->{'error'})) {
5376: $hash{'error'}='Bad data';
5377: return (\%hash, $string);
5378: }
5379: } elsif($string =~ /^__ARRAY_REF__/) {
5380: ($value, $string)=&str2arrayref($string);
5381: if($value->[0] eq 'Array reference error') {
5382: $hash{'error'}='Bad data';
5383: return (\%hash, $string);
5384: }
5385: } else {
5386: $value=&get_scalar(\$string,'__END_HASH_REF__');
5387: }
5388: $string =~ s/^&//;
5389:
5390: $hash{$key}=$value;
5391: }
5392:
5393: $string =~ s/^__END_HASH_REF__//;
5394:
5395: return (\%hash, $string);
5396: }
5397:
5398: sub str2array {
5399: my ($string)=@_;
5400: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5401: return @$array;
5402: }
5403:
5404: sub str2arrayref {
5405: my ($string) = @_;
5406: my @array;
5407:
5408: if($string !~ /^__ARRAY_REF__/) {
5409: if (! ($string eq '' || !defined($string))) {
5410: $array[0]='Array reference error';
5411: }
5412: return (\@array, $string);
5413: }
5414:
5415: $string =~ s/^__ARRAY_REF__//;
5416:
5417: while($string !~ /^__END_ARRAY_REF__/) {
5418: my $value='';
5419: if($string =~ /^__HASH_REF__/) {
5420: ($value, $string)=&str2hashref($string);
5421: if(defined($value->{'error'})) {
5422: $array[0] ='Array reference error';
5423: return (\@array, $string);
5424: }
5425: } elsif($string =~ /^__ARRAY_REF__/) {
5426: ($value, $string)=&str2arrayref($string);
5427: if($value->[0] eq 'Array reference error') {
5428: $array[0] ='Array reference error';
5429: return (\@array, $string);
5430: }
5431: } else {
5432: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5433: }
5434: $string =~ s/^&//;
5435:
5436: push(@array, $value);
5437: }
5438:
5439: $string =~ s/^__END_ARRAY_REF__//;
5440:
5441: return (\@array, $string);
5442: }
5443:
5444: # -------------------------------------------------------------------Temp Store
5445:
5446: sub tmpreset {
5447: my ($symb,$namespace,$domain,$stuname) = @_;
5448: if (!$symb) {
5449: $symb=&symbread();
5450: if (!$symb) { $symb= $env{'request.url'}; }
5451: }
5452: $symb=escape($symb);
5453:
5454: if (!$namespace) { $namespace=$env{'request.state'}; }
5455: $namespace=~s/\//\_/g;
5456: $namespace=~s/\W//g;
5457:
5458: if (!$domain) { $domain=$env{'user.domain'}; }
5459: if (!$stuname) { $stuname=$env{'user.name'}; }
5460: if ($domain eq 'public' && $stuname eq 'public') {
5461: $stuname=$ENV{'REMOTE_ADDR'};
5462: }
5463: my $path=LONCAPA::tempdir();
5464: my %hash;
5465: if (tie(%hash,'GDBM_File',
5466: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
5467: &GDBM_WRCREAT(),0640)) {
5468: foreach my $key (keys(%hash)) {
5469: if ($key=~ /:$symb/) {
5470: delete($hash{$key});
5471: }
5472: }
5473: }
5474: }
5475:
5476: sub tmpstore {
5477: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5478:
5479: if (!$symb) {
5480: $symb=&symbread();
5481: if (!$symb) { $symb= $env{'request.url'}; }
5482: }
5483: $symb=escape($symb);
5484:
5485: if (!$namespace) {
5486: # I don't think we would ever want to store this for a course.
5487: # it seems this will only be used if we don't have a course.
5488: #$namespace=$env{'request.course.id'};
5489: #if (!$namespace) {
5490: $namespace=$env{'request.state'};
5491: #}
5492: }
5493: $namespace=~s/\//\_/g;
5494: $namespace=~s/\W//g;
5495: if (!$domain) { $domain=$env{'user.domain'}; }
5496: if (!$stuname) { $stuname=$env{'user.name'}; }
5497: if ($domain eq 'public' && $stuname eq 'public') {
5498: $stuname=$ENV{'REMOTE_ADDR'};
5499: }
5500: my $now=time;
5501: my %hash;
5502: my $path=LONCAPA::tempdir();
5503: if (tie(%hash,'GDBM_File',
5504: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
5505: &GDBM_WRCREAT(),0640)) {
5506: $hash{"version:$symb"}++;
5507: my $version=$hash{"version:$symb"};
5508: my $allkeys='';
5509: foreach my $key (keys(%$storehash)) {
5510: $allkeys.=$key.':';
5511: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
5512: }
5513: $hash{"$version:$symb:timestamp"}=$now;
5514: $allkeys.='timestamp';
5515: $hash{"$version:keys:$symb"}=$allkeys;
5516: if (untie(%hash)) {
5517: return 'ok';
5518: } else {
5519: return "error:$!";
5520: }
5521: } else {
5522: return "error:$!";
5523: }
5524: }
5525:
5526: # -----------------------------------------------------------------Temp Restore
5527:
5528: sub tmprestore {
5529: my ($symb,$namespace,$domain,$stuname) = @_;
5530:
5531: if (!$symb) {
5532: $symb=&symbread();
5533: if (!$symb) { $symb= $env{'request.url'}; }
5534: }
5535: $symb=escape($symb);
5536:
5537: if (!$namespace) { $namespace=$env{'request.state'}; }
5538:
5539: if (!$domain) { $domain=$env{'user.domain'}; }
5540: if (!$stuname) { $stuname=$env{'user.name'}; }
5541: if ($domain eq 'public' && $stuname eq 'public') {
5542: $stuname=$ENV{'REMOTE_ADDR'};
5543: }
5544: my %returnhash;
5545: $namespace=~s/\//\_/g;
5546: $namespace=~s/\W//g;
5547: my %hash;
5548: my $path=LONCAPA::tempdir();
5549: if (tie(%hash,'GDBM_File',
5550: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
5551: &GDBM_READER(),0640)) {
5552: my $version=$hash{"version:$symb"};
5553: $returnhash{'version'}=$version;
5554: my $scope;
5555: for ($scope=1;$scope<=$version;$scope++) {
5556: my $vkeys=$hash{"$scope:keys:$symb"};
5557: my @keys=split(/:/,$vkeys);
5558: my $key;
5559: $returnhash{"$scope:keys"}=$vkeys;
5560: foreach $key (@keys) {
5561: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5562: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5563: }
5564: }
5565: if (!(untie(%hash))) {
5566: return "error:$!";
5567: }
5568: } else {
5569: return "error:$!";
5570: }
5571: return %returnhash;
5572: }
5573:
5574: # ----------------------------------------------------------------------- Store
5575:
5576: sub store {
5577: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
5578: my $home='';
5579:
5580: if ($stuname) { $home=&homeserver($stuname,$domain); }
5581:
5582: $symb=&symbclean($symb);
5583: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
5584:
5585: if (!$domain) { $domain=$env{'user.domain'}; }
5586: if (!$stuname) { $stuname=$env{'user.name'}; }
5587:
5588: &devalidate($symb,$stuname,$domain);
5589:
5590: $symb=escape($symb);
5591: if (!$namespace) {
5592: unless ($namespace=$env{'request.course.id'}) {
5593: return '';
5594: }
5595: }
5596: if (!$home) { $home=$env{'user.home'}; }
5597:
5598: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5599: $$storehash{'host'}=$perlvar{'lonHostID'};
5600:
5601: my $namevalue='';
5602: foreach my $key (keys(%$storehash)) {
5603: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5604: }
5605: $namevalue=~s/\&$//;
5606: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
5607: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
5608: }
5609:
5610: # -------------------------------------------------------------- Critical Store
5611:
5612: sub cstore {
5613: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
5614: my $home='';
5615:
5616: if ($stuname) { $home=&homeserver($stuname,$domain); }
5617:
5618: $symb=&symbclean($symb);
5619: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
5620:
5621: if (!$domain) { $domain=$env{'user.domain'}; }
5622: if (!$stuname) { $stuname=$env{'user.name'}; }
5623:
5624: &devalidate($symb,$stuname,$domain);
5625:
5626: $symb=escape($symb);
5627: if (!$namespace) {
5628: unless ($namespace=$env{'request.course.id'}) {
5629: return '';
5630: }
5631: }
5632: if (!$home) { $home=$env{'user.home'}; }
5633:
5634: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5635: $$storehash{'host'}=$perlvar{'lonHostID'};
5636:
5637: my $namevalue='';
5638: foreach my $key (keys(%$storehash)) {
5639: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5640: }
5641: $namevalue=~s/\&$//;
5642: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
5643: return critical
5644: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
5645: }
5646:
5647: # --------------------------------------------------------------------- Restore
5648:
5649: sub restore {
5650: my ($symb,$namespace,$domain,$stuname) = @_;
5651: my $home='';
5652:
5653: if ($stuname) { $home=&homeserver($stuname,$domain); }
5654:
5655: if (!$symb) {
5656: return if ($namespace eq 'courserequests');
5657: unless ($symb=escape(&symbread())) { return ''; }
5658: } else {
5659: unless ($namespace eq 'courserequests') {
5660: $symb=&escape(&symbclean($symb));
5661: }
5662: }
5663: if (!$namespace) {
5664: unless ($namespace=$env{'request.course.id'}) {
5665: return '';
5666: }
5667: }
5668: if (!$domain) { $domain=$env{'user.domain'}; }
5669: if (!$stuname) { $stuname=$env{'user.name'}; }
5670: if (!$home) { $home=$env{'user.home'}; }
5671: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5672:
5673: my %returnhash=();
5674: foreach my $line (split(/\&/,$answer)) {
5675: my ($name,$value)=split(/\=/,$line);
5676: $returnhash{&unescape($name)}=&thaw_unescape($value);
5677: }
5678: my $version;
5679: for ($version=1;$version<=$returnhash{'version'};$version++) {
5680: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5681: $returnhash{$item}=$returnhash{$version.':'.$item};
5682: }
5683: }
5684: return %returnhash;
5685: }
5686:
5687: # ---------------------------------------------------------- Course Description
5688: #
5689: #
5690:
5691: sub coursedescription {
5692: my ($courseid,$args)=@_;
5693: $courseid=~s/^\///;
5694: $courseid=~s/\_/\//g;
5695: my ($cdomain,$cnum)=split(/\//,$courseid);
5696: my $chome=&homeserver($cnum,$cdomain);
5697: my $normalid=$cdomain.'_'.$cnum;
5698: # need to always cache even if we get errors otherwise we keep
5699: # trying and trying and trying to get the course description.
5700: my %envhash=();
5701: my %returnhash=();
5702:
5703: my $expiretime=600;
5704: if ($env{'request.course.id'} eq $normalid) {
5705: $expiretime=120;
5706: }
5707:
5708: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5709: if (!$args->{'freshen_cache'}
5710: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5711: foreach my $key (keys(%env)) {
5712: next if ($key !~ /^\Q$prefix\E(.*)/);
5713: my ($setting) = $1;
5714: $returnhash{$setting} = $env{$key};
5715: }
5716: return %returnhash;
5717: }
5718:
5719: # get the data again
5720:
5721: if (!$args->{'one_time'}) {
5722: $envhash{'course.'.$normalid.'.last_cache'}=time;
5723: }
5724:
5725: if ($chome ne 'no_host') {
5726: %returnhash=&dump('environment',$cdomain,$cnum);
5727: if (!exists($returnhash{'con_lost'})) {
5728: my $username = $env{'user.name'}; # Defult username
5729: if(defined $args->{'user'}) {
5730: $username = $args->{'user'};
5731: }
5732: $returnhash{'home'}= $chome;
5733: $returnhash{'domain'} = $cdomain;
5734: $returnhash{'num'} = $cnum;
5735: if (!defined($returnhash{'type'})) {
5736: $returnhash{'type'} = 'Course';
5737: }
5738: while (my ($name,$value) = each %returnhash) {
5739: $envhash{'course.'.$normalid.'.'.$name}=$value;
5740: }
5741: $returnhash{'url'}=&clutter($returnhash{'url'});
5742: $returnhash{'fn'}=LONCAPA::tempdir() .
5743: $username.'_'.$cdomain.'_'.$cnum;
5744: $envhash{'course.'.$normalid.'.home'}=$chome;
5745: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5746: $envhash{'course.'.$normalid.'.num'}=$cnum;
5747: }
5748: }
5749: if (!$args->{'one_time'}) {
5750: &appenv(\%envhash);
5751: }
5752: return %returnhash;
5753: }
5754:
5755: sub update_released_required {
5756: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5757: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5758: $cid = $env{'request.course.id'};
5759: $cdom = $env{'course.'.$cid.'.domain'};
5760: $cnum = $env{'course.'.$cid.'.num'};
5761: $chome = $env{'course.'.$cid.'.home'};
5762: }
5763: if ($needsrelease) {
5764: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5765: my $needsupdate;
5766: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5767: $needsupdate = 1;
5768: } else {
5769: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5770: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5771: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5772: $needsupdate = 1;
5773: }
5774: }
5775: if ($needsupdate) {
5776: my %needshash = (
5777: 'internal.releaserequired' => $needsrelease,
5778: );
5779: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5780: if ($putresult eq 'ok') {
5781: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5782: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5783: if (ref($crsinfo{$cid}) eq 'HASH') {
5784: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5785: &courseidput($cdom,\%crsinfo,$chome,'notime');
5786: }
5787: }
5788: }
5789: }
5790: return;
5791: }
5792:
5793: # -------------------------------------------------See if a user is privileged
5794:
5795: sub privileged {
5796: my ($username,$domain,$possdomains,$possroles)=@_;
5797: my $now = time;
5798: my $roles;
5799: if (ref($possroles) eq 'ARRAY') {
5800: $roles = $possroles;
5801: } else {
5802: $roles = ['dc','su'];
5803: }
5804: if (ref($possdomains) eq 'ARRAY') {
5805: my %privileged = &privileged_by_domain($possdomains,$roles);
5806: foreach my $dom (@{$possdomains}) {
5807: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5808: (ref($privileged{$dom}) eq 'HASH')) {
5809: foreach my $role (@{$roles}) {
5810: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5811: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5812: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5813: return 1 unless (($end && $end < $now) ||
5814: ($start && $start > $now));
5815: }
5816: }
5817: }
5818: }
5819: }
5820: } else {
5821: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5822: my $now = time;
5823:
5824: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
5825: my ($trole, $tend, $tstart) = split(/_/, $role);
5826: if (grep(/^\Q$trole\E$/,@{$roles})) {
5827: return 1 unless ($tend && $tend < $now)
5828: or ($tstart && $tstart > $now);
5829: }
5830: }
5831: }
5832: return 0;
5833: }
5834:
5835: sub privileged_by_domain {
5836: my ($domains,$roles) = @_;
5837: my %privileged = ();
5838: my $cachetime = 60*60*24;
5839: my $now = time;
5840: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5841: return %privileged;
5842: }
5843: foreach my $dom (@{$domains}) {
5844: next if (ref($privileged{$dom}) eq 'HASH');
5845: my $needroles;
5846: foreach my $role (@{$roles}) {
5847: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5848: if (defined($cached)) {
5849: if (ref($result) eq 'HASH') {
5850: $privileged{$dom}{$role} = $result;
5851: }
5852: } else {
5853: $needroles = 1;
5854: }
5855: }
5856: if ($needroles) {
5857: my %dompersonnel = &get_domain_roles($dom,$roles);
5858: $privileged{$dom} = {};
5859: foreach my $server (keys(%dompersonnel)) {
5860: if (ref($dompersonnel{$server}) eq 'HASH') {
5861: foreach my $item (keys(%{$dompersonnel{$server}})) {
5862: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5863: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5864: next if ($end && $end < $now);
5865: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5866: $dompersonnel{$server}{$item};
5867: }
5868: }
5869: }
5870: if (ref($privileged{$dom}) eq 'HASH') {
5871: foreach my $role (@{$roles}) {
5872: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5873: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5874: } else {
5875: my %hash = ();
5876: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5877: }
5878: }
5879: }
5880: }
5881: }
5882: return %privileged;
5883: }
5884:
5885: # -------------------------------------------------------- Get user privileges
5886:
5887: sub rolesinit {
5888: my ($domain, $username) = @_;
5889: my %userroles = ('user.login.time' => time);
5890: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5891:
5892: # firstaccess and timerinterval are related to timed maps/resources.
5893: # also, blocking can be triggered by an activating timer
5894: # it's saved in the user's %env.
5895: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5896: my %timerinterval = &dump('timerinterval', $domain, $username);
5897: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5898: %timerintchk, %timerintenv);
5899:
5900: foreach my $key (keys(%firstaccess)) {
5901: my ($cid, $rest) = split(/\0/, $key);
5902: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5903: }
5904:
5905: foreach my $key (keys(%timerinterval)) {
5906: my ($cid,$rest) = split(/\0/,$key);
5907: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5908: }
5909:
5910: my %allroles=();
5911: my %allgroups=();
5912:
5913: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
5914: my $role = $rolesdump{$area};
5915: $area =~ s/\_\w\w$//;
5916:
5917: my ($trole, $tend, $tstart, $group_privs);
5918:
5919: if ($role =~ /^cr/) {
5920: # Custom role, defined by a user
5921: # e.g., user.role.cr/msu/smith/mynewrole
5922: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5923: $trole = $1;
5924: ($tend, $tstart) = split('_', $2);
5925: } else {
5926: $trole = $role;
5927: }
5928: } elsif ($role =~ m|^gr/|) {
5929: # Role of member in a group, defined within a course/community
5930: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5931: ($trole, $tend, $tstart) = split(/_/, $role);
5932: next if $tstart eq '-1';
5933: ($trole, $group_privs) = split(/\//, $trole);
5934: $group_privs = &unescape($group_privs);
5935: } else {
5936: # Just a normal role, defined in roles.tab
5937: ($trole, $tend, $tstart) = split(/_/,$role);
5938: }
5939:
5940: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5941: $username);
5942: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5943:
5944: # role expired or not available yet?
5945: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5946: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5947:
5948: next if $area eq '' or $trole eq '';
5949:
5950: my $spec = "$trole.$area";
5951: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5952:
5953: if ($trole =~ /^cr\//) {
5954: # Custom role, defined by a user
5955: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5956: } elsif ($trole eq 'gr') {
5957: # Role of a member in a group, defined within a course/community
5958: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5959: next;
5960: } else {
5961: # Normal role, defined in roles.tab
5962: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5963: }
5964:
5965: my $cid = $tdomain.'_'.$trest;
5966: unless ($firstaccchk{$cid}) {
5967: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5968: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5969: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5970: $coursetimerstarts{$cid}{$item};
5971: }
5972: }
5973: $firstaccchk{$cid} = 1;
5974: }
5975: unless ($timerintchk{$cid}) {
5976: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5977: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5978: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5979: $coursetimerintervals{$cid}{$item};
5980: }
5981: }
5982: $timerintchk{$cid} = 1;
5983: }
5984: }
5985:
5986: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
5987: \%allroles, \%allgroups);
5988: $env{'user.adv'} = $userroles{'user.adv'};
5989: $env{'user.rar'} = $userroles{'user.rar'};
5990:
5991: return (\%userroles,\%firstaccenv,\%timerintenv);
5992: }
5993:
5994: sub set_arearole {
5995: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5996: unless ($nolog) {
5997: # log the associated role with the area
5998: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5999: }
6000: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
6001: }
6002:
6003: sub custom_roleprivs {
6004: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6005: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
6006: my $homsvr = &homeserver($rauthor,$rdomain);
6007: if (&hostname($homsvr) ne '') {
6008: my ($rdummy,$roledef)=
6009: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6010: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6011: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6012: if (defined($syspriv)) {
6013: if ($trest =~ /^$match_community$/) {
6014: $syspriv =~ s/bre\&S//;
6015: }
6016: $$allroles{'cm./'}.=':'.$syspriv;
6017: $$allroles{$spec.'./'}.=':'.$syspriv;
6018: }
6019: if ($tdomain ne '') {
6020: if (defined($dompriv)) {
6021: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6022: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6023: }
6024: if (($trest ne '') && (defined($coursepriv))) {
6025: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6026: my $rolename = $1;
6027: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6028: }
6029: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6030: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6031: }
6032: }
6033: }
6034: }
6035: }
6036:
6037: sub course_adhocrole_privs {
6038: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6039: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6040: if ($overrides{"internal.adhocpriv.$rolename"}) {
6041: my (%currprivs,%storeprivs);
6042: foreach my $item (split(/:/,$coursepriv)) {
6043: my ($priv,$restrict) = split(/\&/,$item);
6044: $currprivs{$priv} = $restrict;
6045: }
6046: my (%possadd,%possremove,%full);
6047: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6048: my ($priv,$restrict)=split(/\&/,$item);
6049: $full{$priv} = $restrict;
6050: }
6051: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6052: next if ($item eq '');
6053: my ($rule,$rest) = split(/=/,$item);
6054: next unless (($rule eq 'off') || ($rule eq 'on'));
6055: foreach my $priv (split(/:/,$rest)) {
6056: if ($priv ne '') {
6057: if ($rule eq 'off') {
6058: $possremove{$priv} = 1;
6059: } else {
6060: $possadd{$priv} = 1;
6061: }
6062: }
6063: }
6064: }
6065: foreach my $priv (sort(keys(%full))) {
6066: if (exists($currprivs{$priv})) {
6067: unless (exists($possremove{$priv})) {
6068: $storeprivs{$priv} = $currprivs{$priv};
6069: }
6070: } elsif (exists($possadd{$priv})) {
6071: $storeprivs{$priv} = $full{$priv};
6072: }
6073: }
6074: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6075: }
6076: return $coursepriv;
6077: }
6078:
6079: sub group_roleprivs {
6080: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6081: my $access = 1;
6082: my $now = time;
6083: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6084: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6085: if ($access) {
6086: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
6087: $$allgroups{$course}{$group} .=':'.$group_privs;
6088: }
6089: }
6090:
6091: sub standard_roleprivs {
6092: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6093: if (defined($pr{$trole.':s'})) {
6094: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6095: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6096: }
6097: if ($tdomain ne '') {
6098: if (defined($pr{$trole.':d'})) {
6099: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6100: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6101: }
6102: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6103: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6104: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6105: }
6106: }
6107: }
6108:
6109: sub set_userprivs {
6110: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
6111: my $author=0;
6112: my $adv=0;
6113: my $rar=0;
6114: my %grouproles = ();
6115: if (keys(%{$allgroups}) > 0) {
6116: my @groupkeys;
6117: foreach my $role (keys(%{$allroles})) {
6118: push(@groupkeys,$role);
6119: }
6120: if (ref($groups_roles) eq 'HASH') {
6121: foreach my $key (keys(%{$groups_roles})) {
6122: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6123: push(@groupkeys,$key);
6124: }
6125: }
6126: }
6127: if (@groupkeys > 0) {
6128: foreach my $role (@groupkeys) {
6129: my ($trole,$area,$sec,$extendedarea);
6130: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6131: $trole = $1;
6132: $area = $2;
6133: $sec = $3;
6134: $extendedarea = $area.$sec;
6135: if (exists($$allgroups{$area})) {
6136: foreach my $group (keys(%{$$allgroups{$area}})) {
6137: my $spec = $trole.'.'.$extendedarea;
6138: $grouproles{$spec.'.'.$area.'/'.$group} =
6139: $$allgroups{$area}{$group};
6140: }
6141: }
6142: }
6143: }
6144: }
6145: }
6146: foreach my $group (keys(%grouproles)) {
6147: $$allroles{$group} = $grouproles{$group};
6148: }
6149: foreach my $role (keys(%{$allroles})) {
6150: my %thesepriv;
6151: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
6152: foreach my $item (split(/:/,$$allroles{$role})) {
6153: if ($item ne '') {
6154: my ($privilege,$restrictions)=split(/&/,$item);
6155: if ($restrictions eq '') {
6156: $thesepriv{$privilege}='F';
6157: } elsif ($thesepriv{$privilege} ne 'F') {
6158: $thesepriv{$privilege}.=$restrictions;
6159: }
6160: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
6161: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
6162: }
6163: }
6164: my $thesestr='';
6165: foreach my $priv (sort(keys(%thesepriv))) {
6166: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6167: }
6168: $userroles->{'user.priv.'.$role} = $thesestr;
6169: }
6170: return ($author,$adv,$rar);
6171: }
6172:
6173: sub role_status {
6174: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
6175: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
6176: my ($one,$two) = split(m{\./},$rolekey,2);
6177: (undef,undef,$$role) = split(/\./,$one,3);
6178: unless (!defined($$role) || $$role eq '') {
6179: $$where = '/'.$two;
6180: $$trolecode=$$role.'.'.$$where;
6181: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6182: $$tstatus='is';
6183: if ($$tstart && $$tstart>$update) {
6184: $$tstatus='future';
6185: if ($$tstart<$now) {
6186: if ($$tstart && $$tstart>$refresh) {
6187: if (($$where ne '') && ($$role ne '')) {
6188: my (%allroles,%allgroups,$group_privs,
6189: %groups_roles,@rolecodes);
6190: my %userroles = (
6191: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6192: );
6193: @rolecodes = ('cm');
6194: my $spec=$$role.'.'.$$where;
6195: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6196: if ($$role =~ /^cr\//) {
6197: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
6198: push(@rolecodes,'cr');
6199: } elsif ($$role eq 'gr') {
6200: push(@rolecodes,$$role);
6201: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6202: $env{'user.name'});
6203: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
6204: (undef,my $group_privs) = split(/\//,$trole);
6205: $group_privs = &unescape($group_privs);
6206: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
6207: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
6208: &get_groups_roles($tdomain,$trest,
6209: \%course_roles,\@rolecodes,
6210: \%groups_roles);
6211: } else {
6212: push(@rolecodes,$$role);
6213: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6214: }
6215: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6216: \%groups_roles);
6217: &appenv(\%userroles,\@rolecodes);
6218: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
6219: }
6220: }
6221: $$tstatus = 'is';
6222: }
6223: }
6224: if ($$tend) {
6225: if ($$tend<$update) {
6226: $$tstatus='expired';
6227: } elsif ($$tend<$now) {
6228: $$tstatus='will_not';
6229: }
6230: }
6231: }
6232: }
6233: }
6234:
6235: sub get_groups_roles {
6236: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6237: return unless((ref($cdom_courseroles) eq 'HASH') &&
6238: (ref($rolecodes) eq 'ARRAY') &&
6239: (ref($groups_roles) eq 'HASH'));
6240: if (keys(%{$cdom_courseroles}) > 0) {
6241: my ($cnum) = ($rest =~ /^($match_courseid)/);
6242: if ($cdom ne '' && $cnum ne '') {
6243: foreach my $key (keys(%{$cdom_courseroles})) {
6244: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6245: my $crsrole = $1;
6246: my $crssec = $2;
6247: if ($crsrole =~ /^cr/) {
6248: unless (grep(/^cr$/,@{$rolecodes})) {
6249: push(@{$rolecodes},'cr');
6250: }
6251: } else {
6252: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6253: push(@{$rolecodes},$crsrole);
6254: }
6255: }
6256: my $rolekey = "$crsrole./$cdom/$cnum";
6257: if ($crssec ne '') {
6258: $rolekey .= "/$crssec";
6259: }
6260: $rolekey .= './';
6261: $groups_roles->{$rolekey} = $rolecodes;
6262: }
6263: }
6264: }
6265: }
6266: return;
6267: }
6268:
6269: sub delete_env_groupprivs {
6270: my ($where,$courseroles,$possroles) = @_;
6271: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6272: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6273: unless (ref($courseroles->{$udom}) eq 'HASH') {
6274: %{$courseroles->{$udom}} =
6275: &get_my_roles('','','userroles',['active'],
6276: $possroles,[$udom],1);
6277: }
6278: if (ref($courseroles->{$udom}) eq 'HASH') {
6279: foreach my $item (keys(%{$courseroles->{$udom}})) {
6280: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6281: my $area = '/'.$cdom.'/'.$cnum;
6282: my $privkey = "user.priv.$crsrole.$area";
6283: if ($crssec ne '') {
6284: $privkey .= '/'.$crssec;
6285: }
6286: $privkey .= ".$area/$group";
6287: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6288: }
6289: }
6290: return;
6291: }
6292:
6293: sub check_adhoc_privs {
6294: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
6295: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
6296: if ($sec) {
6297: $cckey .= '/'.$sec;
6298: }
6299: my $setprivs;
6300: if ($env{$cckey}) {
6301: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
6302: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
6303: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
6304: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
6305: $setprivs = 1;
6306: }
6307: } else {
6308: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
6309: $setprivs = 1;
6310: }
6311: return $setprivs;
6312: }
6313:
6314: sub set_adhoc_privileges {
6315: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
6316: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
6317: my $area = '/'.$dcdom.'/'.$pickedcourse;
6318: if ($sec ne '') {
6319: $area .= '/'.$sec;
6320: }
6321: my $spec = $role.'.'.$area;
6322: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
6323: $env{'user.name'},1);
6324: my %rolehash = ();
6325: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6326: my $rolename = $1;
6327: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
6328: my %domdef = &get_domain_defaults($dcdom);
6329: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6330: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6331: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6332: }
6333: }
6334: } else {
6335: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6336: }
6337: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
6338: &appenv(\%userroles,[$role,'cm']);
6339: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
6340: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
6341: &appenv( {'request.role' => $spec,
6342: 'request.role.domain' => $dcdom,
6343: 'request.course.sec' => $sec,
6344: }
6345: );
6346: my $tadv=0;
6347: if (&allowed('adv') eq 'F') { $tadv=1; }
6348: &appenv({'request.role.adv' => $tadv});
6349: }
6350: }
6351:
6352: # --------------------------------------------------------------- get interface
6353:
6354: sub get {
6355: my ($namespace,$storearr,$udomain,$uname)=@_;
6356: my $items='';
6357: foreach my $item (@$storearr) {
6358: $items.=&escape($item).'&';
6359: }
6360: $items=~s/\&$//;
6361: if (!$udomain) { $udomain=$env{'user.domain'}; }
6362: if (!$uname) { $uname=$env{'user.name'}; }
6363: my $uhome=&homeserver($uname,$udomain);
6364:
6365: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
6366: my @pairs=split(/\&/,$rep);
6367: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6368: return @pairs;
6369: }
6370: my %returnhash=();
6371: my $i=0;
6372: foreach my $item (@$storearr) {
6373: $returnhash{$item}=&thaw_unescape($pairs[$i]);
6374: $i++;
6375: }
6376: return %returnhash;
6377: }
6378:
6379: # --------------------------------------------------------------- del interface
6380:
6381: sub del {
6382: my ($namespace,$storearr,$udomain,$uname)=@_;
6383: my $items='';
6384: foreach my $item (@$storearr) {
6385: $items.=&escape($item).'&';
6386: }
6387:
6388: $items=~s/\&$//;
6389: if (!$udomain) { $udomain=$env{'user.domain'}; }
6390: if (!$uname) { $uname=$env{'user.name'}; }
6391: my $uhome=&homeserver($uname,$udomain);
6392: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
6393: }
6394:
6395: # -------------------------------------------------------------- dump interface
6396:
6397: sub unserialize {
6398: my ($rep, $escapedkeys) = @_;
6399:
6400: return {} if $rep =~ /^error/;
6401:
6402: my %returnhash=();
6403: foreach my $item (split(/\&/,$rep)) {
6404: my ($key, $value) = split(/=/, $item, 2);
6405: $key = unescape($key) unless $escapedkeys;
6406: next if $key =~ /^error: 2 /;
6407: $returnhash{$key} = &thaw_unescape($value);
6408: }
6409: #return %returnhash;
6410: return \%returnhash;
6411: }
6412:
6413: # see Lond::dump_with_regexp
6414: # if $escapedkeys hash keys won't get unescaped.
6415: sub dump {
6416: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
6417: if (!$udomain) { $udomain=$env{'user.domain'}; }
6418: if (!$uname) { $uname=$env{'user.name'}; }
6419: my $uhome=&homeserver($uname,$udomain);
6420:
6421: if ($regexp) {
6422: $regexp=&escape($regexp);
6423: } else {
6424: $regexp='.';
6425: }
6426: if (grep { $_ eq $uhome } current_machine_ids()) {
6427: # user is hosted on this machine
6428: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
6429: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
6430: return %{unserialize($reply, $escapedkeys)};
6431: }
6432: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
6433: my @pairs=split(/\&/,$rep);
6434: my %returnhash=();
6435: if (!($rep =~ /^error/ )) {
6436: foreach my $item (@pairs) {
6437: my ($key,$value)=split(/=/,$item,2);
6438: $key = unescape($key) unless $escapedkeys;
6439: #$key = &unescape($key);
6440: next if ($key =~ /^error: 2 /);
6441: $returnhash{$key}=&thaw_unescape($value);
6442: }
6443: }
6444: return %returnhash;
6445: }
6446:
6447:
6448: # --------------------------------------------------------- dumpstore interface
6449:
6450: sub dumpstore {
6451: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
6452: # same as dump but keys must be escaped. They may contain colon separated
6453: # lists of values that may themself contain colons (e.g. symbs).
6454: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
6455: }
6456:
6457: # -------------------------------------------------------------- keys interface
6458:
6459: sub getkeys {
6460: my ($namespace,$udomain,$uname)=@_;
6461: if (!$udomain) { $udomain=$env{'user.domain'}; }
6462: if (!$uname) { $uname=$env{'user.name'}; }
6463: my $uhome=&homeserver($uname,$udomain);
6464: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6465: my @keyarray=();
6466: foreach my $key (split(/\&/,$rep)) {
6467: next if ($key =~ /^error: 2 /);
6468: push(@keyarray,&unescape($key));
6469: }
6470: return @keyarray;
6471: }
6472:
6473: # --------------------------------------------------------------- currentdump
6474: sub currentdump {
6475: my ($courseid,$sdom,$sname)=@_;
6476: $courseid = $env{'request.course.id'} if (! defined($courseid));
6477: $sdom = $env{'user.domain'} if (! defined($sdom));
6478: $sname = $env{'user.name'} if (! defined($sname));
6479: my $uhome = &homeserver($sname,$sdom);
6480: my $rep;
6481:
6482: if (grep { $_ eq $uhome } current_machine_ids()) {
6483: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6484: $courseid)));
6485: } else {
6486: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6487: }
6488:
6489: return if ($rep =~ /^(error:|no_such_host)/);
6490: #
6491: my %returnhash=();
6492: #
6493: if ($rep eq 'unknown_cmd') {
6494: # an old lond will not know currentdump
6495: # Do a dump and make it look like a currentdump
6496: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
6497: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6498: my %hash = @tmp;
6499: @tmp=();
6500: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
6501: } else {
6502: my @pairs=split(/\&/,$rep);
6503: foreach my $pair (@pairs) {
6504: my ($key,$value)=split(/=/,$pair,2);
6505: my ($symb,$param) = split(/:/,$key);
6506: $returnhash{&unescape($symb)}->{&unescape($param)} =
6507: &thaw_unescape($value);
6508: }
6509: }
6510: return %returnhash;
6511: }
6512:
6513: sub convert_dump_to_currentdump{
6514: my %hash = %{shift()};
6515: my %returnhash;
6516: # Code ripped from lond, essentially. The only difference
6517: # here is the unescaping done by lonnet::dump(). Conceivably
6518: # we might run in to problems with parameter names =~ /^v\./
6519: while (my ($key,$value) = each(%hash)) {
6520: my ($v,$symb,$param) = split(/:/,$key);
6521: $symb = &unescape($symb);
6522: $param = &unescape($param);
6523: next if ($v eq 'version' || $symb eq 'keys');
6524: next if (exists($returnhash{$symb}) &&
6525: exists($returnhash{$symb}->{$param}) &&
6526: $returnhash{$symb}->{'v.'.$param} > $v);
6527: $returnhash{$symb}->{$param}=$value;
6528: $returnhash{$symb}->{'v.'.$param}=$v;
6529: }
6530: #
6531: # Remove all of the keys in the hashes which keep track of
6532: # the version of the parameter.
6533: while (my ($symb,$param_hash) = each(%returnhash)) {
6534: # use a foreach because we are going to delete from the hash.
6535: foreach my $key (keys(%$param_hash)) {
6536: delete($param_hash->{$key}) if ($key =~ /^v\./);
6537: }
6538: }
6539: return \%returnhash;
6540: }
6541:
6542: # ------------------------------------------------------ critical inc interface
6543:
6544: sub cinc {
6545: return &inc(@_,'critical');
6546: }
6547:
6548: # --------------------------------------------------------------- inc interface
6549:
6550: sub inc {
6551: my ($namespace,$store,$udomain,$uname,$critical) = @_;
6552: if (!$udomain) { $udomain=$env{'user.domain'}; }
6553: if (!$uname) { $uname=$env{'user.name'}; }
6554: my $uhome=&homeserver($uname,$udomain);
6555: my $items='';
6556: if (! ref($store)) {
6557: # got a single value, so use that instead
6558: $items = &escape($store).'=&';
6559: } elsif (ref($store) eq 'SCALAR') {
6560: $items = &escape($$store).'=&';
6561: } elsif (ref($store) eq 'ARRAY') {
6562: $items = join('=&',map {&escape($_);} @{$store});
6563: } elsif (ref($store) eq 'HASH') {
6564: while (my($key,$value) = each(%{$store})) {
6565: $items.= &escape($key).'='.&escape($value).'&';
6566: }
6567: }
6568: $items=~s/\&$//;
6569: if ($critical) {
6570: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
6571: } else {
6572: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
6573: }
6574: }
6575:
6576: # --------------------------------------------------------------- put interface
6577:
6578: sub put {
6579: my ($namespace,$storehash,$udomain,$uname)=@_;
6580: if (!$udomain) { $udomain=$env{'user.domain'}; }
6581: if (!$uname) { $uname=$env{'user.name'}; }
6582: my $uhome=&homeserver($uname,$udomain);
6583: my $items='';
6584: foreach my $item (keys(%$storehash)) {
6585: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
6586: }
6587: $items=~s/\&$//;
6588: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
6589: }
6590:
6591: # ------------------------------------------------------------ newput interface
6592:
6593: sub newput {
6594: my ($namespace,$storehash,$udomain,$uname)=@_;
6595: if (!$udomain) { $udomain=$env{'user.domain'}; }
6596: if (!$uname) { $uname=$env{'user.name'}; }
6597: my $uhome=&homeserver($uname,$udomain);
6598: my $items='';
6599: foreach my $key (keys(%$storehash)) {
6600: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6601: }
6602: $items=~s/\&$//;
6603: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
6604: }
6605:
6606: # --------------------------------------------------------- putstore interface
6607:
6608: sub putstore {
6609: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
6610: if (!$udomain) { $udomain=$env{'user.domain'}; }
6611: if (!$uname) { $uname=$env{'user.name'}; }
6612: my $uhome=&homeserver($uname,$udomain);
6613: my $items='';
6614: foreach my $key (keys(%$storehash)) {
6615: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6616: }
6617: $items=~s/\&$//;
6618: my $esc_symb=&escape($symb);
6619: my $esc_v=&escape($version);
6620: my $reply =
6621: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
6622: $uhome);
6623: if (($tolog) && ($reply eq 'ok')) {
6624: my $namevalue='';
6625: foreach my $key (keys(%{$storehash})) {
6626: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6627: }
6628: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
6629: '&host='.&escape($perlvar{'lonHostID'}).
6630: '&version='.$esc_v.
6631: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
6632: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
6633: }
6634: if ($reply eq 'unknown_cmd') {
6635: # gfall back to way things use to be done
6636: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
6637: $uname);
6638: }
6639: return $reply;
6640: }
6641:
6642: sub old_putstore {
6643: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
6644: if (!$udomain) { $udomain=$env{'user.domain'}; }
6645: if (!$uname) { $uname=$env{'user.name'}; }
6646: my $uhome=&homeserver($uname,$udomain);
6647: my %newstorehash;
6648: foreach my $item (keys(%$storehash)) {
6649: my $key = $version.':'.&escape($symb).':'.$item;
6650: $newstorehash{$key} = $storehash->{$item};
6651: }
6652: my $items='';
6653: my %allitems = ();
6654: foreach my $item (keys(%newstorehash)) {
6655: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
6656: my $key = $1.':keys:'.$2;
6657: $allitems{$key} .= $3.':';
6658: }
6659: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
6660: }
6661: foreach my $item (keys(%allitems)) {
6662: $allitems{$item} =~ s/\:$//;
6663: $items.= $item.'='.$allitems{$item}.'&';
6664: }
6665: $items=~s/\&$//;
6666: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
6667: }
6668:
6669: # ------------------------------------------------------ critical put interface
6670:
6671: sub cput {
6672: my ($namespace,$storehash,$udomain,$uname)=@_;
6673: if (!$udomain) { $udomain=$env{'user.domain'}; }
6674: if (!$uname) { $uname=$env{'user.name'}; }
6675: my $uhome=&homeserver($uname,$udomain);
6676: my $items='';
6677: foreach my $item (keys(%$storehash)) {
6678: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
6679: }
6680: $items=~s/\&$//;
6681: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
6682: }
6683:
6684: # -------------------------------------------------------------- eget interface
6685:
6686: sub eget {
6687: my ($namespace,$storearr,$udomain,$uname)=@_;
6688: my $items='';
6689: foreach my $item (@$storearr) {
6690: $items.=&escape($item).'&';
6691: }
6692: $items=~s/\&$//;
6693: if (!$udomain) { $udomain=$env{'user.domain'}; }
6694: if (!$uname) { $uname=$env{'user.name'}; }
6695: my $uhome=&homeserver($uname,$udomain);
6696: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
6697: my @pairs=split(/\&/,$rep);
6698: my %returnhash=();
6699: my $i=0;
6700: foreach my $item (@$storearr) {
6701: $returnhash{$item}=&thaw_unescape($pairs[$i]);
6702: $i++;
6703: }
6704: return %returnhash;
6705: }
6706:
6707: # ------------------------------------------------------------ tmpput interface
6708: sub tmpput {
6709: my ($storehash,$server,$context)=@_;
6710: my $items='';
6711: foreach my $item (keys(%$storehash)) {
6712: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
6713: }
6714: $items=~s/\&$//;
6715: if (defined($context)) {
6716: $items .= ':'.&escape($context);
6717: }
6718: return &reply("tmpput:$items",$server);
6719: }
6720:
6721: # ------------------------------------------------------------ tmpget interface
6722: sub tmpget {
6723: my ($token,$server)=@_;
6724: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6725: my $rep=&reply("tmpget:$token",$server);
6726: my %returnhash;
6727: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
6728: return %returnhash;
6729: }
6730: foreach my $item (split(/\&/,$rep)) {
6731: my ($key,$value)=split(/=/,$item);
6732: $returnhash{&unescape($key)}=&thaw_unescape($value);
6733: }
6734: return %returnhash;
6735: }
6736:
6737: # ------------------------------------------------------------ tmpdel interface
6738: sub tmpdel {
6739: my ($token,$server)=@_;
6740: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6741: return &reply("tmpdel:$token",$server);
6742: }
6743:
6744: # ------------------------------------------------------------ get_timebased_id
6745:
6746: sub get_timebased_id {
6747: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6748: $maxtries) = @_;
6749: my ($newid,$error,$dellock);
6750: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6751: return ('','ok','invalid call to get suffix');
6752: }
6753:
6754: # set defaults for any optional args for which values were not supplied
6755: if ($who eq '') {
6756: $who = $env{'user.name'}.':'.$env{'user.domain'};
6757: }
6758: if (!$locktries) {
6759: $locktries = 3;
6760: }
6761: if (!$maxtries) {
6762: $maxtries = 10;
6763: }
6764:
6765: if (($cdom eq '') || ($cnum eq '')) {
6766: if ($env{'request.course.id'}) {
6767: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6768: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6769: }
6770: if (($cdom eq '') || ($cnum eq '')) {
6771: return ('','ok','call to get suffix not in course context');
6772: }
6773: }
6774:
6775: # construct locking item
6776: my $lockhash = {
6777: $prefix."\0".'locked_'.$keyid => $who,
6778: };
6779: my $tries = 0;
6780:
6781: # attempt to get lock on nohist_$namespace file
6782: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6783: while (($gotlock ne 'ok') && $tries <$locktries) {
6784: $tries ++;
6785: sleep 1;
6786: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6787: }
6788:
6789: # attempt to get unique identifier, based on current timestamp
6790: if ($gotlock eq 'ok') {
6791: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6792: my $id = time;
6793: $newid = $id;
6794: if ($idtype eq 'addcode') {
6795: $newid .= &sixnum_code();
6796: }
6797: my $idtries = 0;
6798: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6799: if ($idtype eq 'concat') {
6800: $newid = $id.$idtries;
6801: } elsif ($idtype eq 'addcode') {
6802: $newid = $newid.&sixnum_code();
6803: } else {
6804: $newid ++;
6805: }
6806: $idtries ++;
6807: }
6808: if (!exists($inuse{$prefix."\0".$newid})) {
6809: my %new_item = (
6810: $prefix."\0".$newid => $who,
6811: );
6812: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6813: $cdom,$cnum);
6814: if ($putresult ne 'ok') {
6815: undef($newid);
6816: $error = 'error saving new item: '.$putresult;
6817: }
6818: } else {
6819: undef($newid);
6820: $error = ('error: no unique suffix available for the new item ');
6821: }
6822: # remove lock
6823: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6824: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6825: } else {
6826: $error = "error: could not obtain lockfile\n";
6827: $dellock = 'ok';
6828: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6829: $dellock = 'nolock';
6830: }
6831: }
6832: return ($newid,$dellock,$error);
6833: }
6834:
6835: sub sixnum_code {
6836: my $code;
6837: for (0..6) {
6838: $code .= int( rand(9) );
6839: }
6840: return $code;
6841: }
6842:
6843: # -------------------------------------------------- portfolio access checking
6844:
6845: sub portfolio_access {
6846: my ($requrl,$clientip) = @_;
6847: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
6848: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
6849: if ($result) {
6850: my %setters;
6851: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6852: my ($startblock,$endblock) =
6853: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6854: if ($startblock && $endblock) {
6855: return 'B';
6856: }
6857: } else {
6858: my ($startblock,$endblock) =
6859: &Apache::loncommon::blockcheck(\%setters,'port');
6860: if ($startblock && $endblock) {
6861: return 'B';
6862: }
6863: }
6864: }
6865: if ($result eq 'ok') {
6866: return 'F';
6867: } elsif ($result =~ /^[^:]+:guest_/) {
6868: return 'A';
6869: }
6870: return '';
6871: }
6872:
6873: sub get_portfolio_access {
6874: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
6875:
6876: if (!ref($access_hash)) {
6877: my $current_perms = &get_portfile_permissions($udom,$unum);
6878: my %access_controls = &get_access_controls($current_perms,$group,
6879: $file_name);
6880: $access_hash = $access_controls{$file_name};
6881: }
6882:
6883: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
6884: my $now = time;
6885: if (ref($access_hash) eq 'HASH') {
6886: foreach my $key (keys(%{$access_hash})) {
6887: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6888: if ($start > $now) {
6889: next;
6890: }
6891: if ($end && $end<$now) {
6892: next;
6893: }
6894: if ($scope eq 'public') {
6895: $public = $key;
6896: last;
6897: } elsif ($scope eq 'guest') {
6898: $guest = $key;
6899: } elsif ($scope eq 'domains') {
6900: push(@domains,$key);
6901: } elsif ($scope eq 'users') {
6902: push(@users,$key);
6903: } elsif ($scope eq 'course') {
6904: push(@courses,$key);
6905: } elsif ($scope eq 'group') {
6906: push(@groups,$key);
6907: } elsif ($scope eq 'ip') {
6908: push(@ips,$key);
6909: }
6910: }
6911: if ($public) {
6912: return 'ok';
6913: } elsif (@ips > 0) {
6914: my $allowed;
6915: foreach my $ipkey (@ips) {
6916: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6917: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6918: $allowed = 1;
6919: last;
6920: }
6921: }
6922: }
6923: if ($allowed) {
6924: return 'ok';
6925: }
6926: }
6927: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6928: if ($guest) {
6929: return $guest;
6930: }
6931: } else {
6932: if (@domains > 0) {
6933: foreach my $domkey (@domains) {
6934: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6935: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6936: return 'ok';
6937: }
6938: }
6939: }
6940: }
6941: if (@users > 0) {
6942: foreach my $userkey (@users) {
6943: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6944: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6945: if (ref($item) eq 'HASH') {
6946: if (($item->{'uname'} eq $env{'user.name'}) &&
6947: ($item->{'udom'} eq $env{'user.domain'})) {
6948: return 'ok';
6949: }
6950: }
6951: }
6952: }
6953: }
6954: }
6955: my %roleshash;
6956: my @courses_and_groups = @courses;
6957: push(@courses_and_groups,@groups);
6958: if (@courses_and_groups > 0) {
6959: my (%allgroups,%allroles);
6960: my ($start,$end,$role,$sec,$group);
6961: foreach my $envkey (%env) {
6962: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
6963: my $cid = $2.'_'.$3;
6964: if ($1 eq 'gr') {
6965: $group = $4;
6966: $allgroups{$cid}{$group} = $env{$envkey};
6967: } else {
6968: if ($4 eq '') {
6969: $sec = 'none';
6970: } else {
6971: $sec = $4;
6972: }
6973: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6974: }
6975: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
6976: my $cid = $2.'_'.$3;
6977: if ($4 eq '') {
6978: $sec = 'none';
6979: } else {
6980: $sec = $4;
6981: }
6982: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6983: }
6984: }
6985: if (keys(%allroles) == 0) {
6986: return;
6987: }
6988: foreach my $key (@courses_and_groups) {
6989: my %content = %{$$access_hash{$key}};
6990: my $cnum = $content{'number'};
6991: my $cdom = $content{'domain'};
6992: my $cid = $cdom.'_'.$cnum;
6993: if (!exists($allroles{$cid})) {
6994: next;
6995: }
6996: foreach my $role_id (keys(%{$content{'roles'}})) {
6997: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6998: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6999: my @status = @{$content{'roles'}{$role_id}{'access'}};
7000: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7001: foreach my $role (keys(%{$allroles{$cid}})) {
7002: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7003: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7004: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7005: if (grep/^all$/,@sections) {
7006: return 'ok';
7007: } else {
7008: if (grep/^$sec$/,@sections) {
7009: return 'ok';
7010: }
7011: }
7012: }
7013: }
7014: if (keys(%{$allgroups{$cid}}) == 0) {
7015: if (grep/^none$/,@groups) {
7016: return 'ok';
7017: }
7018: } else {
7019: if (grep/^all$/,@groups) {
7020: return 'ok';
7021: }
7022: foreach my $group (keys(%{$allgroups{$cid}})) {
7023: if (grep/^$group$/,@groups) {
7024: return 'ok';
7025: }
7026: }
7027: }
7028: }
7029: }
7030: }
7031: }
7032: }
7033: if ($guest) {
7034: return $guest;
7035: }
7036: }
7037: }
7038: return;
7039: }
7040:
7041: sub course_group_datechecker {
7042: my ($dates,$now,$status) = @_;
7043: my ($start,$end) = split(/\./,$dates);
7044: if (!$start && !$end) {
7045: return 'ok';
7046: }
7047: if (grep/^active$/,@{$status}) {
7048: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7049: return 'ok';
7050: }
7051: }
7052: if (grep/^previous$/,@{$status}) {
7053: if ($end > $now ) {
7054: return 'ok';
7055: }
7056: }
7057: if (grep/^future$/,@{$status}) {
7058: if ($start > $now) {
7059: return 'ok';
7060: }
7061: }
7062: return;
7063: }
7064:
7065: sub parse_portfolio_url {
7066: my ($url) = @_;
7067:
7068: my ($type,$udom,$unum,$group,$file_name);
7069:
7070: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
7071: $type = 1;
7072: $udom = $1;
7073: $unum = $2;
7074: $file_name = $3;
7075: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
7076: $type = 2;
7077: $udom = $1;
7078: $unum = $2;
7079: $group = $3;
7080: $file_name = $3.'/'.$4;
7081: }
7082: if (wantarray) {
7083: return ($type,$udom,$unum,$file_name,$group);
7084: }
7085: return $type;
7086: }
7087:
7088: sub is_portfolio_url {
7089: my ($url) = @_;
7090: return scalar(&parse_portfolio_url($url));
7091: }
7092:
7093: sub is_portfolio_file {
7094: my ($file) = @_;
7095: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
7096: return 1;
7097: }
7098: return;
7099: }
7100:
7101: sub usertools_access {
7102: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
7103: my ($access,%tools);
7104: if ($context eq '') {
7105: $context = 'tools';
7106: }
7107: if ($context eq 'requestcourses') {
7108: %tools = (
7109: official => 1,
7110: unofficial => 1,
7111: community => 1,
7112: textbook => 1,
7113: placement => 1,
7114: );
7115: } elsif ($context eq 'requestauthor') {
7116: %tools = (
7117: requestauthor => 1,
7118: );
7119: } else {
7120: %tools = (
7121: aboutme => 1,
7122: blog => 1,
7123: webdav => 1,
7124: portfolio => 1,
7125: );
7126: }
7127: return if (!defined($tools{$tool}));
7128:
7129: if (($udom eq '') || ($uname eq '')) {
7130: $udom = $env{'user.domain'};
7131: $uname = $env{'user.name'};
7132: }
7133:
7134: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7135: if ($action ne 'reload') {
7136: if ($context eq 'requestcourses') {
7137: return $env{'environment.canrequest.'.$tool};
7138: } elsif ($context eq 'requestauthor') {
7139: return $env{'environment.canrequest.author'};
7140: } else {
7141: return $env{'environment.availabletools.'.$tool};
7142: }
7143: }
7144: }
7145:
7146: my ($toolstatus,$inststatus,$envkey);
7147: if ($context eq 'requestauthor') {
7148: $envkey = $context;
7149: } else {
7150: $envkey = $context.'.'.$tool;
7151: }
7152:
7153: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7154: ($action ne 'reload')) {
7155: $toolstatus = $env{'environment.'.$envkey};
7156: $inststatus = $env{'environment.inststatus'};
7157: } else {
7158: if (ref($userenvref) eq 'HASH') {
7159: $toolstatus = $userenvref->{$envkey};
7160: $inststatus = $userenvref->{'inststatus'};
7161: } else {
7162: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7163: $toolstatus = $userenv{$envkey};
7164: $inststatus = $userenv{'inststatus'};
7165: }
7166: }
7167:
7168: if ($toolstatus ne '') {
7169: if ($toolstatus) {
7170: $access = 1;
7171: } else {
7172: $access = 0;
7173: }
7174: return $access;
7175: }
7176:
7177: my ($is_adv,%domdef);
7178: if (ref($is_advref) eq 'HASH') {
7179: $is_adv = $is_advref->{'is_adv'};
7180: } else {
7181: $is_adv = &is_advanced_user($udom,$uname);
7182: }
7183: if (ref($domdefref) eq 'HASH') {
7184: %domdef = %{$domdefref};
7185: } else {
7186: %domdef = &get_domain_defaults($udom);
7187: }
7188: if (ref($domdef{$tool}) eq 'HASH') {
7189: if ($is_adv) {
7190: if ($domdef{$tool}{'_LC_adv'} ne '') {
7191: if ($domdef{$tool}{'_LC_adv'}) {
7192: $access = 1;
7193: } else {
7194: $access = 0;
7195: }
7196: return $access;
7197: }
7198: }
7199: if ($inststatus ne '') {
7200: my ($hasaccess,$hasnoaccess);
7201: foreach my $affiliation (split(/:/,$inststatus)) {
7202: if ($domdef{$tool}{$affiliation} ne '') {
7203: if ($domdef{$tool}{$affiliation}) {
7204: $hasaccess = 1;
7205: } else {
7206: $hasnoaccess = 1;
7207: }
7208: }
7209: }
7210: if ($hasaccess || $hasnoaccess) {
7211: if ($hasaccess) {
7212: $access = 1;
7213: } elsif ($hasnoaccess) {
7214: $access = 0;
7215: }
7216: return $access;
7217: }
7218: } else {
7219: if ($domdef{$tool}{'default'} ne '') {
7220: if ($domdef{$tool}{'default'}) {
7221: $access = 1;
7222: } elsif ($domdef{$tool}{'default'} == 0) {
7223: $access = 0;
7224: }
7225: return $access;
7226: }
7227: }
7228: } else {
7229: if (($context eq 'tools') && ($tool ne 'webdav')) {
7230: $access = 1;
7231: } else {
7232: $access = 0;
7233: }
7234: return $access;
7235: }
7236: }
7237:
7238: sub is_course_owner {
7239: my ($cdom,$cnum,$udom,$uname) = @_;
7240: if (($udom eq '') || ($uname eq '')) {
7241: $udom = $env{'user.domain'};
7242: $uname = $env{'user.name'};
7243: }
7244: unless (($udom eq '') || ($uname eq '')) {
7245: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7246: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7247: return 1;
7248: } else {
7249: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7250: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7251: return 1;
7252: }
7253: }
7254: }
7255: }
7256: return;
7257: }
7258:
7259: sub is_advanced_user {
7260: my ($udom,$uname) = @_;
7261: if ($udom ne '' && $uname ne '') {
7262: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7263: if (wantarray) {
7264: return ($env{'user.adv'},$env{'user.author'});
7265: } else {
7266: return $env{'user.adv'};
7267: }
7268: }
7269: }
7270: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7271: my %allroles;
7272: my ($is_adv,$is_author);
7273: foreach my $role (keys(%roleshash)) {
7274: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7275: my $area = '/'.$tdomain.'/'.$trest;
7276: if ($sec ne '') {
7277: $area .= '/'.$sec;
7278: }
7279: if (($area ne '') && ($trole ne '')) {
7280: my $spec=$trole.'.'.$area;
7281: if ($trole =~ /^cr\//) {
7282: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7283: } elsif ($trole ne 'gr') {
7284: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7285: }
7286: if ($trole eq 'au') {
7287: $is_author = 1;
7288: }
7289: }
7290: }
7291: foreach my $role (keys(%allroles)) {
7292: last if ($is_adv);
7293: foreach my $item (split(/:/,$allroles{$role})) {
7294: if ($item ne '') {
7295: my ($privilege,$restrictions)=split(/&/,$item);
7296: if ($privilege eq 'adv') {
7297: $is_adv = 1;
7298: last;
7299: }
7300: }
7301: }
7302: }
7303: if (wantarray) {
7304: return ($is_adv,$is_author);
7305: }
7306: return $is_adv;
7307: }
7308:
7309: sub check_can_request {
7310: my ($dom,$can_request,$request_domains) = @_;
7311: my $canreq = 0;
7312: my ($types,$typename) = &Apache::loncommon::course_types();
7313: my @options = ('approval','validate','autolimit');
7314: my $optregex = join('|',@options);
7315: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7316: foreach my $type (@{$types}) {
7317: if (&usertools_access($env{'user.name'},
7318: $env{'user.domain'},
7319: $type,undef,'requestcourses')) {
7320: $canreq ++;
7321: if (ref($request_domains) eq 'HASH') {
7322: push(@{$request_domains->{$type}},$env{'user.domain'});
7323: }
7324: if ($dom eq $env{'user.domain'}) {
7325: $can_request->{$type} = 1;
7326: }
7327: }
7328: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
7329: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7330: if (@curr > 0) {
7331: foreach my $item (@curr) {
7332: if (ref($request_domains) eq 'HASH') {
7333: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7334: if ($otherdom ne '') {
7335: if (ref($request_domains->{$type}) eq 'ARRAY') {
7336: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7337: push(@{$request_domains->{$type}},$otherdom);
7338: }
7339: } else {
7340: push(@{$request_domains->{$type}},$otherdom);
7341: }
7342: }
7343: }
7344: }
7345: unless($dom eq $env{'user.domain'}) {
7346: $canreq ++;
7347: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7348: $can_request->{$type} = 1;
7349: }
7350: }
7351: }
7352: }
7353: }
7354: }
7355: return $canreq;
7356: }
7357:
7358: # ---------------------------------------------- Custom access rule evaluation
7359:
7360: sub customaccess {
7361: my ($priv,$uri)=@_;
7362: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
7363: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
7364: $udom = &LONCAPA::clean_domain($udom);
7365: $ucrs = &LONCAPA::clean_username($ucrs);
7366: my $access=0;
7367: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
7368: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7369: if ($type eq 'user') {
7370: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7371: my ($tdom,$tuname)=split(m{/},$scope);
7372: if ($tdom) {
7373: if ($tdom ne $env{'user.domain'}) { next; }
7374: }
7375: if ($tuname) {
7376: if ($tuname ne $env{'user.name'}) { next; }
7377: }
7378: $access=($effect eq 'allow');
7379: last;
7380: }
7381: } else {
7382: if ($role) {
7383: if ($role ne $urole) { next; }
7384: }
7385: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7386: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7387: if ($tdom) {
7388: if ($tdom ne $udom) { next; }
7389: }
7390: if ($tcrs) {
7391: if ($tcrs ne $ucrs) { next; }
7392: }
7393: if ($tsec) {
7394: if ($tsec ne $usec) { next; }
7395: }
7396: $access=($effect eq 'allow');
7397: last;
7398: }
7399: if ($realm eq '' && $role eq '') {
7400: $access=($effect eq 'allow');
7401: }
7402: }
7403: }
7404: return $access;
7405: }
7406:
7407: # ------------------------------------------------- Check for a user privilege
7408:
7409: sub allowed {
7410: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
7411: my $ver_orguri=$uri;
7412: $uri=&deversion($uri);
7413: my $orguri=$uri;
7414: $uri=&declutter($uri);
7415:
7416: if ($priv eq 'evb') {
7417: # Evade communication block restrictions for specified role in a course
7418: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7419: return $1;
7420: } else {
7421: return;
7422: }
7423: }
7424:
7425: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
7426: # Free bre access to adm and meta resources
7427: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$}))
7428: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7429: && ($priv eq 'bre')) {
7430: return 'F';
7431: }
7432:
7433: # Free bre access to user's own portfolio contents
7434: my ($space,$domain,$name,@dir)=split('/',$uri);
7435: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
7436: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
7437: my %setters;
7438: my ($startblock,$endblock) =
7439: &Apache::loncommon::blockcheck(\%setters,'port');
7440: if ($startblock && $endblock) {
7441: return 'B';
7442: } else {
7443: return 'F';
7444: }
7445: }
7446:
7447: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
7448: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7449: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7450: if (exists($env{'request.course.id'})) {
7451: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7452: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7453: if (($domain eq $cdom) && ($name eq $cnum)) {
7454: my $courseprivid=$env{'request.course.id'};
7455: $courseprivid=~s/\_/\//;
7456: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7457: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7458: return $1;
7459: } else {
7460: if ($env{'request.course.sec'}) {
7461: $courseprivid.='/'.$env{'request.course.sec'};
7462: }
7463: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7464: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7465: return $2;
7466: }
7467: }
7468: }
7469: }
7470: }
7471:
7472: # Free bre to public access
7473:
7474: if ($priv eq 'bre') {
7475: my $copyright=&metadata($uri,'copyright');
7476: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
7477: return 'F';
7478: }
7479: if ($copyright eq 'priv') {
7480: $uri=~/([^\/]+)\/([^\/]+)\//;
7481: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
7482: return '';
7483: }
7484: }
7485: if ($copyright eq 'domain') {
7486: $uri=~/([^\/]+)\/([^\/]+)\//;
7487: unless (($env{'user.domain'} eq $1) ||
7488: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
7489: return '';
7490: }
7491: }
7492: if ($env{'request.role'}=~ /li\.\//) {
7493: # Library role, so allow browsing of resources in this domain.
7494: return 'F';
7495: }
7496: if ($copyright eq 'custom') {
7497: unless (&customaccess($priv,$uri)) { return ''; }
7498: }
7499: }
7500: # Domain coordinator is trying to create a course
7501: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
7502: # uri is the requested domain in this case.
7503: # comparison to 'request.role.domain' shows if the user has selected
7504: # a role of dc for the domain in question.
7505: return 'F' if ($uri eq $env{'request.role.domain'});
7506: }
7507:
7508: my $thisallowed='';
7509: my $statecond=0;
7510: my $courseprivid='';
7511:
7512: my $ownaccess;
7513: # Community Coordinator or Assistant Co-author browsing resource space.
7514: if (($priv eq 'bro') && ($env{'user.author'})) {
7515: if ($uri eq '') {
7516: $ownaccess = 1;
7517: } else {
7518: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
7519: my $udom = $env{'user.domain'};
7520: my $uname = $env{'user.name'};
7521: if ($uri =~ m{^\Q$udom\E/?$}) {
7522: $ownaccess = 1;
7523: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
7524: unless ($uri =~ m{\.\./}) {
7525: $ownaccess = 1;
7526: }
7527: } elsif (($udom ne 'public') && ($uname ne 'public')) {
7528: my $now = time;
7529: if ($uri =~ m{^([^/]+)/?$}) {
7530: my $adom = $1;
7531: foreach my $key (keys(%env)) {
7532: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
7533: my ($start,$end) = split('.',$env{$key});
7534: if (($now >= $start) && (!$end || $end < $now)) {
7535: $ownaccess = 1;
7536: last;
7537: }
7538: }
7539: }
7540: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
7541: my $adom = $1;
7542: my $aname = $2;
7543: foreach my $role ('ca','aa') {
7544: if ($env{"user.role.$role./$adom/$aname"}) {
7545: my ($start,$end) =
7546: split('.',$env{"user.role.$role./$adom/$aname"});
7547: if (($now >= $start) && (!$end || $end < $now)) {
7548: $ownaccess = 1;
7549: last;
7550: }
7551: }
7552: }
7553: }
7554: }
7555: }
7556: }
7557: }
7558:
7559: # Course
7560:
7561: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
7562: unless (($priv eq 'bro') && (!$ownaccess)) {
7563: $thisallowed.=$1;
7564: }
7565: }
7566:
7567: # Domain
7568:
7569: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
7570: =~/\Q$priv\E\&([^\:]*)/) {
7571: unless (($priv eq 'bro') && (!$ownaccess)) {
7572: $thisallowed.=$1;
7573: }
7574: }
7575:
7576: # User who is not author or co-author might still be able to edit
7577: # resource of an author in the domain (e.g., if Domain Coordinator).
7578: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
7579: (&allowed('mdc',$env{'request.course.id'}))) {
7580: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
7581: $thisallowed.=$1;
7582: }
7583: }
7584:
7585: # Course: uri itself is a course
7586: my $courseuri=$uri;
7587: $courseuri=~s/\_(\d)/\/$1/;
7588: $courseuri=~s/^([^\/])/\/$1/;
7589:
7590: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
7591: =~/\Q$priv\E\&([^\:]*)/) {
7592: unless (($priv eq 'bro') && (!$ownaccess)) {
7593: $thisallowed.=$1;
7594: }
7595: }
7596:
7597: # URI is an uploaded document for this course, default permissions don't matter
7598: # not allowing 'edit' access (editupload) to uploaded course docs
7599: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
7600: $thisallowed='';
7601: my ($match)=&is_on_map($uri);
7602: if ($match) {
7603: if ($env{'user.priv.'.$env{'request.role'}.'./'}
7604: =~/\Q$priv\E\&([^\:]*)/) {
7605: my $value = $1;
7606: if ($noblockcheck) {
7607: $thisallowed.=$value;
7608: } else {
7609: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7610: if (@blockers > 0) {
7611: $thisallowed = 'B';
7612: } else {
7613: $thisallowed.=$value;
7614: }
7615: }
7616: }
7617: } else {
7618: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
7619: if ($refuri) {
7620: if ($refuri =~ m|^/adm/|) {
7621: $thisallowed='F';
7622: } else {
7623: $refuri=&declutter($refuri);
7624: my ($match) = &is_on_map($refuri);
7625: if ($match) {
7626: if ($noblockcheck) {
7627: $thisallowed='F';
7628: } else {
7629: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7630: if (@blockers > 0) {
7631: $thisallowed = 'B';
7632: } else {
7633: $thisallowed='F';
7634: }
7635: }
7636: }
7637: }
7638: }
7639: }
7640: }
7641:
7642: if ($priv eq 'bre'
7643: && $thisallowed ne 'F'
7644: && $thisallowed ne '2'
7645: && &is_portfolio_url($uri)) {
7646: $thisallowed = &portfolio_access($uri,$clientip);
7647: }
7648:
7649: # Full access at system, domain or course-wide level? Exit.
7650: if ($thisallowed=~/F/) {
7651: return 'F';
7652: }
7653:
7654: # If this is generating or modifying users, exit with special codes
7655:
7656: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
7657: if (($priv eq 'cca') || ($priv eq 'caa')) {
7658: my ($audom,$auname)=split('/',$uri);
7659: # no author name given, so this just checks on the general right to make a co-author in this domain
7660: unless ($auname) { return $thisallowed; }
7661: # an author name is given, so we are about to actually make a co-author for a certain account
7662: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
7663: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
7664: ($audom ne $env{'request.role.domain'}))) { return ''; }
7665: }
7666: return $thisallowed;
7667: }
7668: #
7669: # Gathered so far: system, domain and course wide privileges
7670: #
7671: # Course: See if uri or referer is an individual resource that is part of
7672: # the course
7673:
7674: if ($env{'request.course.id'}) {
7675:
7676: $courseprivid=$env{'request.course.id'};
7677: if ($env{'request.course.sec'}) {
7678: $courseprivid.='/'.$env{'request.course.sec'};
7679: }
7680: $courseprivid=~s/\_/\//;
7681: my $checkreferer=1;
7682: my ($match,$cond)=&is_on_map($uri);
7683: if ($match) {
7684: $statecond=$cond;
7685: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
7686: =~/\Q$priv\E\&([^\:]*)/) {
7687: my $value = $1;
7688: if ($priv eq 'bre') {
7689: if ($noblockcheck) {
7690: $thisallowed.=$value;
7691: } else {
7692: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7693: if (@blockers > 0) {
7694: $thisallowed = 'B';
7695: } else {
7696: $thisallowed.=$value;
7697: }
7698: }
7699: } else {
7700: $thisallowed.=$value;
7701: }
7702: $checkreferer=0;
7703: }
7704: }
7705:
7706: if ($checkreferer) {
7707: my $refuri=$env{'httpref.'.$orguri};
7708: unless ($refuri) {
7709: foreach my $key (keys(%env)) {
7710: if ($key=~/^httpref\..*\*/) {
7711: my $pattern=$key;
7712: $pattern=~s/^httpref\.\/res\///;
7713: $pattern=~s/\*/\[\^\/\]\+/g;
7714: $pattern=~s/\//\\\//g;
7715: if ($orguri=~/$pattern/) {
7716: $refuri=$env{$key};
7717: }
7718: }
7719: }
7720: }
7721:
7722: if ($refuri) {
7723: $refuri=&declutter($refuri);
7724: my ($match,$cond)=&is_on_map($refuri);
7725: if ($match) {
7726: my $refstatecond=$cond;
7727: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
7728: =~/\Q$priv\E\&([^\:]*)/) {
7729: my $value = $1;
7730: if ($priv eq 'bre') {
7731: if ($noblockcheck) {
7732: $thisallowed.=$value;
7733: } else {
7734: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7735: if (@blockers > 0) {
7736: $thisallowed = 'B';
7737: } else {
7738: $thisallowed.=$value;
7739: }
7740: }
7741: } else {
7742: $thisallowed.=$value;
7743: }
7744: $uri=$refuri;
7745: $statecond=$refstatecond;
7746: }
7747: }
7748: }
7749: }
7750: }
7751:
7752: #
7753: # Gathered now: all privileges that could apply, and condition number
7754: #
7755: #
7756: # Full or no access?
7757: #
7758:
7759: if ($thisallowed=~/F/) {
7760: return 'F';
7761: }
7762:
7763: unless ($thisallowed) {
7764: return '';
7765: }
7766:
7767: # Restrictions exist, deal with them
7768: #
7769: # C:according to course preferences
7770: # R:according to resource settings
7771: # L:unless locked
7772: # X:according to user session state
7773: #
7774:
7775: # Possibly locked functionality, check all courses
7776: # Locks might take effect only after 10 minutes cache expiration for other
7777: # courses, and 2 minutes for current course
7778:
7779: my $envkey;
7780: if ($thisallowed=~/L/) {
7781: foreach $envkey (keys(%env)) {
7782: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7783: my $courseid=$2;
7784: my $roleid=$1.'.'.$2;
7785: $courseid=~s/^\///;
7786: my $expiretime=600;
7787: if ($env{'request.role'} eq $roleid) {
7788: $expiretime=120;
7789: }
7790: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7791: my $prefix='course.'.$cdom.'_'.$cnum.'.';
7792: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
7793: &coursedescription($courseid,{'freshen_cache' => 1});
7794: }
7795: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7796: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7797: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7798: &log($env{'user.domain'},$env{'user.name'},
7799: $env{'user.home'},
7800: 'Locked by res: '.$priv.' for '.$uri.' due to '.
7801: $cdom.'/'.$cnum.'/'.$csec.' expire '.
7802: $env{$prefix.'priv.'.$priv.'.lock.expire'});
7803: return '';
7804: }
7805: }
7806: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7807: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7808: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7809: &log($env{'user.domain'},$env{'user.name'},
7810: $env{'user.home'},
7811: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
7812: $cdom.'/'.$cnum.'/'.$csec.' expire '.
7813: $env{$prefix.'priv.'.$priv.'.lock.expire'});
7814: return '';
7815: }
7816: }
7817: }
7818: }
7819: }
7820:
7821: #
7822: # Rest of the restrictions depend on selected course
7823: #
7824:
7825: unless ($env{'request.course.id'}) {
7826: if ($thisallowed eq 'A') {
7827: return 'A';
7828: } elsif ($thisallowed eq 'B') {
7829: return 'B';
7830: } else {
7831: return '1';
7832: }
7833: }
7834:
7835: #
7836: # Now user is definitely in a course
7837: #
7838:
7839:
7840: # Course preferences
7841:
7842: if ($thisallowed=~/C/) {
7843: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7844: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7845: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
7846: =~/\Q$rolecode\E/) {
7847: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
7848: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7849: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7850: $env{'request.course.id'});
7851: }
7852: return '';
7853: }
7854:
7855: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
7856: =~/\Q$unamedom\E/) {
7857: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
7858: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7859: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7860: $env{'request.course.id'});
7861: }
7862: return '';
7863: }
7864: }
7865:
7866: # Resource preferences
7867:
7868: if ($thisallowed=~/R/) {
7869: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7870: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
7871: if (($priv ne 'pch') && ($priv ne 'plc')) {
7872: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7873: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7874: }
7875: return '';
7876: }
7877: }
7878:
7879: # Restricted by state or randomout?
7880:
7881: if ($thisallowed=~/X/) {
7882: if ($env{'acc.randomout'}) {
7883: if (!$symb) { $symb=&symbread($uri,1); }
7884: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
7885: return '';
7886: }
7887: }
7888: if (&condval($statecond)) {
7889: return '2';
7890: } else {
7891: return '';
7892: }
7893: }
7894:
7895: if ($thisallowed eq 'A') {
7896: return 'A';
7897: } elsif ($thisallowed eq 'B') {
7898: return 'B';
7899: }
7900: return 'F';
7901: }
7902:
7903: # ------------------------------------------- Check construction space access
7904:
7905: sub constructaccess {
7906: my ($url,$setpriv)=@_;
7907:
7908: # We do not allow editing of previous versions of files
7909: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7910:
7911: # Get username and domain from URL
7912: my ($ownername,$ownerdomain,$ownerhome);
7913:
7914: ($ownerdomain,$ownername) =
7915: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
7916:
7917: # The URL does not really point to any authorspace, forget it
7918: unless (($ownername) && ($ownerdomain)) { return ''; }
7919:
7920: # Now we need to see if the user has access to the authorspace of
7921: # $ownername at $ownerdomain
7922:
7923: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7924: # Real author for this?
7925: $ownerhome = $env{'user.home'};
7926: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7927: return ($ownername,$ownerdomain,$ownerhome);
7928: }
7929: } else {
7930: # Co-author for this?
7931: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7932: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7933: $ownerhome = &homeserver($ownername,$ownerdomain);
7934: return ($ownername,$ownerdomain,$ownerhome);
7935: }
7936: if ($env{'request.course.id'}) {
7937: if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
7938: ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
7939: if (&allowed('mdc',$env{'request.course.id'})) {
7940: $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
7941: return ($ownername,$ownerdomain,$ownerhome);
7942: }
7943: }
7944: }
7945: }
7946:
7947: # We don't have any access right now. If we are not possibly going to do anything about this,
7948: # we might as well leave
7949: unless ($setpriv) { return ''; }
7950:
7951: # Backdoor access?
7952: my $allowed=&allowed('eco',$ownerdomain);
7953: # Nope
7954: unless ($allowed) { return ''; }
7955: # Looks like we may have access, but could be locked by the owner of the construction space
7956: if ($allowed eq 'U') {
7957: my %blocked=&get('environment',['domcoord.author'],
7958: $ownerdomain,$ownername);
7959: # Is blocked by owner
7960: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7961: }
7962: if (($allowed eq 'F') || ($allowed eq 'U')) {
7963: # Grant temporary access
7964: my $then=$env{'user.login.time'};
7965: my $update=$env{'user.update.time'};
7966: if (!$update) { $update = $then; }
7967: my $refresh=$env{'user.refresh.time'};
7968: if (!$refresh) { $refresh = $update; }
7969: my $now = time;
7970: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7971: $now,'ca','constructaccess');
7972: $ownerhome = &homeserver($ownername,$ownerdomain);
7973: return($ownername,$ownerdomain,$ownerhome);
7974: }
7975: # No business here
7976: return '';
7977: }
7978:
7979: # ----------------------------------------------------------- Content Blocking
7980:
7981: {
7982: # Caches for faster Course Contents display where content blocking
7983: # is in operation (i.e., interval param set) for timed quiz.
7984: #
7985: # User for whom data are being temporarily cached.
7986: my $cacheduser='';
7987: # Cached blockers for this user (a hash of blocking items).
7988: my %cachedblockers=();
7989: # When the data were last cached.
7990: my $cachedlast='';
7991:
7992: sub load_all_blockers {
7993: my ($uname,$udom,$blocks)=@_;
7994: if (($uname ne '') && ($udom ne '')) {
7995: if (($cacheduser eq $uname.':'.$udom) &&
7996: (abs($cachedlast-time)<5)) {
7997: return;
7998: }
7999: }
8000: $cachedlast=time;
8001: $cacheduser=$uname.':'.$udom;
8002: %cachedblockers = &get_commblock_resources($blocks);
8003: }
8004:
8005: sub get_comm_blocks {
8006: my ($cdom,$cnum) = @_;
8007: if ($cdom eq '' || $cnum eq '') {
8008: return unless ($env{'request.course.id'});
8009: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8010: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8011: }
8012: my %commblocks;
8013: my $hashid=$cdom.'_'.$cnum;
8014: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8015: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8016: %commblocks = %{$blocksref};
8017: } else {
8018: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8019: my $cachetime = 600;
8020: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8021: }
8022: return %commblocks;
8023: }
8024:
8025: sub get_commblock_resources {
8026: my ($blocks) = @_;
8027: my %blockers = ();
8028: return %blockers unless ($env{'request.course.id'});
8029: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
8030: my %commblocks;
8031: if (ref($blocks) eq 'HASH') {
8032: %commblocks = %{$blocks};
8033: } else {
8034: %commblocks = &get_comm_blocks();
8035: }
8036: return %blockers unless (keys(%commblocks) > 0);
8037: my $navmap = Apache::lonnavmaps::navmap->new();
8038: return %blockers unless (ref($navmap));
8039: my $now = time;
8040: foreach my $block (keys(%commblocks)) {
8041: if ($block =~ /^(\d+)____(\d+)$/) {
8042: my ($start,$end) = ($1,$2);
8043: if ($start <= $now && $end >= $now) {
8044: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8045: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8046: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8047: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8048: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8049: }
8050: }
8051: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8052: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8053: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
8054: }
8055: }
8056: }
8057: }
8058: }
8059: } elsif ($block =~ /^firstaccess____(.+)$/) {
8060: my $item = $1;
8061: my @to_test;
8062: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8063: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8064: my @interval;
8065: my $type = 'map';
8066: if ($item eq 'course') {
8067: $type = 'course';
8068: @interval=&EXT("resource.0.interval");
8069: } else {
8070: if ($item =~ /___\d+___/) {
8071: $type = 'resource';
8072: @interval=&EXT("resource.0.interval",$item);
8073: if (ref($navmap)) {
8074: my $res = $navmap->getBySymb($item);
8075: push(@to_test,$res);
8076: }
8077: } else {
8078: my $mapsymb = &symbread($item,1);
8079: if ($mapsymb) {
8080: if (ref($navmap)) {
8081: my $mapres = $navmap->getBySymb($mapsymb);
8082: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
8083: foreach my $res (@to_test) {
8084: my $symb = $res->symb();
8085: next if ($symb eq $mapsymb);
8086: if ($symb ne '') {
8087: @interval=&EXT("resource.0.interval",$symb);
8088: if ($interval[1] eq 'map') {
8089: last;
8090: }
8091: }
8092: }
8093: }
8094: }
8095: }
8096: }
8097: if ($interval[0] =~ /^(\d+)/) {
8098: my $timelimit = $1;
8099: my $first_access;
8100: if ($type eq 'resource') {
8101: $first_access=&get_first_access($interval[1],$item);
8102: } elsif ($type eq 'map') {
8103: $first_access=&get_first_access($interval[1],undef,$item);
8104: } else {
8105: $first_access=&get_first_access($interval[1]);
8106: }
8107: if ($first_access) {
8108: my $timesup = $first_access+$timelimit;
8109: if ($timesup > $now) {
8110: my $activeblock;
8111: foreach my $res (@to_test) {
8112: if ($res->answerable()) {
8113: $activeblock = 1;
8114: last;
8115: }
8116: }
8117: if ($activeblock) {
8118: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8119: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8120: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8121: }
8122: }
8123: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8124: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8125: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
8126: }
8127: }
8128: }
8129: }
8130: }
8131: }
8132: }
8133: }
8134: }
8135: }
8136: return %blockers;
8137: }
8138:
8139: sub has_comm_blocking {
8140: my ($priv,$symb,$uri,$blocks) = @_;
8141: my @blockers;
8142: return unless ($env{'request.course.id'});
8143: return unless ($priv eq 'bre');
8144: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
8145: return if ($env{'request.state'} eq 'construct');
8146: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
8147: return unless (keys(%cachedblockers) > 0);
8148: my (%possibles,@symbs);
8149: if (!$symb) {
8150: $symb = &symbread($uri,1,1,1,\%possibles);
8151: }
8152: if ($symb) {
8153: @symbs = ($symb);
8154: } elsif (keys(%possibles)) {
8155: @symbs = keys(%possibles);
8156: }
8157: my $noblock;
8158: foreach my $symb (@symbs) {
8159: last if ($noblock);
8160: my ($map,$resid,$resurl)=&decode_symb($symb);
8161: foreach my $block (keys(%cachedblockers)) {
8162: if ($block =~ /^firstaccess____(.+)$/) {
8163: my $item = $1;
8164: if (($item eq $map) || ($item eq $symb)) {
8165: $noblock = 1;
8166: last;
8167: }
8168: }
8169: if (ref($cachedblockers{$block}) eq 'HASH') {
8170: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
8171: if ($cachedblockers{$block}{'resources'}{$symb}) {
8172: unless (grep(/^\Q$block\E$/,@blockers)) {
8173: push(@blockers,$block);
8174: }
8175: }
8176: }
8177: }
8178: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
8179: if ($cachedblockers{$block}{'maps'}{$map}) {
8180: unless (grep(/^\Q$block\E$/,@blockers)) {
8181: push(@blockers,$block);
8182: }
8183: }
8184: }
8185: }
8186: }
8187: return if ($noblock);
8188: return @blockers;
8189: }
8190: }
8191:
8192: # -------------------------------- Deversion and split uri into path an filename
8193:
8194: #
8195: # Removes the version from a URI and
8196: # splits it in to its filename and path to the filename.
8197: # Seems like File::Basename could have done this more clearly.
8198: # Parameters:
8199: # $uri - input URI
8200: # Returns:
8201: # Two element list consisting of
8202: # $pathname - the URI up to and excluding the trailing /
8203: # $filename - The part of the URI following the last /
8204: # NOTE:
8205: # Another realization of this is simply:
8206: # use File::Basename;
8207: # ...
8208: # $uri = shift;
8209: # $filename = basename($uri);
8210: # $path = dirname($uri);
8211: # return ($filename, $path);
8212: #
8213: # The implementation below is probably faster however.
8214: #
8215: sub split_uri_for_cond {
8216: my $uri=&deversion(&declutter(shift));
8217: my @uriparts=split(/\//,$uri);
8218: my $filename=pop(@uriparts);
8219: my $pathname=join('/',@uriparts);
8220: return ($pathname,$filename);
8221: }
8222: # --------------------------------------------------- Is a resource on the map?
8223:
8224: sub is_on_map {
8225: my ($pathname,$filename) = &split_uri_for_cond(shift);
8226: #Trying to find the conditional for the file
8227: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
8228: /\&\Q$filename\E\:([\d\|]+)\&/);
8229: if ($match) {
8230: return (1,$1);
8231: } else {
8232: return (0,0);
8233: }
8234: }
8235:
8236: # --------------------------------------------------------- Get symb from alias
8237:
8238: sub get_symb_from_alias {
8239: my $symb=shift;
8240: my ($map,$resid,$url)=&decode_symb($symb);
8241: # Already is a symb
8242: if ($url) { return $symb; }
8243: # Must be an alias
8244: my $aliassymb='';
8245: my %bighash;
8246: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8247: &GDBM_READER(),0640)) {
8248: my $rid=$bighash{'mapalias_'.$symb};
8249: if ($rid) {
8250: my ($mapid,$resid)=split(/\./,$rid);
8251: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8252: $resid,$bighash{'src_'.$rid});
8253: }
8254: untie %bighash;
8255: }
8256: return $aliassymb;
8257: }
8258:
8259: # ----------------------------------------------------------------- Define Role
8260:
8261: sub definerole {
8262: if (allowed('mcr','/')) {
8263: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
8264: foreach my $role (split(':',$sysrole)) {
8265: my ($crole,$cqual)=split(/\&/,$role);
8266: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8267: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8268: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
8269: return "refused:s:$crole&$cqual";
8270: }
8271: }
8272: }
8273: foreach my $role (split(':',$domrole)) {
8274: my ($crole,$cqual)=split(/\&/,$role);
8275: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8276: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8277: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
8278: return "refused:d:$crole&$cqual";
8279: }
8280: }
8281: }
8282: foreach my $role (split(':',$courole)) {
8283: my ($crole,$cqual)=split(/\&/,$role);
8284: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8285: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8286: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
8287: return "refused:c:$crole&$cqual";
8288: }
8289: }
8290: }
8291: my $uhome;
8292: if (($uname ne '') && ($udom ne '')) {
8293: $uhome = &homeserver($uname,$udom);
8294: return $uhome if ($uhome eq 'no_host');
8295: } else {
8296: $uname = $env{'user.name'};
8297: $udom = $env{'user.domain'};
8298: $uhome = $env{'user.home'};
8299: }
8300: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
8301: "$udom:$uname:rolesdef_$rolename=".
8302: escape($sysrole.'_'.$domrole.'_'.$courole);
8303: return reply($command,$uhome);
8304: } else {
8305: return 'refused';
8306: }
8307: }
8308:
8309: # ---------------- Make a metadata query against the network of library servers
8310:
8311: sub metadata_query {
8312: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
8313: my %rhash;
8314: my %libserv = &all_library();
8315: my @server_list = (defined($server_array) ? @$server_array
8316: : keys(%libserv) );
8317: for my $server (@server_list) {
8318: my $domains = '';
8319: if (ref($domains_hash) eq 'HASH') {
8320: $domains = $domains_hash->{$server};
8321: }
8322: unless ($custom or $customshow) {
8323: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
8324: $rhash{$server}=$reply;
8325: }
8326: else {
8327: my $reply=&reply("querysend:".&escape($query).':'.
8328: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
8329: $server);
8330: $rhash{$server}=$reply;
8331: }
8332: }
8333: return \%rhash;
8334: }
8335:
8336: # ----------------------------------------- Send log queries and wait for reply
8337:
8338: sub log_query {
8339: my ($uname,$udom,$query,%filters)=@_;
8340: my $uhome=&homeserver($uname,$udom);
8341: if ($uhome eq 'no_host') { return 'error: no_host'; }
8342: my $uhost=&hostname($uhome);
8343: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
8344: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8345: $uhome);
8346: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
8347: return get_query_reply($queryid);
8348: }
8349:
8350: # -------------------------- Update MySQL table for portfolio file
8351:
8352: sub update_portfolio_table {
8353: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
8354: if ($group ne '') {
8355: $file_name =~s /^\Q$group\E//;
8356: }
8357: my $homeserver = &homeserver($uname,$udom);
8358: my $queryid=
8359: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8360: ':'.&escape($file_name).':'.$action,$homeserver);
8361: my $reply = &get_query_reply($queryid);
8362: return $reply;
8363: }
8364:
8365: # -------------------------- Update MySQL allusers table
8366:
8367: sub update_allusers_table {
8368: my ($uname,$udom,$names) = @_;
8369: my $homeserver = &homeserver($uname,$udom);
8370: my $queryid=
8371: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8372: 'lastname='.&escape($names->{'lastname'}).'%%'.
8373: 'firstname='.&escape($names->{'firstname'}).'%%'.
8374: 'middlename='.&escape($names->{'middlename'}).'%%'.
8375: 'generation='.&escape($names->{'generation'}).'%%'.
8376: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8377: 'id='.&escape($names->{'id'}),$homeserver);
8378: return;
8379: }
8380:
8381: # ------- Request retrieval of institutional classlists for course(s)
8382:
8383: sub fetch_enrollment_query {
8384: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
8385: my ($homeserver,$sleep,$loopmax);
8386: my $maxtries = 1;
8387: if ($context eq 'automated') {
8388: $homeserver = $perlvar{'lonHostID'};
8389: $sleep = 2;
8390: $loopmax = 100;
8391: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
8392: } else {
8393: $homeserver = &homeserver($cnum,$dom);
8394: }
8395: my $host=&hostname($homeserver);
8396: my $cmd = '';
8397: foreach my $affiliate (keys(%{$affiliatesref})) {
8398: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
8399: }
8400: $cmd =~ s/%%$//;
8401: $cmd = &escape($cmd);
8402: my $query = 'fetchenrollment';
8403: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
8404: unless ($queryid=~/^\Q$host\E\_/) {
8405: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
8406: return 'error: '.$queryid;
8407: }
8408: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
8409: my $tries = 1;
8410: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8411: $reply = &get_query_reply($queryid,$sleep,$loopmax);
8412: $tries ++;
8413: }
8414: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8415: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8416: } else {
8417: my @responses = split(/:/,$reply);
8418: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
8419: foreach my $line (@responses) {
8420: my ($key,$value) = split(/=/,$line,2);
8421: $$replyref{$key} = $value;
8422: }
8423: } else {
8424: my $pathname = LONCAPA::tempdir();
8425: foreach my $line (@responses) {
8426: my ($key,$value) = split(/=/,$line);
8427: $$replyref{$key} = $value;
8428: if ($value > 0) {
8429: foreach my $item (@{$$affiliatesref{$key}}) {
8430: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
8431: my $destname = $pathname.'/'.$filename;
8432: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
8433: if ($xml_classlist =~ /^error/) {
8434: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
8435: } else {
8436: if ( open(FILE,">$destname") ) {
8437: print FILE &unescape($xml_classlist);
8438: close(FILE);
8439: } else {
8440: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
8441: }
8442: }
8443: }
8444: }
8445: }
8446: }
8447: return 'ok';
8448: }
8449: return 'error';
8450: }
8451:
8452: sub get_query_reply {
8453: my ($queryid,$sleep,$loopmax) = @_;;
8454: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
8455: $sleep = 0.2;
8456: }
8457: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
8458: $loopmax = 100;
8459: }
8460: my $replyfile=LONCAPA::tempdir().$queryid;
8461: my $reply='';
8462: for (1..$loopmax) {
8463: sleep($sleep);
8464: if (-e $replyfile.'.end') {
8465: if (open(my $fh,$replyfile)) {
8466: $reply = join('',<$fh>);
8467: close($fh);
8468: } else { return 'error: reply_file_error'; }
8469: return &unescape($reply);
8470: }
8471: }
8472: return 'timeout:'.$queryid;
8473: }
8474:
8475: sub courselog_query {
8476: #
8477: # possible filters:
8478: # url: url or symb
8479: # username
8480: # domain
8481: # action: view, submit, grade
8482: # start: timestamp
8483: # end: timestamp
8484: #
8485: my (%filters)=@_;
8486: unless ($env{'request.course.id'}) { return 'no_course'; }
8487: if ($filters{'url'}) {
8488: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
8489: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
8490: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
8491: }
8492: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8493: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
8494: return &log_query($cname,$cdom,'courselog',%filters);
8495: }
8496:
8497: sub userlog_query {
8498: #
8499: # possible filters:
8500: # action: log check role
8501: # start: timestamp
8502: # end: timestamp
8503: #
8504: my ($uname,$udom,%filters)=@_;
8505: return &log_query($uname,$udom,'userlog',%filters);
8506: }
8507:
8508: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
8509:
8510: sub auto_run {
8511: my ($cnum,$cdom) = @_;
8512: my $response = 0;
8513: my $settings;
8514: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
8515: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
8516: $settings = $domconfig{'autoenroll'};
8517: if ($settings->{'run'} eq '1') {
8518: $response = 1;
8519: }
8520: } else {
8521: my $homeserver;
8522: if (&is_course($cdom,$cnum)) {
8523: $homeserver = &homeserver($cnum,$cdom);
8524: } else {
8525: $homeserver = &domain($cdom,'primary');
8526: }
8527: if ($homeserver ne 'no_host') {
8528: $response = &reply('autorun:'.$cdom,$homeserver);
8529: }
8530: }
8531: return $response;
8532: }
8533:
8534: sub auto_get_sections {
8535: my ($cnum,$cdom,$inst_coursecode) = @_;
8536: my $homeserver;
8537: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8538: $homeserver = &homeserver($cnum,$cdom);
8539: }
8540: if (!defined($homeserver)) {
8541: if ($cdom =~ /^$match_domain$/) {
8542: $homeserver = &domain($cdom,'primary');
8543: }
8544: }
8545: my @secs;
8546: if (defined($homeserver)) {
8547: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
8548: unless ($response eq 'refused') {
8549: @secs = split(/:/,$response);
8550: }
8551: }
8552: return @secs;
8553: }
8554:
8555: sub auto_new_course {
8556: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
8557: my $homeserver = &homeserver($cnum,$cdom);
8558: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
8559: return $response;
8560: }
8561:
8562: sub auto_validate_courseID {
8563: my ($cnum,$cdom,$inst_course_id) = @_;
8564: my $homeserver = &homeserver($cnum,$cdom);
8565: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
8566: return $response;
8567: }
8568:
8569: sub auto_validate_instcode {
8570: my ($cnum,$cdom,$instcode,$owner) = @_;
8571: my ($homeserver,$response);
8572: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8573: $homeserver = &homeserver($cnum,$cdom);
8574: }
8575: if (!defined($homeserver)) {
8576: if ($cdom =~ /^$match_domain$/) {
8577: $homeserver = &domain($cdom,'primary');
8578: }
8579: }
8580: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
8581: &escape($instcode).':'.&escape($owner),$homeserver));
8582: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
8583: return ($outcome,$description,$defaultcredits);
8584: }
8585:
8586: sub auto_create_password {
8587: my ($cnum,$cdom,$authparam,$udom) = @_;
8588: my ($homeserver,$response);
8589: my $create_passwd = 0;
8590: my $authchk = '';
8591: if ($udom =~ /^$match_domain$/) {
8592: $homeserver = &domain($udom,'primary');
8593: }
8594: if ($homeserver eq '') {
8595: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8596: $homeserver = &homeserver($cnum,$cdom);
8597: }
8598: }
8599: if ($homeserver eq '') {
8600: $authchk = 'nodomain';
8601: } else {
8602: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
8603: if ($response eq 'refused') {
8604: $authchk = 'refused';
8605: } else {
8606: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
8607: }
8608: }
8609: return ($authparam,$create_passwd,$authchk);
8610: }
8611:
8612: sub auto_photo_permission {
8613: my ($cnum,$cdom,$students) = @_;
8614: my $homeserver = &homeserver($cnum,$cdom);
8615: my ($outcome,$perm_reqd,$conditions) =
8616: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
8617: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8618: return (undef,undef);
8619: }
8620: return ($outcome,$perm_reqd,$conditions);
8621: }
8622:
8623: sub auto_checkphotos {
8624: my ($uname,$udom,$pid) = @_;
8625: my $homeserver = &homeserver($uname,$udom);
8626: my ($result,$resulttype);
8627: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
8628: &escape($uname).':'.&escape($pid),
8629: $homeserver));
8630: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8631: return (undef,undef);
8632: }
8633: if ($outcome) {
8634: ($result,$resulttype) = split(/:/,$outcome);
8635: }
8636: return ($result,$resulttype);
8637: }
8638:
8639: sub auto_photochoice {
8640: my ($cnum,$cdom) = @_;
8641: my $homeserver = &homeserver($cnum,$cdom);
8642: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
8643: &escape($cdom),
8644: $homeserver)));
8645: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8646: return (undef,undef);
8647: }
8648: return ($update,$comment);
8649: }
8650:
8651: sub auto_photoupdate {
8652: my ($affiliatesref,$dom,$cnum,$photo) = @_;
8653: my $homeserver = &homeserver($cnum,$dom);
8654: my $host=&hostname($homeserver);
8655: my $cmd = '';
8656: my $maxtries = 1;
8657: foreach my $affiliate (keys(%{$affiliatesref})) {
8658: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
8659: }
8660: $cmd =~ s/%%$//;
8661: $cmd = &escape($cmd);
8662: my $query = 'institutionalphotos';
8663: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
8664: unless ($queryid=~/^\Q$host\E\_/) {
8665: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
8666: return 'error: '.$queryid;
8667: }
8668: my $reply = &get_query_reply($queryid);
8669: my $tries = 1;
8670: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8671: $reply = &get_query_reply($queryid);
8672: $tries ++;
8673: }
8674: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8675: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8676: } else {
8677: my @responses = split(/:/,$reply);
8678: my $outcome = shift(@responses);
8679: foreach my $item (@responses) {
8680: my ($key,$value) = split(/=/,$item);
8681: $$photo{$key} = $value;
8682: }
8683: return $outcome;
8684: }
8685: return 'error';
8686: }
8687:
8688: sub auto_instcode_format {
8689: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
8690: $cat_order) = @_;
8691: my $courses = '';
8692: my @homeservers;
8693: if ($caller eq 'global') {
8694: my %servers = &get_servers($codedom,'library');
8695: foreach my $tryserver (keys(%servers)) {
8696: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8697: push(@homeservers,$tryserver);
8698: }
8699: }
8700: } elsif ($caller eq 'requests') {
8701: if ($codedom =~ /^$match_domain$/) {
8702: my $chome = &domain($codedom,'primary');
8703: unless ($chome eq 'no_host') {
8704: push(@homeservers,$chome);
8705: }
8706: }
8707: } else {
8708: push(@homeservers,&homeserver($caller,$codedom));
8709: }
8710: foreach my $code (keys(%{$instcodes})) {
8711: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
8712: }
8713: chop($courses);
8714: my $ok_response = 0;
8715: my $response;
8716: while (@homeservers > 0 && $ok_response == 0) {
8717: my $server = shift(@homeservers);
8718: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
8719: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
8720: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
8721: split(/:/,$response);
8722: %{$codes} = (%{$codes},&str2hash($codes_str));
8723: push(@{$codetitles},&str2array($codetitles_str));
8724: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
8725: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
8726: $ok_response = 1;
8727: }
8728: }
8729: if ($ok_response) {
8730: return 'ok';
8731: } else {
8732: return $response;
8733: }
8734: }
8735:
8736: sub auto_instcode_defaults {
8737: my ($domain,$returnhash,$code_order) = @_;
8738: my @homeservers;
8739:
8740: my %servers = &get_servers($domain,'library');
8741: foreach my $tryserver (keys(%servers)) {
8742: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8743: push(@homeservers,$tryserver);
8744: }
8745: }
8746:
8747: my $response;
8748: foreach my $server (@homeservers) {
8749: $response=&reply('autoinstcodedefaults:'.$domain,$server);
8750: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8751:
8752: foreach my $pair (split(/\&/,$response)) {
8753: my ($name,$value)=split(/\=/,$pair);
8754: if ($name eq 'code_order') {
8755: @{$code_order} = split(/\&/,&unescape($value));
8756: } else {
8757: $returnhash->{&unescape($name)}=&unescape($value);
8758: }
8759: }
8760: return 'ok';
8761: }
8762:
8763: return $response;
8764: }
8765:
8766: sub auto_possible_instcodes {
8767: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
8768: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
8769: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8770: return;
8771: }
8772: my (@homeservers,$uhome);
8773: if (defined(&domain($domain,'primary'))) {
8774: $uhome=&domain($domain,'primary');
8775: push(@homeservers,&domain($domain,'primary'));
8776: } else {
8777: my %servers = &get_servers($domain,'library');
8778: foreach my $tryserver (keys(%servers)) {
8779: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8780: push(@homeservers,$tryserver);
8781: }
8782: }
8783: }
8784: my $response;
8785: foreach my $server (@homeservers) {
8786: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8787: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8788: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8789: split(':',$response);
8790: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8791: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
8792: foreach my $item (split('&',$cat_title)) {
8793: my ($name,$value)=split('=',$item);
8794: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
8795: }
8796: foreach my $item (split('&',$cat_order)) {
8797: my ($name,$value)=split('=',$item);
8798: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
8799: }
8800: return 'ok';
8801: }
8802: return $response;
8803: }
8804:
8805: sub auto_courserequest_checks {
8806: my ($dom) = @_;
8807: my ($homeserver,%validations);
8808: if ($dom =~ /^$match_domain$/) {
8809: $homeserver = &domain($dom,'primary');
8810: }
8811: unless ($homeserver eq 'no_host') {
8812: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8813: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8814: my @items = split(/&/,$response);
8815: foreach my $item (@items) {
8816: my ($key,$value) = split('=',$item);
8817: $validations{&unescape($key)} = &thaw_unescape($value);
8818: }
8819: }
8820: }
8821: return %validations;
8822: }
8823:
8824: sub auto_courserequest_validation {
8825: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
8826: my ($homeserver,$response);
8827: if ($dom =~ /^$match_domain$/) {
8828: $homeserver = &domain($dom,'primary');
8829: }
8830: unless ($homeserver eq 'no_host') {
8831: my $customdata;
8832: if (ref($custominfo) eq 'HASH') {
8833: $customdata = &freeze_escape($custominfo);
8834: }
8835: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
8836: ':'.&escape($crstype).':'.&escape($inststatuslist).
8837: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8838: $customdata,$homeserver));
8839: }
8840: return $response;
8841: }
8842:
8843: sub auto_validate_class_sec {
8844: my ($cdom,$cnum,$owners,$inst_class) = @_;
8845: my $homeserver = &homeserver($cnum,$cdom);
8846: my $ownerlist;
8847: if (ref($owners) eq 'ARRAY') {
8848: $ownerlist = join(',',@{$owners});
8849: } else {
8850: $ownerlist = $owners;
8851: }
8852: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
8853: &escape($ownerlist).':'.$cdom,$homeserver);
8854: return $response;
8855: }
8856:
8857: sub auto_crsreq_update {
8858: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
8859: $code,$accessstart,$accessend,$inbound) = @_;
8860: my ($homeserver,%crsreqresponse);
8861: if ($cdom =~ /^$match_domain$/) {
8862: $homeserver = &domain($cdom,'primary');
8863: }
8864: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8865: my $info;
8866: if (ref($inbound) eq 'HASH') {
8867: $info = &freeze_escape($inbound);
8868: }
8869: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8870: ':'.&escape($action).':'.&escape($ownername).':'.
8871: &escape($ownerdomain).':'.&escape($fullname).':'.
8872: &escape($title).':'.&escape($code).':'.
8873: &escape($accessstart).':'.&escape($accessend).':'.$info,
8874: $homeserver);
8875: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8876: my @items = split(/&/,$response);
8877: foreach my $item (@items) {
8878: my ($key,$value) = split('=',$item);
8879: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8880: }
8881: }
8882: }
8883: return \%crsreqresponse;
8884: }
8885:
8886: sub auto_export_grades {
8887: my ($cdom,$cnum,$inforef,$gradesref) = @_;
8888: my ($homeserver,%exportresponse);
8889: if ($cdom =~ /^$match_domain$/) {
8890: $homeserver = &domain($cdom,'primary');
8891: }
8892: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8893: my $info;
8894: if (ref($inforef) eq 'HASH') {
8895: $info = &freeze_escape($inforef);
8896: }
8897: if (ref($gradesref) eq 'HASH') {
8898: my $grades = &freeze_escape($gradesref);
8899: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
8900: $info.':'.$grades,$homeserver);
8901: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
8902: my @items = split(/&/,$response);
8903: foreach my $item (@items) {
8904: my ($key,$value) = split('=',$item);
8905: $exportresponse{&unescape($key)} = &thaw_unescape($value);
8906: }
8907: }
8908: }
8909: }
8910: return \%exportresponse;
8911: }
8912:
8913: sub check_instcode_cloning {
8914: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8915: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8916: return;
8917: }
8918: my $canclone;
8919: if (@{$code_order} > 0) {
8920: my $instcoderegexp ='^';
8921: my @clonecodes = split(/\&/,$cloner);
8922: foreach my $item (@{$code_order}) {
8923: if (grep(/^\Q$item\E=/,@clonecodes)) {
8924: foreach my $pair (@clonecodes) {
8925: my ($key,$val) = split(/\=/,$pair,2);
8926: $val = &unescape($val);
8927: if ($key eq $item) {
8928: $instcoderegexp .= '('.$val.')';
8929: last;
8930: }
8931: }
8932: } else {
8933: $instcoderegexp .= $codedefaults->{$item};
8934: }
8935: }
8936: $instcoderegexp .= '$';
8937: my (@from,@to);
8938: eval {
8939: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8940: (@to) = ($clonetocode =~ /$instcoderegexp/);
8941: };
8942: if ((@from > 0) && (@to > 0)) {
8943: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8944: if (!@diffs) {
8945: $canclone = 1;
8946: }
8947: }
8948: }
8949: return $canclone;
8950: }
8951:
8952: sub default_instcode_cloning {
8953: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8954: my (%codedefaults,@code_order,$canclone);
8955: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8956: %codedefaults = %{$codedefaultsref};
8957: @code_order = @{$codeorderref};
8958: } elsif ($clonedom) {
8959: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8960: }
8961: if (($domdefclone) && (@code_order)) {
8962: my @clonecodes = split(/\+/,$domdefclone);
8963: my $instcoderegexp ='^';
8964: foreach my $item (@code_order) {
8965: if (grep(/^\Q$item\E$/,@clonecodes)) {
8966: $instcoderegexp .= '('.$codedefaults{$item}.')';
8967: } else {
8968: $instcoderegexp .= $codedefaults{$item};
8969: }
8970: }
8971: $instcoderegexp .= '$';
8972: my (@from,@to);
8973: eval {
8974: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8975: (@to) = ($clonetocode =~ /$instcoderegexp/);
8976: };
8977: if ((@from > 0) && (@to > 0)) {
8978: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8979: if (!@diffs) {
8980: $canclone = 1;
8981: }
8982: }
8983: }
8984: return $canclone;
8985: }
8986:
8987: # ------------------------------------------------------- Course Group routines
8988:
8989: sub get_coursegroups {
8990: my ($cdom,$cnum,$group,$namespace) = @_;
8991: return(&dump($namespace,$cdom,$cnum,$group));
8992: }
8993:
8994: sub modify_coursegroup {
8995: my ($cdom,$cnum,$groupsettings) = @_;
8996: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8997: }
8998:
8999: sub toggle_coursegroup_status {
9000: my ($cdom,$cnum,$group,$action) = @_;
9001: my ($from_namespace,$to_namespace);
9002: if ($action eq 'delete') {
9003: $from_namespace = 'coursegroups';
9004: $to_namespace = 'deleted_groups';
9005: } else {
9006: $from_namespace = 'deleted_groups';
9007: $to_namespace = 'coursegroups';
9008: }
9009: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
9010: if (my $tmp = &error(%curr_group)) {
9011: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
9012: return ('read error',$tmp);
9013: } else {
9014: my %savedsettings = %curr_group;
9015: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
9016: my $deloutcome;
9017: if ($result eq 'ok') {
9018: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
9019: } else {
9020: return ('write error',$result);
9021: }
9022: if ($deloutcome eq 'ok') {
9023: return 'ok';
9024: } else {
9025: return ('delete error',$deloutcome);
9026: }
9027: }
9028: }
9029:
9030: sub modify_group_roles {
9031: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
9032: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
9033: my $role = 'gr/'.&escape($userprivs);
9034: my ($uname,$udom) = split(/:/,$user);
9035: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
9036: if ($result eq 'ok') {
9037: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
9038: }
9039: return $result;
9040: }
9041:
9042: sub modify_coursegroup_membership {
9043: my ($cdom,$cnum,$membership) = @_;
9044: my $result = &put('groupmembership',$membership,$cdom,$cnum);
9045: return $result;
9046: }
9047:
9048: sub get_active_groups {
9049: my ($udom,$uname,$cdom,$cnum) = @_;
9050: my $now = time;
9051: my %groups = ();
9052: foreach my $key (keys(%env)) {
9053: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
9054: my ($start,$end) = split(/\./,$env{$key});
9055: if (($end!=0) && ($end<$now)) { next; }
9056: if (($start!=0) && ($start>$now)) { next; }
9057: if ($1 eq $cdom && $2 eq $cnum) {
9058: $groups{$3} = $env{$key} ;
9059: }
9060: }
9061: }
9062: return %groups;
9063: }
9064:
9065: sub get_group_membership {
9066: my ($cdom,$cnum,$group) = @_;
9067: return(&dump('groupmembership',$cdom,$cnum,$group));
9068: }
9069:
9070: sub get_users_groups {
9071: my ($udom,$uname,$courseid) = @_;
9072: my @usersgroups;
9073: my $cachetime=1800;
9074:
9075: my $hashid="$udom:$uname:$courseid";
9076: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
9077: if (defined($cached)) {
9078: @usersgroups = split(/:/,$grouplist);
9079: } else {
9080: $grouplist = '';
9081: my $courseurl = &courseid_to_courseurl($courseid);
9082: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
9083: my $access_end = $env{'course.'.$courseid.
9084: '.default_enrollment_end_date'};
9085: my $now = time;
9086: foreach my $key (keys(%roleshash)) {
9087: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
9088: my $group = $1;
9089: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
9090: my $start = $2;
9091: my $end = $1;
9092: if ($start == -1) { next; } # deleted from group
9093: if (($start!=0) && ($start>$now)) { next; }
9094: if (($end!=0) && ($end<$now)) {
9095: if ($access_end && $access_end < $now) {
9096: if ($access_end - $end < 86400) {
9097: push(@usersgroups,$group);
9098: }
9099: }
9100: next;
9101: }
9102: push(@usersgroups,$group);
9103: }
9104: }
9105: }
9106: @usersgroups = &sort_course_groups($courseid,@usersgroups);
9107: $grouplist = join(':',@usersgroups);
9108: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
9109: }
9110: return @usersgroups;
9111: }
9112:
9113: sub devalidate_getgroups_cache {
9114: my ($udom,$uname,$cdom,$cnum)=@_;
9115: my $courseid = $cdom.'_'.$cnum;
9116:
9117: my $hashid="$udom:$uname:$courseid";
9118: &devalidate_cache_new('getgroups',$hashid);
9119: }
9120:
9121: # ------------------------------------------------------------------ Plain Text
9122:
9123: sub plaintext {
9124: my ($short,$type,$cid,$forcedefault) = @_;
9125: if ($short =~ m{^cr/}) {
9126: return (split('/',$short))[-1];
9127: }
9128: if (!defined($cid)) {
9129: $cid = $env{'request.course.id'};
9130: }
9131: my %rolenames = (
9132: Course => 'std',
9133: Community => 'alt1',
9134: Placement => 'std',
9135: );
9136: if ($cid ne '') {
9137: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
9138: unless ($forcedefault) {
9139: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
9140: &Apache::lonlocal::mt_escape(\$roletext);
9141: return &Apache::lonlocal::mt($roletext);
9142: }
9143: }
9144: }
9145: if ((defined($type)) && (defined($rolenames{$type})) &&
9146: (defined($rolenames{$type})) &&
9147: (defined($prp{$short}{$rolenames{$type}}))) {
9148: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
9149: } elsif ($cid ne '') {
9150: my $crstype = $env{'course.'.$cid.'.type'};
9151: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
9152: (defined($prp{$short}{$rolenames{$crstype}}))) {
9153: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
9154: }
9155: }
9156: return &Apache::lonlocal::mt($prp{$short}{'std'});
9157: }
9158:
9159: # ----------------------------------------------------------------- Assign Role
9160:
9161: sub assignrole {
9162: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
9163: $context)=@_;
9164: my $mrole;
9165: if ($role =~ /^cr\//) {
9166: my $cwosec=$url;
9167: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
9168: unless (&allowed('ccr',$cwosec)) {
9169: my $refused = 1;
9170: if ($context eq 'requestcourses') {
9171: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
9172: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
9173: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
9174: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9175: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9176: if ($crsenv{'internal.courseowner'} eq
9177: $env{'user.name'}.':'.$env{'user.domain'}) {
9178: $refused = '';
9179: }
9180: }
9181: }
9182: }
9183: }
9184: if ($refused) {
9185: &logthis('Refused custom assignrole: '.
9186: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
9187: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
9188: return 'refused';
9189: }
9190: }
9191: $mrole='cr';
9192: } elsif ($role =~ /^gr\//) {
9193: my $cwogrp=$url;
9194: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
9195: unless (&allowed('mdg',$cwogrp)) {
9196: &logthis('Refused group assignrole: '.
9197: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
9198: $env{'user.name'}.' at '.$env{'user.domain'});
9199: return 'refused';
9200: }
9201: $mrole='gr';
9202: } else {
9203: my $cwosec=$url;
9204: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
9205: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
9206: my $refused;
9207: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
9208: if (!(&allowed('c'.$role,$url))) {
9209: $refused = 1;
9210: }
9211: } else {
9212: $refused = 1;
9213: }
9214: if ($refused) {
9215: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9216: if (!$selfenroll && $context eq 'course') {
9217: my %crsenv;
9218: if ($role eq 'cc' || $role eq 'co') {
9219: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9220: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
9221: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
9222: if ($crsenv{'internal.courseowner'} eq
9223: $env{'user.name'}.':'.$env{'user.domain'}) {
9224: $refused = '';
9225: }
9226: }
9227: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
9228: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
9229: if ($crsenv{'internal.courseowner'} eq
9230: $env{'user.name'}.':'.$env{'user.domain'}) {
9231: $refused = '';
9232: }
9233: }
9234: }
9235: }
9236: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
9237: $refused = '';
9238: } elsif ($context eq 'requestcourses') {
9239: my @possroles = ('st','ta','ep','in','cc','co');
9240: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
9241: my $wrongcc;
9242: if ($cnum =~ /^$match_community$/) {
9243: $wrongcc = 1 if ($role eq 'cc');
9244: } else {
9245: $wrongcc = 1 if ($role eq 'co');
9246: }
9247: unless ($wrongcc) {
9248: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9249: if ($crsenv{'internal.courseowner'} eq
9250: $env{'user.name'}.':'.$env{'user.domain'}) {
9251: $refused = '';
9252: }
9253: }
9254: }
9255: } elsif ($context eq 'requestauthor') {
9256: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
9257: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
9258: if ($env{'environment.requestauthor'} eq 'automatic') {
9259: $refused = '';
9260: } else {
9261: my %domdefaults = &get_domain_defaults($udom);
9262: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
9263: my $checkbystatus;
9264: if ($env{'user.adv'}) {
9265: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9266: if ($disposition eq 'automatic') {
9267: $refused = '';
9268: } elsif ($disposition eq '') {
9269: $checkbystatus = 1;
9270: }
9271: } else {
9272: $checkbystatus = 1;
9273: }
9274: if ($checkbystatus) {
9275: if ($env{'environment.inststatus'}) {
9276: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9277: foreach my $type (@inststatuses) {
9278: if (($type ne '') &&
9279: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9280: $refused = '';
9281: }
9282: }
9283: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9284: $refused = '';
9285: }
9286: }
9287: }
9288: }
9289: }
9290: }
9291: if ($refused) {
9292: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9293: ' '.$role.' '.$end.' '.$start.' by '.
9294: $env{'user.name'}.' at '.$env{'user.domain'});
9295: return 'refused';
9296: }
9297: }
9298: } elsif ($role eq 'au') {
9299: if ($url ne '/'.$udom.'/') {
9300: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9301: ' to assign author role for '.$uname.':'.$udom.
9302: ' in domain: '.$url.' refused (wrong domain).');
9303: return 'refused';
9304: }
9305: }
9306: $mrole=$role;
9307: }
9308: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
9309: "$udom:$uname:$url".'_'."$mrole=$role";
9310: if ($end) { $command.='_'.$end; }
9311: if ($start) {
9312: if ($end) {
9313: $command.='_'.$start;
9314: } else {
9315: $command.='_0_'.$start;
9316: }
9317: }
9318: my $origstart = $start;
9319: my $origend = $end;
9320: my $delflag;
9321: # actually delete
9322: if ($deleteflag) {
9323: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
9324: # modify command to delete the role
9325: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
9326: "$udom:$uname:$url".'_'."$mrole";
9327: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
9328: # set start and finish to negative values for userrolelog
9329: $start=-1;
9330: $end=-1;
9331: $delflag = 1;
9332: }
9333: }
9334: # send command
9335: my $answer=&reply($command,&homeserver($uname,$udom));
9336: # log new user role if status is ok
9337: if ($answer eq 'ok') {
9338: &userrolelog($role,$uname,$udom,$url,$start,$end);
9339: if (($role eq 'cc') || ($role eq 'in') ||
9340: ($role eq 'ep') || ($role eq 'ad') ||
9341: ($role eq 'ta') || ($role eq 'st') ||
9342: ($role=~/^cr/) || ($role eq 'gr') ||
9343: ($role eq 'co')) {
9344: # for course roles, perform group memberships changes triggered by role change.
9345: unless ($role =~ /^gr/) {
9346: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
9347: $origstart,$selfenroll,$context);
9348: }
9349: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9350: $selfenroll,$context);
9351: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
9352: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
9353: ($role eq 'da')) {
9354: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9355: $context);
9356: } elsif (($role eq 'ca') || ($role eq 'aa')) {
9357: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9358: $context);
9359: }
9360: if ($role eq 'cc') {
9361: &autoupdate_coowners($url,$end,$start,$uname,$udom);
9362: }
9363: }
9364: return $answer;
9365: }
9366:
9367: sub autoupdate_coowners {
9368: my ($url,$end,$start,$uname,$udom) = @_;
9369: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
9370: if (($cdom ne '') && ($cnum ne '')) {
9371: my $now = time;
9372: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
9373: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
9374: my %coursehash = &coursedescription($cdom.'_'.$cnum);
9375: my $instcode = $coursehash{'internal.coursecode'};
9376: if ($instcode ne '') {
9377: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
9378: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
9379: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
9380: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
9381: if ($result eq 'valid') {
9382: if ($coursehash{'internal.co-owners'}) {
9383: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9384: push(@newcoowners,$coowner);
9385: }
9386: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
9387: push(@newcoowners,$uname.':'.$udom);
9388: }
9389: @newcoowners = sort(@newcoowners);
9390: } else {
9391: push(@newcoowners,$uname.':'.$udom);
9392: }
9393: } else {
9394: if ($coursehash{'internal.co-owners'}) {
9395: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9396: unless ($coowner eq $uname.':'.$udom) {
9397: push(@newcoowners,$coowner);
9398: }
9399: }
9400: unless (@newcoowners > 0) {
9401: $delcoowners = 1;
9402: $coowners = '';
9403: }
9404: }
9405: }
9406: if (@newcoowners || $delcoowners) {
9407: &store_coowners($cdom,$cnum,$coursehash{'home'},
9408: $delcoowners,@newcoowners);
9409: }
9410: }
9411: }
9412: }
9413: }
9414: }
9415: }
9416:
9417: sub store_coowners {
9418: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
9419: my $cid = $cdom.'_'.$cnum;
9420: my ($coowners,$delresult,$putresult);
9421: if (@newcoowners) {
9422: $coowners = join(',',@newcoowners);
9423: my %coownershash = (
9424: 'internal.co-owners' => $coowners,
9425: );
9426: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
9427: if ($putresult eq 'ok') {
9428: if ($env{'course.'.$cid.'.num'} eq $cnum) {
9429: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
9430: }
9431: }
9432: }
9433: if ($delcoowners) {
9434: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
9435: if ($delresult eq 'ok') {
9436: if ($env{'course.'.$cid.'.internal.co-owners'}) {
9437: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
9438: }
9439: }
9440: }
9441: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
9442: my %crsinfo =
9443: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
9444: if (ref($crsinfo{$cid}) eq 'HASH') {
9445: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
9446: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
9447: }
9448: }
9449: }
9450:
9451: # -------------------------------------------------- Modify user authentication
9452: # Overrides without validation
9453:
9454: sub modifyuserauth {
9455: my ($udom,$uname,$umode,$upass)=@_;
9456: my $uhome=&homeserver($uname,$udom);
9457: unless (&allowed('mau',$udom)) { return 'refused'; }
9458: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
9459: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9460: ' in domain '.$env{'request.role.domain'});
9461: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
9462: &escape($upass),$uhome);
9463: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
9464: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
9465: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
9466: &log($udom,,$uname,$uhome,
9467: 'Authentication changed by '.$env{'user.domain'}.', '.
9468: $env{'user.name'}.', '.$umode.
9469: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
9470: unless ($reply eq 'ok') {
9471: &logthis('Authentication mode error: '.$reply);
9472: return 'error: '.$reply;
9473: }
9474: return 'ok';
9475: }
9476:
9477: # --------------------------------------------------------------- Modify a user
9478:
9479: sub modifyuser {
9480: my ($udom, $uname, $uid,
9481: $umode, $upass, $first,
9482: $middle, $last, $gene,
9483: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
9484: $udom= &LONCAPA::clean_domain($udom);
9485: $uname=&LONCAPA::clean_username($uname);
9486: my $showcandelete = 'none';
9487: if (ref($candelete) eq 'ARRAY') {
9488: if (@{$candelete} > 0) {
9489: $showcandelete = join(', ',@{$candelete});
9490: }
9491: }
9492: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
9493: $umode.', '.$first.', '.$middle.', '.
9494: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
9495: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
9496: ' desiredhome not specified').
9497: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9498: ' in domain '.$env{'request.role.domain'});
9499: my $uhome=&homeserver($uname,$udom,'true');
9500: my $newuser;
9501: if ($uhome eq 'no_host') {
9502: $newuser = 1;
9503: }
9504: # ----------------------------------------------------------------- Create User
9505: if (($uhome eq 'no_host') &&
9506: (($umode && $upass) || ($umode eq 'localauth'))) {
9507: my $unhome='';
9508: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
9509: $unhome = $desiredhome;
9510: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
9511: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
9512: } else { # load balancing routine for determining $unhome
9513: my $loadm=10000000;
9514: my %servers = &get_servers($udom,'library');
9515: foreach my $tryserver (keys(%servers)) {
9516: my $answer=reply('load',$tryserver);
9517: if (($answer=~/\d+/) && ($answer<$loadm)) {
9518: $loadm=$answer;
9519: $unhome=$tryserver;
9520: }
9521: }
9522: }
9523: if (($unhome eq '') || ($unhome eq 'no_host')) {
9524: return 'error: unable to find a home server for '.$uname.
9525: ' in domain '.$udom;
9526: }
9527: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
9528: &escape($upass),$unhome);
9529: unless ($reply eq 'ok') {
9530: return 'error: '.$reply;
9531: }
9532: $uhome=&homeserver($uname,$udom,'true');
9533: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
9534: return 'error: unable verify users home machine.';
9535: }
9536: } # End of creation of new user
9537: # ---------------------------------------------------------------------- Add ID
9538: if ($uid) {
9539: $uid=~tr/A-Z/a-z/;
9540: my %uidhash=&idrget($udom,$uname);
9541: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
9542: && (!$forceid)) {
9543: unless ($uid eq $uidhash{$uname}) {
9544: return 'error: user id "'.$uid.'" does not match '.
9545: 'current user id "'.$uidhash{$uname}.'".';
9546: }
9547: } else {
9548: &idput($udom,{$uname => $uid},$uhome,'ids');
9549: }
9550: }
9551: # -------------------------------------------------------------- Add names, etc
9552: my @tmp=&get('environment',
9553: ['firstname','middlename','lastname','generation','id',
9554: 'permanentemail','inststatus'],
9555: $udom,$uname);
9556: my (%names,%oldnames);
9557: if ($tmp[0] =~ m/^error:.*/) {
9558: %names=();
9559: } else {
9560: %names = @tmp;
9561: %oldnames = %names;
9562: }
9563: #
9564: # If name, email and/or uid are blank (e.g., because an uploaded file
9565: # of users did not contain them), do not overwrite existing values
9566: # unless field is in $candelete array ref.
9567: #
9568:
9569: my @fields = ('firstname','middlename','lastname','generation',
9570: 'permanentemail','id');
9571: my %newvalues;
9572: if (ref($candelete) eq 'ARRAY') {
9573: foreach my $field (@fields) {
9574: if (grep(/^\Q$field\E$/,@{$candelete})) {
9575: if ($field eq 'firstname') {
9576: $names{$field} = $first;
9577: } elsif ($field eq 'middlename') {
9578: $names{$field} = $middle;
9579: } elsif ($field eq 'lastname') {
9580: $names{$field} = $last;
9581: } elsif ($field eq 'generation') {
9582: $names{$field} = $gene;
9583: } elsif ($field eq 'permanentemail') {
9584: $names{$field} = $email;
9585: } elsif ($field eq 'id') {
9586: $names{$field} = $uid;
9587: }
9588: }
9589: }
9590: }
9591: if ($first) { $names{'firstname'} = $first; }
9592: if (defined($middle)) { $names{'middlename'} = $middle; }
9593: if ($last) { $names{'lastname'} = $last; }
9594: if (defined($gene)) { $names{'generation'} = $gene; }
9595: if ($email) {
9596: $email=~s/[^\w\@\.\-\,]//gs;
9597: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
9598: }
9599: if ($uid) { $names{'id'} = $uid; }
9600: if (defined($inststatus)) {
9601: $names{'inststatus'} = '';
9602: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
9603: if (ref($usertypes) eq 'HASH') {
9604: my @okstatuses;
9605: foreach my $item (split(/:/,$inststatus)) {
9606: if (defined($usertypes->{$item})) {
9607: push(@okstatuses,$item);
9608: }
9609: }
9610: if (@okstatuses) {
9611: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
9612: }
9613: }
9614: }
9615: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
9616: $umode.', '.$first.', '.$middle.', '.
9617: $last.', '.$gene.', '.$email.', '.$inststatus;
9618: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
9619: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
9620: } else {
9621: $logmsg .= ' during self creation';
9622: }
9623: my $changed;
9624: if ($newuser) {
9625: $changed = 1;
9626: } else {
9627: foreach my $field (@fields) {
9628: if ($names{$field} ne $oldnames{$field}) {
9629: $changed = 1;
9630: last;
9631: }
9632: }
9633: }
9634: unless ($changed) {
9635: $logmsg = 'No changes in user information needed for: '.$logmsg;
9636: &logthis($logmsg);
9637: return 'ok';
9638: }
9639: my $reply = &put('environment', \%names, $udom,$uname);
9640: if ($reply ne 'ok') {
9641: return 'error: '.$reply;
9642: }
9643: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
9644: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
9645: }
9646: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
9647: &devalidate_cache_new('namescache',$uname.':'.$udom);
9648: $logmsg = 'Success modifying user '.$logmsg;
9649: &logthis($logmsg);
9650: return 'ok';
9651: }
9652:
9653: # -------------------------------------------------------------- Modify student
9654:
9655: sub modifystudent {
9656: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
9657: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
9658: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
9659: if (!$cid) {
9660: unless ($cid=$env{'request.course.id'}) {
9661: return 'not_in_class';
9662: }
9663: }
9664: # --------------------------------------------------------------- Make the user
9665: my $reply=&modifyuser
9666: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
9667: $desiredhome,$email,$inststatus);
9668: unless ($reply eq 'ok') { return $reply; }
9669: # This will cause &modify_student_enrollment to get the uid from the
9670: # student's environment
9671: $uid = undef if (!$forceid);
9672: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
9673: $gene,$usec,$end,$start,$type,$locktype,
9674: $cid,$selfenroll,$context,$credits,$instsec);
9675: return $reply;
9676: }
9677:
9678: sub modify_student_enrollment {
9679: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
9680: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
9681: my ($cdom,$cnum,$chome);
9682: if (!$cid) {
9683: unless ($cid=$env{'request.course.id'}) {
9684: return 'not_in_class';
9685: }
9686: $cdom=$env{'course.'.$cid.'.domain'};
9687: $cnum=$env{'course.'.$cid.'.num'};
9688: } else {
9689: ($cdom,$cnum)=split(/_/,$cid);
9690: }
9691: $chome=$env{'course.'.$cid.'.home'};
9692: if (!$chome) {
9693: $chome=&homeserver($cnum,$cdom);
9694: }
9695: if (!$chome) { return 'unknown_course'; }
9696: # Make sure the user exists
9697: my $uhome=&homeserver($uname,$udom);
9698: if (($uhome eq '') || ($uhome eq 'no_host')) {
9699: return 'error: no such user';
9700: }
9701: # Get student data if we were not given enough information
9702: if (!defined($first) || $first eq '' ||
9703: !defined($last) || $last eq '' ||
9704: !defined($uid) || $uid eq '' ||
9705: !defined($middle) || $middle eq '' ||
9706: !defined($gene) || $gene eq '') {
9707: # They did not supply us with enough data to enroll the student, so
9708: # we need to pick up more information.
9709: my %tmp = &get('environment',
9710: ['firstname','middlename','lastname', 'generation','id']
9711: ,$udom,$uname);
9712:
9713: #foreach my $key (keys(%tmp)) {
9714: # &logthis("key $key = ".$tmp{$key});
9715: #}
9716: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
9717: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
9718: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
9719: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
9720: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
9721: }
9722: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
9723: my $user = "$uname:$udom";
9724: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
9725: my $reply=cput('classlist',
9726: {$user =>
9727: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
9728: $cdom,$cnum);
9729: if (($reply eq 'ok') || ($reply eq 'delayed')) {
9730: &devalidate_getsection_cache($udom,$uname,$cid);
9731: } else {
9732: return 'error: '.$reply;
9733: }
9734: # Add student role to user
9735: my $uurl='/'.$cid;
9736: $uurl=~s/\_/\//g;
9737: if ($usec) {
9738: $uurl.='/'.$usec;
9739: }
9740: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
9741: $selfenroll,$context);
9742: if ($result ne 'ok') {
9743: if ($old_entry{$user} ne '') {
9744: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
9745: } else {
9746: $reply = &del('classlist',[$user],$cdom,$cnum);
9747: }
9748: }
9749: return $result;
9750: }
9751:
9752: sub format_name {
9753: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
9754: my $name;
9755: if ($first ne 'lastname') {
9756: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
9757: } else {
9758: if ($lastname=~/\S/) {
9759: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
9760: $name=~s/\s+,/,/;
9761: } else {
9762: $name.= $firstname.' '.$middlename.' '.$generation;
9763: }
9764: }
9765: $name=~s/^\s+//;
9766: $name=~s/\s+$//;
9767: $name=~s/\s+/ /g;
9768: return $name;
9769: }
9770:
9771: # ------------------------------------------------- Write to course preferences
9772:
9773: sub writecoursepref {
9774: my ($courseid,%prefs)=@_;
9775: $courseid=~s/^\///;
9776: $courseid=~s/\_/\//g;
9777: my ($cdomain,$cnum)=split(/\//,$courseid);
9778: my $chome=homeserver($cnum,$cdomain);
9779: if (($chome eq '') || ($chome eq 'no_host')) {
9780: return 'error: no such course';
9781: }
9782: my $cstring='';
9783: foreach my $pref (keys(%prefs)) {
9784: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
9785: }
9786: $cstring=~s/\&$//;
9787: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
9788: }
9789:
9790: # ---------------------------------------------------------- Make/modify course
9791:
9792: sub createcourse {
9793: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
9794: $course_owner,$crstype,$cnum,$context,$category)=@_;
9795: $url=&declutter($url);
9796: my $cid='';
9797: if ($context eq 'requestcourses') {
9798: my $can_create = 0;
9799: my ($ownername,$ownerdom) = split(':',$course_owner);
9800: if ($udom eq $ownerdom) {
9801: if (&usertools_access($ownername,$ownerdom,$category,undef,
9802: $context)) {
9803: $can_create = 1;
9804: }
9805: } else {
9806: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
9807: $category);
9808: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
9809: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
9810: if (@curr > 0) {
9811: my @options = qw(approval validate autolimit);
9812: my $optregex = join('|',@options);
9813: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9814: $can_create = 1;
9815: }
9816: }
9817: }
9818: }
9819: if ($can_create) {
9820: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9821: unless (&allowed('ccc',$udom)) {
9822: return 'refused';
9823: }
9824: }
9825: } else {
9826: return 'refused';
9827: }
9828: } elsif (!&allowed('ccc',$udom)) {
9829: return 'refused';
9830: }
9831: # --------------------------------------------------------------- Get Unique ID
9832: my $uname;
9833: if ($cnum =~ /^$match_courseid$/) {
9834: my $chome=&homeserver($cnum,$udom,'true');
9835: if (($chome eq '') || ($chome eq 'no_host')) {
9836: $uname = $cnum;
9837: } else {
9838: $uname = &generate_coursenum($udom,$crstype);
9839: }
9840: } else {
9841: $uname = &generate_coursenum($udom,$crstype);
9842: }
9843: return $uname if ($uname =~ /^error/);
9844: # -------------------------------------------------- Check supplied server name
9845: if (!defined($course_server)) {
9846: if (defined(&domain($udom,'primary'))) {
9847: $course_server = &domain($udom,'primary');
9848: } else {
9849: $course_server = $env{'user.home'};
9850: }
9851: }
9852: my %host_servers =
9853: &Apache::lonnet::get_servers($udom,'library');
9854: unless ($host_servers{$course_server}) {
9855: return 'error: invalid home server for course: '.$course_server;
9856: }
9857: # ------------------------------------------------------------- Make the course
9858: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
9859: $course_server);
9860: unless ($reply eq 'ok') { return 'error: '.$reply; }
9861: my $uhome=&homeserver($uname,$udom,'true');
9862: if (($uhome eq '') || ($uhome eq 'no_host')) {
9863: return 'error: no such course';
9864: }
9865: # ----------------------------------------------------------------- Course made
9866: # log existence
9867: my $now = time;
9868: my $newcourse = {
9869: $udom.'_'.$uname => {
9870: description => $description,
9871: inst_code => $inst_code,
9872: owner => $course_owner,
9873: type => $crstype,
9874: creator => $env{'user.name'}.':'.
9875: $env{'user.domain'},
9876: created => $now,
9877: context => $context,
9878: },
9879: };
9880: &courseidput($udom,$newcourse,$uhome,'notime');
9881: # set toplevel url
9882: my $topurl=$url;
9883: unless ($nonstandard) {
9884: # ------------------------------------------ For standard courses, make top url
9885: my $mapurl=&clutter($url);
9886: if ($mapurl eq '/res/') { $mapurl=''; }
9887: $env{'form.initmap'}=(<<ENDINITMAP);
9888: <map>
9889: <resource id="1" type="start"></resource>
9890: <resource id="2" src="$mapurl"></resource>
9891: <resource id="3" type="finish"></resource>
9892: <link index="1" from="1" to="2"></link>
9893: <link index="2" from="2" to="3"></link>
9894: </map>
9895: ENDINITMAP
9896: $topurl=&declutter(
9897: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
9898: );
9899: }
9900: # ----------------------------------------------------------- Write preferences
9901: &writecoursepref($udom.'_'.$uname,
9902: ('description' => $description,
9903: 'url' => $topurl,
9904: 'internal.creator' => $env{'user.name'}.':'.
9905: $env{'user.domain'},
9906: 'internal.created' => $now,
9907: 'internal.creationcontext' => $context)
9908: );
9909: return '/'.$udom.'/'.$uname;
9910: }
9911:
9912: # ------------------------------------------------------------------- Create ID
9913: sub generate_coursenum {
9914: my ($udom,$crstype) = @_;
9915: my $domdesc = &domain($udom);
9916: return 'error: invalid domain' if ($domdesc eq '');
9917: my $first;
9918: if ($crstype eq 'Community') {
9919: $first = '0';
9920: } else {
9921: $first = int(1+rand(9));
9922: }
9923: my $uname=$first.
9924: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9925: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9926: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9927: # ----------------------------------------------- Make sure that does not exist
9928: my $uhome=&homeserver($uname,$udom,'true');
9929: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9930: if ($crstype eq 'Community') {
9931: $first = '0';
9932: } else {
9933: $first = int(1+rand(9));
9934: }
9935: $uname=$first.
9936: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9937: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9938: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9939: $uhome=&homeserver($uname,$udom,'true');
9940: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9941: return 'error: unable to generate unique course-ID';
9942: }
9943: }
9944: return $uname;
9945: }
9946:
9947: sub is_course {
9948: my ($cdom, $cnum) = scalar(@_) == 1 ?
9949: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9950:
9951: return unless $cdom and $cnum;
9952:
9953: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9954: '.');
9955:
9956: return unless(exists($courses{$cdom.'_'.$cnum}));
9957: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
9958: }
9959:
9960: sub store_userdata {
9961: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
9962: my $result;
9963: if ($datakey ne '') {
9964: if (ref($storehash) eq 'HASH') {
9965: if ($udom eq '' || $uname eq '') {
9966: $udom = $env{'user.domain'};
9967: $uname = $env{'user.name'};
9968: }
9969: my $uhome=&homeserver($uname,$udom);
9970: if (($uhome eq '') || ($uhome eq 'no_host')) {
9971: $result = 'error: no_host';
9972: } else {
9973: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9974: $storehash->{'host'} = $perlvar{'lonHostID'};
9975:
9976: my $namevalue='';
9977: foreach my $key (keys(%{$storehash})) {
9978: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9979: }
9980: $namevalue=~s/\&$//;
9981: unless ($namespace eq 'courserequests') {
9982: $datakey = &escape($datakey);
9983: }
9984: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9985: $namevalue,$uhome);
9986: }
9987: } else {
9988: $result = 'error: data to store was not a hash reference';
9989: }
9990: } else {
9991: $result= 'error: invalid requestkey';
9992: }
9993: return $result;
9994: }
9995:
9996: # ---------------------------------------------------------- Assign Custom Role
9997:
9998: sub assigncustomrole {
9999: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10000: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10001: $end,$start,$deleteflag,$selfenroll,$context);
10002: }
10003:
10004: # ----------------------------------------------------------------- Revoke Role
10005:
10006: sub revokerole {
10007: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10008: my $now=time;
10009: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10010: }
10011:
10012: # ---------------------------------------------------------- Revoke Custom Role
10013:
10014: sub revokecustomrole {
10015: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10016: my $now=time;
10017: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10018: $deleteflag,$selfenroll,$context);
10019: }
10020:
10021: # ------------------------------------------------------------ Disk usage
10022: sub diskusage {
10023: my ($udom,$uname,$directorypath,$getpropath)=@_;
10024: $directorypath =~ s/\/$//;
10025: my $listing=&reply('du2:'.&escape($directorypath).':'
10026: .&escape($getpropath).':'.&escape($uname).':'
10027: .&escape($udom),homeserver($uname,$udom));
10028: if ($listing eq 'unknown_cmd') {
10029: if ($getpropath) {
10030: $directorypath = &propath($udom,$uname).'/'.$directorypath;
10031: }
10032: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10033: }
10034: return $listing;
10035: }
10036:
10037: sub is_locked {
10038: my ($file_name, $domain, $user, $which) = @_;
10039: my @check;
10040: my $is_locked;
10041: push (@check,$file_name);
10042: my %locked = &get('file_permissions',\@check,
10043: $env{'user.domain'},$env{'user.name'});
10044: my ($tmp)=keys(%locked);
10045: if ($tmp=~/^error:/) { undef(%locked); }
10046:
10047: if (ref($locked{$file_name}) eq 'ARRAY') {
10048: $is_locked = 'false';
10049: foreach my $entry (@{$locked{$file_name}}) {
10050: if (ref($entry) eq 'ARRAY') {
10051: $is_locked = 'true';
10052: if (ref($which) eq 'ARRAY') {
10053: push(@{$which},$entry);
10054: } else {
10055: last;
10056: }
10057: }
10058: }
10059: } else {
10060: $is_locked = 'false';
10061: }
10062: return $is_locked;
10063: }
10064:
10065: sub declutter_portfile {
10066: my ($file) = @_;
10067: $file =~ s{^(/portfolio/|portfolio/)}{/};
10068: return $file;
10069: }
10070:
10071: # ------------------------------------------------------------- Mark as Read Only
10072:
10073: sub mark_as_readonly {
10074: my ($domain,$user,$files,$what) = @_;
10075: my %current_permissions = &dump('file_permissions',$domain,$user);
10076: my ($tmp)=keys(%current_permissions);
10077: if ($tmp=~/^error:/) { undef(%current_permissions); }
10078: foreach my $file (@{$files}) {
10079: $file = &declutter_portfile($file);
10080: push(@{$current_permissions{$file}},$what);
10081: }
10082: &put('file_permissions',\%current_permissions,$domain,$user);
10083: return;
10084: }
10085:
10086: # ------------------------------------------------------------Save Selected Files
10087:
10088: sub save_selected_files {
10089: my ($user, $path, @files) = @_;
10090: my $filename = $user."savedfiles";
10091: my @other_files = &files_not_in_path($user, $path);
10092: open (OUT, '>'.$tmpdir.$filename);
10093: foreach my $file (@files) {
10094: print (OUT $env{'form.currentpath'}.$file."\n");
10095: }
10096: foreach my $file (@other_files) {
10097: print (OUT $file."\n");
10098: }
10099: close (OUT);
10100: return 'ok';
10101: }
10102:
10103: sub clear_selected_files {
10104: my ($user) = @_;
10105: my $filename = $user."savedfiles";
10106: open (OUT, '>'.LONCAPA::tempdir().$filename);
10107: print (OUT undef);
10108: close (OUT);
10109: return ("ok");
10110: }
10111:
10112: sub files_in_path {
10113: my ($user, $path) = @_;
10114: my $filename = $user."savedfiles";
10115: my %return_files;
10116: open (IN, '<'.LONCAPA::tempdir().$filename);
10117: while (my $line_in = <IN>) {
10118: chomp ($line_in);
10119: my @paths_and_file = split (m!/!, $line_in);
10120: my $file_part = pop (@paths_and_file);
10121: my $path_part = join ('/', @paths_and_file);
10122: $path_part.='/';
10123: my $path_and_file = $path_part.$file_part;
10124: if ($path_part eq $path) {
10125: $return_files{$file_part}= 'selected';
10126: }
10127: }
10128: close (IN);
10129: return (\%return_files);
10130: }
10131:
10132: # called in portfolio select mode, to show files selected NOT in current directory
10133: sub files_not_in_path {
10134: my ($user, $path) = @_;
10135: my $filename = $user."savedfiles";
10136: my @return_files;
10137: my $path_part;
10138: open(IN, '<'.LONCAPA::.$filename);
10139: while (my $line = <IN>) {
10140: #ok, I know it's clunky, but I want it to work
10141: my @paths_and_file = split(m|/|, $line);
10142: my $file_part = pop(@paths_and_file);
10143: chomp($file_part);
10144: my $path_part = join('/', @paths_and_file);
10145: $path_part .= '/';
10146: my $path_and_file = $path_part.$file_part;
10147: if ($path_part ne $path) {
10148: push(@return_files, ($path_and_file));
10149: }
10150: }
10151: close(OUT);
10152: return (@return_files);
10153: }
10154:
10155: #------------------------------Submitted/Handedback Portfolio Files Versioning
10156:
10157: sub portfiles_versioning {
10158: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10159: my $portfolio_root = '/userfiles/portfolio';
10160: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10161: foreach my $file (@{$portfiles}) {
10162: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10163: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10164: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10165: my $getpropath = 1;
10166: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10167: $stu_name,$getpropath);
10168: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10169: my $new_answer =
10170: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10171: if ($new_answer ne 'problem getting file') {
10172: push(@{$versioned_portfiles}, $directory.$new_answer);
10173: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10174: [$symb,$env{'request.course.id'},'graded']);
10175: }
10176: }
10177: }
10178:
10179: sub get_next_version {
10180: my ($answer_name, $answer_ext, $dir_list) = @_;
10181: my $version;
10182: if (ref($dir_list) eq 'ARRAY') {
10183: foreach my $row (@{$dir_list}) {
10184: my ($file) = split(/\&/,$row,2);
10185: my ($file_name,$file_version,$file_ext) =
10186: &file_name_version_ext($file);
10187: if (($file_name eq $answer_name) &&
10188: ($file_ext eq $answer_ext)) {
10189: # gets here if filename and extension match,
10190: # regardless of version
10191: if ($file_version ne '') {
10192: # a versioned file is found so save it for later
10193: if ($file_version > $version) {
10194: $version = $file_version;
10195: }
10196: }
10197: }
10198: }
10199: }
10200: $version ++;
10201: return($version);
10202: }
10203:
10204: sub version_selected_portfile {
10205: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10206: my ($answer_name,$answer_ver,$answer_ext) =
10207: &file_name_version_ext($file_name);
10208: my $new_answer;
10209: $env{'form.copy'} =
10210: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10211: if($env{'form.copy'} eq '-1') {
10212: $new_answer = 'problem getting file';
10213: } else {
10214: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10215: my $copy_result =
10216: &finishuserfileupload($stu_name,$domain,'copy',
10217: '/portfolio'.$directory.$new_answer);
10218: }
10219: undef($env{'form.copy'});
10220: return ($new_answer);
10221: }
10222:
10223: sub file_name_version_ext {
10224: my ($file)=@_;
10225: my @file_parts = split(/\./, $file);
10226: my ($name,$version,$ext);
10227: if (@file_parts > 1) {
10228: $ext=pop(@file_parts);
10229: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10230: $version=pop(@file_parts);
10231: }
10232: $name=join('.',@file_parts);
10233: } else {
10234: $name=join('.',@file_parts);
10235: }
10236: return($name,$version,$ext);
10237: }
10238:
10239: #----------------------------------------------Get portfolio file permissions
10240:
10241: sub get_portfile_permissions {
10242: my ($domain,$user) = @_;
10243: my %current_permissions = &dump('file_permissions',$domain,$user);
10244: my ($tmp)=keys(%current_permissions);
10245: if ($tmp=~/^error:/) { undef(%current_permissions); }
10246: return \%current_permissions;
10247: }
10248:
10249: #---------------------------------------------Get portfolio file access controls
10250:
10251: sub get_access_controls {
10252: my ($current_permissions,$group,$file) = @_;
10253: my %access;
10254: my $real_file = $file;
10255: $file =~ s/\.meta$//;
10256: if (defined($file)) {
10257: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10258: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10259: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10260: }
10261: }
10262: } else {
10263: foreach my $key (keys(%{$current_permissions})) {
10264: if ($key =~ /\0accesscontrol$/) {
10265: if (defined($group)) {
10266: if ($key !~ m-^\Q$group\E/-) {
10267: next;
10268: }
10269: }
10270: my ($fullpath) = split(/\0/,$key);
10271: if (ref($$current_permissions{$key}) eq 'HASH') {
10272: foreach my $control (keys(%{$$current_permissions{$key}})) {
10273: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10274: }
10275: }
10276: }
10277: }
10278: }
10279: return %access;
10280: }
10281:
10282: sub modify_access_controls {
10283: my ($file_name,$changes,$domain,$user)=@_;
10284: my ($outcome,$deloutcome);
10285: my %store_permissions;
10286: my %new_values;
10287: my %new_control;
10288: my %translation;
10289: my @deletions = ();
10290: my $now = time;
10291: if (exists($$changes{'activate'})) {
10292: if (ref($$changes{'activate'}) eq 'HASH') {
10293: my @newitems = sort(keys(%{$$changes{'activate'}}));
10294: my $numnew = scalar(@newitems);
10295: for (my $i=0; $i<$numnew; $i++) {
10296: my $newkey = $newitems[$i];
10297: my $newid = &Apache::loncommon::get_cgi_id();
10298: if ($newkey =~ /^\d+:/) {
10299: $newkey =~ s/^(\d+)/$newid/;
10300: $translation{$1} = $newid;
10301: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10302: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10303: $translation{$1} = $newid;
10304: }
10305: $new_values{$file_name."\0".$newkey} =
10306: $$changes{'activate'}{$newitems[$i]};
10307: $new_control{$newkey} = $now;
10308: }
10309: }
10310: }
10311: my %todelete;
10312: my %changed_items;
10313: foreach my $action ('delete','update') {
10314: if (exists($$changes{$action})) {
10315: if (ref($$changes{$action}) eq 'HASH') {
10316: foreach my $key (keys(%{$$changes{$action}})) {
10317: my ($itemnum) = ($key =~ /^([^:]+):/);
10318: if ($action eq 'delete') {
10319: $todelete{$itemnum} = 1;
10320: } else {
10321: $changed_items{$itemnum} = $key;
10322: }
10323: }
10324: }
10325: }
10326: }
10327: # get lock on access controls for file.
10328: my $lockhash = {
10329: $file_name."\0".'locked_access_records' => $env{'user.name'}.
10330: ':'.$env{'user.domain'},
10331: };
10332: my $tries = 0;
10333: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10334:
10335: while (($gotlock ne 'ok') && $tries < 10) {
10336: $tries ++;
10337: sleep(0.1);
10338: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10339: }
10340: if ($gotlock eq 'ok') {
10341: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10342: my ($tmp)=keys(%curr_permissions);
10343: if ($tmp=~/^error:/) { undef(%curr_permissions); }
10344: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10345: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10346: if (ref($curr_controls) eq 'HASH') {
10347: foreach my $control_item (keys(%{$curr_controls})) {
10348: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10349: if (defined($todelete{$itemnum})) {
10350: push(@deletions,$file_name."\0".$control_item);
10351: } else {
10352: if (defined($changed_items{$itemnum})) {
10353: $new_control{$changed_items{$itemnum}} = $now;
10354: push(@deletions,$file_name."\0".$control_item);
10355: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10356: } else {
10357: $new_control{$control_item} = $$curr_controls{$control_item};
10358: }
10359: }
10360: }
10361: }
10362: }
10363: my ($group);
10364: if (&is_course($domain,$user)) {
10365: ($group,my $file) = split(/\//,$file_name,2);
10366: }
10367: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10368: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10369: $outcome = &put('file_permissions',\%new_values,$domain,$user);
10370: # remove lock
10371: my @del_lock = ($file_name."\0".'locked_access_records');
10372: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10373: my $sqlresult =
10374: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10375: $group);
10376: } else {
10377: $outcome = "error: could not obtain lockfile\n";
10378: }
10379: return ($outcome,$deloutcome,\%new_values,\%translation);
10380: }
10381:
10382: sub make_public_indefinitely {
10383: my (@requrl) = @_;
10384: return &automated_portfile_access('public',\@requrl);
10385: }
10386:
10387: sub automated_portfile_access {
10388: my ($accesstype,$addsref,$delsref,$info) = @_;
10389: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
10390: return 'invalid';
10391: }
10392: my %urls;
10393: if (ref($addsref) eq 'ARRAY') {
10394: foreach my $requrl (@{$addsref}) {
10395: if (&is_portfolio_url($requrl)) {
10396: unless (exists($urls{$requrl})) {
10397: $urls{$requrl} = 'add';
10398: }
10399: }
10400: }
10401: }
10402: if (ref($delsref) eq 'ARRAY') {
10403: foreach my $requrl (@{$delsref}) {
10404: if (&is_portfolio_url($requrl)) {
10405: unless (exists($urls{$requrl})) {
10406: $urls{$requrl} = 'delete';
10407: }
10408: }
10409: }
10410: }
10411: unless (keys(%urls)) {
10412: return 'invalid';
10413: }
10414: my $ip;
10415: if ($accesstype eq 'ip') {
10416: if (ref($info) eq 'HASH') {
10417: if ($info->{'ip'} ne '') {
10418: $ip = $info->{'ip'};
10419: }
10420: }
10421: if ($ip eq '') {
10422: return 'invalid';
10423: }
10424: }
10425: my $errors;
10426: my $now = time;
10427: my %current_perms;
10428: foreach my $requrl (sort(keys(%urls))) {
10429: my $action;
10430: if ($urls{$requrl} eq 'add') {
10431: $action = 'activate';
10432: } else {
10433: $action = 'none';
10434: }
10435: my $aclnum = 0;
10436: my (undef,$udom,$unum,$file_name,$group) =
10437: &parse_portfolio_url($requrl);
10438: unless (exists($current_perms{$unum.':'.$udom})) {
10439: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
10440: }
10441: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
10442: $group,$file_name);
10443: foreach my $key (keys(%{$access_controls{$file_name}})) {
10444: my ($num,$scope,$end,$start) =
10445: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10446: if ($scope eq $accesstype) {
10447: if (($start <= $now) && ($end == 0)) {
10448: if ($accesstype eq 'ip') {
10449: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
10450: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
10451: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
10452: if ($urls{$requrl} eq 'add') {
10453: $action = 'none';
10454: last;
10455: } else {
10456: $action = 'delete';
10457: $aclnum = $num;
10458: last;
10459: }
10460: }
10461: }
10462: }
10463: } elsif ($accesstype eq 'public') {
10464: if ($urls{$requrl} eq 'add') {
10465: $action = 'none';
10466: last;
10467: } else {
10468: $action = 'delete';
10469: $aclnum = $num;
10470: last;
10471: }
10472: }
10473: } elsif ($accesstype eq 'public') {
10474: $action = 'update';
10475: $aclnum = $num;
10476: last;
10477: }
10478: }
10479: }
10480: if ($action eq 'none') {
10481: next;
10482: } else {
10483: my %changes;
10484: my $newend = 0;
10485: my $newstart = $now;
10486: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
10487: $changes{$action}{$newkey} = {
10488: type => $accesstype,
10489: time => {
10490: start => $newstart,
10491: end => $newend,
10492: },
10493: };
10494: if ($accesstype eq 'ip') {
10495: $changes{$action}{$newkey}{'ip'} = [$ip];
10496: }
10497: my ($outcome,$deloutcome,$new_values,$translation) =
10498: &modify_access_controls($file_name,\%changes,$udom,$unum);
10499: unless ($outcome eq 'ok') {
10500: $errors .= $outcome.' ';
10501: }
10502: }
10503: }
10504: if ($errors) {
10505: $errors =~ s/\s$//;
10506: return $errors;
10507: } else {
10508: return 'ok';
10509: }
10510: }
10511:
10512: #------------------------------------------------------Get Marked as Read Only
10513:
10514: sub get_marked_as_readonly {
10515: my ($domain,$user,$what,$group) = @_;
10516: my $current_permissions = &get_portfile_permissions($domain,$user);
10517: my @readonly_files;
10518: my $cmp1=$what;
10519: if (ref($what)) { $cmp1=join('',@{$what}) };
10520: while (my ($file_name,$value) = each(%{$current_permissions})) {
10521: if (defined($group)) {
10522: if ($file_name !~ m-^\Q$group\E/-) {
10523: next;
10524: }
10525: }
10526: if (ref($value) eq "ARRAY"){
10527: foreach my $stored_what (@{$value}) {
10528: my $cmp2=$stored_what;
10529: if (ref($stored_what) eq 'ARRAY') {
10530: $cmp2=join('',@{$stored_what});
10531: }
10532: if ($cmp1 eq $cmp2) {
10533: push(@readonly_files, $file_name);
10534: last;
10535: } elsif (!defined($what)) {
10536: push(@readonly_files, $file_name);
10537: last;
10538: }
10539: }
10540: }
10541: }
10542: return @readonly_files;
10543: }
10544: #-----------------------------------------------------------Get Marked as Read Only Hash
10545:
10546: sub get_marked_as_readonly_hash {
10547: my ($current_permissions,$group,$what) = @_;
10548: my %readonly_files;
10549: while (my ($file_name,$value) = each(%{$current_permissions})) {
10550: if (defined($group)) {
10551: if ($file_name !~ m-^\Q$group\E/-) {
10552: next;
10553: }
10554: }
10555: if (ref($value) eq "ARRAY"){
10556: foreach my $stored_what (@{$value}) {
10557: if (ref($stored_what) eq 'ARRAY') {
10558: foreach my $lock_descriptor(@{$stored_what}) {
10559: if ($lock_descriptor eq 'graded') {
10560: $readonly_files{$file_name} = 'graded';
10561: } elsif ($lock_descriptor eq 'handback') {
10562: $readonly_files{$file_name} = 'handback';
10563: } else {
10564: if (!exists($readonly_files{$file_name})) {
10565: $readonly_files{$file_name} = 'locked';
10566: }
10567: }
10568: }
10569: }
10570: }
10571: }
10572: }
10573: return %readonly_files;
10574: }
10575: # ------------------------------------------------------------ Unmark as Read Only
10576:
10577: sub unmark_as_readonly {
10578: # unmarks $file_name (if $file_name is defined), or all files locked by $what
10579: # for portfolio submissions, $what contains [$symb,$crsid]
10580: my ($domain,$user,$what,$file_name,$group) = @_;
10581: $file_name = &declutter_portfile($file_name);
10582: my $symb_crs = $what;
10583: if (ref($what)) { $symb_crs=join('',@$what); }
10584: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
10585: my ($tmp)=keys(%current_permissions);
10586: if ($tmp=~/^error:/) { undef(%current_permissions); }
10587: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
10588: foreach my $file (@readonly_files) {
10589: my $clean_file = &declutter_portfile($file);
10590: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
10591: my $current_locks = $current_permissions{$file};
10592: my @new_locks;
10593: my @del_keys;
10594: if (ref($current_locks) eq "ARRAY"){
10595: foreach my $locker (@{$current_locks}) {
10596: my $compare=$locker;
10597: if (ref($locker) eq 'ARRAY') {
10598: $compare=join('',@{$locker});
10599: if ($compare ne $symb_crs) {
10600: push(@new_locks, $locker);
10601: }
10602: }
10603: }
10604: if (scalar(@new_locks) > 0) {
10605: $current_permissions{$file} = \@new_locks;
10606: } else {
10607: push(@del_keys, $file);
10608: &del('file_permissions',\@del_keys, $domain, $user);
10609: delete($current_permissions{$file});
10610: }
10611: }
10612: }
10613: &put('file_permissions',\%current_permissions,$domain,$user);
10614: return;
10615: }
10616:
10617: # ------------------------------------------------------------ Directory lister
10618:
10619: sub dirlist {
10620: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
10621: $uri=~s/^\///;
10622: $uri=~s/\/$//;
10623: my ($udom, $uname);
10624: if ($getuserdir) {
10625: $udom = $userdomain;
10626: $uname = $username;
10627: } else {
10628: (undef,$udom,$uname)=split(/\//,$uri);
10629: if(defined($userdomain)) {
10630: $udom = $userdomain;
10631: }
10632: if(defined($username)) {
10633: $uname = $username;
10634: }
10635: }
10636: my ($dirRoot,$listing,@listing_results);
10637:
10638: $dirRoot = $perlvar{'lonDocRoot'};
10639: if (defined($getpropath)) {
10640: $dirRoot = &propath($udom,$uname);
10641: $dirRoot =~ s/\/$//;
10642: } elsif (defined($getuserdir)) {
10643: my $subdir=$uname.'__';
10644: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10645: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10646: ."/$udom/$subdir/$uname";
10647: } elsif (defined($alternateRoot)) {
10648: $dirRoot = $alternateRoot;
10649: }
10650:
10651: if($udom) {
10652: if($uname) {
10653: my $uhome = &homeserver($uname,$udom);
10654: if ($uhome eq 'no_host') {
10655: return ([],'no_host');
10656: }
10657: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
10658: .$getuserdir.':'.&escape($dirRoot)
10659: .':'.&escape($uname).':'.&escape($udom),$uhome);
10660: if ($listing eq 'unknown_cmd') {
10661: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
10662: } else {
10663: @listing_results = map { &unescape($_); } split(/:/,$listing);
10664: }
10665: if ($listing eq 'unknown_cmd') {
10666: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
10667: @listing_results = split(/:/,$listing);
10668: } else {
10669: @listing_results = map { &unescape($_); } split(/:/,$listing);
10670: }
10671: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10672: ($listing eq 'rejected') || ($listing eq 'refused') ||
10673: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10674: return ([],$listing);
10675: } else {
10676: return (\@listing_results);
10677: }
10678: } elsif(!$alternateRoot) {
10679: my (%allusers,%listerror);
10680: my %servers = &get_servers($udom,'library');
10681: foreach my $tryserver (keys(%servers)) {
10682: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10683: &escape($udom),$tryserver);
10684: if ($listing eq 'unknown_cmd') {
10685: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10686: $udom, $tryserver);
10687: } else {
10688: @listing_results = map { &unescape($_); } split(/:/,$listing);
10689: }
10690: if ($listing eq 'unknown_cmd') {
10691: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10692: $udom, $tryserver);
10693: @listing_results = split(/:/,$listing);
10694: } else {
10695: @listing_results =
10696: map { &unescape($_); } split(/:/,$listing);
10697: }
10698: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10699: ($listing eq 'rejected') || ($listing eq 'refused') ||
10700: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10701: $listerror{$tryserver} = $listing;
10702: } else {
10703: foreach my $line (@listing_results) {
10704: my ($entry) = split(/&/,$line,2);
10705: $allusers{$entry} = 1;
10706: }
10707: }
10708: }
10709: my @alluserslist=();
10710: foreach my $user (sort(keys(%allusers))) {
10711: push(@alluserslist,$user.'&user');
10712: }
10713:
10714: if (!%listerror) {
10715: # no errors
10716: return (\@alluserslist);
10717: } elsif (scalar(keys(%servers)) == 1) {
10718: # one library server, one error
10719: my ($key) = keys(%listerror);
10720: return (\@alluserslist, $listerror{$key});
10721: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10722: # con_lost indicates that we might miss data from at least one
10723: # library server
10724: return (\@alluserslist, 'con_lost');
10725: } else {
10726: # multiple library servers and no con_lost -> data should be
10727: # complete.
10728: return (\@alluserslist);
10729: }
10730:
10731: } else {
10732: return ([],'missing username');
10733: }
10734: } elsif(!defined($getpropath)) {
10735: my $path = $perlvar{'lonDocRoot'}.'/res/';
10736: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10737: return (\@all_domains);
10738: } else {
10739: return ([],'missing domain');
10740: }
10741: }
10742:
10743: # --------------------------------------------- GetFileTimestamp
10744: # This function utilizes dirlist and returns the date stamp for
10745: # when it was last modified. It will also return an error of -1
10746: # if an error occurs
10747:
10748: sub GetFileTimestamp {
10749: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
10750: $studentDomain = &LONCAPA::clean_domain($studentDomain);
10751: $studentName = &LONCAPA::clean_username($studentName);
10752: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10753: undef,$getuserdir);
10754: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10755: return -1;
10756: }
10757: if (ref($fileref) eq 'ARRAY') {
10758: my @stats = split('&',$fileref->[0]);
10759: # @stats contains first the filename, then the stat output
10760: return $stats[10]; # so this is 10 instead of 9.
10761: } else {
10762: return -1;
10763: }
10764: }
10765:
10766: sub stat_file {
10767: my ($uri) = @_;
10768: $uri = &clutter_with_no_wrapper($uri);
10769:
10770: my ($udom,$uname,$file);
10771: if ($uri =~ m-^/(uploaded|editupload)/-) {
10772: ($udom,$uname,$file) =
10773: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
10774: $file = 'userfiles/'.$file;
10775: }
10776: if ($uri =~ m-^/res/-) {
10777: ($udom,$uname) =
10778: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
10779: $file = $uri;
10780: }
10781:
10782: if (!$udom || !$uname || !$file) {
10783: # unable to handle the uri
10784: return ();
10785: }
10786: my $getpropath;
10787: if ($file =~ /^userfiles\//) {
10788: $getpropath = 1;
10789: }
10790: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10791: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10792: return ();
10793: } else {
10794: if (ref($listref) eq 'ARRAY') {
10795: my @stats = split('&',$listref->[0]);
10796: shift(@stats); #filename is first
10797: return @stats;
10798: }
10799: }
10800: return ();
10801: }
10802:
10803: # --------------------------------------------------------- recursedirs
10804: # Recursive function to traverse either a specific user's Authoring Space
10805: # or corresponding Published Resource Space, and populate the hash ref:
10806: # $dirhashref with URLs of all directories, and if $filehashref hash
10807: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
10808: # or .rights files in resource space, and .meta, .save, .log, and .bak
10809: # files in Authoring Space.
10810: #
10811: # Inputs:
10812: #
10813: # $is_home - true if current server is home server for user's space
10814: # $context - either: priv, or res respectively for Authoring or Resource Space.
10815: # $docroot - Document root (i.e., /home/httpd/html
10816: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
10817: # $relpath - Current path (relative to top level).
10818: # $dirhashref - reference to hash to populate with URLs of directories (Required)
10819: # $filehashref - reference to hash to populate with URLs of files (Optional)
10820: #
10821: # Returns: nothing
10822: #
10823: # Side Effects: populates $dirhashref, and $filehashref (if provided).
10824: #
10825: # Currently used by interface/londocs.pm to create linked select boxes for
10826: # directory and filename to import a Course "Author" resource into a course, and
10827: # also to create linked select boxes for Authoring Space and Directory to choose
10828: # save location for creation of a new "standard" problem from the Course Editor.
10829: #
10830:
10831: sub recursedirs {
10832: my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
10833: return unless (ref($dirhashref) eq 'HASH');
10834: my $currpath = $docroot.$toppath;
10835: if ($relpath) {
10836: $currpath .= "/$relpath";
10837: }
10838: my $savefile;
10839: if (ref($filehashref)) {
10840: $savefile = 1;
10841: }
10842: if ($is_home) {
10843: if (opendir(my $dirh,$currpath)) {
10844: foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
10845: next if ($item eq '');
10846: if (-d "$currpath/$item") {
10847: my $newpath;
10848: if ($relpath) {
10849: $newpath = "$relpath/$item";
10850: } else {
10851: $newpath = $item;
10852: }
10853: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10854: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10855: } elsif ($savefile) {
10856: if ($context eq 'priv') {
10857: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10858: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10859: }
10860: } else {
10861: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
10862: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10863: }
10864: }
10865: }
10866: }
10867: closedir($dirh);
10868: }
10869: } else {
10870: my ($dirlistref,$listerror) =
10871: &dirlist($toppath.$relpath);
10872: my @dir_lines;
10873: my $dirptr=16384;
10874: if (ref($dirlistref) eq 'ARRAY') {
10875: foreach my $dir_line (sort
10876: {
10877: my ($afile)=split('&',$a,2);
10878: my ($bfile)=split('&',$b,2);
10879: return (lc($afile) cmp lc($bfile));
10880: } (@{$dirlistref})) {
10881: my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
10882: split(/\&/,$dir_line,16);
10883: $item =~ s/\s+$//;
10884: next if (($item =~ /^\.\.?$/) || ($obs));
10885: if ($dirptr&$testdir) {
10886: my $newpath;
10887: if ($relpath) {
10888: $newpath = "$relpath/$item";
10889: } else {
10890: $relpath = '/';
10891: $newpath = $item;
10892: }
10893: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10894: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10895: } elsif ($savefile) {
10896: if ($context eq 'priv') {
10897: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10898: $filehashref->{$relpath}{$item} = 1;
10899: }
10900: } else {
10901: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
10902: $filehashref->{$relpath}{$item} = 1;
10903: }
10904: }
10905: }
10906: }
10907: }
10908: }
10909: return;
10910: }
10911:
10912: # -------------------------------------------------------- Value of a Condition
10913:
10914: # gets the value of a specific preevaluated condition
10915: # stored in the string $env{user.state.<cid>}
10916: # or looks up a condition reference in the bighash and if if hasn't
10917: # already been evaluated recurses into docondval to get the value of
10918: # the condition, then memoizing it to
10919: # $env{user.state.<cid>.<condition>}
10920: sub directcondval {
10921: my $number=shift;
10922: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
10923: &Apache::lonuserstate::evalstate();
10924: }
10925: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10926: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10927: } elsif ($number =~ /^_/) {
10928: my $sub_condition;
10929: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10930: &GDBM_READER(),0640)) {
10931: $sub_condition=$bighash{'conditions'.$number};
10932: untie(%bighash);
10933: }
10934: my $value = &docondval($sub_condition);
10935: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
10936: return $value;
10937: }
10938: if ($env{'user.state.'.$env{'request.course.id'}}) {
10939: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
10940: } else {
10941: return 2;
10942: }
10943: }
10944:
10945: # get the collection of conditions for this resource
10946: sub condval {
10947: my $condidx=shift;
10948: my $allpathcond='';
10949: foreach my $cond (split(/\|/,$condidx)) {
10950: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10951: $allpathcond.=
10952: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10953: }
10954: }
10955: $allpathcond=~s/\|$//;
10956: return &docondval($allpathcond);
10957: }
10958:
10959: #evaluates an expression of conditions
10960: sub docondval {
10961: my ($allpathcond) = @_;
10962: my $result=0;
10963: if ($env{'request.course.id'}
10964: && defined($allpathcond)) {
10965: my $operand='|';
10966: my @stack;
10967: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10968: if ($chunk eq '(') {
10969: push @stack,($operand,$result);
10970: } elsif ($chunk eq ')') {
10971: my $before=pop @stack;
10972: if (pop @stack eq '&') {
10973: $result=$result>$before?$before:$result;
10974: } else {
10975: $result=$result>$before?$result:$before;
10976: }
10977: } elsif (($chunk eq '&') || ($chunk eq '|')) {
10978: $operand=$chunk;
10979: } else {
10980: my $new=directcondval($chunk);
10981: if ($operand eq '&') {
10982: $result=$result>$new?$new:$result;
10983: } else {
10984: $result=$result>$new?$result:$new;
10985: }
10986: }
10987: }
10988: }
10989: return $result;
10990: }
10991:
10992: # ---------------------------------------------------- Devalidate courseresdata
10993:
10994: sub devalidatecourseresdata {
10995: my ($coursenum,$coursedomain)=@_;
10996: my $hashid=$coursenum.':'.$coursedomain;
10997: &devalidate_cache_new('courseres',$hashid);
10998: }
10999:
11000:
11001: # --------------------------------------------------- Course Resourcedata Query
11002: #
11003: # Parameters:
11004: # $coursenum - Number of the course.
11005: # $coursedomain - Domain at which the course was created.
11006: # Returns:
11007: # A hash of the course parameters along (I think) with timestamps
11008: # and version info.
11009:
11010: sub get_courseresdata {
11011: my ($coursenum,$coursedomain)=@_;
11012: my $coursehom=&homeserver($coursenum,$coursedomain);
11013: my $hashid=$coursenum.':'.$coursedomain;
11014: my ($result,$cached)=&is_cached_new('courseres',$hashid);
11015: my %dumpreply;
11016: unless (defined($cached)) {
11017: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11018: $result=\%dumpreply;
11019: my ($tmp) = keys(%dumpreply);
11020: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11021: &do_cache_new('courseres',$hashid,$result,600);
11022: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11023: return $tmp;
11024: } elsif ($tmp =~ /^(error)/) {
11025: $result=undef;
11026: &do_cache_new('courseres',$hashid,$result,600);
11027: }
11028: }
11029: return $result;
11030: }
11031:
11032: sub devalidateuserresdata {
11033: my ($uname,$udom)=@_;
11034: my $hashid="$udom:$uname";
11035: &devalidate_cache_new('userres',$hashid);
11036: }
11037:
11038: sub get_userresdata {
11039: my ($uname,$udom)=@_;
11040: #most student don\'t have any data set, check if there is some data
11041: if (&EXT_cache_status($udom,$uname)) { return undef; }
11042:
11043: my $hashid="$udom:$uname";
11044: my ($result,$cached)=&is_cached_new('userres',$hashid);
11045: if (!defined($cached)) {
11046: my %resourcedata=&dump('resourcedata',$udom,$uname);
11047: $result=\%resourcedata;
11048: &do_cache_new('userres',$hashid,$result,600);
11049: }
11050: my ($tmp)=keys(%$result);
11051: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11052: return $result;
11053: }
11054: #error 2 occurs when the .db doesn't exist
11055: if ($tmp!~/error: 2 /) {
11056: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11057: &logthis("<font color=\"blue\">WARNING:".
11058: " Trying to get resource data for ".
11059: $uname." at ".$udom.": ".
11060: $tmp."</font>");
11061: }
11062: } elsif ($tmp=~/error: 2 /) {
11063: #&EXT_cache_set($udom,$uname);
11064: &do_cache_new('userres',$hashid,undef,600);
11065: undef($tmp); # not really an error so don't send it back
11066: }
11067: return $tmp;
11068: }
11069: #----------------------------------------------- resdata - return resource data
11070: # Purpose:
11071: # Return resource data for either users or for a course.
11072: # Parameters:
11073: # $name - Course/user name.
11074: # $domain - Name of the domain the user/course is registered on.
11075: # $type - Type of thing $name is (must be 'course' or 'user')
11076: # $mapp - decluttered URL of enclosing map
11077: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
11078: # $recurseup - Ref to array of map URLs, starting with map containing
11079: # $mapp up through hierarchy of nested maps to top level map.
11080: # $courseid - CourseID (first part of param identifier).
11081: # $modifier - Middle part of param identifier.
11082: # $what - Last part of param identifier.
11083: # @which - Array of names of resources desired.
11084: # Returns:
11085: # The value of the first reasource in @which that is found in the
11086: # resource hash.
11087: # Exceptional Conditions:
11088: # If the $type passed in is not valid (not the string 'course' or
11089: # 'user', an undefined reference is returned.
11090: # If none of the resources are found, an undef is returned
11091: sub resdata {
11092: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11093: $modifier,$what,@which)=@_;
11094: my $result;
11095: if ($type eq 'course') {
11096: $result=&get_courseresdata($name,$domain);
11097: } elsif ($type eq 'user') {
11098: $result=&get_userresdata($name,$domain);
11099: }
11100: if (!ref($result)) { return $result; }
11101: foreach my $item (@which) {
11102: if ($item->[1] eq 'course') {
11103: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11104: unless ($$recursed) {
11105: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11106: $$recursed = 1;
11107: }
11108: foreach my $item (@${recurseup}) {
11109: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11110: last if (defined($result->{$norecursechk}));
11111: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11112: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11113: }
11114: }
11115: }
11116: if (defined($result->{$item->[0]})) {
11117: return [$result->{$item->[0]},$item->[1]];
11118: }
11119: }
11120: return undef;
11121: }
11122:
11123: sub get_domain_ltitools {
11124: my ($cdom) = @_;
11125: my %ltitools;
11126: my ($result,$cached)=&is_cached_new('ltitools',$cdom);
11127: if (defined($cached)) {
11128: if (ref($result) eq 'HASH') {
11129: %ltitools = %{$result};
11130: }
11131: } else {
11132: my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
11133: if (ref($domconfig{'ltitools'}) eq 'HASH') {
11134: %ltitools = %{$domconfig{'ltitools'}};
11135: my %encdomconfig = &get_dom('encconfig',['ltitools'],$cdom);
11136: if (ref($encdomconfig{'ltitools'}) eq 'HASH') {
11137: foreach my $id (keys(%ltitools)) {
11138: if (ref($encdomconfig{'ltitools'}{$id}) eq 'HASH') {
11139: foreach my $item ('key','secret') {
11140: $ltitools{$id}{$item} = $encdomconfig{'ltitools'}{$id}{$item};
11141: }
11142: }
11143: }
11144: }
11145: }
11146: my $cachetime = 24*60*60;
11147: &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
11148: }
11149: return %ltitools;
11150: }
11151:
11152: sub get_numsuppfiles {
11153: my ($cnum,$cdom,$ignorecache)=@_;
11154: my $hashid=$cnum.':'.$cdom;
11155: my ($suppcount,$cached);
11156: unless ($ignorecache) {
11157: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11158: }
11159: unless (defined($cached)) {
11160: my $chome=&homeserver($cnum,$cdom);
11161: unless ($chome eq 'no_host') {
11162: ($suppcount,my $errors) = (0,0);
11163: my $suppmap = 'supplemental.sequence';
11164: ($suppcount,$errors) =
11165: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11166: }
11167: &do_cache_new('suppcount',$hashid,$suppcount,600);
11168: }
11169: return $suppcount;
11170: }
11171:
11172: #
11173: # EXT resource caching routines
11174: #
11175:
11176: {
11177: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11178: #
11179: # The course for which we cache
11180: my $cachedmapkey='';
11181: # The cached recursive maps for this course
11182: my %cachedmaps=();
11183: # When this was last done
11184: my $cachedmaptime='';
11185:
11186: sub clear_EXT_cache_status {
11187: &delenv('cache.EXT.');
11188: }
11189:
11190: sub EXT_cache_status {
11191: my ($target_domain,$target_user) = @_;
11192: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11193: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11194: # We know already the user has no data
11195: return 1;
11196: } else {
11197: return 0;
11198: }
11199: }
11200:
11201: sub EXT_cache_set {
11202: my ($target_domain,$target_user) = @_;
11203: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11204: #&appenv({$cachename => time});
11205: }
11206:
11207: # --------------------------------------------------------- Value of a Variable
11208: sub EXT {
11209:
11210: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11211: unless ($varname) { return ''; }
11212: #get real user name/domain, courseid and symb
11213: my $courseid;
11214: my $publicuser;
11215: if ($symbparm) {
11216: $symbparm=&get_symb_from_alias($symbparm);
11217: }
11218: if (!($uname && $udom)) {
11219: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11220: if (!$symbparm) { $symbparm=$cursymb; }
11221: } else {
11222: $courseid=$env{'request.course.id'};
11223: }
11224: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11225: my $rest;
11226: if (defined($therest[0])) {
11227: $rest=join('.',@therest);
11228: } else {
11229: $rest='';
11230: }
11231:
11232: my $qualifierrest=$qualifier;
11233: if ($rest) { $qualifierrest.='.'.$rest; }
11234: my $spacequalifierrest=$space;
11235: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11236: if ($realm eq 'user') {
11237: # --------------------------------------------------------------- user.resource
11238: if ($space eq 'resource') {
11239: if ( (defined($Apache::lonhomework::parsing_a_problem)
11240: || defined($Apache::lonhomework::parsing_a_task))
11241: &&
11242: ($symbparm eq &symbread()) ) {
11243: # if we are in the middle of processing the resource the
11244: # get the value we are planning on committing
11245: if (defined($Apache::lonhomework::results{$qualifierrest})) {
11246: return $Apache::lonhomework::results{$qualifierrest};
11247: } else {
11248: return $Apache::lonhomework::history{$qualifierrest};
11249: }
11250: } else {
11251: my %restored;
11252: if ($publicuser || $env{'request.state'} eq 'construct') {
11253: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11254: } else {
11255: %restored=&restore($symbparm,$courseid,$udom,$uname);
11256: }
11257: return $restored{$qualifierrest};
11258: }
11259: # ----------------------------------------------------------------- user.access
11260: } elsif ($space eq 'access') {
11261: # FIXME - not supporting calls for a specific user
11262: return &allowed($qualifier,$rest);
11263: # ------------------------------------------ user.preferences, user.environment
11264: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11265: if (($uname eq $env{'user.name'}) &&
11266: ($udom eq $env{'user.domain'})) {
11267: return $env{join('.',('environment',$qualifierrest))};
11268: } else {
11269: my %returnhash;
11270: if (!$publicuser) {
11271: %returnhash=&userenvironment($udom,$uname,
11272: $qualifierrest);
11273: }
11274: return $returnhash{$qualifierrest};
11275: }
11276: # ----------------------------------------------------------------- user.course
11277: } elsif ($space eq 'course') {
11278: # FIXME - not supporting calls for a specific user
11279: return $env{join('.',('request.course',$qualifier))};
11280: # ------------------------------------------------------------------- user.role
11281: } elsif ($space eq 'role') {
11282: # FIXME - not supporting calls for a specific user
11283: my ($role,$where)=split(/\./,$env{'request.role'});
11284: if ($qualifier eq 'value') {
11285: return $role;
11286: } elsif ($qualifier eq 'extent') {
11287: return $where;
11288: }
11289: # ----------------------------------------------------------------- user.domain
11290: } elsif ($space eq 'domain') {
11291: return $udom;
11292: # ------------------------------------------------------------------- user.name
11293: } elsif ($space eq 'name') {
11294: return $uname;
11295: # ---------------------------------------------------- Any other user namespace
11296: } else {
11297: my %reply;
11298: if (!$publicuser) {
11299: %reply=&get($space,[$qualifierrest],$udom,$uname);
11300: }
11301: return $reply{$qualifierrest};
11302: }
11303: } elsif ($realm eq 'query') {
11304: # ---------------------------------------------- pull stuff out of query string
11305: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11306: [$spacequalifierrest]);
11307: return $env{'form.'.$spacequalifierrest};
11308: } elsif ($realm eq 'request') {
11309: # ------------------------------------------------------------- request.browser
11310: if ($space eq 'browser') {
11311: return $env{'browser.'.$qualifier};
11312: # ------------------------------------------------------------ request.filename
11313: } else {
11314: return $env{'request.'.$spacequalifierrest};
11315: }
11316: } elsif ($realm eq 'course') {
11317: # ---------------------------------------------------------- course.description
11318: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11319: } elsif ($realm eq 'resource') {
11320:
11321: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11322: if (!$symbparm) { $symbparm=&symbread(); }
11323: }
11324:
11325: if ($qualifier eq '') {
11326: if ($space eq 'title') {
11327: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11328: return &gettitle($symbparm);
11329: }
11330:
11331: if ($space eq 'map') {
11332: my ($map) = &decode_symb($symbparm);
11333: return &symbread($map);
11334: }
11335: if ($space eq 'maptitle') {
11336: my ($map) = &decode_symb($symbparm);
11337: return &gettitle($map);
11338: }
11339: if ($space eq 'filename') {
11340: if ($symbparm) {
11341: return &clutter((&decode_symb($symbparm))[2]);
11342: }
11343: return &hreflocation('',$env{'request.filename'});
11344: }
11345:
11346: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11347: if ($space eq 'visibleparts') {
11348: my $navmap = Apache::lonnavmaps::navmap->new();
11349: my $item;
11350: if (ref($navmap)) {
11351: my $res = $navmap->getBySymb($symbparm);
11352: my $parts = $res->parts();
11353: if (ref($parts) eq 'ARRAY') {
11354: $item = join(',',@{$parts});
11355: }
11356: undef($navmap);
11357: }
11358: return $item;
11359: }
11360: }
11361: }
11362:
11363: my ($section, $group, @groups, @recurseup, $recursed);
11364: my ($courselevelm,$courseleveli,$courselevel,$mapp);
11365: if (($courseid eq '') && ($cid)) {
11366: $courseid = $cid;
11367: }
11368: if (($symbparm && $courseid) &&
11369: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
11370:
11371: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11372:
11373: # ----------------------------------------------------- Cascading lookup scheme
11374: my $symbp=$symbparm;
11375: $mapp=&deversion((&decode_symb($symbp))[0]);
11376: my $symbparm=$symbp.'.'.$spacequalifierrest;
11377: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
11378: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11379: if (($env{'user.name'} eq $uname) &&
11380: ($env{'user.domain'} eq $udom)) {
11381: $section=$env{'request.course.sec'};
11382: @groups = split(/:/,$env{'request.course.groups'});
11383: @groups=&sort_course_groups($courseid,@groups);
11384: } else {
11385: if (! defined($usection)) {
11386: $section=&getsection($udom,$uname,$courseid);
11387: } else {
11388: $section = $usection;
11389: }
11390: @groups = &get_users_groups($udom,$uname,$courseid);
11391: }
11392:
11393: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11394: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11395: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
11396: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11397:
11398: $courselevel=$courseid.'.'.$spacequalifierrest;
11399: my $courselevelr=$courseid.'.'.$symbparm;
11400: $courseleveli=$courseid.'.'.$recurseparm;
11401: $courselevelm=$courseid.'.'.$mapparm;
11402:
11403: # ----------------------------------------------------------- first, check user
11404:
11405: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
11406: \@recurseup,$courseid,'.',$spacequalifierrest,
11407: ([$courselevelr,'resource'],
11408: [$courselevelm,'map' ],
11409: [$courseleveli,'map' ],
11410: [$courselevel, 'course' ]));
11411: if (defined($userreply)) { return &get_reply($userreply); }
11412:
11413: # ------------------------------------------------ second, check some of course
11414: my $coursereply;
11415: if (@groups > 0) {
11416: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11417: $recurseparm,$mapparm,$spacequalifierrest,
11418: $mapp,\$recursed,\@recurseup);
11419: if (defined($coursereply)) { return &get_reply($coursereply); }
11420: }
11421:
11422: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11423: $env{'course.'.$courseid.'.domain'},
11424: 'course',$mapp,\$recursed,\@recurseup,
11425: $courseid,'.['.$section.'].',$spacequalifierrest,
11426: ([$seclevelr, 'resource'],
11427: [$seclevelm, 'map' ],
11428: [$secleveli, 'map' ],
11429: [$seclevel, 'course' ],
11430: [$courselevelr,'resource']));
11431: if (defined($coursereply)) { return &get_reply($coursereply); }
11432:
11433: # ------------------------------------------------------ third, check map parms
11434: my %parmhash=();
11435: my $thisparm='';
11436: if (tie(%parmhash,'GDBM_File',
11437: $env{'request.course.fn'}.'_parms.db',
11438: &GDBM_READER(),0640)) {
11439: $thisparm=$parmhash{$symbparm};
11440: untie(%parmhash);
11441: }
11442: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
11443: }
11444: # ------------------------------------------ fourth, look in resource metadata
11445:
11446: my $what = $spacequalifierrest;
11447: $what=~s/\./\_/;
11448: my $filename;
11449: if (!$symbparm) { $symbparm=&symbread(); }
11450: if ($symbparm) {
11451: $filename=(&decode_symb($symbparm))[2];
11452: } else {
11453: $filename=$env{'request.filename'};
11454: }
11455: my $metadata=&metadata($filename,$what);
11456: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11457: $metadata=&metadata($filename,'parameter_'.$what);
11458: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11459:
11460: # ----------------------------------------------- fifth, look in rest of course
11461: if ($symbparm && defined($courseid) &&
11462: $courseid eq $env{'request.course.id'}) {
11463: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11464: $env{'course.'.$courseid.'.domain'},
11465: 'course',$mapp,\$recursed,\@recurseup,
11466: $courseid,'.',$spacequalifierrest,
11467: ([$courselevelm,'map' ],
11468: [$courseleveli,'map' ],
11469: [$courselevel, 'course']));
11470: if (defined($coursereply)) { return &get_reply($coursereply); }
11471: }
11472: # ------------------------------------------------------------------ Cascade up
11473: unless ($space eq '0') {
11474: my @parts=split(/_/,$space);
11475: my $id=pop(@parts);
11476: my $part=join('_',@parts);
11477: if ($part eq '') { $part='0'; }
11478: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
11479: $symbparm,$udom,$uname,$section,1);
11480: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
11481: }
11482: if ($recurse) { return undef; }
11483: my $pack_def=&packages_tab_default($filename,$varname);
11484: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
11485: # ---------------------------------------------------- Any other user namespace
11486: } elsif ($realm eq 'environment') {
11487: # ----------------------------------------------------------------- environment
11488: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11489: return $env{'environment.'.$spacequalifierrest};
11490: } else {
11491: if ($uname eq 'anonymous' && $udom eq '') {
11492: return '';
11493: }
11494: my %returnhash=&userenvironment($udom,$uname,
11495: $spacequalifierrest);
11496: return $returnhash{$spacequalifierrest};
11497: }
11498: } elsif ($realm eq 'system') {
11499: # ----------------------------------------------------------------- system.time
11500: if ($space eq 'time') {
11501: return time;
11502: }
11503: } elsif ($realm eq 'server') {
11504: # ----------------------------------------------------------------- system.time
11505: if ($space eq 'name') {
11506: return $ENV{'SERVER_NAME'};
11507: }
11508: }
11509: return '';
11510: }
11511:
11512: sub get_reply {
11513: my ($reply_value) = @_;
11514: if (ref($reply_value) eq 'ARRAY') {
11515: if (wantarray) {
11516: return @$reply_value;
11517: }
11518: return $reply_value->[0];
11519: } else {
11520: return $reply_value;
11521: }
11522: }
11523:
11524: sub check_group_parms {
11525: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
11526: $recursed,$recurseupref) = @_;
11527: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
11528: [$what,'course']);
11529: my $coursereply;
11530: foreach my $group (@{$groups}) {
11531: my @groupitems = ();
11532: foreach my $level (@levels) {
11533: my $item = $courseid.'.['.$group.'].'.$level->[0];
11534: push(@groupitems,[$item,$level->[1]]);
11535: }
11536: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11537: $env{'course.'.$courseid.'.domain'},
11538: 'course',$mapp,$recursed,$recurseupref,
11539: $courseid,'.['.$group.'].',$what,
11540: @groupitems);
11541: last if (defined($coursereply));
11542: }
11543: return $coursereply;
11544: }
11545:
11546: sub get_map_hierarchy {
11547: my ($mapname,$courseid) = @_;
11548: my @recurseup = ();
11549: if ($mapname) {
11550: if (($cachedmapkey eq $courseid) &&
11551: (abs($cachedmaptime-time)<5)) {
11552: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
11553: return @{$cachedmaps{$mapname}};
11554: }
11555: }
11556: my $navmap = Apache::lonnavmaps::navmap->new();
11557: if (ref($navmap)) {
11558: @recurseup = $navmap->recurseup_maps($mapname);
11559: undef($navmap);
11560: $cachedmaps{$mapname} = \@recurseup;
11561: $cachedmaptime=time;
11562: $cachedmapkey=$courseid;
11563: }
11564: }
11565: return @recurseup;
11566: }
11567:
11568: }
11569:
11570: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
11571: my ($courseid,@groups) = @_;
11572: @groups = sort(@groups);
11573: return @groups;
11574: }
11575:
11576: sub packages_tab_default {
11577: my ($uri,$varname)=@_;
11578: my (undef,$part,$name)=split(/\./,$varname);
11579:
11580: my (@extension,@specifics,$do_default);
11581: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
11582: my ($pack_type,$pack_part)=split(/_/,$package,2);
11583: if ($pack_type eq 'default') {
11584: $do_default=1;
11585: } elsif ($pack_type eq 'extension') {
11586: push(@extension,[$package,$pack_type,$pack_part]);
11587: } elsif ($pack_part eq $part || $pack_type eq 'part') {
11588: # only look at packages defaults for packages that this id is
11589: push(@specifics,[$package,$pack_type,$pack_part]);
11590: }
11591: }
11592: # first look for a package that matches the requested part id
11593: foreach my $package (@specifics) {
11594: my (undef,$pack_type,$pack_part)=@{$package};
11595: next if ($pack_part ne $part);
11596: if (defined($packagetab{"$pack_type&$name&default"})) {
11597: return $packagetab{"$pack_type&$name&default"};
11598: }
11599: }
11600: # look for any possible matching non extension_ package
11601: foreach my $package (@specifics) {
11602: my (undef,$pack_type,$pack_part)=@{$package};
11603: if (defined($packagetab{"$pack_type&$name&default"})) {
11604: return $packagetab{"$pack_type&$name&default"};
11605: }
11606: if ($pack_type eq 'part') { $pack_part='0'; }
11607: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11608: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
11609: }
11610: }
11611: # look for any posible extension_ match
11612: foreach my $package (@extension) {
11613: my ($package,$pack_type)=@{$package};
11614: if (defined($packagetab{"$pack_type&$name&default"})) {
11615: return $packagetab{"$pack_type&$name&default"};
11616: }
11617: if (defined($packagetab{$package."&$name&default"})) {
11618: return $packagetab{$package."&$name&default"};
11619: }
11620: }
11621: # look for a global default setting
11622: if ($do_default && defined($packagetab{"default&$name&default"})) {
11623: return $packagetab{"default&$name&default"};
11624: }
11625: return undef;
11626: }
11627:
11628: sub add_prefix_and_part {
11629: my ($prefix,$part)=@_;
11630: my $keyroot;
11631: if (defined($prefix) && $prefix !~ /^__/) {
11632: # prefix that has a part already
11633: $keyroot=$prefix;
11634: } elsif (defined($prefix)) {
11635: # prefix that is missing a part
11636: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11637: } else {
11638: # no prefix at all
11639: if (defined($part)) { $keyroot='_'.$part; }
11640: }
11641: return $keyroot;
11642: }
11643:
11644: # ---------------------------------------------------------------- Get metadata
11645:
11646: my %metaentry;
11647: my %importedpartids;
11648: sub metadata {
11649: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
11650: $uri=&declutter($uri);
11651: # if it is a non metadata possible uri return quickly
11652: if (($uri eq '') ||
11653: (($uri =~ m|^/*adm/|) &&
11654: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
11655: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
11656: return undef;
11657: }
11658: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
11659: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
11660: return undef;
11661: }
11662: my $filename=$uri;
11663: $uri=~s/\.meta$//;
11664: #
11665: # Is the metadata already cached?
11666: # Look at timestamp of caching
11667: # Everything is cached by the main uri, libraries are never directly cached
11668: #
11669: if (!defined($liburi)) {
11670: my ($result,$cached)=&is_cached_new('meta',$uri);
11671: if (defined($cached)) { return $result->{':'.$what}; }
11672: }
11673: {
11674: # Imported parts would go here
11675: my %importedids=();
11676: my @origfileimportpartids=();
11677: my $importedparts=0;
11678: #
11679: # Is this a recursive call for a library?
11680: #
11681: # if (! exists($metacache{$uri})) {
11682: # $metacache{$uri}={};
11683: # }
11684: my $cachetime = 60*60;
11685: if ($liburi) {
11686: $liburi=&declutter($liburi);
11687: $filename=$liburi;
11688: } else {
11689: &devalidate_cache_new('meta',$uri);
11690: undef(%metaentry);
11691: }
11692: my %metathesekeys=();
11693: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
11694: my $metastring;
11695: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
11696: my $which = &hreflocation('','/'.($liburi || $uri));
11697: $metastring =
11698: &Apache::lonnet::ssi_body($which,
11699: ('grade_target' => 'meta'));
11700: $cachetime = 1; # only want this cached in the child not long term
11701: } elsif (($uri !~ m -^(editupload)/-) &&
11702: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
11703: my $file=&filelocation('',&clutter($filename));
11704: #push(@{$metaentry{$uri.'.file'}},$file);
11705: $metastring=&getfile($file);
11706: }
11707: my $parser=HTML::LCParser->new(\$metastring);
11708: my $token;
11709: undef %metathesekeys;
11710: while ($token=$parser->get_token) {
11711: if ($token->[0] eq 'S') {
11712: if (defined($token->[2]->{'package'})) {
11713: #
11714: # This is a package - get package info
11715: #
11716: my $package=$token->[2]->{'package'};
11717: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11718: if (defined($token->[2]->{'id'})) {
11719: $keyroot.='_'.$token->[2]->{'id'};
11720: }
11721: if ($metaentry{':packages'}) {
11722: $metaentry{':packages'}.=','.$package.$keyroot;
11723: } else {
11724: $metaentry{':packages'}=$package.$keyroot;
11725: }
11726: foreach my $pack_entry (keys(%packagetab)) {
11727: my $part=$keyroot;
11728: $part=~s/^\_//;
11729: if ($pack_entry=~/^\Q$package\E\&/ ||
11730: $pack_entry=~/^\Q$package\E_0\&/) {
11731: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
11732: # ignore package.tab specified default values
11733: # here &package_tab_default() will fetch those
11734: if ($subp eq 'default') { next; }
11735: my $value=$packagetab{$pack_entry};
11736: my $unikey;
11737: if ($pack =~ /_0$/) {
11738: $unikey='parameter_0_'.$name;
11739: $part=0;
11740: } else {
11741: $unikey='parameter'.$keyroot.'_'.$name;
11742: }
11743: if ($subp eq 'display') {
11744: $value.=' [Part: '.$part.']';
11745: }
11746: $metaentry{':'.$unikey.'.part'}=$part;
11747: $metathesekeys{$unikey}=1;
11748: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11749: $metaentry{':'.$unikey.'.'.$subp}=$value;
11750: }
11751: if (defined($metaentry{':'.$unikey.'.default'})) {
11752: $metaentry{':'.$unikey}=
11753: $metaentry{':'.$unikey.'.default'};
11754: }
11755: }
11756: }
11757: } else {
11758: #
11759: # This is not a package - some other kind of start tag
11760: #
11761: my $entry=$token->[1];
11762: my $unikey='';
11763:
11764: if ($entry eq 'import') {
11765: #
11766: # Importing a library here
11767: #
11768: my $location=$parser->get_text('/import');
11769: my $dir=$filename;
11770: $dir=~s|[^/]*$||;
11771: $location=&filelocation($dir,$location);
11772:
11773: my $importmode=$token->[2]->{'importmode'};
11774: if ($importmode eq 'problem') {
11775: # Import as problem/response
11776: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11777: } elsif ($importmode eq 'part') {
11778: # Import as part(s)
11779: $importedparts=1;
11780: # We need to get the original file and the imported file to get the part order correct
11781: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11782: # Load and inspect original file
11783: if ($#origfileimportpartids<0) {
11784: undef(%importedpartids);
11785: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11786: my $origfile=&getfile($origfilelocation);
11787: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11788: }
11789:
11790: # Load and inspect imported file
11791: my $impfile=&getfile($location);
11792: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11793: if ($#impfilepartids>=0) {
11794: # This problem had parts
11795: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
11796: } else {
11797: # Importing by turning a single problem into a problem part
11798: # It gets the import-tags ID as part-ID
11799: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
11800: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
11801: }
11802: } else {
11803: # Normal import
11804: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11805: if (defined($token->[2]->{'id'})) {
11806: $unikey.='_'.$token->[2]->{'id'};
11807: }
11808: }
11809:
11810: if ($depthcount<20) {
11811: my $metadata =
11812: &metadata($uri,'keys', $location,$unikey,
11813: $depthcount+1);
11814: foreach my $meta (split(',',$metadata)) {
11815: $metaentry{':'.$meta}=$metaentry{':'.$meta};
11816: $metathesekeys{$meta}=1;
11817: }
11818:
11819: }
11820: } else {
11821: #
11822: # Not importing, some other kind of non-package, non-library start tag
11823: #
11824: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11825: if (defined($token->[2]->{'id'})) {
11826: $unikey.='_'.$token->[2]->{'id'};
11827: }
11828: if (defined($token->[2]->{'name'})) {
11829: $unikey.='_'.$token->[2]->{'name'};
11830: }
11831: $metathesekeys{$unikey}=1;
11832: foreach my $param (@{$token->[3]}) {
11833: $metaentry{':'.$unikey.'.'.$param} =
11834: $token->[2]->{$param};
11835: }
11836: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
11837: my $default=$metaentry{':'.$unikey.'.default'};
11838: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11839: # only ws inside the tag, and not in default, so use default
11840: # as value
11841: $metaentry{':'.$unikey}=$default;
11842: } elsif ( $internaltext =~ /\S/ ) {
11843: # something interesting inside the tag
11844: $metaentry{':'.$unikey}=$internaltext;
11845: } else {
11846: # no interesting values, don't set a default
11847: }
11848: # end of not-a-package not-a-library import
11849: }
11850: # end of not-a-package start tag
11851: }
11852: # the next is the end of "start tag"
11853: }
11854: }
11855: my ($extension) = ($uri =~ /\.(\w+)$/);
11856: $extension = lc($extension);
11857: if ($extension eq 'htm') { $extension='html'; }
11858:
11859: foreach my $key (keys(%packagetab)) {
11860: #no specific packages #how's our extension
11861: if ($key!~/^extension_\Q$extension\E&/) { next; }
11862: &metadata_create_package_def($uri,$key,'extension_'.$extension,
11863: \%metathesekeys);
11864: }
11865:
11866: if (!exists($metaentry{':packages'})
11867: || $packagetab{"import_defaults&extension_$extension"}) {
11868: foreach my $key (keys(%packagetab)) {
11869: #no specific packages well let's get default then
11870: if ($key!~/^default&/) { next; }
11871: &metadata_create_package_def($uri,$key,'default',
11872: \%metathesekeys);
11873: }
11874: }
11875: # are there custom rights to evaluate
11876: if ($metaentry{':copyright'} eq 'custom') {
11877:
11878: #
11879: # Importing a rights file here
11880: #
11881: unless ($depthcount) {
11882: my $location=$metaentry{':customdistributionfile'};
11883: my $dir=$filename;
11884: $dir=~s|[^/]*$||;
11885: $location=&filelocation($dir,$location);
11886: my $rights_metadata =
11887: &metadata($uri,'keys',$location,'_rights',
11888: $depthcount+1);
11889: foreach my $rights (split(',',$rights_metadata)) {
11890: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11891: $metathesekeys{$rights}=1;
11892: }
11893: }
11894: }
11895: # uniqifiy package listing
11896: my %seen;
11897: my @uniq_packages =
11898: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11899: $metaentry{':packages'} = join(',',@uniq_packages);
11900:
11901: if ($importedparts) {
11902: # We had imported parts and need to rebuild partorder
11903: $metaentry{':partorder'}='';
11904: $metathesekeys{'partorder'}=1;
11905: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
11906: if ($origfileimportpartids[$index] eq 'part') {
11907: # original part, part of the problem
11908: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
11909: } else {
11910: # we have imported parts at this position
11911: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
11912: }
11913: }
11914: $metaentry{':partorder'}=~s/^\,//;
11915: }
11916:
11917: $metaentry{':keys'} = join(',',keys(%metathesekeys));
11918: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
11919: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
11920: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
11921: # this is the end of "was not already recently cached
11922: }
11923: return $metaentry{':'.$what};
11924: }
11925:
11926: sub metadata_create_package_def {
11927: my ($uri,$key,$package,$metathesekeys)=@_;
11928: my ($pack,$name,$subp)=split(/\&/,$key);
11929: if ($subp eq 'default') { next; }
11930:
11931: if (defined($metaentry{':packages'})) {
11932: $metaentry{':packages'}.=','.$package;
11933: } else {
11934: $metaentry{':packages'}=$package;
11935: }
11936: my $value=$packagetab{$key};
11937: my $unikey;
11938: $unikey='parameter_0_'.$name;
11939: $metaentry{':'.$unikey.'.part'}=0;
11940: $$metathesekeys{$unikey}=1;
11941: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11942: $metaentry{':'.$unikey.'.'.$subp}=$value;
11943: }
11944: if (defined($metaentry{':'.$unikey.'.default'})) {
11945: $metaentry{':'.$unikey}=
11946: $metaentry{':'.$unikey.'.default'};
11947: }
11948: }
11949:
11950: sub metadata_generate_part0 {
11951: my ($metadata,$metacache,$uri) = @_;
11952: my %allnames;
11953: foreach my $metakey (keys(%$metadata)) {
11954: if ($metakey=~/^parameter\_(.*)/) {
11955: my $part=$$metacache{':'.$metakey.'.part'};
11956: my $name=$$metacache{':'.$metakey.'.name'};
11957: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
11958: $allnames{$name}=$part;
11959: }
11960: }
11961: }
11962: foreach my $name (keys(%allnames)) {
11963: $$metadata{"parameter_0_$name"}=1;
11964: my $key=":parameter_0_$name";
11965: $$metacache{"$key.part"}='0';
11966: $$metacache{"$key.name"}=$name;
11967: $$metacache{"$key.type"}=$$metacache{':parameter_'.
11968: $allnames{$name}.'_'.$name.
11969: '.type'};
11970: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
11971: '.display'};
11972: my $expr='[Part: '.$allnames{$name}.']';
11973: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
11974: $$metacache{"$key.display"}=$olddis;
11975: }
11976: }
11977:
11978: # ------------------------------------------------------ Devalidate title cache
11979:
11980: sub devalidate_title_cache {
11981: my ($url)=@_;
11982: if (!$env{'request.course.id'}) { return; }
11983: my $symb=&symbread($url);
11984: if (!$symb) { return; }
11985: my $key=$env{'request.course.id'}."\0".$symb;
11986: &devalidate_cache_new('title',$key);
11987: }
11988:
11989: # ------------------------------------------------- Get the title of a course
11990:
11991: sub current_course_title {
11992: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
11993: }
11994: # ------------------------------------------------- Get the title of a resource
11995:
11996: sub gettitle {
11997: my $urlsymb=shift;
11998: my $symb=&symbread($urlsymb);
11999: if ($symb) {
12000: my $key=$env{'request.course.id'}."\0".$symb;
12001: my ($result,$cached)=&is_cached_new('title',$key);
12002: if (defined($cached)) {
12003: return $result;
12004: }
12005: my ($map,$resid,$url)=&decode_symb($symb);
12006: my $title='';
12007: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12008: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12009: } else {
12010: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12011: &GDBM_READER(),0640)) {
12012: my $mapid=$bighash{'map_pc_'.&clutter($map)};
12013: $title=$bighash{'title_'.$mapid.'.'.$resid};
12014: untie(%bighash);
12015: }
12016: }
12017: $title=~s/\&colon\;/\:/gs;
12018: if ($title) {
12019: # Remember both $symb and $title for dynamic metadata
12020: $accesshash{$symb.'___crstitle'}=$title;
12021: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12022: # Cache this title and then return it
12023: return &do_cache_new('title',$key,$title,600);
12024: }
12025: $urlsymb=$url;
12026: }
12027: my $title=&metadata($urlsymb,'title');
12028: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
12029: return $title;
12030: }
12031:
12032: sub get_slot {
12033: my ($which,$cnum,$cdom)=@_;
12034: if (!$cnum || !$cdom) {
12035: (undef,my $courseid)=&whichuser();
12036: $cdom=$env{'course.'.$courseid.'.domain'};
12037: $cnum=$env{'course.'.$courseid.'.num'};
12038: }
12039: my $key=join("\0",'slots',$cdom,$cnum,$which);
12040: my %slotinfo;
12041: if (exists($remembered{$key})) {
12042: $slotinfo{$which} = $remembered{$key};
12043: } else {
12044: %slotinfo=&get('slots',[$which],$cdom,$cnum);
12045: &Apache::lonhomework::showhash(%slotinfo);
12046: my ($tmp)=keys(%slotinfo);
12047: if ($tmp=~/^error:/) { return (); }
12048: $remembered{$key} = $slotinfo{$which};
12049: }
12050: if (ref($slotinfo{$which}) eq 'HASH') {
12051: return %{$slotinfo{$which}};
12052: }
12053: return $slotinfo{$which};
12054: }
12055:
12056: sub get_reservable_slots {
12057: my ($cnum,$cdom,$uname,$udom) = @_;
12058: my $now = time;
12059: my $reservable_info;
12060: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12061: if (exists($remembered{$key})) {
12062: $reservable_info = $remembered{$key};
12063: } else {
12064: my %resv;
12065: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12066: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12067: $reservable_info = \%resv;
12068: $remembered{$key} = $reservable_info;
12069: }
12070: return $reservable_info;
12071: }
12072:
12073: sub get_course_slots {
12074: my ($cnum,$cdom) = @_;
12075: my $hashid=$cnum.':'.$cdom;
12076: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12077: if (defined($cached)) {
12078: if (ref($result) eq 'HASH') {
12079: return %{$result};
12080: }
12081: } else {
12082: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12083: my ($tmp) = keys(%slots);
12084: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12085: &do_cache_new('allslots',$hashid,\%slots,600);
12086: return %slots;
12087: }
12088: }
12089: return;
12090: }
12091:
12092: sub devalidate_slots_cache {
12093: my ($cnum,$cdom)=@_;
12094: my $hashid=$cnum.':'.$cdom;
12095: &devalidate_cache_new('allslots',$hashid);
12096: }
12097:
12098: sub get_coursechange {
12099: my ($cdom,$cnum) = @_;
12100: if ($cdom eq '' || $cnum eq '') {
12101: return unless ($env{'request.course.id'});
12102: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12103: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12104: }
12105: my $hashid=$cdom.'_'.$cnum;
12106: my ($change,$cached)=&is_cached_new('crschange',$hashid);
12107: if ((defined($cached)) && ($change ne '')) {
12108: return $change;
12109: } else {
12110: my %crshash;
12111: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12112: if ($crshash{'internal.contentchange'} eq '') {
12113: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12114: if ($change eq '') {
12115: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12116: $change = $crshash{'internal.created'};
12117: }
12118: } else {
12119: $change = $crshash{'internal.contentchange'};
12120: }
12121: my $cachetime = 600;
12122: &do_cache_new('crschange',$hashid,$change,$cachetime);
12123: }
12124: return $change;
12125: }
12126:
12127: sub devalidate_coursechange_cache {
12128: my ($cnum,$cdom)=@_;
12129: my $hashid=$cnum.':'.$cdom;
12130: &devalidate_cache_new('crschange',$hashid);
12131: }
12132:
12133: # ------------------------------------------------- Update symbolic store links
12134:
12135: sub symblist {
12136: my ($mapname,%newhash)=@_;
12137: $mapname=&deversion(&declutter($mapname));
12138: my %hash;
12139: if (($env{'request.course.fn'}) && (%newhash)) {
12140: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12141: &GDBM_WRCREAT(),0640)) {
12142: foreach my $url (keys(%newhash)) {
12143: next if ($url eq 'last_known'
12144: && $env{'form.no_update_last_known'});
12145: $hash{declutter($url)}=&encode_symb($mapname,
12146: $newhash{$url}->[1],
12147: $newhash{$url}->[0]);
12148: }
12149: if (untie(%hash)) {
12150: return 'ok';
12151: }
12152: }
12153: }
12154: return 'error';
12155: }
12156:
12157: # --------------------------------------------------------------- Verify a symb
12158:
12159: sub symbverify {
12160: my ($symb,$thisurl,$encstate)=@_;
12161: my $thisfn=$thisurl;
12162: $thisfn=&declutter($thisfn);
12163: # direct jump to resource in page or to a sequence - will construct own symbs
12164: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12165: # check URL part
12166: my ($map,$resid,$url)=&decode_symb($symb);
12167:
12168: unless ($url eq $thisfn) { return 0; }
12169:
12170: $symb=&symbclean($symb);
12171: $thisurl=&deversion($thisurl);
12172: $thisfn=&deversion($thisfn);
12173:
12174: my %bighash;
12175: my $okay=0;
12176:
12177: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12178: &GDBM_READER(),0640)) {
12179: my $noclutter;
12180: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12181: $thisurl =~ s/\?.+$//;
12182: if ($map =~ m{^uploaded/.+\.page$}) {
12183: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12184: $thisurl =~ s{^\Qhttp://https://\E}{https://};
12185: $noclutter = 1;
12186: }
12187: }
12188: my $ids;
12189: if ($noclutter) {
12190: $ids=$bighash{'ids_'.$thisurl};
12191: } else {
12192: $ids=$bighash{'ids_'.&clutter($thisurl)};
12193: }
12194: unless ($ids) {
12195: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
12196: $ids=$bighash{$idkey};
12197: }
12198: if ($ids) {
12199: # ------------------------------------------------------------------- Has ID(s)
12200: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12201: $symb =~ s/\?.+$//;
12202: }
12203: foreach my $id (split(/\,/,$ids)) {
12204: my ($mapid,$resid)=split(/\./,$id);
12205: if (
12206: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12207: eq $symb) {
12208: if (ref($encstate)) {
12209: $$encstate = $bighash{'encrypted_'.$id};
12210: }
12211: if (($env{'request.role.adv'}) ||
12212: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12213: ($thisurl eq '/adm/navmaps')) {
12214: $okay=1;
12215: last;
12216: }
12217: }
12218: }
12219: }
12220: untie(%bighash);
12221: }
12222: return $okay;
12223: }
12224:
12225: # --------------------------------------------------------------- Clean-up symb
12226:
12227: sub symbclean {
12228: my $symb=shift;
12229: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12230: # remove version from map
12231: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
12232:
12233: # remove version from URL
12234: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
12235:
12236: # remove wrapper
12237:
12238: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
12239: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
12240: return $symb;
12241: }
12242:
12243: # ---------------------------------------------- Split symb to find map and url
12244:
12245: sub encode_symb {
12246: my ($map,$resid,$url)=@_;
12247: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12248: }
12249:
12250: sub decode_symb {
12251: my $symb=shift;
12252: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12253: my ($map,$resid,$url)=split(/___/,$symb);
12254: return (&fixversion($map),$resid,&fixversion($url));
12255: }
12256:
12257: sub fixversion {
12258: my $fn=shift;
12259: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
12260: my %bighash;
12261: my $uri=&clutter($fn);
12262: my $key=$env{'request.course.id'}.'_'.$uri;
12263: # is this cached?
12264: my ($result,$cached)=&is_cached_new('courseresversion',$key);
12265: if (defined($cached)) { return $result; }
12266: # unfortunately not cached, or expired
12267: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12268: &GDBM_READER(),0640)) {
12269: if ($bighash{'version_'.$uri}) {
12270: my $version=$bighash{'version_'.$uri};
12271: unless (($version eq 'mostrecent') ||
12272: ($version==&getversion($uri))) {
12273: $uri=~s/\.(\w+)$/\.$version\.$1/;
12274: }
12275: }
12276: untie %bighash;
12277: }
12278: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
12279: }
12280:
12281: sub deversion {
12282: my $url=shift;
12283: $url=~s/\.\d+\.(\w+)$/\.$1/;
12284: return $url;
12285: }
12286:
12287: # ------------------------------------------------------ Return symb list entry
12288:
12289: sub symbread {
12290: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
12291: my $cache_str='request.symbread.cached.'.$thisfn;
12292: if (defined($env{$cache_str})) {
12293: if ($ignorecachednull) {
12294: return $env{$cache_str} unless ($env{$cache_str} eq '');
12295: } else {
12296: return $env{$cache_str};
12297: }
12298: }
12299: # no filename provided? try from environment
12300: unless ($thisfn) {
12301: if ($env{'request.symb'}) {
12302: return $env{$cache_str}=&symbclean($env{'request.symb'});
12303: }
12304: $thisfn=$env{'request.filename'};
12305: }
12306: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12307: # is that filename actually a symb? Verify, clean, and return
12308: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
12309: if (&symbverify($thisfn,$1)) {
12310: return $env{$cache_str}=&symbclean($thisfn);
12311: }
12312: }
12313: $thisfn=declutter($thisfn);
12314: my %hash;
12315: my %bighash;
12316: my $syval='';
12317: if (($env{'request.course.fn'}) && ($thisfn)) {
12318: my $targetfn = $thisfn;
12319: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
12320: $targetfn = 'adm/wrapper/'.$thisfn;
12321: }
12322: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12323: $targetfn=$1;
12324: }
12325: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12326: &GDBM_READER(),0640)) {
12327: $syval=$hash{$targetfn};
12328: untie(%hash);
12329: }
12330: # ---------------------------------------------------------- There was an entry
12331: if ($syval) {
12332: #unless ($syval=~/\_\d+$/) {
12333: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
12334: #&appenv({'request.ambiguous' => $thisfn});
12335: #return $env{$cache_str}='';
12336: #}
12337: #$syval.=$1;
12338: #}
12339: } else {
12340: # ------------------------------------------------------- Was not in symb table
12341: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12342: &GDBM_READER(),0640)) {
12343: # ---------------------------------------------- Get ID(s) for current resource
12344: my $ids=$bighash{'ids_'.&clutter($thisfn)};
12345: unless ($ids) {
12346: $ids=$bighash{'ids_/'.$thisfn};
12347: }
12348: unless ($ids) {
12349: # alias?
12350: $ids=$bighash{'mapalias_'.$thisfn};
12351: }
12352: if ($ids) {
12353: # ------------------------------------------------------------------- Has ID(s)
12354: my @possibilities=split(/\,/,$ids);
12355: if ($#possibilities==0) {
12356: # ----------------------------------------------- There is only one possibility
12357: my ($mapid,$resid)=split(/\./,$ids);
12358: $syval=&encode_symb($bighash{'map_id_'.$mapid},
12359: $resid,$thisfn);
12360: if (ref($possibles) eq 'HASH') {
12361: $possibles->{$syval} = 1;
12362: }
12363: if ($checkforblock) {
12364: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
12365: if (@blockers) {
12366: $syval = '';
12367: return;
12368: }
12369: }
12370: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12371: # ------------------------------------------ There is more than one possibility
12372: my $realpossible=0;
12373: foreach my $id (@possibilities) {
12374: my $file=$bighash{'src_'.$id};
12375: my $canaccess;
12376: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12377: $canaccess = 1;
12378: } else {
12379: $canaccess = &allowed('bre',$file);
12380: }
12381: if ($canaccess) {
12382: my ($mapid,$resid)=split(/\./,$id);
12383: if ($bighash{'map_type_'.$mapid} ne 'page') {
12384: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12385: $resid,$thisfn);
12386: if (ref($possibles) eq 'HASH') {
12387: $possibles->{$syval} = 1;
12388: }
12389: if ($checkforblock) {
12390: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
12391: unless (@blockers > 0) {
12392: $syval = $poss_syval;
12393: $realpossible++;
12394: }
12395: } else {
12396: $syval = $poss_syval;
12397: $realpossible++;
12398: }
12399: }
12400: }
12401: }
12402: if ($realpossible!=1) { $syval=''; }
12403: } else {
12404: $syval='';
12405: }
12406: }
12407: untie(%bighash);
12408: }
12409: }
12410: if ($syval) {
12411: return $env{$cache_str}=$syval;
12412: }
12413: }
12414: &appenv({'request.ambiguous' => $thisfn});
12415: return $env{$cache_str}='';
12416: }
12417:
12418: # ---------------------------------------------------------- Return random seed
12419:
12420: sub numval {
12421: my $txt=shift;
12422: $txt=~tr/A-J/0-9/;
12423: $txt=~tr/a-j/0-9/;
12424: $txt=~tr/K-T/0-9/;
12425: $txt=~tr/k-t/0-9/;
12426: $txt=~tr/U-Z/0-5/;
12427: $txt=~tr/u-z/0-5/;
12428: $txt=~s/\D//g;
12429: if ($_64bit) { if ($txt > 2**32) { return -1; } }
12430: return int($txt);
12431: }
12432:
12433: sub numval2 {
12434: my $txt=shift;
12435: $txt=~tr/A-J/0-9/;
12436: $txt=~tr/a-j/0-9/;
12437: $txt=~tr/K-T/0-9/;
12438: $txt=~tr/k-t/0-9/;
12439: $txt=~tr/U-Z/0-5/;
12440: $txt=~tr/u-z/0-5/;
12441: $txt=~s/\D//g;
12442: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12443: my $total;
12444: foreach my $val (@txts) { $total+=$val; }
12445: if ($_64bit) { if ($total > 2**32) { return -1; } }
12446: return int($total);
12447: }
12448:
12449: sub numval3 {
12450: use integer;
12451: my $txt=shift;
12452: $txt=~tr/A-J/0-9/;
12453: $txt=~tr/a-j/0-9/;
12454: $txt=~tr/K-T/0-9/;
12455: $txt=~tr/k-t/0-9/;
12456: $txt=~tr/U-Z/0-5/;
12457: $txt=~tr/u-z/0-5/;
12458: $txt=~s/\D//g;
12459: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12460: my $total;
12461: foreach my $val (@txts) { $total+=$val; }
12462: if ($_64bit) { $total=(($total<<32)>>32); }
12463: return $total;
12464: }
12465:
12466: sub digest {
12467: my ($data)=@_;
12468: my $digest=&Digest::MD5::md5($data);
12469: my ($a,$b,$c,$d)=unpack("iiii",$digest);
12470: my ($e,$f);
12471: {
12472: use integer;
12473: $e=($a+$b);
12474: $f=($c+$d);
12475: if ($_64bit) {
12476: $e=(($e<<32)>>32);
12477: $f=(($f<<32)>>32);
12478: }
12479: }
12480: if (wantarray) {
12481: return ($e,$f);
12482: } else {
12483: my $g;
12484: {
12485: use integer;
12486: $g=($e+$f);
12487: if ($_64bit) {
12488: $g=(($g<<32)>>32);
12489: }
12490: }
12491: return $g;
12492: }
12493: }
12494:
12495: sub latest_rnd_algorithm_id {
12496: return '64bit5';
12497: }
12498:
12499: sub get_rand_alg {
12500: my ($courseid)=@_;
12501: if (!$courseid) { $courseid=(&whichuser())[1]; }
12502: if ($courseid) {
12503: return $env{"course.$courseid.rndseed"};
12504: }
12505: return &latest_rnd_algorithm_id();
12506: }
12507:
12508: sub validCODE {
12509: my ($CODE)=@_;
12510: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12511: return 0;
12512: }
12513:
12514: sub getCODE {
12515: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
12516: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12517: defined($Apache::lonhomework::parsing_a_task) ) &&
12518: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
12519: return $Apache::lonhomework::history{'resource.CODE'};
12520: }
12521: return undef;
12522: }
12523: #
12524: # Determines the random seed for a specific context:
12525: #
12526: # parameters:
12527: # symb - in course context the symb for the seed.
12528: # course_id - The course id of the form domain_coursenum.
12529: # domain - Domain for the user.
12530: # course - Course for the user.
12531: # cenv - environment of the course.
12532: #
12533: # NOTE:
12534: # All parameters are picked out of the environment if missing
12535: # or not defined.
12536: # If a symb cannot be determined the current time is used instead.
12537: #
12538: # For a given well defined symb, courside, domain, username,
12539: # and course environment, the seed is reproducible.
12540: #
12541: sub rndseed {
12542: my ($symb,$courseid,$domain,$username, $cenv)=@_;
12543: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
12544: if (!defined($symb)) {
12545: unless ($symb=$wsymb) { return time; }
12546: }
12547: if (!defined $courseid) {
12548: $courseid=$wcourseid;
12549: }
12550: if (!defined $domain) { $domain=$wdomain; }
12551: if (!defined $username) { $username=$wusername }
12552:
12553: my $which;
12554: if (defined($cenv->{'rndseed'})) {
12555: $which = $cenv->{'rndseed'};
12556: } else {
12557: $which =&get_rand_alg($courseid);
12558: }
12559: if (defined(&getCODE())) {
12560:
12561: if ($which eq '64bit5') {
12562: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12563: } elsif ($which eq '64bit4') {
12564: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12565: } else {
12566: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12567: }
12568: } elsif ($which eq '64bit5') {
12569: return &rndseed_64bit5($symb,$courseid,$domain,$username);
12570: } elsif ($which eq '64bit4') {
12571: return &rndseed_64bit4($symb,$courseid,$domain,$username);
12572: } elsif ($which eq '64bit3') {
12573: return &rndseed_64bit3($symb,$courseid,$domain,$username);
12574: } elsif ($which eq '64bit2') {
12575: return &rndseed_64bit2($symb,$courseid,$domain,$username);
12576: } elsif ($which eq '64bit') {
12577: return &rndseed_64bit($symb,$courseid,$domain,$username);
12578: }
12579: return &rndseed_32bit($symb,$courseid,$domain,$username);
12580: }
12581:
12582: sub rndseed_32bit {
12583: my ($symb,$courseid,$domain,$username)=@_;
12584: {
12585: use integer;
12586: my $symbchck=unpack("%32C*",$symb) << 27;
12587: my $symbseed=numval($symb) << 22;
12588: my $namechck=unpack("%32C*",$username) << 17;
12589: my $nameseed=numval($username) << 12;
12590: my $domainseed=unpack("%32C*",$domain) << 7;
12591: my $courseseed=unpack("%32C*",$courseid);
12592: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
12593: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12594: #&logthis("rndseed :$num:$symb");
12595: if ($_64bit) { $num=(($num<<32)>>32); }
12596: return $num;
12597: }
12598: }
12599:
12600: sub rndseed_64bit {
12601: my ($symb,$courseid,$domain,$username)=@_;
12602: {
12603: use integer;
12604: my $symbchck=unpack("%32S*",$symb) << 21;
12605: my $symbseed=numval($symb) << 10;
12606: my $namechck=unpack("%32S*",$username);
12607:
12608: my $nameseed=numval($username) << 21;
12609: my $domainseed=unpack("%32S*",$domain) << 10;
12610: my $courseseed=unpack("%32S*",$courseid);
12611:
12612: my $num1=$symbchck+$symbseed+$namechck;
12613: my $num2=$nameseed+$domainseed+$courseseed;
12614: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12615: #&logthis("rndseed :$num:$symb");
12616: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12617: return "$num1,$num2";
12618: }
12619: }
12620:
12621: sub rndseed_64bit2 {
12622: my ($symb,$courseid,$domain,$username)=@_;
12623: {
12624: use integer;
12625: # strings need to be an even # of cahracters long, it it is odd the
12626: # last characters gets thrown away
12627: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12628: my $symbseed=numval($symb) << 10;
12629: my $namechck=unpack("%32S*",$username.' ');
12630:
12631: my $nameseed=numval($username) << 21;
12632: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12633: my $courseseed=unpack("%32S*",$courseid.' ');
12634:
12635: my $num1=$symbchck+$symbseed+$namechck;
12636: my $num2=$nameseed+$domainseed+$courseseed;
12637: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12638: #&logthis("rndseed :$num:$symb");
12639: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12640: return "$num1,$num2";
12641: }
12642: }
12643:
12644: sub rndseed_64bit3 {
12645: my ($symb,$courseid,$domain,$username)=@_;
12646: {
12647: use integer;
12648: # strings need to be an even # of cahracters long, it it is odd the
12649: # last characters gets thrown away
12650: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12651: my $symbseed=numval2($symb) << 10;
12652: my $namechck=unpack("%32S*",$username.' ');
12653:
12654: my $nameseed=numval2($username) << 21;
12655: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12656: my $courseseed=unpack("%32S*",$courseid.' ');
12657:
12658: my $num1=$symbchck+$symbseed+$namechck;
12659: my $num2=$nameseed+$domainseed+$courseseed;
12660: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12661: #&logthis("rndseed :$num1:$num2:$_64bit");
12662: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12663:
12664: return "$num1:$num2";
12665: }
12666: }
12667:
12668: sub rndseed_64bit4 {
12669: my ($symb,$courseid,$domain,$username)=@_;
12670: {
12671: use integer;
12672: # strings need to be an even # of cahracters long, it it is odd the
12673: # last characters gets thrown away
12674: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12675: my $symbseed=numval3($symb) << 10;
12676: my $namechck=unpack("%32S*",$username.' ');
12677:
12678: my $nameseed=numval3($username) << 21;
12679: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12680: my $courseseed=unpack("%32S*",$courseid.' ');
12681:
12682: my $num1=$symbchck+$symbseed+$namechck;
12683: my $num2=$nameseed+$domainseed+$courseseed;
12684: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12685: #&logthis("rndseed :$num1:$num2:$_64bit");
12686: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12687:
12688: return "$num1:$num2";
12689: }
12690: }
12691:
12692: sub rndseed_64bit5 {
12693: my ($symb,$courseid,$domain,$username)=@_;
12694: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12695: return "$num1:$num2";
12696: }
12697:
12698: sub rndseed_CODE_64bit {
12699: my ($symb,$courseid,$domain,$username)=@_;
12700: {
12701: use integer;
12702: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12703: my $symbseed=numval2($symb);
12704: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12705: my $CODEseed=numval(&getCODE());
12706: my $courseseed=unpack("%32S*",$courseid.' ');
12707: my $num1=$symbseed+$CODEchck;
12708: my $num2=$CODEseed+$courseseed+$symbchck;
12709: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12710: #&logthis("rndseed :$num1:$num2:$symb");
12711: if ($_64bit) { $num1=(($num1<<32)>>32); }
12712: if ($_64bit) { $num2=(($num2<<32)>>32); }
12713: return "$num1:$num2";
12714: }
12715: }
12716:
12717: sub rndseed_CODE_64bit4 {
12718: my ($symb,$courseid,$domain,$username)=@_;
12719: {
12720: use integer;
12721: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12722: my $symbseed=numval3($symb);
12723: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12724: my $CODEseed=numval3(&getCODE());
12725: my $courseseed=unpack("%32S*",$courseid.' ');
12726: my $num1=$symbseed+$CODEchck;
12727: my $num2=$CODEseed+$courseseed+$symbchck;
12728: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12729: #&logthis("rndseed :$num1:$num2:$symb");
12730: if ($_64bit) { $num1=(($num1<<32)>>32); }
12731: if ($_64bit) { $num2=(($num2<<32)>>32); }
12732: return "$num1:$num2";
12733: }
12734: }
12735:
12736: sub rndseed_CODE_64bit5 {
12737: my ($symb,$courseid,$domain,$username)=@_;
12738: my $code = &getCODE();
12739: my ($num1,$num2)=&digest("$symb,$courseid,$code");
12740: return "$num1:$num2";
12741: }
12742:
12743: sub setup_random_from_rndseed {
12744: my ($rndseed)=@_;
12745: if ($rndseed =~/([,:])/) {
12746: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12747: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12748: &Math::Random::random_set_seed_from_phrase($rndseed);
12749: } else {
12750: &Math::Random::random_set_seed($num1,$num2);
12751: }
12752: } else {
12753: &Math::Random::random_set_seed_from_phrase($rndseed);
12754: }
12755: }
12756:
12757: sub latest_receipt_algorithm_id {
12758: return 'receipt3';
12759: }
12760:
12761: sub recunique {
12762: my $fucourseid=shift;
12763: my $unique;
12764: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12765: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
12766: $unique=$env{"course.$fucourseid.internal.encseed"};
12767: } else {
12768: $unique=$perlvar{'lonReceipt'};
12769: }
12770: return unpack("%32C*",$unique);
12771: }
12772:
12773: sub recprefix {
12774: my $fucourseid=shift;
12775: my $prefix;
12776: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12777: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
12778: $prefix=$env{"course.$fucourseid.internal.encpref"};
12779: } else {
12780: $prefix=$perlvar{'lonHostID'};
12781: }
12782: return unpack("%32C*",$prefix);
12783: }
12784:
12785: sub ireceipt {
12786: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
12787:
12788: my $return =&recprefix($fucourseid).'-';
12789:
12790: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12791: $env{'request.state'} eq 'construct') {
12792: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12793: return $return;
12794: }
12795:
12796: my $cuname=unpack("%32C*",$funame);
12797: my $cudom=unpack("%32C*",$fudom);
12798: my $cucourseid=unpack("%32C*",$fucourseid);
12799: my $cusymb=unpack("%32C*",$fusymb);
12800: my $cunique=&recunique($fucourseid);
12801: my $cpart=unpack("%32S*",$part);
12802: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12803:
12804: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
12805:
12806: $return.= ($cunique%$cuname+
12807: $cunique%$cudom+
12808: $cusymb%$cuname+
12809: $cusymb%$cudom+
12810: $cucourseid%$cuname+
12811: $cucourseid%$cudom+
12812: $cpart%$cuname+
12813: $cpart%$cudom);
12814: } else {
12815: $return.= ($cunique%$cuname+
12816: $cunique%$cudom+
12817: $cusymb%$cuname+
12818: $cusymb%$cudom+
12819: $cucourseid%$cuname+
12820: $cucourseid%$cudom);
12821: }
12822: return $return;
12823: }
12824:
12825: sub receipt {
12826: my ($part)=@_;
12827: my ($symb,$courseid,$domain,$name) = &whichuser();
12828: return &ireceipt($name,$domain,$courseid,$symb,$part);
12829: }
12830:
12831: sub whichuser {
12832: my ($passedsymb)=@_;
12833: my ($symb,$courseid,$domain,$name,$publicuser);
12834: if (defined($env{'form.grade_symb'})) {
12835: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12836: my $allowed=&allowed('vgr',$tmp_courseid);
12837: if (!$allowed &&
12838: exists($env{'request.course.sec'}) &&
12839: $env{'request.course.sec'} !~ /^\s*$/) {
12840: $allowed=&allowed('vgr',$tmp_courseid.
12841: '/'.$env{'request.course.sec'});
12842: }
12843: if ($allowed) {
12844: ($symb)=&get_env_multiple('form.grade_symb');
12845: $courseid=$tmp_courseid;
12846: ($domain)=&get_env_multiple('form.grade_domain');
12847: ($name)=&get_env_multiple('form.grade_username');
12848: return ($symb,$courseid,$domain,$name,$publicuser);
12849: }
12850: }
12851: if (!$passedsymb) {
12852: $symb=&symbread();
12853: } else {
12854: $symb=$passedsymb;
12855: }
12856: $courseid=$env{'request.course.id'};
12857: $domain=$env{'user.domain'};
12858: $name=$env{'user.name'};
12859: if ($name eq 'public' && $domain eq 'public') {
12860: if (!defined($env{'form.username'})) {
12861: $env{'form.username'}.=time.rand(10000000);
12862: }
12863: $name.=$env{'form.username'};
12864: }
12865: return ($symb,$courseid,$domain,$name,$publicuser);
12866:
12867: }
12868:
12869: # ------------------------------------------------------------ Serves up a file
12870: # returns either the contents of the file or
12871: # -1 if the file doesn't exist
12872: #
12873: # if the target is a file that was uploaded via DOCS,
12874: # a check will be made to see if a current copy exists on the local server,
12875: # if it does this will be served, otherwise a copy will be retrieved from
12876: # the home server for the course and stored in /home/httpd/html/userfiles on
12877: # the local server.
12878:
12879: sub getfile {
12880: my ($file) = @_;
12881: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
12882: &repcopy($file);
12883: return &readfile($file);
12884: }
12885:
12886: sub repcopy_userfile {
12887: my ($file)=@_;
12888: my $londocroot = $perlvar{'lonDocRoot'};
12889: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
12890: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
12891: my ($cdom,$cnum,$filename) =
12892: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
12893: my $uri="/uploaded/$cdom/$cnum/$filename";
12894: if (-e "$file") {
12895: # we already have a local copy, check it out
12896: my @fileinfo = stat($file);
12897: my $rtncode;
12898: my $info;
12899: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
12900: if ($lwpresp ne 'ok') {
12901: # there is no such file anymore, even though we had a local copy
12902: if ($rtncode eq '404') {
12903: unlink($file);
12904: }
12905: return -1;
12906: }
12907: if ($info < $fileinfo[9]) {
12908: # nice, the file we have is up-to-date, just say okay
12909: return 'ok';
12910: } else {
12911: # the file is outdated, get rid of it
12912: unlink($file);
12913: }
12914: }
12915: # one way or the other, at this point, we don't have the file
12916: # construct the correct path for the file
12917: my @parts = ($cdom,$cnum);
12918: if ($filename =~ m|^(.+)/[^/]+$|) {
12919: push @parts, split(/\//,$1);
12920: }
12921: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
12922: foreach my $part (@parts) {
12923: $path .= '/'.$part;
12924: if (!-e $path) {
12925: mkdir($path,0770);
12926: }
12927: }
12928: # now the path exists for sure
12929: # get a user agent
12930: my $transferfile=$file.'.in.transfer';
12931: # FIXME: this should flock
12932: if (-e $transferfile) { return 'ok'; }
12933: my $request;
12934: $uri=~s/^\///;
12935: my $homeserver = &homeserver($cnum,$cdom);
12936: my $protocol = $protocol{$homeserver};
12937: $protocol = 'http' if ($protocol ne 'https');
12938: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
12939: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
12940: # did it work?
12941: if ($response->is_error()) {
12942: unlink($transferfile);
12943: &logthis("Userfile repcopy failed for $uri");
12944: return -1;
12945: }
12946: # worked, rename the transfer file
12947: rename($transferfile,$file);
12948: return 'ok';
12949: }
12950:
12951: sub tokenwrapper {
12952: my $uri=shift;
12953: $uri=~s|^https?\://([^/]+)||;
12954: $uri=~s|^/||;
12955: $env{'user.environment'}=~/\/([^\/]+)\.id/;
12956: my $token=$1;
12957: my (undef,$udom,$uname,$file)=split('/',$uri,4);
12958: if ($udom && $uname && $file) {
12959: $file=~s|(\?\.*)*$||;
12960: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
12961: my $homeserver = &homeserver($uname,$udom);
12962: my $protocol = $protocol{$homeserver};
12963: $protocol = 'http' if ($protocol ne 'https');
12964: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
12965: (($uri=~/\?/)?'&':'?').'token='.$token.
12966: '&tokenissued='.$perlvar{'lonHostID'};
12967: } else {
12968: return '/adm/notfound.html';
12969: }
12970: }
12971:
12972: # call with reqtype HEAD: get last modification time
12973: # call with reqtype GET: get the file contents
12974: # Do not call this with reqtype GET for large files! It loads everything into memory
12975: #
12976: sub getuploaded {
12977: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
12978: $uri=~s/^\///;
12979: my $homeserver = &homeserver($cnum,$cdom);
12980: my $protocol = $protocol{$homeserver};
12981: $protocol = 'http' if ($protocol ne 'https');
12982: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
12983: my $request=new HTTP::Request($reqtype,$uri);
12984: my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
12985: $$rtncode = $response->code;
12986: if (! $response->is_success()) {
12987: return 'failed';
12988: }
12989: if ($reqtype eq 'HEAD') {
12990: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
12991: } elsif ($reqtype eq 'GET') {
12992: $$info = $response->content;
12993: }
12994: return 'ok';
12995: }
12996:
12997: sub readfile {
12998: my $file = shift;
12999: if ( (! -e $file ) || ($file eq '') ) { return -1; };
13000: my $fh;
13001: open($fh,"<$file");
13002: my $a='';
13003: while (my $line = <$fh>) { $a .= $line; }
13004: return $a;
13005: }
13006:
13007: sub filelocation {
13008: my ($dir,$file) = @_;
13009: my $location;
13010: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13011:
13012: if ($file =~ m-^/adm/-) {
13013: $file=~s-^/adm/wrapper/-/-;
13014: $file=~s-^/adm/coursedocs/showdoc/-/-;
13015: }
13016:
13017: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13018: $location = $file;
13019: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13020: my ($udom,$uname,$filename)=
13021: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13022: my $home=&homeserver($uname,$udom);
13023: my $is_me=0;
13024: my @ids=¤t_machine_ids();
13025: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13026: if ($is_me) {
13027: $location=propath($udom,$uname).'/userfiles/'.$filename;
13028: } else {
13029: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13030: $udom.'/'.$uname.'/'.$filename;
13031: }
13032: } elsif ($file =~ m-^/adm/-) {
13033: $location = $perlvar{'lonDocRoot'}.'/'.$file;
13034: } else {
13035: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13036: $file=~s:^/(res|priv)/:/:;
13037: my $space=$1;
13038: if ( !( $file =~ m:^/:) ) {
13039: $location = $dir. '/'.$file;
13040: } else {
13041: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13042: }
13043: }
13044: $location=~s://+:/:g; # remove duplicate /
13045: while ($location=~m{/\.\./}) {
13046: if ($location =~ m{/[^/]+/\.\./}) {
13047: $location=~ s{/[^/]+/\.\./}{/}g;
13048: } else {
13049: $location=~ s{/\.\./}{/}g;
13050: }
13051: } #remove dir/..
13052: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13053: return $location;
13054: }
13055:
13056: sub hreflocation {
13057: my ($dir,$file)=@_;
13058: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13059: $file=filelocation($dir,$file);
13060: } elsif ($file=~m-^/adm/-) {
13061: $file=~s-^/adm/wrapper/-/-;
13062: $file=~s-^/adm/coursedocs/showdoc/-/-;
13063: }
13064: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13065: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13066: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13067: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13068: {/uploaded/$1/$2/}x;
13069: }
13070: if ($file=~ m{^/userfiles/}) {
13071: $file =~ s{^/userfiles/}{/uploaded/};
13072: }
13073: return $file;
13074: }
13075:
13076:
13077:
13078:
13079:
13080: sub current_machine_domains {
13081: return &machine_domains(&hostname($perlvar{'lonHostID'}));
13082: }
13083:
13084: sub machine_domains {
13085: my ($hostname) = @_;
13086: my @domains;
13087: my %hostname = &all_hostnames();
13088: while( my($id, $name) = each(%hostname)) {
13089: # &logthis("-$id-$name-$hostname-");
13090: if ($hostname eq $name) {
13091: push(@domains,&host_domain($id));
13092: }
13093: }
13094: return @domains;
13095: }
13096:
13097: sub current_machine_ids {
13098: return &machine_ids(&hostname($perlvar{'lonHostID'}));
13099: }
13100:
13101: sub machine_ids {
13102: my ($hostname) = @_;
13103: $hostname ||= &hostname($perlvar{'lonHostID'});
13104: my @ids;
13105: my %name_to_host = &all_names();
13106: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13107: return @{ $name_to_host{$hostname} };
13108: }
13109: return;
13110: }
13111:
13112: sub additional_machine_domains {
13113: my @domains;
13114: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
13115: while( my $line = <$fh>) {
13116: $line =~ s/\s//g;
13117: push(@domains,$line);
13118: }
13119: return @domains;
13120: }
13121:
13122: sub default_login_domain {
13123: my $domain = $perlvar{'lonDefDomain'};
13124: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13125: foreach my $posdom (¤t_machine_domains(),
13126: &additional_machine_domains()) {
13127: if (lc($posdom) eq lc($testdomain)) {
13128: $domain=$posdom;
13129: last;
13130: }
13131: }
13132: return $domain;
13133: }
13134:
13135: # ------------------------------------------------------------- Declutters URLs
13136:
13137: sub declutter {
13138: my $thisfn=shift;
13139: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13140: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13141: $thisfn=~s{^/home/httpd/html}{};
13142: }
13143: $thisfn=~s/^\///;
13144: $thisfn=~s|^adm/wrapper/||;
13145: $thisfn=~s|^adm/coursedocs/showdoc/||;
13146: $thisfn=~s/^res\///;
13147: $thisfn=~s/^priv\///;
13148: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13149: $thisfn=~s/\?.+$//;
13150: }
13151: return $thisfn;
13152: }
13153:
13154: # ------------------------------------------------------------- Clutter up URLs
13155:
13156: sub clutter {
13157: my $thisfn='/'.&declutter(shift);
13158: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
13159: || $thisfn =~ m{^/adm/(includes|pages)} ) {
13160: $thisfn='/res'.$thisfn;
13161: }
13162: if ($thisfn !~m|^/adm|) {
13163: if ($thisfn =~ m|^/ext/|) {
13164: $thisfn='/adm/wrapper'.$thisfn;
13165: } else {
13166: my ($ext) = ($thisfn =~ /\.(\w+)$/);
13167: my $embstyle=&Apache::loncommon::fileembstyle($ext);
13168: if ($embstyle eq 'ssi'
13169: || ($embstyle eq 'hdn')
13170: || ($embstyle eq 'rat')
13171: || ($embstyle eq 'prv')
13172: || ($embstyle eq 'ign')) {
13173: #do nothing with these
13174: } elsif (($embstyle eq 'img')
13175: || ($embstyle eq 'emb')
13176: || ($embstyle eq 'wrp')) {
13177: $thisfn='/adm/wrapper'.$thisfn;
13178: } elsif ($embstyle eq 'unk'
13179: && $thisfn!~/\.(sequence|page)$/) {
13180: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
13181: } else {
13182: # &logthis("Got a blank emb style");
13183: }
13184: }
13185: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
13186: $thisfn='/adm/wrapper'.$thisfn;
13187: }
13188: return $thisfn;
13189: }
13190:
13191: sub clutter_with_no_wrapper {
13192: my $uri = &clutter(shift);
13193: if ($uri =~ m-^/adm/-) {
13194: $uri =~ s-^/adm/wrapper/-/-;
13195: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
13196: }
13197: return $uri;
13198: }
13199:
13200: sub freeze_escape {
13201: my ($value)=@_;
13202: if (ref($value)) {
13203: $value=&nfreeze($value);
13204: return '__FROZEN__'.&escape($value);
13205: }
13206: return &escape($value);
13207: }
13208:
13209:
13210: sub thaw_unescape {
13211: my ($value)=@_;
13212: if ($value =~ /^__FROZEN__/) {
13213: substr($value,0,10,undef);
13214: $value=&unescape($value);
13215: return &thaw($value);
13216: }
13217: return &unescape($value);
13218: }
13219:
13220: sub correct_line_ends {
13221: my ($result)=@_;
13222: $$result =~s/\r\n/\n/mg;
13223: $$result =~s/\r/\n/mg;
13224: }
13225: # ================================================================ Main Program
13226:
13227: sub goodbye {
13228: &logthis("Starting Shut down");
13229: #not converted to using infrastruture and probably shouldn't be
13230: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
13231: #converted
13232: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
13233: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13234: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13235: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
13236: #1.1 only
13237: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13238: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13239: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13240: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13241: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
13242: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13243: &logthis(sprintf("%-20s is %s",'hits',$hits));
13244: &flushcourselogs();
13245: &logthis("Shutting down");
13246: }
13247:
13248: sub get_dns {
13249: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
13250: if (!$ignore_cache) {
13251: my ($content,$cached)=
13252: &Apache::lonnet::is_cached_new('dns',$url);
13253: if ($cached) {
13254: &$func($content,$hashref);
13255: return;
13256: }
13257: }
13258:
13259: my %alldns;
13260: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
13261: foreach my $dns (<$config>) {
13262: next if ($dns !~ /^\^(\S*)/x);
13263: my $line = $1;
13264: my ($host,$protocol) = split(/:/,$line);
13265: if ($protocol ne 'https') {
13266: $protocol = 'http';
13267: }
13268: $alldns{$host} = $protocol;
13269: }
13270: while (%alldns) {
13271: my ($dns) = sort { $b cmp $a } keys(%alldns);
13272: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13273: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
13274: delete($alldns{$dns});
13275: next if ($response->is_error());
13276: my @content = split("\n",$response->content);
13277: unless ($nocache) {
13278: &do_cache_new('dns',$url,\@content,30*24*60*60);
13279: }
13280: &$func(\@content,$hashref);
13281: return;
13282: }
13283: close($config);
13284: my $which = (split('/',$url))[3];
13285: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13286: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
13287: my @content = <$config>;
13288: &$func(\@content,$hashref);
13289: return;
13290: }
13291:
13292: # ------------------------------------------------------Get DNS checksums file
13293: sub parse_dns_checksums_tab {
13294: my ($lines,$hashref) = @_;
13295: my $lonhost = $perlvar{'lonHostID'};
13296: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
13297: my $loncaparev = &get_server_loncaparev($machine_dom);
13298: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13299: my $webconfdir = '/etc/httpd/conf';
13300: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13301: $webconfdir = '/etc/apache2';
13302: } elsif ($distro =~ /^sles(\d+)$/) {
13303: if ($1 >= 10) {
13304: $webconfdir = '/etc/apache2';
13305: }
13306: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13307: if ($1 >= 10.0) {
13308: $webconfdir = '/etc/apache2';
13309: }
13310: }
13311: my ($release,$timestamp) = split(/\-/,$loncaparev);
13312: my (%chksum,%revnum);
13313: if (ref($lines) eq 'ARRAY') {
13314: chomp(@{$lines});
13315: my $version = shift(@{$lines});
13316: if ($version eq $release) {
13317: foreach my $line (@{$lines}) {
13318: my ($file,$version,$shasum) = split(/,/,$line);
13319: if ($file =~ m{^/etc/httpd/conf}) {
13320: if ($webconfdir eq '/etc/apache2') {
13321: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13322: }
13323: }
13324: $chksum{$file} = $shasum;
13325: $revnum{$file} = $version;
13326: }
13327: if (ref($hashref) eq 'HASH') {
13328: %{$hashref} = (
13329: sums => \%chksum,
13330: versions => \%revnum,
13331: );
13332: }
13333: }
13334: }
13335: return;
13336: }
13337:
13338: sub fetch_dns_checksums {
13339: my %checksums;
13340: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
13341: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
13342: my ($release,$timestamp) = split(/\-/,$loncaparev);
13343: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
13344: \%checksums);
13345: return \%checksums;
13346: }
13347:
13348: # ------------------------------------------------------------ Read domain file
13349: {
13350: my $loaded;
13351: my %domain;
13352:
13353: sub parse_domain_tab {
13354: my ($lines) = @_;
13355: foreach my $line (@$lines) {
13356: next if ($line =~ /^(\#|\s*$ )/x);
13357:
13358: chomp($line);
13359: my ($name,@elements) = split(/:/,$line,9);
13360: my %this_domain;
13361: foreach my $field ('description', 'auth_def', 'auth_arg_def',
13362: 'lang_def', 'city', 'longi', 'lati',
13363: 'primary') {
13364: $this_domain{$field} = shift(@elements);
13365: }
13366: $domain{$name} = \%this_domain;
13367: }
13368: }
13369:
13370: sub reset_domain_info {
13371: undef($loaded);
13372: undef(%domain);
13373: }
13374:
13375: sub load_domain_tab {
13376: my ($ignore_cache,$nocache) = @_;
13377: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
13378: my $fh;
13379: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
13380: my @lines = <$fh>;
13381: &parse_domain_tab(\@lines);
13382: }
13383: close($fh);
13384: $loaded = 1;
13385: }
13386:
13387: sub domain {
13388: &load_domain_tab() if (!$loaded);
13389:
13390: my ($name,$what) = @_;
13391: return if ( !exists($domain{$name}) );
13392:
13393: if (!$what) {
13394: return $domain{$name}{'description'};
13395: }
13396: return $domain{$name}{$what};
13397: }
13398:
13399: sub domain_info {
13400: &load_domain_tab() if (!$loaded);
13401: return %domain;
13402: }
13403:
13404: }
13405:
13406:
13407: # ------------------------------------------------------------- Read hosts file
13408: {
13409: my %hostname;
13410: my %hostdom;
13411: my %libserv;
13412: my $loaded;
13413: my %name_to_host;
13414: my %internetdom;
13415: my %LC_dns_serv;
13416:
13417: sub parse_hosts_tab {
13418: my ($file) = @_;
13419: foreach my $configline (@$file) {
13420: next if ($configline =~ /^(\#|\s*$ )/x);
13421: chomp($configline);
13422: if ($configline =~ /^\^/) {
13423: if ($configline =~ /^\^([\w.\-]+)/) {
13424: $LC_dns_serv{$1} = 1;
13425: }
13426: next;
13427: }
13428: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
13429: $name=~s/\s//g;
13430: if ($id && $domain && $role && $name) {
13431: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13432: my $curr = $hostname{$id};
13433: my $skip;
13434: if (ref($name_to_host{$curr}) eq 'ARRAY') {
13435: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13436: $skip = 1;
13437: } else {
13438: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13439: }
13440: }
13441: unless ($skip) {
13442: push(@{$name_to_host{$name}},$id);
13443: }
13444: } else {
13445: push(@{$name_to_host{$name}},$id);
13446: }
13447: $hostname{$id}=$name;
13448: $hostdom{$id}=$domain;
13449: if ($role eq 'library') { $libserv{$id}=$name; }
13450: if (defined($protocol)) {
13451: if ($protocol eq 'https') {
13452: $protocol{$id} = $protocol;
13453: } else {
13454: $protocol{$id} = 'http';
13455: }
13456: } else {
13457: $protocol{$id} = 'http';
13458: }
13459: if (defined($intdom)) {
13460: $internetdom{$id} = $intdom;
13461: }
13462: }
13463: }
13464: }
13465:
13466: sub reset_hosts_info {
13467: &purge_remembered();
13468: &reset_domain_info();
13469: &reset_hosts_ip_info();
13470: undef(%internetdom);
13471: undef(%name_to_host);
13472: undef(%hostname);
13473: undef(%hostdom);
13474: undef(%libserv);
13475: undef($loaded);
13476: }
13477:
13478: sub load_hosts_tab {
13479: my ($ignore_cache,$nocache) = @_;
13480: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
13481: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
13482: my @config = <$config>;
13483: &parse_hosts_tab(\@config);
13484: close($config);
13485: $loaded=1;
13486: }
13487:
13488: sub hostname {
13489: &load_hosts_tab() if (!$loaded);
13490:
13491: my ($lonid) = @_;
13492: return $hostname{$lonid};
13493: }
13494:
13495: sub all_hostnames {
13496: &load_hosts_tab() if (!$loaded);
13497:
13498: return %hostname;
13499: }
13500:
13501: sub all_names {
13502: my ($ignore_cache,$nocache) = @_;
13503: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
13504:
13505: return %name_to_host;
13506: }
13507:
13508: sub all_host_domain {
13509: &load_hosts_tab() if (!$loaded);
13510: return %hostdom;
13511: }
13512:
13513: sub all_host_intdom {
13514: &load_hosts_tab() if (!$loaded);
13515: return %internetdom;
13516: }
13517:
13518: sub is_library {
13519: &load_hosts_tab() if (!$loaded);
13520:
13521: return exists($libserv{$_[0]});
13522: }
13523:
13524: sub all_library {
13525: &load_hosts_tab() if (!$loaded);
13526:
13527: return %libserv;
13528: }
13529:
13530: sub unique_library {
13531: #2x reverse removes all hostnames that appear more than once
13532: my %unique = reverse &all_library();
13533: return reverse %unique;
13534: }
13535:
13536: sub get_servers {
13537: &load_hosts_tab() if (!$loaded);
13538:
13539: my ($domain,$type) = @_;
13540: my %possible_hosts = ($type eq 'library') ? %libserv
13541: : %hostname;
13542: my %result;
13543: if (ref($domain) eq 'ARRAY') {
13544: while ( my ($host,$hostname) = each(%possible_hosts)) {
13545: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
13546: $result{$host} = $hostname;
13547: }
13548: }
13549: } else {
13550: while ( my ($host,$hostname) = each(%possible_hosts)) {
13551: if ($hostdom{$host} eq $domain) {
13552: $result{$host} = $hostname;
13553: }
13554: }
13555: }
13556: return %result;
13557: }
13558:
13559: sub get_unique_servers {
13560: my %unique = reverse &get_servers(@_);
13561: return reverse %unique;
13562: }
13563:
13564: sub host_domain {
13565: &load_hosts_tab() if (!$loaded);
13566:
13567: my ($lonid) = @_;
13568: return $hostdom{$lonid};
13569: }
13570:
13571: sub all_domains {
13572: &load_hosts_tab() if (!$loaded);
13573:
13574: my %seen;
13575: my @uniq = grep(!$seen{$_}++, values(%hostdom));
13576: return @uniq;
13577: }
13578:
13579: sub internet_dom {
13580: &load_hosts_tab() if (!$loaded);
13581:
13582: my ($lonid) = @_;
13583: return $internetdom{$lonid};
13584: }
13585:
13586: sub is_LC_dns {
13587: &load_hosts_tab() if (!$loaded);
13588:
13589: my ($hostname) = @_;
13590: return exists($LC_dns_serv{$hostname});
13591: }
13592:
13593: }
13594:
13595: {
13596: my %iphost;
13597: my %name_to_ip;
13598: my %lonid_to_ip;
13599:
13600: sub get_hosts_from_ip {
13601: my ($ip) = @_;
13602: my %iphosts = &get_iphost();
13603: if (ref($iphosts{$ip})) {
13604: return @{$iphosts{$ip}};
13605: }
13606: return;
13607: }
13608:
13609: sub reset_hosts_ip_info {
13610: undef(%iphost);
13611: undef(%name_to_ip);
13612: undef(%lonid_to_ip);
13613: }
13614:
13615: sub get_host_ip {
13616: my ($lonid) = @_;
13617: if (exists($lonid_to_ip{$lonid})) {
13618: return $lonid_to_ip{$lonid};
13619: }
13620: my $name=&hostname($lonid);
13621: my $ip = gethostbyname($name);
13622: return if (!$ip || length($ip) ne 4);
13623: $ip=inet_ntoa($ip);
13624: $name_to_ip{$name} = $ip;
13625: $lonid_to_ip{$lonid} = $ip;
13626: return $ip;
13627: }
13628:
13629: sub get_iphost {
13630: my ($ignore_cache,$nocache) = @_;
13631:
13632: if (!$ignore_cache) {
13633: if (%iphost) {
13634: return %iphost;
13635: }
13636: my ($ip_info,$cached)=
13637: &Apache::lonnet::is_cached_new('iphost','iphost');
13638: if ($cached) {
13639: %iphost = %{$ip_info->[0]};
13640: %name_to_ip = %{$ip_info->[1]};
13641: %lonid_to_ip = %{$ip_info->[2]};
13642: return %iphost;
13643: }
13644: }
13645:
13646: # get yesterday's info for fallback
13647: my %old_name_to_ip;
13648: my ($ip_info,$cached)=
13649: &Apache::lonnet::is_cached_new('iphost','iphost');
13650: if ($cached) {
13651: %old_name_to_ip = %{$ip_info->[1]};
13652: }
13653:
13654: my %name_to_host = &all_names($ignore_cache,$nocache);
13655: foreach my $name (keys(%name_to_host)) {
13656: my $ip;
13657: if (!exists($name_to_ip{$name})) {
13658: $ip = gethostbyname($name);
13659: if (!$ip || length($ip) ne 4) {
13660: if (defined($old_name_to_ip{$name})) {
13661: $ip = $old_name_to_ip{$name};
13662: &logthis("Can't find $name defaulting to old $ip");
13663: } else {
13664: &logthis("Name $name no IP found");
13665: next;
13666: }
13667: } else {
13668: $ip=inet_ntoa($ip);
13669: }
13670: $name_to_ip{$name} = $ip;
13671: } else {
13672: $ip = $name_to_ip{$name};
13673: }
13674: foreach my $id (@{ $name_to_host{$name} }) {
13675: $lonid_to_ip{$id} = $ip;
13676: }
13677: push(@{$iphost{$ip}},@{$name_to_host{$name}});
13678: }
13679: unless ($nocache) {
13680: &do_cache_new('iphost','iphost',
13681: [\%iphost,\%name_to_ip,\%lonid_to_ip],
13682: 48*60*60);
13683: }
13684:
13685: return %iphost;
13686: }
13687:
13688: #
13689: # Given a DNS returns the loncapa host name for that DNS
13690: #
13691: sub host_from_dns {
13692: my ($dns) = @_;
13693: my @hosts;
13694: my $ip;
13695:
13696: if (exists($name_to_ip{$dns})) {
13697: $ip = $name_to_ip{$dns};
13698: }
13699: if (!$ip) {
13700: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13701: if (length($ip) == 4) {
13702: $ip = &IO::Socket::inet_ntoa($ip);
13703: }
13704: }
13705: if ($ip) {
13706: @hosts = get_hosts_from_ip($ip);
13707: return $hosts[0];
13708: }
13709: return undef;
13710: }
13711:
13712: sub get_internet_names {
13713: my ($lonid) = @_;
13714: return if ($lonid eq '');
13715: my ($idnref,$cached)=
13716: &Apache::lonnet::is_cached_new('internetnames',$lonid);
13717: if ($cached) {
13718: return $idnref;
13719: }
13720: my $ip = &get_host_ip($lonid);
13721: my @hosts = &get_hosts_from_ip($ip);
13722: my %iphost = &get_iphost();
13723: my (@idns,%seen);
13724: foreach my $id (@hosts) {
13725: my $dom = &host_domain($id);
13726: my $prim_id = &domain($dom,'primary');
13727: my $prim_ip = &get_host_ip($prim_id);
13728: next if ($seen{$prim_ip});
13729: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
13730: foreach my $id (@{$iphost{$prim_ip}}) {
13731: my $intdom = &internet_dom($id);
13732: unless (grep(/^\Q$intdom\E$/,@idns)) {
13733: push(@idns,$intdom);
13734: }
13735: }
13736: }
13737: $seen{$prim_ip} = 1;
13738: }
13739: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
13740: }
13741:
13742: }
13743:
13744: sub all_loncaparevs {
13745: 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);
13746: }
13747:
13748: # ---------------------------------------------------------- Read loncaparev table
13749: {
13750: sub load_loncaparevs {
13751: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
13752: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
13753: while (my $configline=<$config>) {
13754: chomp($configline);
13755: my ($hostid,$loncaparev)=split(/:/,$configline);
13756: $loncaparevs{$hostid}=$loncaparev;
13757: }
13758: close($config);
13759: }
13760: }
13761: }
13762: }
13763:
13764: # ---------------------------------------------------------- Read serverhostID table
13765: {
13766: sub load_serverhomeIDs {
13767: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
13768: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
13769: while (my $configline=<$config>) {
13770: chomp($configline);
13771: my ($name,$id)=split(/:/,$configline);
13772: $serverhomeIDs{$name}=$id;
13773: }
13774: close($config);
13775: }
13776: }
13777: }
13778: }
13779:
13780:
13781: BEGIN {
13782:
13783: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13784: unless ($readit) {
13785: {
13786: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13787: %perlvar = (%perlvar,%{$configvars});
13788: }
13789:
13790:
13791: # ------------------------------------------------------ Read spare server file
13792: {
13793: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
13794:
13795: while (my $configline=<$config>) {
13796: chomp($configline);
13797: if ($configline) {
13798: my ($host,$type) = split(':',$configline,2);
13799: if (!defined($type) || $type eq '') { $type = 'default' };
13800: push(@{ $spareid{$type} }, $host);
13801: }
13802: }
13803: close($config);
13804: }
13805: # ------------------------------------------------------------ Read permissions
13806: {
13807: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
13808:
13809: while (my $configline=<$config>) {
13810: chomp($configline);
13811: if ($configline) {
13812: my ($role,$perm)=split(/ /,$configline);
13813: if ($perm ne '') { $pr{$role}=$perm; }
13814: }
13815: }
13816: close($config);
13817: }
13818:
13819: # -------------------------------------------- Read plain texts for permissions
13820: {
13821: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
13822:
13823: while (my $configline=<$config>) {
13824: chomp($configline);
13825: if ($configline) {
13826: my ($short,@plain)=split(/:/,$configline);
13827: %{$prp{$short}} = ();
13828: if (@plain > 0) {
13829: $prp{$short}{'std'} = $plain[0];
13830: for (my $i=1; $i<@plain; $i++) {
13831: $prp{$short}{'alt'.$i} = $plain[$i];
13832: }
13833: }
13834: }
13835: }
13836: close($config);
13837: }
13838:
13839: # ---------------------------------------------------------- Read package table
13840: {
13841: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
13842:
13843: while (my $configline=<$config>) {
13844: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
13845: chomp($configline);
13846: my ($short,$plain)=split(/:/,$configline);
13847: my ($pack,$name)=split(/\&/,$short);
13848: if ($plain ne '') {
13849: $packagetab{$pack.'&'.$name.'&name'}=$name;
13850: $packagetab{$short}=$plain;
13851: }
13852: }
13853: close($config);
13854: }
13855:
13856: # ---------------------------------------------------------- Read loncaparev table
13857:
13858: &load_loncaparevs();
13859:
13860: # ---------------------------------------------------------- Read serverhostID table
13861:
13862: &load_serverhomeIDs();
13863:
13864: # ---------------------------------------------------------- Read releaseslist XML
13865: {
13866: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
13867: if (-e $file) {
13868: my $parser = HTML::LCParser->new($file);
13869: while (my $token = $parser->get_token()) {
13870: if ($token->[0] eq 'S') {
13871: my $item = $token->[1];
13872: my $name = $token->[2]{'name'};
13873: my $value = $token->[2]{'value'};
13874: my $valuematch = $token->[2]{'valuematch'};
13875: my $namematch = $token->[2]{'namematch'};
13876: if ($item eq 'parameter') {
13877: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
13878: my $release = $parser->get_text();
13879: $release =~ s/(^\s*|\s*$ )//gx;
13880: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
13881: }
13882: } elsif ($item ne '' && $name ne '') {
13883: my $release = $parser->get_text();
13884: $release =~ s/(^\s*|\s*$ )//gx;
13885: $needsrelease{$item.':'.$name.':'.$value} = $release;
13886: }
13887: }
13888: }
13889: }
13890: }
13891:
13892: # ---------------------------------------------------------- Read managers table
13893: {
13894: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
13895: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
13896: while (my $configline=<$config>) {
13897: chomp($configline);
13898: next if ($configline =~ /^\#/);
13899: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
13900: $managerstab{$configline} = 1;
13901: }
13902: }
13903: close($config);
13904: }
13905: }
13906: }
13907:
13908: # ------------- set up temporary directory
13909: {
13910: $tmpdir = LONCAPA::tempdir();
13911:
13912: }
13913:
13914: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
13915: 'compress_threshold'=> 20_000,
13916: });
13917:
13918: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
13919: $dumpcount=0;
13920: $locknum=0;
13921:
13922: &logtouch();
13923: &logthis('<font color="yellow">INFO: Read configuration</font>');
13924: $readit=1;
13925: {
13926: use integer;
13927: my $test=(2**32)+1;
13928: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
13929: &logthis(" Detected 64bit platform ($_64bit)");
13930: }
13931: }
13932: }
13933:
13934: 1;
13935: __END__
13936:
13937: =pod
13938:
13939: =head1 NAME
13940:
13941: Apache::lonnet - Subroutines to ask questions about things in the network.
13942:
13943: =head1 SYNOPSIS
13944:
13945: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
13946:
13947: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
13948:
13949: Common parameters:
13950:
13951: =over 4
13952:
13953: =item *
13954:
13955: $uname : an internal username (if $cname expecting a course Id specifically)
13956:
13957: =item *
13958:
13959: $udom : a domain (if $cdom expecting a course's domain specifically)
13960:
13961: =item *
13962:
13963: $symb : a resource instance identifier
13964:
13965: =item *
13966:
13967: $namespace : the name of a .db file that contains the data needed or
13968: being set.
13969:
13970: =back
13971:
13972: =head1 OVERVIEW
13973:
13974: lonnet provides subroutines which interact with the
13975: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
13976: about classes, users, and resources.
13977:
13978: For many of these objects you can also use this to store data about
13979: them or modify them in various ways.
13980:
13981: =head2 Symbs
13982:
13983: To identify a specific instance of a resource, LON-CAPA uses symbols
13984: or "symbs"X<symb>. These identifiers are built from the URL of the
13985: map, the resource number of the resource in the map, and the URL of
13986: the resource itself. The latter is somewhat redundant, but might help
13987: if maps change.
13988:
13989: An example is
13990:
13991: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
13992:
13993: The respective map entry is
13994:
13995: <resource id="19" src="/res/msu/korte/tests/part12.problem"
13996: title="Problem 2">
13997: </resource>
13998:
13999: Symbs are used by the random number generator, as well as to store and
14000: restore data specific to a certain instance of for example a problem.
14001:
14002: =head2 Storing And Retrieving Data
14003:
14004: X<store()>X<cstore()>X<restore()>Three of the most important functions
14005: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14006: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14007: is is the non-critical message twin of cstore. These functions are for
14008: handlers to store a perl hash to a user's permanent data space in an
14009: easy manner, and to retrieve it again on another call. It is expected
14010: that a handler would use this once at the beginning to retrieve data,
14011: and then again once at the end to send only the new data back.
14012:
14013: The data is stored in the user's data directory on the user's
14014: homeserver under the ID of the course.
14015:
14016: The hash that is returned by restore will have all of the previous
14017: value for all of the elements of the hash.
14018:
14019: Example:
14020:
14021: #creating a hash
14022: my %hash;
14023: $hash{'foo'}='bar';
14024:
14025: #storing it
14026: &Apache::lonnet::cstore(\%hash);
14027:
14028: #changing a value
14029: $hash{'foo'}='notbar';
14030:
14031: #adding a new value
14032: $hash{'bar'}='foo';
14033: &Apache::lonnet::cstore(\%hash);
14034:
14035: #retrieving the hash
14036: my %history=&Apache::lonnet::restore();
14037:
14038: #print the hash
14039: foreach my $key (sort(keys(%history))) {
14040: print("\%history{$key} = $history{$key}");
14041: }
14042:
14043: Will print out:
14044:
14045: %history{1:foo} = bar
14046: %history{1:keys} = foo:timestamp
14047: %history{1:timestamp} = 990455579
14048: %history{2:bar} = foo
14049: %history{2:foo} = notbar
14050: %history{2:keys} = foo:bar:timestamp
14051: %history{2:timestamp} = 990455580
14052: %history{bar} = foo
14053: %history{foo} = notbar
14054: %history{timestamp} = 990455580
14055: %history{version} = 2
14056:
14057: Note that the special hash entries C<keys>, C<version> and
14058: C<timestamp> were added to the hash. C<version> will be equal to the
14059: total number of versions of the data that have been stored. The
14060: C<timestamp> attribute will be the UNIX time the hash was
14061: stored. C<keys> is available in every historical section to list which
14062: keys were added or changed at a specific historical revision of a
14063: hash.
14064:
14065: B<Warning>: do not store the hash that restore returns directly. This
14066: will cause a mess since it will restore the historical keys as if the
14067: were new keys. I.E. 1:foo will become 1:1:foo etc.
14068:
14069: Calling convention:
14070:
14071: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
14072: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
14073:
14074: For more detailed information, see lonnet specific documentation.
14075:
14076: =head1 RETURN MESSAGES
14077:
14078: =over 4
14079:
14080: =item * B<con_lost>: unable to contact remote host
14081:
14082: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14083: when the connection is brought back up
14084:
14085: =item * B<con_failed>: unable to contact remote host and unable to save message
14086: for later delivery
14087:
14088: =item * B<error:>: an error a occurred, a description of the error follows the :
14089:
14090: =item * B<no_such_host>: unable to fund a host associated with the user/domain
14091: that was requested
14092:
14093: =back
14094:
14095: =head1 PUBLIC SUBROUTINES
14096:
14097: =head2 Session Environment Functions
14098:
14099: =over 4
14100:
14101: =item *
14102: X<appenv()>
14103: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
14104: the user envirnoment file, and will be restored for each access this
14105: user makes during this session, also modifies the %env for the current
14106: process. Optional rolesarrayref - if defined contains a reference to an array
14107: of roles which are exempt from the restriction on modifying user.role entries
14108: in the user's environment.db and in %env.
14109:
14110: =item *
14111: X<delenv()>
14112: B<delenv($delthis,$regexp)>: removes all items from the session
14113: environment file that begin with $delthis. If the
14114: optional second arg - $regexp - is true, $delthis is treated as a
14115: regular expression, otherwise \Q$delthis\E is used.
14116: The values are also deleted from the current processes %env.
14117:
14118: =item * get_env_multiple($name)
14119:
14120: gets $name from the %env hash, it seemlessly handles the cases where multiple
14121: values may be defined and end up as an array ref.
14122:
14123: returns an array of values
14124:
14125: =back
14126:
14127: =head2 User Information
14128:
14129: =over 4
14130:
14131: =item *
14132: X<queryauthenticate()>
14133: B<queryauthenticate($uname,$udom)>: try to determine user's current
14134: authentication scheme
14135:
14136: =item *
14137: X<authenticate()>
14138: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
14139: authenticate user from domain's lib servers (first use the current
14140: one). C<$upass> should be the users password.
14141: $checkdefauth is optional (value is 1 if a check should be made to
14142: authenticate user using default authentication method, and allow
14143: account creation if username does not have account in the domain).
14144: $clientcancheckhost is optional (value is 1 if checking whether the
14145: server can host will occur on the client side in lonauth.pm).
14146:
14147: =item *
14148: X<homeserver()>
14149: B<homeserver($uname,$udom)>: find the server which has
14150: the user's directory and files (there must be only one), this caches
14151: the answer, and also caches if there is a borken connection.
14152:
14153: =item *
14154: X<idget()>
14155: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
14156: a list of student/employee IDs or clicker IDs
14157: (student/employee IDs are a unique resource in a domain, there must be
14158: only 1 ID per username, and only 1 username per ID in a specific domain).
14159: clickerIDs are not necessarily unique, as students might share clickers.
14160: (returns hash: id=>name,id=>name)
14161:
14162: =item *
14163: X<idrget()>
14164: B<idrget($udom,@unames)>: find the IDs behind a list of
14165: usernames (returns hash: name=>id,name=>id)
14166:
14167: =item *
14168: X<idput()>
14169: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
14170: names and associated student/employee IDs or clicker IDs.
14171:
14172: =item *
14173: X<iddel()>
14174: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
14175: student/employee ID or clicker ID username look-ups from domain.
14176: The homeserver ($uhome) and namespace ($namespace) are optional.
14177: If no $uhome is provided, it will be determined usig &homeserver()
14178: for each user. If no $namespace is provided, the default is ids.
14179:
14180: =item *
14181: X<updateclickers()>
14182: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
14183: clicker ID-to-username look-ups in clickers.db on library server.
14184: Permitted actions are add or del (i.e., add or delete). The
14185: clickers.db contains clickerID as keys (escaped), and each corresponding
14186: value is an escaped comma-separated list of usernames (for whom the
14187: library server is the homeserver), who registered that particular ID.
14188: If $critical is true, the update will be sent via &critical, otherwise
14189: &reply() will be used.
14190:
14191: =item *
14192: X<rolesinit()>
14193: B<rolesinit($udom,$username)>: get user privileges.
14194: returns user role, first access and timer interval hashes
14195:
14196: =item *
14197: X<privileged()>
14198: B<privileged($username,$domain)>: returns a true if user has a
14199: privileged and active role (i.e. su or dc), false otherwise.
14200:
14201: =item *
14202: X<getsection()>
14203: B<getsection($udom,$uname,$cname)>: finds the section of student in the
14204: course $cname, return section name/number or '' for "not in course"
14205: and '-1' for "no section"
14206:
14207: =item *
14208: X<userenvironment()>
14209: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
14210: passed in @what from the requested user's environment, returns a hash
14211:
14212: =item *
14213: X<userlog_query()>
14214: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14215: activity.log file. %filters defines filters applied when parsing the
14216: log file. These can be start or end timestamps, or the type of action
14217: - log to look for Login or Logout events, check for Checkin or
14218: Checkout, role for role selection. The response is in the form
14219: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
14220: escaped strings of the action recorded in the activity.log file.
14221:
14222: =back
14223:
14224: =head2 User Roles
14225:
14226: =over 4
14227:
14228: =item *
14229:
14230: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
14231: returns codes for allowed actions.
14232:
14233: The first argument is required, all others are optional.
14234:
14235: $priv is the privilege being checked.
14236: $uri contains additional information about what is being checked for access (e.g.,
14237: URL, course ID etc.).
14238: $symb is the unique resource instance identifier in a course; if needed,
14239: but not provided, it will be retrieved via a call to &symbread().
14240: $role is the role for which a priv is being checked (only used if priv is evb).
14241: $clientip is the user's IP address (only used when checking for access to portfolio
14242: files).
14243: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
14244: prevents recursive calls to &allowed.
14245:
14246: F: full access
14247: U,I,K: authentication modes (cxx only)
14248: '': forbidden
14249: 1: user needs to choose course
14250: 2: browse allowed
14251: A: passphrase authentication needed
14252: B: access temporarily blocked because of a blocking event in a course.
14253:
14254: =item *
14255:
14256: constructaccess($url,$setpriv) : check for access to construction space URL
14257:
14258: See if the owner domain and name in the URL match those in the
14259: expected environment. If so, return three element list
14260: ($ownername,$ownerdomain,$ownerhome).
14261:
14262: Otherwise return the null string.
14263:
14264: If second argument 'setpriv' is true, it assigns the privileges,
14265: and returns the same three element list, unless the owner has
14266: blocked "ad hoc" Domain Coordinator access to the Author Space,
14267: in which case the null string is returned.
14268:
14269: =item *
14270:
14271: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14272: define a custom role rolename set privileges in format of lonTabs/roles.tab
14273: for system, domain, and course level. $uname and $udom are optional (current
14274: user's username and domain will be used when either of $uname or $udom are absent.
14275:
14276: =item *
14277:
14278: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
14279: (rolesplain.tab); plain text explanation of a user role term.
14280: $type is Course (default) or Community.
14281: If $forcedefault evaluates to true, text returned will be default
14282: text for $type. Otherwise, if this is a course, the text returned
14283: will be a custom name for the role (if defined in the course's
14284: environment). If no custom name is defined the default is returned.
14285:
14286: =item *
14287:
14288: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
14289: All arguments are optional. Returns a hash of a roles, either for
14290: co-author/assistant author roles for a user's Construction Space
14291: (default), or if $context is 'userroles', roles for the user himself,
14292: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14293: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14294: For each key, value is set to colon-separated start and end times for
14295: the role. If no username and domain are specified, will default to
14296: current user/domain. Types, roles, and roledoms are references to arrays
14297: of role statuses (active, future or previous), roles
14298: (e.g., cc,in, st etc.) and domains of the roles which can be used
14299: to restrict the list of roles reported. If no array ref is
14300: provided for types, will default to return only active roles.
14301:
14302: =item *
14303:
14304: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14305: user: $uname:$udom has a role in the course: $cdom_$cnum.
14306:
14307: Additional optional arguments are: $type (if role checking is to be restricted
14308: to certain user status types -- previous (expired roles), active (currently
14309: available roles) or future (roles available in the future), and
14310: $hideprivileged -- if true will not report course roles for users who
14311: have active Domain Coordinator role in course's domain or in additional
14312: domains (specified in 'Domains to check for privileged users' in course
14313: environment -- set via: Course Settings -> Classlists and staff listing).
14314:
14315: =item *
14316:
14317: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14318: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14319: $possdomains and $possroles are optional array refs -- to domains to check and
14320: roles to check. If $possdomains is not specified, a dump will be done of the
14321: users' roles.db to check for a dc or su role in any domain. This can be
14322: time consuming if &privileged is called repeatedly (e.g., when displaying a
14323: classlist), so in such cases, supplying a $possdomains array is preferred, as
14324: this then allows &privileged_by_domain() to be used, which caches the identity
14325: of privileged users, eliminating the need for repeated calls to &dump().
14326:
14327: =item *
14328:
14329: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14330: where the outer hash keys are domains specified in the $possdomains array ref,
14331: next inner hash keys are privileged roles specified in the $roles array ref,
14332: and the innermost hash contains key = value pairs for username:domain = end:start
14333: for active or future "privileged" users with that role in that domain. To avoid
14334: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14335: innerhash are cached using priv_$role and $dom as the identifiers.
14336:
14337: =back
14338:
14339: =head2 User Modification
14340:
14341: =over 4
14342:
14343: =item *
14344:
14345: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
14346: user for the level given by URL. Optional start and end dates (leave empty
14347: string or zero for "no date")
14348:
14349: =item *
14350:
14351: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14352: change a users, password, possible return values are: ok,
14353: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14354: refused
14355:
14356: =item *
14357:
14358: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
14359:
14360: =item *
14361:
14362: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14363: $forceid,$desiredhome,$email,$inststatus,$candelete) :
14364:
14365: will update user information (firstname,middlename,lastname,generation,
14366: permanentemail), and if forceid is true, student/employee ID also.
14367: A user's institutional affiliation(s) can also be updated.
14368: User information fields will not be overwritten with empty entries
14369: unless the field is included in the $candelete array reference.
14370: This array is included when a single user is modified via "Manage Users",
14371: or when Autoupdate.pl is run by cron in a domain.
14372:
14373: =item *
14374:
14375: modifystudent
14376:
14377: modify a student's enrollment and identification information.
14378: The course id is resolved based on the current user's environment.
14379: This means the invoking user must be a course coordinator or otherwise
14380: associated with a course.
14381:
14382: This call is essentially a wrapper for lonnet::modifyuser and
14383: lonnet::modify_student_enrollment
14384:
14385: Inputs:
14386:
14387: =over 4
14388:
14389: =item B<$udom> Student's loncapa domain
14390:
14391: =item B<$uname> Student's loncapa login name
14392:
14393: =item B<$uid> Student/Employee ID
14394:
14395: =item B<$umode> Student's authentication mode
14396:
14397: =item B<$upass> Student's password
14398:
14399: =item B<$first> Student's first name
14400:
14401: =item B<$middle> Student's middle name
14402:
14403: =item B<$last> Student's last name
14404:
14405: =item B<$gene> Student's generation
14406:
14407: =item B<$usec> Student's section in course
14408:
14409: =item B<$end> Unix time of the roles expiration
14410:
14411: =item B<$start> Unix time of the roles start date
14412:
14413: =item B<$forceid> If defined, allow $uid to be changed
14414:
14415: =item B<$desiredhome> server to use as home server for student
14416:
14417: =item B<$email> Student's permanent e-mail address
14418:
14419: =item B<$type> Type of enrollment (auto or manual)
14420:
14421: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
14422:
14423: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
14424:
14425: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
14426:
14427: =item B<$context> role change context (shown in User Management Logs display in a course)
14428:
14429: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14430:
14431: =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.
14432:
14433: =back
14434:
14435: =item *
14436:
14437: modify_student_enrollment
14438:
14439: Change a student's enrollment status in a class. The environment variable
14440: 'role.request.course' must be defined for this function to proceed.
14441:
14442: Inputs:
14443:
14444: =over 4
14445:
14446: =item $udom, student's domain
14447:
14448: =item $uname, student's name
14449:
14450: =item $uid, student's user id
14451:
14452: =item $first, student's first name
14453:
14454: =item $middle
14455:
14456: =item $last
14457:
14458: =item $gene
14459:
14460: =item $usec
14461:
14462: =item $end
14463:
14464: =item $start
14465:
14466: =item $type
14467:
14468: =item $locktype
14469:
14470: =item $cid
14471:
14472: =item $selfenroll
14473:
14474: =item $context
14475:
14476: =item $credits, number of credits student will earn from this class
14477:
14478: =item $instsec, institutional course section code for student
14479:
14480: =back
14481:
14482:
14483: =item *
14484:
14485: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14486: custom role; give a custom role to a user for the level given by URL. Specify
14487: name and domain of role author, and role name
14488:
14489: =item *
14490:
14491: revokerole($udom,$uname,$url,$role) : revoke a role for url
14492:
14493: =item *
14494:
14495: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14496:
14497: =back
14498:
14499: =head2 Course Infomation
14500:
14501: =over 4
14502:
14503: =item *
14504:
14505: coursedescription($courseid,$options) : returns a hash of information about the
14506: specified course id, including all environment settings for the
14507: course, the description of the course will be in the hash under the
14508: key 'description'
14509:
14510: $options is an optional parameter that if supplied is a hash reference that controls
14511: what how this function works. It has the following key/values:
14512:
14513: =over 4
14514:
14515: =item freshen_cache
14516:
14517: If defined, and the environment cache for the course is valid, it is
14518: returned in the returned hash.
14519:
14520: =item one_time
14521:
14522: If defined, the last cache time is set to _now_
14523:
14524: =item user
14525:
14526: If defined, the supplied username is used instead of the current user.
14527:
14528:
14529: =back
14530:
14531: =item *
14532:
14533: resdata($name,$domain,$type,@which) : request for current parameter
14534: setting for a specific $type, where $type is either 'course' or 'user',
14535: @what should be a list of parameters to ask about. This routine caches
14536: answers for 10 minutes.
14537:
14538: =item *
14539:
14540: get_courseresdata($courseid, $domain) : dump the entire course resource
14541: data base, returning a hash that is keyed by the resource name and has
14542: values that are the resource value. I believe that the timestamps and
14543: versions are also returned.
14544:
14545: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14546: supplemental content area. This routine caches the number of files for
14547: 10 minutes.
14548:
14549: =back
14550:
14551: =head2 Course Modification
14552:
14553: =over 4
14554:
14555: =item *
14556:
14557: writecoursepref($courseid,%prefs) : write preferences (environment
14558: database) for a course
14559:
14560: =item *
14561:
14562: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14563:
14564: =item *
14565:
14566: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
14567:
14568: =item *
14569:
14570: is_course($courseid), is_course($cdom, $cnum)
14571:
14572: Accepts either a combined $courseid (in the form of domain_courseid) or the
14573: two component version $cdom, $cnum. It checks if the specified course exists.
14574:
14575: Returns:
14576: undef if the course doesn't exist, otherwise
14577: in scalar context the combined courseid.
14578: in list context the two components of the course identifier, domain and
14579: courseid.
14580:
14581: =back
14582:
14583: =head2 Resource Subroutines
14584:
14585: =over 4
14586:
14587: =item *
14588:
14589: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
14590:
14591: =item *
14592:
14593: repcopy($filename) : subscribes to the requested file, and attempts to
14594: replicate from the owning library server, Might return
14595: 'unavailable', 'not_found', 'forbidden', 'ok', or
14596: 'bad_request', also attempts to grab the metadata for the
14597: resource. Expects the local filesystem pathname
14598: (/home/httpd/html/res/....)
14599:
14600: =back
14601:
14602: =head2 Resource Information
14603:
14604: =over 4
14605:
14606: =item *
14607:
14608: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
14609: and returns the value of a variety of different possible values,
14610: $varname should be a request string, and the other parameters can be
14611: used to specify who and what one is asking about. Ordinarily, $cid
14612: does not need to be specified, as it is retrived from
14613: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14614: within lonuserstate::loadmap() when initializing a course, before
14615: $env{'request.course.id'} has been set, so it needs to be provided
14616: in that one case.
14617:
14618: Possible values for $varname are environment.lastname (or other item
14619: from the envirnment hash), user.name (or someother aspect about the
14620: user), resource.0.maxtries (or some other part and parameter of a
14621: resource)
14622:
14623: =item *
14624:
14625: directcondval($number) : get current value of a condition; reads from a state
14626: string
14627:
14628: =item *
14629:
14630: condval($condidx) : value of condition index based on state
14631:
14632: =item *
14633:
14634: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14635: resource's metadata, $what should be either a specific key, or either
14636: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14637: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
14638:
14639: this function automatically caches all requests
14640:
14641: =item *
14642:
14643: metadata_query($query,$custom,$customshow) : make a metadata query against the
14644: network of library servers; returns file handle of where SQL and regex results
14645: will be stored for query
14646:
14647: =item *
14648:
14649: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
14650: return symbolic list entry (all arguments optional).
14651:
14652: Args: filename is the filename (including path) for the file for which a symb
14653: is required; donotrecurse, if true will prevent calls to allowed() being made
14654: to check access status if more than one resource was found in the bighash
14655: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
14656: a randompick); ignorecachednull, if true will prevent a symb of '' being
14657: returned if $env{$cache_str} is defined as ''; checkforblock if true will
14658: cause possible symbs to be checked to determine if they are subject to content
14659: blocking, if so they will not be included as possible symbs; possibles is a
14660: ref to a hash, which, as a side effect, will be populated with all possible
14661: symbs (content blocking not tested).
14662:
14663: returns the data handle
14664:
14665: =item *
14666:
14667: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
14668: and is a possible symb for the URL in $thisfn, and if is an encrypted
14669: resource that the user accessed using /enc/ returns a 1 on success, 0
14670: on failure, user must be in a course, as it assumes the existence of
14671: the course initial hash, and uses $env('request.course.id'}. The third
14672: arg is an optional reference to a scalar. If this arg is passed in the
14673: call to symbverify, it will be set to 1 if the symb has been set to be
14674: encrypted; otherwise it will be null.
14675:
14676: =item *
14677:
14678: symbclean($symb) : removes versions numbers from a symb, returns the
14679: cleaned symb
14680:
14681: =item *
14682:
14683: is_on_map($uri) : checks if the $uri is somewhere on the current
14684: course map, user must be in a course for it to work.
14685:
14686: =item *
14687:
14688: numval($salt) : return random seed value (addend for rndseed)
14689:
14690: =item *
14691:
14692: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
14693: a random seed, all arguments are optional, if they aren't sent it uses the
14694: environment to derive them. Note: if symb isn't sent and it can't get one
14695: from &symbread it will use the current time as its return value
14696:
14697: =item *
14698:
14699: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
14700: unfakeable, receipt
14701:
14702: =item *
14703:
14704: receipt() : API to ireceipt working off of env values; given out to users
14705:
14706: =item *
14707:
14708: countacc($url) : count the number of accesses to a given URL
14709:
14710: =item *
14711:
14712: 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
14713:
14714: =item *
14715:
14716: 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)
14717:
14718: =item *
14719:
14720: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
14721:
14722: =item *
14723:
14724: devalidate($symb) : devalidate temporary spreadsheet calculations,
14725: forcing spreadsheet to reevaluate the resource scores next time.
14726:
14727: =item *
14728:
14729: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
14730: when viewing in course context.
14731:
14732: input: six args -- filename (decluttered), course number, course domain,
14733: url, symb (if registered) and group (if this is a
14734: group item -- e.g., bulletin board, group page etc.).
14735:
14736: output: array of five scalars --
14737: $cfile -- url for file editing if editable on current server
14738: $home -- homeserver of resource (i.e., for author if published,
14739: or course if uploaded.).
14740: $switchserver -- 1 if server switch will be needed.
14741: $forceedit -- 1 if icon/link should be to go to edit mode
14742: $forceview -- 1 if icon/link should be to go to view mode
14743:
14744: =item *
14745:
14746: is_course_upload($file,$cnum,$cdom)
14747:
14748: Used in course context to determine if current file was uploaded to
14749: the course (i.e., would be found in /userfiles/docs on the course's
14750: homeserver.
14751:
14752: input: 3 args -- filename (decluttered), course number and course domain.
14753: output: boolean -- 1 if file was uploaded.
14754:
14755: =back
14756:
14757: =head2 Storing/Retreiving Data
14758:
14759: =over 4
14760:
14761: =item *
14762:
14763: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
14764: permanently for this url; hashref needs to be given and should be a \%hashname;
14765: the remaining args aren't required and if they aren't passed or are '' they will
14766: be derived from the env (with the exception of $laststore, which is an
14767: optional arg used when a user's submission is stored in grading).
14768: $laststore is $version=$timestamp, where $version is the most recent version
14769: number retrieved for the corresponding $symb in the $namespace db file, and
14770: $timestamp is the timestamp for that transaction (UNIX time).
14771: $laststore is currently only passed when cstore() is called by
14772: structuretags::finalize_storage().
14773:
14774: =item *
14775:
14776: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
14777: but uses critical subroutine
14778:
14779: =item *
14780:
14781: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
14782: all args are optional
14783:
14784: =item *
14785:
14786: dumpstore($namespace,$udom,$uname,$regexp,$range) :
14787: dumps the complete (or key matching regexp) namespace into a hash
14788: ($udom, $uname, $regexp, $range are optional) for a namespace that is
14789: normally &store()ed into
14790:
14791: $range should be either an integer '100' (give me the first 100
14792: matching records)
14793: or be two integers sperated by a - with no spaces
14794: '30-50' (give me the 30th through the 50th matching
14795: records)
14796:
14797:
14798: =item *
14799:
14800: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
14801: replaces a &store() version of data with a replacement set of data
14802: for a particular resource in a namespace passed in the $storehash hash
14803: reference. If $tolog is true, the transaction is logged in the courselog
14804: with an action=PUTSTORE.
14805:
14806: =item *
14807:
14808: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
14809: works very similar to store/cstore, but all data is stored in a
14810: temporary location and can be reset using tmpreset, $storehash should
14811: be a hash reference, returns nothing on success
14812:
14813: =item *
14814:
14815: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
14816: similar to restore, but all data is stored in a temporary location and
14817: can be reset using tmpreset. Returns a hash of values on success,
14818: error string otherwise.
14819:
14820: =item *
14821:
14822: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
14823: deltes all keys for $symb form the temporary storage hash.
14824:
14825: =item *
14826:
14827: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14828: reference filled in from namesp ($udom and $uname are optional)
14829:
14830: =item *
14831:
14832: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
14833: namesp ($udom and $uname are optional)
14834:
14835: =item *
14836:
14837: dump($namespace,$udom,$uname,$regexp,$range) :
14838: dumps the complete (or key matching regexp) namespace into a hash
14839: ($udom, $uname, $regexp, $range are optional)
14840:
14841: $range should be either an integer '100' (give me the first 100
14842: matching records)
14843: or be two integers sperated by a - with no spaces
14844: '30-50' (give me the 30th through the 50th matching
14845: records)
14846: =item *
14847:
14848: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
14849: $store can be a scalar, an array reference, or if the amount to be
14850: incremented is > 1, a hash reference.
14851:
14852: ($udom and $uname are optional)
14853:
14854: =item *
14855:
14856: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
14857: ($udom and $uname are optional)
14858:
14859: =item *
14860:
14861: cput($namespace,$storehash,$udom,$uname) : critical put
14862: ($udom and $uname are optional)
14863:
14864: =item *
14865:
14866: newput($namespace,$storehash,$udom,$uname) :
14867:
14868: Attempts to store the items in the $storehash, but only if they don't
14869: currently exist, if this succeeds you can be certain that you have
14870: successfully created a new key value pair in the $namespace db.
14871:
14872:
14873: Args:
14874: $namespace: name of database to store values to
14875: $storehash: hashref to store to the db
14876: $udom: (optional) domain of user containing the db
14877: $uname: (optional) name of user caontaining the db
14878:
14879: Returns:
14880: 'ok' -> succeeded in storing all keys of $storehash
14881: 'key_exists: <key>' -> failed to anything out of $storehash, as at
14882: least <key> already existed in the db (other
14883: requested keys may also already exist)
14884: 'error: <msg>' -> unable to tie the DB or other error occurred
14885: 'con_lost' -> unable to contact request server
14886: 'refused' -> action was not allowed by remote machine
14887:
14888:
14889: =item *
14890:
14891: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14892: reference filled in from namesp (encrypts the return communication)
14893: ($udom and $uname are optional)
14894:
14895: =item *
14896:
14897: log($udom,$name,$home,$message) : write to permanent log for user; use
14898: critical subroutine
14899:
14900: =item *
14901:
14902: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
14903: array reference filled in from namespace found in domain level on either
14904: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
14905:
14906: =item *
14907:
14908: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
14909: domain level either on specified domain server ($uhome) or primary domain
14910: server ($udom and $uhome are optional)
14911:
14912: =item *
14913:
14914: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
14915: for: authentication, language, quotas, timezone, date locale, and portal URL in
14916: the target domain.
14917:
14918: May also include additional key => value pairs for the following groups:
14919:
14920: =over
14921:
14922: =item
14923: disk quotas (MB allocated by default to portfolios and authoring spaces).
14924:
14925: =over
14926:
14927: =item defaultquota, authorquota
14928:
14929: =back
14930:
14931: =item
14932: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
14933: portfolio for users).
14934:
14935: =over
14936:
14937: =item
14938: aboutme, blog, webdav, portfolio
14939:
14940: =back
14941:
14942: =item
14943: requestcourses: ability to request courses, and how requests are processed.
14944:
14945: =over
14946:
14947: =item
14948: official, unofficial, community, textbook, placement
14949:
14950: =back
14951:
14952: =item
14953: inststatus: types of institutional affiliation, and order in which they are displayed.
14954:
14955: =over
14956:
14957: =item
14958: inststatustypes, inststatusorder, inststatusguest
14959:
14960: =back
14961:
14962: =item
14963: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
14964: for course's uploaded content.
14965:
14966: =over
14967:
14968: =item
14969: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
14970: communityquota, textbookquota, placementquota
14971:
14972: =back
14973:
14974: =item
14975: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
14976: on your servers.
14977:
14978: =over
14979:
14980: =item
14981: remotesessions, hostedsessions
14982:
14983: =back
14984:
14985: =back
14986:
14987: In cases where a domain coordinator has never used the "Set Domain Configuration"
14988: utility to create a configuration.db file on a domain's primary library server
14989: only the following domain defaults: auth_def, auth_arg_def, lang_def
14990: -- corresponding values are authentication type (internal, krb4, krb5,
14991: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
14992: will be available. Values are retrieved from cache (if current), unless the
14993: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
14994: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
14995:
14996: Typical usage:
14997:
14998: %domdefaults = &get_domain_defaults($target_domain);
14999:
15000: =back
15001:
15002: =head2 Network Status Functions
15003:
15004: =over 4
15005:
15006: =item *
15007:
15008: dirlist() : return directory list based on URI (first arg).
15009:
15010: Inputs: 1 required, 5 optional.
15011:
15012: =over
15013:
15014: =item
15015: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15016:
15017: =item
15018: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
15019:
15020: =item
15021: $username - username of user/course to be listed. Extracted from $uri if absent.
15022:
15023: =item
15024: $getpropath - boolean: 1 if prepend path using &propath().
15025:
15026: =item
15027: $getuserdir - boolean: 1 if prepend path for "userfiles".
15028:
15029: =item
15030: $alternateRoot - path to prepend in place of path from $uri.
15031:
15032: =back
15033:
15034: Returns: Array of up to two items.
15035:
15036: =over
15037:
15038: a reference to an array of files/subdirectories
15039:
15040: =over
15041:
15042: Each element in the array of files/subdirectories is a & separated list of
15043: item name and the result of running stat on the item. If dirlist was requested
15044: for a file instead of a directory, the item name will be ''. For a directory
15045: listing, if the item is a metadata file, the element will end &N&M
15046: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15047: default copyright set (1).
15048:
15049: =back
15050:
15051: a scalar containing error condition (if encountered).
15052:
15053: =over
15054:
15055: =item
15056: no_host (no homeserver identified for $username:$domain).
15057:
15058: =item
15059: no_such_host (server contacted for listing not identified as valid host).
15060:
15061: =item
15062: con_lost (connection to remote server failed).
15063:
15064: =item
15065: refused (invalid $username:$domain received on lond side).
15066:
15067: =item
15068: no_such_dir (directory at specified path on lond side does not exist).
15069:
15070: =item
15071: empty (directory at specified path on lond side is empty).
15072:
15073: =over
15074:
15075: This is currently not encountered because the &ls3, &ls2,
15076: &ls (_handler) routines on the lond side do not filter out
15077: . and .. from a directory listing.
15078:
15079: =back
15080:
15081: =back
15082:
15083: =back
15084:
15085: =item *
15086:
15087: spareserver() : find server with least workload from spare.tab
15088:
15089:
15090: =item *
15091:
15092: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15093: if there is no corresponding loncapa host.
15094:
15095: =back
15096:
15097:
15098: =head2 Apache Request
15099:
15100: =over 4
15101:
15102: =item *
15103:
15104: ssi($url,%hash) : server side include, does a complete request cycle on url to
15105: localhost, posts hash
15106:
15107: =back
15108:
15109: =head2 Data to String to Data
15110:
15111: =over 4
15112:
15113: =item *
15114:
15115: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15116: and '&' separators, supports elements that are arrayrefs and hashrefs
15117:
15118: =item *
15119:
15120: hashref2str($hashref) : convert a hashref into a string complete with
15121: escaping and '=' and '&' separators, supports elements that are
15122: arrayrefs and hashrefs
15123:
15124: =item *
15125:
15126: arrayref2str($arrayref) : convert an arrayref into a string complete
15127: with escaping and '&' separators, supports elements that are arrayrefs
15128: and hashrefs
15129:
15130: =item *
15131:
15132: str2hash($string) : convert string to hash using unescaping and
15133: splitting on '=' and '&', supports elements that are arrayrefs and
15134: hashrefs
15135:
15136: =item *
15137:
15138: str2array($string) : convert string to hash using unescaping and
15139: splitting on '&', supports elements that are arrayrefs and hashrefs
15140:
15141: =back
15142:
15143: =head2 Logging Routines
15144:
15145:
15146: These routines allow one to make log messages in the lonnet.log and
15147: lonnet.perm logfiles.
15148:
15149: =over 4
15150:
15151: =item *
15152:
15153: logtouch() : make sure the logfile, lonnet.log, exists
15154:
15155: =item *
15156:
15157: logthis() : append message to the normal lonnet.log file, it gets
15158: preiodically rolled over and deleted.
15159:
15160: =item *
15161:
15162: logperm() : append a permanent message to lonnet.perm.log, this log
15163: file never gets deleted by any automated portion of the system, only
15164: messages of critical importance should go in here.
15165:
15166:
15167: =back
15168:
15169: =head2 General File Helper Routines
15170:
15171: =over 4
15172:
15173: =item *
15174:
15175: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15176: (a) files in /uploaded
15177: (i) If a local copy of the file exists -
15178: compares modification date of local copy with last-modified date for
15179: definitive version stored on home server for course. If local copy is
15180: stale, requests a new version from the home server and stores it.
15181: If the original has been removed from the home server, then local copy
15182: is unlinked.
15183: (ii) If local copy does not exist -
15184: requests the file from the home server and stores it.
15185:
15186: If $caller is 'uploadrep':
15187: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15188: for request for files originally uploaded via DOCS.
15189: - returns 'ok' if fresh local copy now available, -1 otherwise.
15190:
15191: Otherwise:
15192: This indicates a call from the content generation phase of the request.
15193: - returns the entire contents of the file or -1.
15194:
15195: (b) files in /res
15196: - returns the entire contents of a file or -1;
15197: it properly subscribes to and replicates the file if neccessary.
15198:
15199:
15200: =item *
15201:
15202: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15203: reference
15204:
15205: returns either a stat() list of data about the file or an empty list
15206: if the file doesn't exist or couldn't find out about it (connection
15207: problems or user unknown)
15208:
15209: =item *
15210:
15211: filelocation($dir,$file) : returns file system location of a file
15212: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15213: directory that relative $file lookups are to looked in ($dir of /a/dir
15214: and a file of ../bob will become /a/bob)
15215:
15216: =item *
15217:
15218: hreflocation($dir,$file) : returns file system location or a URL; same as
15219: filelocation except for hrefs
15220:
15221: =item *
15222:
15223: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15224: also removes beginning /home/httpd/html unless /priv/ follows it.
15225:
15226: =back
15227:
15228: =head2 Usererfile file routines (/uploaded*)
15229:
15230: =over 4
15231:
15232: =item *
15233:
15234: userfileupload(): main rotine for putting a file in a user or course's
15235: filespace, arguments are,
15236:
15237: formname - required - this is the name of the element in $env where the
15238: filename, and the contents of the file to create/modifed exist
15239: the filename is in $env{'form.'.$formname.'.filename'} and the
15240: contents of the file is located in $env{'form.'.$formname}
15241: context - if coursedoc, store the file in the course of the active role
15242: of the current user;
15243: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15244: if 'canceloverwrite': delete file in tmp/overwrites directory
15245: subdir - required - subdirectory to put the file in under ../userfiles/
15246: if undefined, it will be placed in "unknown"
15247:
15248: (This routine calls clean_filename() to remove any dangerous
15249: characters from the filename, and then calls finuserfileupload() to
15250: complete the transaction)
15251:
15252: returns either the url of the uploaded file (/uploaded/....) if successful
15253: and /adm/notfound.html if unsuccessful
15254:
15255: =item *
15256:
15257: clean_filename(): routine for cleaing a filename up for storage in
15258: userfile space, argument is:
15259:
15260: filename - proposed filename
15261:
15262: returns: the new clean filename
15263:
15264: =item *
15265:
15266: finishuserfileupload(): routine that creates and sends the file to
15267: userspace, probably shouldn't be called directly
15268:
15269: docuname: username or courseid of destination for the file
15270: docudom: domain of user/course of destination for the file
15271: formname: same as for userfileupload()
15272: fname: filename (including subdirectories) for the file
15273: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15274: allfiles: reference to hash used to store objects found by parser
15275: codebase: reference to hash used for codebases of java objects found by parser
15276: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15277: thumbheight: height (pixels) of thumbnail to be created for uploaded image
15278: resizewidth: width to be used to resize image using resizeImage from ImageMagick
15279: resizeheight: height to be used to resize image using resizeImage from ImageMagick
15280: context: if 'overwrite', will move the uploaded file from its temporary location to
15281: userfiles to facilitate overwriting a previously uploaded file with same name.
15282: mimetype: reference to scalar to accommodate mime type determined
15283: from File::MMagic if $parser = parse.
15284:
15285: returns either the url of the uploaded file (/uploaded/....) if successful
15286: and /adm/notfound.html if unsuccessful (or an error message if context
15287: was 'overwrite').
15288:
15289:
15290: =item *
15291:
15292: renameuserfile(): renames an existing userfile to a new name
15293:
15294: Args:
15295: docuname: username or courseid of destination for the file
15296: docudom: domain of user/course of destination for the file
15297: old: current file name (including any subdirs under userfiles)
15298: new: desired file name (including any subdirs under userfiles)
15299:
15300: =item *
15301:
15302: mkdiruserfile(): creates a directory is a userfiles dir
15303:
15304: Args:
15305: docuname: username or courseid of destination for the file
15306: docudom: domain of user/course of destination for the file
15307: dir: dir to create (including any subdirs under userfiles)
15308:
15309: =item *
15310:
15311: removeuserfile(): removes a file that exists in userfiles
15312:
15313: Args:
15314: docuname: username or courseid of destination for the file
15315: docudom: domain of user/course of destination for the file
15316: fname: filname to delete (including any subdirs under userfiles)
15317:
15318: =item *
15319:
15320: removeuploadedurl(): convience function for removeuserfile()
15321:
15322: Args:
15323: url: a full /uploaded/... url to delete
15324:
15325: =item *
15326:
15327: get_portfile_permissions():
15328: Args:
15329: domain: domain of user or course contain the portfolio files
15330: user: name of user or num of course contain the portfolio files
15331: Returns:
15332: hashref of a dump of the proper file_permissions.db
15333:
15334:
15335: =item *
15336:
15337: get_access_controls():
15338:
15339: Args:
15340: current_permissions: the hash ref returned from get_portfile_permissions()
15341: group: (optional) the group you want the files associated with
15342: file: (optional) the file you want access info on
15343:
15344: Returns:
15345: a hash (keys are file names) of hashes containing
15346: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15347: values are XML containing access control settings (see below)
15348:
15349: Internal notes:
15350:
15351: access controls are stored in file_permissions.db as key=value pairs.
15352: key -> path to file/file_name\0uniqueID:scope_end_start
15353: where scope -> public,guest,course,group,domains or users.
15354: end -> UNIX time for end of access (0 -> no end date)
15355: start -> UNIX time for start of access
15356:
15357: value -> XML description of access control
15358: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15359: <start></start>
15360: <end></end>
15361:
15362: <password></password> for scope type = guest
15363:
15364: <domain></domain> for scope type = course or group
15365: <number></number>
15366: <roles id="">
15367: <role></role>
15368: <access></access>
15369: <section></section>
15370: <group></group>
15371: </roles>
15372:
15373: <dom></dom> for scope type = domains
15374:
15375: <users> for scope type = users
15376: <user>
15377: <uname></uname>
15378: <udom></udom>
15379: </user>
15380: </users>
15381: </scope>
15382:
15383: Access data is also aggregated for each file in an additional key=value pair:
15384: key -> path to file/file_name\0accesscontrol
15385: value -> reference to hash
15386: hash contains key = value pairs
15387: where key = uniqueID:scope_end_start
15388: value = UNIX time record was last updated
15389:
15390: Used to improve speed of look-ups of access controls for each file.
15391:
15392: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15393:
15394: =item *
15395:
15396: modify_access_controls():
15397:
15398: Modifies access controls for a portfolio file
15399: Args
15400: 1. file name
15401: 2. reference to hash of required changes,
15402: 3. domain
15403: 4. username
15404: where domain,username are the domain of the portfolio owner
15405: (either a user or a course)
15406:
15407: Returns:
15408: 1. result of additions or updates ('ok' or 'error', with error message).
15409: 2. result of deletions ('ok' or 'error', with error message).
15410: 3. reference to hash of any new or updated access controls.
15411: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15412: key = integer (inbound ID)
15413: value = uniqueID
15414:
15415: =item *
15416:
15417: get_timebased_id():
15418:
15419: Attempts to get a unique timestamp-based suffix for use with items added to a
15420: course via the Course Editor (e.g., folders, composite pages,
15421: group bulletin boards).
15422:
15423: Args: (first three required; six others optional)
15424:
15425: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15426: docssequence, or name of group
15427:
15428: 2. keyid (alphanumeric): name of temporary locking key in hash,
15429: e.g., num, boardids
15430:
15431: 3. namespace: name of gdbm file used to store suffixes already assigned;
15432: file will be named nohist_namespace.db
15433:
15434: 4. cdom: domain of course; default is current course domain from %env
15435:
15436: 5. cnum: course number; default is current course number from %env
15437:
15438: 6. idtype: set to concat if an additional digit is to be appended to the
15439: unix timestamp to form the suffix, if the plain timestamp is already
15440: in use. Default is to not do this, but simply increment the unix
15441: timestamp by 1 until a unique key is obtained.
15442:
15443: 7. who: holder of locking key; defaults to user:domain for user.
15444:
15445: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
15446: retrying); default is 3.
15447:
15448: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
15449:
15450: Returns:
15451:
15452: 1. suffix obtained (numeric)
15453:
15454: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15455:
15456: 3. error: contains (localized) error message if an error occurred.
15457:
15458:
15459: =back
15460:
15461: =head2 HTTP Helper Routines
15462:
15463: =over 4
15464:
15465: =item *
15466:
15467: escape() : unpack non-word characters into CGI-compatible hex codes
15468:
15469: =item *
15470:
15471: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15472:
15473: =back
15474:
15475: =head1 PRIVATE SUBROUTINES
15476:
15477: =head2 Underlying communication routines (Shouldn't call)
15478:
15479: =over 4
15480:
15481: =item *
15482:
15483: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15484:
15485: =item *
15486:
15487: reply() : uses subreply to send a message to remote machine, logs all failures
15488:
15489: =item *
15490:
15491: critical() : passes a critical message to another server; if cannot
15492: get through then place message in connection buffer directory and
15493: returns con_delayed, if incapable of saving message, returns
15494: con_failed
15495:
15496: =item *
15497:
15498: reconlonc() : tries to reconnect lonc client processes.
15499:
15500: =back
15501:
15502: =head2 Resource Access Logging
15503:
15504: =over 4
15505:
15506: =item *
15507:
15508: flushcourselogs() : flush (save) buffer logs and access logs
15509:
15510: =item *
15511:
15512: courselog($what) : save message for course in hash
15513:
15514: =item *
15515:
15516: courseacclog($what) : save message for course using &courselog(). Perform
15517: special processing for specific resource types (problems, exams, quizzes, etc).
15518:
15519: =item *
15520:
15521: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15522: as a PerlChildExitHandler
15523:
15524: =back
15525:
15526: =head2 Other
15527:
15528: =over 4
15529:
15530: =item *
15531:
15532: symblist($mapname,%newhash) : update symbolic storage links
15533:
15534: =back
15535:
15536: =cut
15537:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>