1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.1353 2017/08/27 13:48:52 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: sub remove_stale_resfile {
3175: my ($url) = @_;
3176: my $stale;
3177: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3178: my $audom = $1;
3179: my $auname = $2;
3180: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
3181: my $homeserver = &homeserver($auname,$audom);
3182: unless (($homeserver eq 'no_host') ||
3183: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3184: my $fname = &filelocation('',$url);
3185: if (-e $fname) {
3186: my $protocol = $protocol{$homeserver};
3187: $protocol = 'http' if ($protocol ne 'https');
3188: my $hostname = &hostname($homeserver);
3189: if ($hostname) {
3190: my $uri = &declutter($url);
3191: my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
3192: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
3193: if ($response->is_success()) {
3194: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3195: my $locmodtime = (stat($fname))[9];
3196: if ($locmodtime < $remmodtime) {
3197: unlink($fname);
3198: if ($uri!~/\.meta$/) {
3199: unlink($fname.'.meta');
3200: }
3201: &reply("unsub:$fname",$homeserver);
3202: $stale = 1;
3203: }
3204: }
3205: }
3206: }
3207: }
3208: }
3209: }
3210: return $stale;
3211: }
3212:
3213: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3214:
3215: sub allowuploaded {
3216: my ($srcurl,$url)=@_;
3217: $url=&clutter(&declutter($url));
3218: my $dir=$url;
3219: $dir=~s/\/[^\/]+$//;
3220: my %httpref=();
3221: my $httpurl=&hreflocation('',$url);
3222: $httpref{'httpref.'.$httpurl}=$srcurl;
3223: &Apache::lonnet::appenv(\%httpref);
3224: }
3225:
3226: #
3227: # Determine if the current user should be able to edit a particular resource,
3228: # when viewing in course context.
3229: # (a) When viewing resource used to determine if "Edit" item is included in
3230: # Functions.
3231: # (b) When displaying folder contents in course editor, used to determine if
3232: # "Edit" link will be displayed alongside resource.
3233: #
3234: # input: six args -- filename (decluttered), course number, course domain,
3235: # url, symb (if registered) and group (if this is a group
3236: # item -- e.g., bulletin board, group page etc.).
3237: # output: array of five scalars --
3238: # $cfile -- url for file editing if editable on current server
3239: # $home -- homeserver of resource (i.e., for author if published,
3240: # or course if uploaded.).
3241: # $switchserver -- 1 if server switch will be needed.
3242: # $forceedit -- 1 if icon/link should be to go to edit mode
3243: # $forceview -- 1 if icon/link should be to go to view mode
3244: #
3245:
3246: sub can_edit_resource {
3247: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3248: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3249: #
3250: # For aboutme pages user can only edit his/her own.
3251: #
3252: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
3253: my ($sdom,$sname) = ($1,$2);
3254: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3255: $home = $env{'user.home'};
3256: $cfile = $resurl;
3257: if ($env{'form.forceedit'}) {
3258: $forceview = 1;
3259: } else {
3260: $forceedit = 1;
3261: }
3262: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3263: } else {
3264: return;
3265: }
3266: }
3267:
3268: if ($env{'request.course.id'}) {
3269: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3270: if ($group ne '') {
3271: # if this is a group homepage or group bulletin board, check group privs
3272: my $allowed = 0;
3273: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3274: if ((&allowed('mdg',$env{'request.course.id'}.
3275: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3276: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3277: $allowed = 1;
3278: }
3279: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3280: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3281: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3282: $allowed = 1;
3283: }
3284: }
3285: if ($allowed) {
3286: $home=&homeserver($cnum,$cdom);
3287: if ($env{'form.forceedit'}) {
3288: $forceview = 1;
3289: } else {
3290: $forceedit = 1;
3291: }
3292: $cfile = $resurl;
3293: } else {
3294: return;
3295: }
3296: } else {
3297: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3298: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3299: return;
3300: }
3301: } elsif (!$crsedit) {
3302: #
3303: # No edit allowed where CC has switched to student role.
3304: #
3305: return;
3306: }
3307: }
3308: }
3309:
3310: if ($file ne '') {
3311: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
3312: if (&is_course_upload($file,$cnum,$cdom)) {
3313: $uploaded = 1;
3314: $incourse = 1;
3315: if ($file =~/\.(htm|html|css|js|txt)$/) {
3316: $cfile = &hreflocation('',$file);
3317: if ($env{'form.forceedit'}) {
3318: $forceview = 1;
3319: } else {
3320: $forceedit = 1;
3321: }
3322: }
3323: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3324: $incourse = 1;
3325: if ($env{'form.forceedit'}) {
3326: $forceview = 1;
3327: } else {
3328: $forceedit = 1;
3329: }
3330: $cfile = $resurl;
3331: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3332: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3333: $incourse = 1;
3334: if ($env{'form.forceedit'}) {
3335: $forceview = 1;
3336: } else {
3337: $forceedit = 1;
3338: }
3339: $cfile = $resurl;
3340: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
3341: $incourse = 1;
3342: $cfile = $resurl.'/smpedit';
3343: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
3344: $incourse = 1;
3345: if ($env{'form.forceedit'}) {
3346: $forceview = 1;
3347: } else {
3348: $forceedit = 1;
3349: }
3350: $cfile = $resurl;
3351: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
3352: $incourse = 1;
3353: if ($env{'form.forceedit'}) {
3354: $forceview = 1;
3355: } else {
3356: $forceedit = 1;
3357: }
3358: $cfile = $resurl;
3359: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3360: $incourse = 1;
3361: if ($env{'form.forceedit'}) {
3362: $forceview = 1;
3363: } else {
3364: $forceedit = 1;
3365: }
3366: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
3367: }
3368: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3369: my $template = '/res/lib/templates/simpleproblem.problem';
3370: if (&is_on_map($template)) {
3371: $incourse = 1;
3372: $forceview = 1;
3373: $cfile = $template;
3374: }
3375: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3376: $incourse = 1;
3377: if ($env{'form.forceedit'}) {
3378: $forceview = 1;
3379: } else {
3380: $forceedit = 1;
3381: }
3382: $cfile = $resurl;
3383: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3384: $incourse = 1;
3385: if ($env{'form.forceedit'}) {
3386: $forceview = 1;
3387: } else {
3388: $forceedit = 1;
3389: }
3390: $cfile = $resurl;
3391: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3392: $incourse = 1;
3393: $forceview = 1;
3394: if ($symb) {
3395: my ($map,$id,$res)=&decode_symb($symb);
3396: $env{'request.symb'} = $symb;
3397: $cfile = &clutter($res);
3398: } else {
3399: $cfile = $env{'form.suppurl'};
3400: my $escfile = &unescape($cfile);
3401: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
3402: $cfile = '/adm/wrapper'.$escfile;
3403: } else {
3404: $escfile =~ s{^http://}{};
3405: $cfile = &escape("/adm/wrapper/ext/$escfile");
3406: }
3407: }
3408: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3409: if ($env{'form.forceedit'}) {
3410: $forceview = 1;
3411: } else {
3412: $forceedit = 1;
3413: }
3414: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
3415: }
3416: }
3417: if ($uploaded || $incourse) {
3418: $home=&homeserver($cnum,$cdom);
3419: } elsif ($file !~ m{/$}) {
3420: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3421: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3422: # Check that the user has permission to edit this resource
3423: my $setpriv = 1;
3424: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3425: if (defined($cfudom)) {
3426: $home=&homeserver($cfuname,$cfudom);
3427: $cfile=$file;
3428: }
3429: }
3430: if (($cfile ne '') && (!$incourse || $uploaded) &&
3431: (($home ne '') && ($home ne 'no_host'))) {
3432: my @ids=¤t_machine_ids();
3433: unless (grep(/^\Q$home\E$/,@ids)) {
3434: $switchserver=1;
3435: }
3436: }
3437: }
3438: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3439: }
3440:
3441: sub is_course_upload {
3442: my ($file,$cnum,$cdom) = @_;
3443: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3444: $uploadpath =~ s{^\/}{};
3445: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3446: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3447: return 1;
3448: }
3449: return;
3450: }
3451:
3452: sub in_course {
3453: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3454: if ($hideprivileged) {
3455: my $skipuser;
3456: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3457: my @possdoms = ($cdom);
3458: if ($coursehash{'checkforpriv'}) {
3459: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3460: }
3461: if (&privileged($uname,$udom,\@possdoms)) {
3462: $skipuser = 1;
3463: if ($coursehash{'nothideprivileged'}) {
3464: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3465: my $user;
3466: if ($item =~ /:/) {
3467: $user = $item;
3468: } else {
3469: $user = join(':',split(/[\@]/,$item));
3470: }
3471: if ($user eq $uname.':'.$udom) {
3472: undef($skipuser);
3473: last;
3474: }
3475: }
3476: }
3477: if ($skipuser) {
3478: return 0;
3479: }
3480: }
3481: }
3482: $type ||= 'any';
3483: if (!defined($cdom) || !defined($cnum)) {
3484: my $cid = $env{'request.course.id'};
3485: $cdom = $env{'course.'.$cid.'.domain'};
3486: $cnum = $env{'course.'.$cid.'.num'};
3487: }
3488: my $typesref;
3489: if (($type eq 'any') || ($type eq 'all')) {
3490: $typesref = ['active','previous','future'];
3491: } elsif ($type eq 'previous' || $type eq 'future') {
3492: $typesref = [$type];
3493: }
3494: my %roles = &get_my_roles($uname,$udom,'userroles',
3495: $typesref,undef,[$cdom]);
3496: my ($tmp) = keys(%roles);
3497: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3498: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3499: if (@course_roles > 0) {
3500: return 1;
3501: }
3502: return 0;
3503: }
3504:
3505: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
3506: # input: action, courseID, current domain, intended
3507: # path to file, source of file, instruction to parse file for objects,
3508: # ref to hash for embedded objects,
3509: # ref to hash for codebase of java objects.
3510: # reference to scalar to accommodate mime type determined
3511: # from File::MMagic if $parser = parse.
3512: #
3513: # output: url to file (if action was uploaddoc),
3514: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
3515: #
3516: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3517: # course.
3518: #
3519: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3520: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3521: # course's home server.
3522: #
3523: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3524: # be copied from $source (current location) to
3525: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3526: # and will then be copied to
3527: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3528: # course's home server.
3529: #
3530: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3531: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
3532: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3533: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3534: # in course's home server.
3535: #
3536:
3537: sub process_coursefile {
3538: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3539: $mimetype)=@_;
3540: my $fetchresult;
3541: my $home=&homeserver($docuname,$docudom);
3542: if ($action eq 'propagate') {
3543: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3544: $home);
3545: } else {
3546: my $fpath = '';
3547: my $fname = $file;
3548: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3549: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3550: my $filepath = &build_filepath($fpath);
3551: if ($action eq 'copy') {
3552: if ($source eq '') {
3553: $fetchresult = 'no source file';
3554: return $fetchresult;
3555: } else {
3556: my $destination = $filepath.'/'.$fname;
3557: rename($source,$destination);
3558: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3559: $home);
3560: }
3561: } elsif ($action eq 'uploaddoc') {
3562: open(my $fh,'>'.$filepath.'/'.$fname);
3563: print $fh $env{'form.'.$source};
3564: close($fh);
3565: if ($parser eq 'parse') {
3566: my $mm = new File::MMagic;
3567: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3568: if ($type eq 'text/html') {
3569: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3570: unless ($parse_result eq 'ok') {
3571: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3572: }
3573: }
3574: if (ref($mimetype)) {
3575: $$mimetype = $type;
3576: }
3577: }
3578: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3579: $home);
3580: if ($fetchresult eq 'ok') {
3581: return '/uploaded/'.$fpath.'/'.$fname;
3582: } else {
3583: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3584: ' to host '.$home.': '.$fetchresult);
3585: return '/adm/notfound.html';
3586: }
3587: }
3588: }
3589: unless ( $fetchresult eq 'ok') {
3590: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3591: ' to host '.$home.': '.$fetchresult);
3592: }
3593: return $fetchresult;
3594: }
3595:
3596: sub build_filepath {
3597: my ($fpath) = @_;
3598: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3599: unless ($fpath eq '') {
3600: my @parts=split('/',$fpath);
3601: foreach my $part (@parts) {
3602: $filepath.= '/'.$part;
3603: if ((-e $filepath)!=1) {
3604: mkdir($filepath,0777);
3605: }
3606: }
3607: }
3608: return $filepath;
3609: }
3610:
3611: sub store_edited_file {
3612: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
3613: my $file = $primary_url;
3614: $file =~ s#^/uploaded/$docudom/$docuname/##;
3615: my $fpath = '';
3616: my $fname = $file;
3617: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3618: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3619: my $filepath = &build_filepath($fpath);
3620: open(my $fh,'>'.$filepath.'/'.$fname);
3621: print $fh $content;
3622: close($fh);
3623: my $home=&homeserver($docuname,$docudom);
3624: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3625: $home);
3626: if ($$fetchresult eq 'ok') {
3627: return '/uploaded/'.$fpath.'/'.$fname;
3628: } else {
3629: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3630: ' to host '.$home.': '.$$fetchresult);
3631: return '/adm/notfound.html';
3632: }
3633: }
3634:
3635: sub clean_filename {
3636: my ($fname,$args)=@_;
3637: # Replace Windows backslashes by forward slashes
3638: $fname=~s/\\/\//g;
3639: if (!$args->{'keep_path'}) {
3640: # Get rid of everything but the actual filename
3641: $fname=~s/^.*\/([^\/]+)$/$1/;
3642: }
3643: # Replace spaces by underscores
3644: $fname=~s/\s+/\_/g;
3645: # Replace all other weird characters by nothing
3646: $fname=~s{[^/\w\.\-]}{}g;
3647: # Replace all .\d. sequences with _\d. so they no longer look like version
3648: # numbers
3649: $fname=~s/\.(\d+)(?=\.)/_$1/g;
3650: return $fname;
3651: }
3652: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3653: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3654: # image with the same aspect ratio as the original, but with dimensions which do
3655: # not exceed $resizewidth and $resizeheight.
3656:
3657: sub resizeImage {
3658: my ($img_path,$resizewidth,$resizeheight) = @_;
3659: my $ima = Image::Magick->new;
3660: my $resized;
3661: if (-e $img_path) {
3662: $ima->Read($img_path);
3663: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3664: my $width = $ima->Get('width');
3665: my $height = $ima->Get('height');
3666: if ($width > $resizewidth) {
3667: my $factor = $width/$resizewidth;
3668: my $newheight = $height/$factor;
3669: $ima->Scale(width=>$resizewidth,height=>$newheight);
3670: $resized = 1;
3671: }
3672: }
3673: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3674: my $width = $ima->Get('width');
3675: my $height = $ima->Get('height');
3676: if ($height > $resizeheight) {
3677: my $factor = $height/$resizeheight;
3678: my $newwidth = $width/$factor;
3679: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3680: $resized = 1;
3681: }
3682: }
3683: if ($resized) {
3684: $ima->Write($img_path);
3685: }
3686: }
3687: return;
3688: }
3689:
3690: # --------------- Take an uploaded file and put it into the userfiles directory
3691: # input: $formname - the contents of the file are in $env{"form.$formname"}
3692: # the desired filename is in $env{"form.$formname.filename"}
3693: # $context - possible values: coursedoc, existingfile, overwrite,
3694: # canceloverwrite, or ''.
3695: # if 'coursedoc': upload to the current course
3696: # if 'existingfile': write file to tmp/overwrites directory
3697: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3698: # $context is passed as argument to &finishuserfileupload
3699: # $subdir - directory in userfile to store the file into
3700: # $parser - instruction to parse file for objects ($parser = parse)
3701: # $allfiles - reference to hash for embedded objects
3702: # $codebase - reference to hash for codebase of java objects
3703: # $desuname - username for permanent storage of uploaded file
3704: # $dsetudom - domain for permanaent storage of uploaded file
3705: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3706: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
3707: # $resizewidth - width (pixels) to which to resize uploaded image
3708: # $resizeheight - height (pixels) to which to resize uploaded image
3709: # $mimetype - reference to scalar to accommodate mime type determined
3710: # from File::MMagic.
3711: #
3712: # output: url of file in userspace, or error: <message>
3713: # or /adm/notfound.html if failure to upload occurse
3714:
3715: sub userfileupload {
3716: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
3717: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
3718: if (!defined($subdir)) { $subdir='unknown'; }
3719: my $fname=$env{'form.'.$formname.'.filename'};
3720: $fname=&clean_filename($fname);
3721: # See if there is anything left
3722: unless ($fname) { return 'error: no uploaded file'; }
3723: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3724: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3725: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3726: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3727: my $now = time;
3728: my $filepath;
3729: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
3730: $filepath = 'tmp/helprequests/'.$now;
3731: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3732: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3733: '_'.$env{'user.domain'}.'/pending';
3734: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3735: my ($docuname,$docudom);
3736: if ($destudom =~ /^$match_domain$/) {
3737: $docudom = $destudom;
3738: } else {
3739: $docudom = $env{'user.domain'};
3740: }
3741: if ($destuname =~ /^$match_username$/) {
3742: $docuname = $destuname;
3743: } else {
3744: $docuname = $env{'user.name'};
3745: }
3746: if (exists($env{'form.group'})) {
3747: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3748: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3749: }
3750: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3751: if ($context eq 'canceloverwrite') {
3752: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3753: if (-e $tempfile) {
3754: my @info = stat($tempfile);
3755: if ($info[9] eq $env{'form.timestamp'}) {
3756: unlink($tempfile);
3757: }
3758: }
3759: return;
3760: }
3761: }
3762: # Create the directory if not present
3763: my @parts=split(/\//,$filepath);
3764: my $fullpath = $perlvar{'lonDaemons'};
3765: for (my $i=0;$i<@parts;$i++) {
3766: $fullpath .= '/'.$parts[$i];
3767: if ((-e $fullpath)!=1) {
3768: mkdir($fullpath,0777);
3769: }
3770: }
3771: open(my $fh,'>'.$fullpath.'/'.$fname);
3772: print $fh $env{'form.'.$formname};
3773: close($fh);
3774: if ($context eq 'existingfile') {
3775: my @info = stat($fullpath.'/'.$fname);
3776: return ($fullpath.'/'.$fname,$info[9]);
3777: } else {
3778: return $fullpath.'/'.$fname;
3779: }
3780: }
3781: if ($subdir eq 'scantron') {
3782: $fname = 'scantron_orig_'.$fname;
3783: } else {
3784: $fname="$subdir/$fname";
3785: }
3786: if ($context eq 'coursedoc') {
3787: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3788: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3789: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
3790: return &finishuserfileupload($docuname,$docudom,
3791: $formname,$fname,$parser,$allfiles,
3792: $codebase,$thumbwidth,$thumbheight,
3793: $resizewidth,$resizeheight,$context,$mimetype);
3794: } else {
3795: if ($env{'form.folder'}) {
3796: $fname=$env{'form.folder'}.'/'.$fname;
3797: }
3798: return &process_coursefile('uploaddoc',$docuname,$docudom,
3799: $fname,$formname,$parser,
3800: $allfiles,$codebase,$mimetype);
3801: }
3802: } elsif (defined($destuname)) {
3803: my $docuname=$destuname;
3804: my $docudom=$destudom;
3805: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3806: $parser,$allfiles,$codebase,
3807: $thumbwidth,$thumbheight,
3808: $resizewidth,$resizeheight,$context,$mimetype);
3809: } else {
3810: my $docuname=$env{'user.name'};
3811: my $docudom=$env{'user.domain'};
3812: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
3813: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3814: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3815: }
3816: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3817: $parser,$allfiles,$codebase,
3818: $thumbwidth,$thumbheight,
3819: $resizewidth,$resizeheight,$context,$mimetype);
3820: }
3821: }
3822:
3823: sub finishuserfileupload {
3824: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
3825: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
3826: my $path=$docudom.'/'.$docuname.'/';
3827: my $filepath=$perlvar{'lonDocRoot'};
3828:
3829: my ($fnamepath,$file,$fetchthumb);
3830: $file=$fname;
3831: if ($fname=~m|/|) {
3832: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3833: $path.=$fnamepath.'/';
3834: }
3835: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
3836: my $count;
3837: for ($count=4;$count<=$#parts;$count++) {
3838: $filepath.="/$parts[$count]";
3839: if ((-e $filepath)!=1) {
3840: mkdir($filepath,0777);
3841: }
3842: }
3843:
3844: # Save the file
3845: {
3846: if (!open(FH,'>'.$filepath.'/'.$file)) {
3847: &logthis('Failed to create '.$filepath.'/'.$file);
3848: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3849: return '/adm/notfound.html';
3850: }
3851: if ($context eq 'overwrite') {
3852: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
3853: my $target = $filepath.'/'.$file;
3854: if (-e $source) {
3855: my @info = stat($source);
3856: if ($info[9] eq $env{'form.timestamp'}) {
3857: unless (&File::Copy::move($source,$target)) {
3858: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3859: return "Moving from $source failed";
3860: }
3861: } else {
3862: return "Temporary file: $source had unexpected date/time for last modification";
3863: }
3864: } else {
3865: return "Temporary file: $source missing";
3866: }
3867: } elsif (!print FH ($env{'form.'.$formname})) {
3868: &logthis('Failed to write to '.$filepath.'/'.$file);
3869: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3870: return '/adm/notfound.html';
3871: }
3872: close(FH);
3873: if ($resizewidth && $resizeheight) {
3874: my $mm = new File::MMagic;
3875: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3876: if ($mime_type =~ m{^image/}) {
3877: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3878: }
3879: }
3880: }
3881: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3882: if (ref($mimetype)) {
3883: if ($$mimetype eq '') {
3884: my $mm = new File::MMagic;
3885: my $type = $mm->checktype_filename($filepath.'/'.$file);
3886: $$mimetype = $type;
3887: }
3888: }
3889: }
3890: if ($parser eq 'parse') {
3891: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
3892: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3893: $allfiles,$codebase);
3894: unless ($parse_result eq 'ok') {
3895: &logthis('Failed to parse '.$filepath.$file.
3896: ' for embedded media: '.$parse_result);
3897: }
3898: }
3899: }
3900: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3901: my $input = $filepath.'/'.$file;
3902: my $output = $filepath.'/'.'tn-'.$file;
3903: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3904: system("convert -sample $thumbsize $input $output");
3905: if (-e $filepath.'/'.'tn-'.$file) {
3906: $fetchthumb = 1;
3907: }
3908: }
3909:
3910: # Notify homeserver to grep it
3911: #
3912: my $docuhome=&homeserver($docuname,$docudom);
3913: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
3914: if ($fetchresult eq 'ok') {
3915: if ($fetchthumb) {
3916: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3917: if ($thumbresult ne 'ok') {
3918: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3919: $docuhome.': '.$thumbresult);
3920: }
3921: }
3922: #
3923: # Return the URL to it
3924: return '/uploaded/'.$path.$file;
3925: } else {
3926: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3927: ': '.$fetchresult);
3928: return '/adm/notfound.html';
3929: }
3930: }
3931:
3932: sub extract_embedded_items {
3933: my ($fullpath,$allfiles,$codebase,$content) = @_;
3934: my @state = ();
3935: my (%lastids,%related,%shockwave,%flashvars);
3936: my %javafiles = (
3937: codebase => '',
3938: code => '',
3939: archive => ''
3940: );
3941: my %mediafiles = (
3942: src => '',
3943: movie => '',
3944: );
3945: my $p;
3946: if ($content) {
3947: $p = HTML::LCParser->new($content);
3948: } else {
3949: $p = HTML::LCParser->new($fullpath);
3950: }
3951: while (my $t=$p->get_token()) {
3952: if ($t->[0] eq 'S') {
3953: my ($tagname, $attr) = ($t->[1],$t->[2]);
3954: push(@state, $tagname);
3955: if (lc($tagname) eq 'allow') {
3956: &add_filetype($allfiles,$attr->{'src'},'src');
3957: }
3958: if (lc($tagname) eq 'img') {
3959: &add_filetype($allfiles,$attr->{'src'},'src');
3960: }
3961: if (lc($tagname) eq 'a') {
3962: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3963: &add_filetype($allfiles,$attr->{'href'},'href');
3964: }
3965: }
3966: if (lc($tagname) eq 'script') {
3967: my $src;
3968: if ($attr->{'archive'} =~ /\.jar$/i) {
3969: &add_filetype($allfiles,$attr->{'archive'},'archive');
3970: } else {
3971: if ($attr->{'src'} ne '') {
3972: $src = $attr->{'src'};
3973: &add_filetype($allfiles,$src,'src');
3974: }
3975: }
3976: my $text = $p->get_trimmed_text();
3977: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3978: my @swfargs = split(/,/,$1);
3979: foreach my $item (@swfargs) {
3980: $item =~ s/["']//g;
3981: $item =~ s/^\s+//;
3982: $item =~ s/\s+$//;
3983: }
3984: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3985: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3986: push(@{$related{$swfargs[0]}},$swfargs[2]);
3987: } else {
3988: $related{$swfargs[0]} = [$swfargs[2]];
3989: }
3990: }
3991: }
3992: }
3993: if (lc($tagname) eq 'link') {
3994: if (lc($attr->{'rel'}) eq 'stylesheet') {
3995: &add_filetype($allfiles,$attr->{'href'},'href');
3996: }
3997: }
3998: if (lc($tagname) eq 'object' ||
3999: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4000: foreach my $item (keys(%javafiles)) {
4001: $javafiles{$item} = '';
4002: }
4003: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4004: $lastids{lc($tagname)} = $attr->{'id'};
4005: }
4006: }
4007: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4008: my $name = lc($attr->{'name'});
4009: foreach my $item (keys(%javafiles)) {
4010: if ($name eq $item) {
4011: $javafiles{$item} = $attr->{'value'};
4012: last;
4013: }
4014: }
4015: my $pathfrom;
4016: foreach my $item (keys(%mediafiles)) {
4017: if ($name eq $item) {
4018: $pathfrom = $attr->{'value'};
4019: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4020: &add_filetype($allfiles,$pathfrom,$name);
4021: last;
4022: }
4023: }
4024: if ($name eq 'flashvars') {
4025: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4026: }
4027: if ($pathfrom ne '') {
4028: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4029: $pathfrom);
4030: }
4031: }
4032: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4033: foreach my $item (keys(%javafiles)) {
4034: if ($attr->{$item}) {
4035: $javafiles{$item} = $attr->{$item};
4036: last;
4037: }
4038: }
4039: foreach my $item (keys(%mediafiles)) {
4040: if ($attr->{$item}) {
4041: &add_filetype($allfiles,$attr->{$item},$item);
4042: last;
4043: }
4044: }
4045: if (lc($tagname) eq 'embed') {
4046: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4047: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4048: $attr->{'src'});
4049: }
4050: }
4051: }
4052: if (lc($tagname) eq 'iframe') {
4053: my $src = $attr->{'src'} ;
4054: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4055: &add_filetype($allfiles,$src,'src');
4056: } elsif ($src =~ m{^/}) {
4057: if ($env{'request.course.id'}) {
4058: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4059: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4060: my $url = &hreflocation('',$fullpath);
4061: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4062: my $relpath = $1;
4063: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4064: &add_filetype($allfiles,$1,'src');
4065: }
4066: }
4067: }
4068: }
4069: }
4070: if ($t->[4] =~ m{/>$}) {
4071: pop(@state);
4072: }
4073: } elsif ($t->[0] eq 'E') {
4074: my ($tagname) = ($t->[1]);
4075: if ($javafiles{'codebase'} ne '') {
4076: $javafiles{'codebase'} .= '/';
4077: }
4078: if (lc($tagname) eq 'applet' ||
4079: lc($tagname) eq 'object' ||
4080: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4081: ) {
4082: foreach my $item (keys(%javafiles)) {
4083: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4084: my $file=$javafiles{'codebase'}.$javafiles{$item};
4085: &add_filetype($allfiles,$file,$item);
4086: }
4087: }
4088: }
4089: pop @state;
4090: }
4091: }
4092: foreach my $id (sort(keys(%flashvars))) {
4093: if ($shockwave{$id} ne '') {
4094: my @pairs = split(/\&/,$flashvars{$id});
4095: foreach my $pair (@pairs) {
4096: my ($key,$value) = split(/\=/,$pair);
4097: if ($key eq 'thumb') {
4098: &add_filetype($allfiles,$value,$key);
4099: } elsif ($key eq 'content') {
4100: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4101: my ($ext) = ($value =~ /\.([^.]+)$/);
4102: if ($ext ne '') {
4103: &add_filetype($allfiles,$path.$value,$ext);
4104: }
4105: }
4106: }
4107: }
4108: }
4109: return 'ok';
4110: }
4111:
4112: sub add_filetype {
4113: my ($allfiles,$file,$type)=@_;
4114: if (exists($allfiles->{$file})) {
4115: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4116: push(@{$allfiles->{$file}}, &escape($type));
4117: }
4118: } else {
4119: @{$allfiles->{$file}} = (&escape($type));
4120: }
4121: }
4122:
4123: sub embedded_dependency {
4124: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4125: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4126: if (($identifier ne '') &&
4127: (ref($related->{$identifier}) eq 'ARRAY') &&
4128: ($pathfrom ne '')) {
4129: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4130: foreach my $dep (@{$related->{$identifier}}) {
4131: &add_filetype($allfiles,$path.$dep,'object');
4132: }
4133: }
4134: }
4135: return;
4136: }
4137:
4138: sub removeuploadedurl {
4139: my ($url)=@_;
4140: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
4141: return &removeuserfile($uname,$udom,$fname);
4142: }
4143:
4144: sub removeuserfile {
4145: my ($docuname,$docudom,$fname)=@_;
4146: my $home=&homeserver($docuname,$docudom);
4147: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
4148: if ($result eq 'ok') {
4149: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4150: my $metafile = $fname.'.meta';
4151: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
4152: my $url = "/uploaded/$docudom/$docuname/$fname";
4153: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
4154: my $sqlresult =
4155: &update_portfolio_table($docuname,$docudom,$file,
4156: 'portfolio_metadata',$group,
4157: 'delete');
4158: }
4159: }
4160: return $result;
4161: }
4162:
4163: sub mkdiruserfile {
4164: my ($docuname,$docudom,$dir)=@_;
4165: my $home=&homeserver($docuname,$docudom);
4166: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4167: }
4168:
4169: sub renameuserfile {
4170: my ($docuname,$docudom,$old,$new)=@_;
4171: my $home=&homeserver($docuname,$docudom);
4172: my $result = &reply("renameuserfile:$docudom:$docuname:".
4173: &escape("$old").':'.&escape("$new"),$home);
4174: if ($result eq 'ok') {
4175: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4176: my $oldmeta = $old.'.meta';
4177: my $newmeta = $new.'.meta';
4178: my $metaresult =
4179: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
4180: my $url = "/uploaded/$docudom/$docuname/$old";
4181: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
4182: my $sqlresult =
4183: &update_portfolio_table($docuname,$docudom,$file,
4184: 'portfolio_metadata',$group,
4185: 'delete');
4186: }
4187: }
4188: return $result;
4189: }
4190:
4191: # ------------------------------------------------------------------------- Log
4192:
4193: sub log {
4194: my ($dom,$nam,$hom,$what)=@_;
4195: return critical("log:$dom:$nam:$what",$hom);
4196: }
4197:
4198: # ------------------------------------------------------------------ Course Log
4199: #
4200: # This routine flushes several buffers of non-mission-critical nature
4201: #
4202:
4203: sub flushcourselogs {
4204: &logthis('Flushing log buffers');
4205: #
4206: # course logs
4207: # This is a log of all transactions in a course, which can be used
4208: # for data mining purposes
4209: #
4210: # It also collects the courseid database, which lists last transaction
4211: # times and course titles for all courseids
4212: #
4213: my %courseidbuffer=();
4214: foreach my $crsid (keys(%courselogs)) {
4215: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
4216: &escape($courselogs{$crsid}),
4217: $coursehombuf{$crsid}) eq 'ok') {
4218: delete $courselogs{$crsid};
4219: } else {
4220: &logthis('Failed to flush log buffer for '.$crsid);
4221: if (length($courselogs{$crsid})>40000) {
4222: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
4223: " exceeded maximum size, deleting.</font>");
4224: delete $courselogs{$crsid};
4225: }
4226: }
4227: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
4228: 'description' => $coursedescrbuf{$crsid},
4229: 'inst_code' => $courseinstcodebuf{$crsid},
4230: 'type' => $coursetypebuf{$crsid},
4231: 'owner' => $courseownerbuf{$crsid},
4232: };
4233: }
4234: #
4235: # Write course id database (reverse lookup) to homeserver of courses
4236: # Is used in pickcourse
4237: #
4238: foreach my $crs_home (keys(%courseidbuffer)) {
4239: my $response = &courseidput(&host_domain($crs_home),
4240: $courseidbuffer{$crs_home},
4241: $crs_home,'timeonly');
4242: }
4243: #
4244: # File accesses
4245: # Writes to the dynamic metadata of resources to get hit counts, etc.
4246: #
4247: foreach my $entry (keys(%accesshash)) {
4248: if ($entry =~ /___count$/) {
4249: my ($dom,$name);
4250: ($dom,$name,undef)=
4251: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
4252: if (! defined($dom) || $dom eq '' ||
4253: ! defined($name) || $name eq '') {
4254: my $cid = $env{'request.course.id'};
4255: $dom = $env{'request.'.$cid.'.domain'};
4256: $name = $env{'request.'.$cid.'.num'};
4257: }
4258: my $value = $accesshash{$entry};
4259: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4260: my %temphash=($url => $value);
4261: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4262: if ($result eq 'ok') {
4263: delete $accesshash{$entry};
4264: }
4265: } else {
4266: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
4267: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
4268: my %temphash=($entry => $accesshash{$entry});
4269: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4270: delete $accesshash{$entry};
4271: }
4272: }
4273: }
4274: #
4275: # Roles
4276: # Reverse lookup of user roles for course faculty/staff and co-authorship
4277: #
4278: foreach my $entry (keys(%userrolehash)) {
4279: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
4280: split(/\:/,$entry);
4281: if (&Apache::lonnet::put('nohist_userroles',
4282: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
4283: $rudom,$runame) eq 'ok') {
4284: delete $userrolehash{$entry};
4285: }
4286: }
4287: #
4288: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
4289: #
4290: my %domrolebuffer = ();
4291: foreach my $entry (keys(%domainrolehash)) {
4292: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
4293: if ($domrolebuffer{$rudom}) {
4294: $domrolebuffer{$rudom}.='&'.&escape($entry).
4295: '='.&escape($domainrolehash{$entry});
4296: } else {
4297: $domrolebuffer{$rudom}.=&escape($entry).
4298: '='.&escape($domainrolehash{$entry});
4299: }
4300: delete $domainrolehash{$entry};
4301: }
4302: foreach my $dom (keys(%domrolebuffer)) {
4303: my %servers;
4304: if (defined(&domain($dom,'primary'))) {
4305: my $primary=&domain($dom,'primary');
4306: my $hostname=&hostname($primary);
4307: $servers{$primary} = $hostname;
4308: } else {
4309: %servers = &get_servers($dom,'library');
4310: }
4311: foreach my $tryserver (keys(%servers)) {
4312: if (&reply('domroleput:'.$dom.':'.
4313: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4314: last;
4315: } else {
4316: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4317: }
4318: }
4319: }
4320: $dumpcount++;
4321: }
4322:
4323: sub courselog {
4324: my $what=shift;
4325: $what=time.':'.$what;
4326: unless ($env{'request.course.id'}) { return ''; }
4327: $coursedombuf{$env{'request.course.id'}}=
4328: $env{'course.'.$env{'request.course.id'}.'.domain'};
4329: $coursenumbuf{$env{'request.course.id'}}=
4330: $env{'course.'.$env{'request.course.id'}.'.num'};
4331: $coursehombuf{$env{'request.course.id'}}=
4332: $env{'course.'.$env{'request.course.id'}.'.home'};
4333: $coursedescrbuf{$env{'request.course.id'}}=
4334: $env{'course.'.$env{'request.course.id'}.'.description'};
4335: $courseinstcodebuf{$env{'request.course.id'}}=
4336: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4337: $courseownerbuf{$env{'request.course.id'}}=
4338: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
4339: $coursetypebuf{$env{'request.course.id'}}=
4340: $env{'course.'.$env{'request.course.id'}.'.type'};
4341: if (defined $courselogs{$env{'request.course.id'}}) {
4342: $courselogs{$env{'request.course.id'}}.='&'.$what;
4343: } else {
4344: $courselogs{$env{'request.course.id'}}.=$what;
4345: }
4346: if (length($courselogs{$env{'request.course.id'}})>4048) {
4347: &flushcourselogs();
4348: }
4349: }
4350:
4351: sub courseacclog {
4352: my $fnsymb=shift;
4353: unless ($env{'request.course.id'}) { return ''; }
4354: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
4355: if ($fnsymb=~/$LONCAPA::assess_re/) {
4356: $what.=':POST';
4357: # FIXME: Probably ought to escape things....
4358: foreach my $key (keys(%env)) {
4359: if ($key=~/^form\.(.*)/) {
4360: my $formitem = $1;
4361: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4362: $what.=':'.$formitem.'='.$env{$key};
4363: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
4364: $what.=':'.$formitem.'='.$env{$key};
4365: }
4366: }
4367: }
4368: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4369: # FIXME: We should not be depending on a form parameter that someone
4370: # editing lonsearchcat.pm might change in the future.
4371: if ($env{'form.phase'} eq 'course_search') {
4372: $what.= ':POST';
4373: # FIXME: Probably ought to escape things....
4374: foreach my $element ('courseexp','crsfulltext','crsrelated',
4375: 'crsdiscuss') {
4376: $what.=':'.$element.'='.$env{'form.'.$element};
4377: }
4378: }
4379: }
4380: &courselog($what);
4381: }
4382:
4383: sub countacc {
4384: my $url=&declutter(shift);
4385: return if (! defined($url) || $url eq '');
4386: unless ($env{'request.course.id'}) { return ''; }
4387: #
4388: # Mark that this url was used in this course
4389: #
4390: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
4391: #
4392: # Increase the access count for this resource in this child process
4393: #
4394: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
4395: $accesshash{$key}++;
4396: }
4397:
4398: sub linklog {
4399: my ($from,$to)=@_;
4400: $from=&declutter($from);
4401: $to=&declutter($to);
4402: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4403: $accesshash{$to.'___'.$from.'___goto'}=1;
4404: }
4405:
4406: sub statslog {
4407: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4408: if ($users<2) { return; }
4409: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4410: 'course' => $env{'request.course.id'},
4411: 'sections' => '"all"',
4412: 'num_students' => $users,
4413: 'part' => $part,
4414: 'symb' => $symb,
4415: 'mean_tries' => $av_attempts,
4416: 'deg_of_diff' => $degdiff});
4417: foreach my $key (keys(%dynstore)) {
4418: $accesshash{$key}=$dynstore{$key};
4419: }
4420: }
4421:
4422: sub userrolelog {
4423: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
4424: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
4425: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4426: $userrolehash
4427: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4428: =$tend.':'.$tstart;
4429: }
4430: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
4431: $userrolehash
4432: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4433: =$tend.':'.$tstart;
4434: }
4435: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
4436: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4437: $domainrolehash
4438: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4439: = $tend.':'.$tstart;
4440: }
4441: }
4442:
4443: sub courserolelog {
4444: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
4445: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4446: my $cdom = $1;
4447: my $cnum = $2;
4448: my $sec = $3;
4449: my $namespace = 'rolelog';
4450: my %storehash = (
4451: role => $trole,
4452: start => $tstart,
4453: end => $tend,
4454: selfenroll => $selfenroll,
4455: context => $context,
4456: );
4457: if ($trole eq 'gr') {
4458: $namespace = 'groupslog';
4459: $storehash{'group'} = $sec;
4460: } else {
4461: $storehash{'section'} = $sec;
4462: }
4463: &write_log('course',$namespace,\%storehash,$delflag,$username,
4464: $domain,$cnum,$cdom);
4465: if (($trole ne 'st') || ($sec ne '')) {
4466: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
4467: }
4468: }
4469: return;
4470: }
4471:
4472: sub domainrolelog {
4473: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4474: if ($area =~ m{^/($match_domain)/$}) {
4475: my $cdom = $1;
4476: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4477: my $namespace = 'rolelog';
4478: my %storehash = (
4479: role => $trole,
4480: start => $tstart,
4481: end => $tend,
4482: context => $context,
4483: );
4484: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4485: $domain,$domconfiguser,$cdom);
4486: }
4487: return;
4488:
4489: }
4490:
4491: sub coauthorrolelog {
4492: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4493: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4494: my $audom = $1;
4495: my $auname = $2;
4496: my $namespace = 'rolelog';
4497: my %storehash = (
4498: role => $trole,
4499: start => $tstart,
4500: end => $tend,
4501: context => $context,
4502: );
4503: &write_log('author',$namespace,\%storehash,$delflag,$username,
4504: $domain,$auname,$audom);
4505: }
4506: return;
4507: }
4508:
4509: sub get_course_adv_roles {
4510: my ($cid,$codes) = @_;
4511: $cid=$env{'request.course.id'} unless (defined($cid));
4512: my %coursehash=&coursedescription($cid);
4513: my $crstype = &Apache::loncommon::course_type($cid);
4514: my %nothide=();
4515: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4516: if ($user !~ /:/) {
4517: $nothide{join(':',split(/[\@]/,$user))}=1;
4518: } else {
4519: $nothide{$user}=1;
4520: }
4521: }
4522: my @possdoms = ($coursehash{'domain'});
4523: if ($coursehash{'checkforpriv'}) {
4524: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4525: }
4526: my %returnhash=();
4527: my %dumphash=
4528: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4529: my $now=time;
4530: my %privileged;
4531: foreach my $entry (keys(%dumphash)) {
4532: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4533: if (($tstart) && ($tstart<0)) { next; }
4534: if (($tend) && ($tend<$now)) { next; }
4535: if (($tstart) && ($now<$tstart)) { next; }
4536: my ($role,$username,$domain,$section)=split(/\:/,$entry);
4537: if ($username eq '' || $domain eq '') { next; }
4538: if ((&privileged($username,$domain,\@possdoms)) &&
4539: (!$nothide{$username.':'.$domain})) { next; }
4540: if ($role eq 'cr') { next; }
4541: if ($codes) {
4542: if ($section) { $role .= ':'.$section; }
4543: if ($returnhash{$role}) {
4544: $returnhash{$role}.=','.$username.':'.$domain;
4545: } else {
4546: $returnhash{$role}=$username.':'.$domain;
4547: }
4548: } else {
4549: my $key=&plaintext($role,$crstype);
4550: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
4551: if ($returnhash{$key}) {
4552: $returnhash{$key}.=','.$username.':'.$domain;
4553: } else {
4554: $returnhash{$key}=$username.':'.$domain;
4555: }
4556: }
4557: }
4558: return %returnhash;
4559: }
4560:
4561: sub get_my_roles {
4562: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
4563: unless (defined($uname)) { $uname=$env{'user.name'}; }
4564: unless (defined($udom)) { $udom=$env{'user.domain'}; }
4565: my (%dumphash,%nothide);
4566: if ($context eq 'userroles') {
4567: %dumphash = &dump('roles',$udom,$uname);
4568: } else {
4569: %dumphash = &dump('nohist_userroles',$udom,$uname);
4570: if ($hidepriv) {
4571: my %coursehash=&coursedescription($udom.'_'.$uname);
4572: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4573: if ($user !~ /:/) {
4574: $nothide{join(':',split(/[\@]/,$user))} = 1;
4575: } else {
4576: $nothide{$user} = 1;
4577: }
4578: }
4579: }
4580: }
4581: my %returnhash=();
4582: my $now=time;
4583: my %privileged;
4584: foreach my $entry (keys(%dumphash)) {
4585: my ($role,$tend,$tstart);
4586: if ($context eq 'userroles') {
4587: next if ($entry =~ /^rolesdef/);
4588: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4589: } else {
4590: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4591: }
4592: if (($tstart) && ($tstart<0)) { next; }
4593: my $status = 'active';
4594: if (($tend) && ($tend<=$now)) {
4595: $status = 'previous';
4596: }
4597: if (($tstart) && ($now<$tstart)) {
4598: $status = 'future';
4599: }
4600: if (ref($types) eq 'ARRAY') {
4601: if (!grep(/^\Q$status\E$/,@{$types})) {
4602: next;
4603: }
4604: } else {
4605: if ($status ne 'active') {
4606: next;
4607: }
4608: }
4609: my ($rolecode,$username,$domain,$section,$area);
4610: if ($context eq 'userroles') {
4611: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
4612: (undef,$domain,$username,$section) = split(/\//,$area);
4613: } else {
4614: ($role,$username,$domain,$section) = split(/\:/,$entry);
4615: }
4616: if (ref($roledoms) eq 'ARRAY') {
4617: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4618: next;
4619: }
4620: }
4621: if (ref($roles) eq 'ARRAY') {
4622: if (!grep(/^\Q$role\E$/,@{$roles})) {
4623: if ($role =~ /^cr\//) {
4624: if (!grep(/^cr$/,@{$roles})) {
4625: next;
4626: }
4627: } elsif ($role =~ /^gr\//) {
4628: if (!grep(/^gr$/,@{$roles})) {
4629: next;
4630: }
4631: } else {
4632: next;
4633: }
4634: }
4635: }
4636: if ($hidepriv) {
4637: my @privroles = ('dc','su');
4638: if ($context eq 'userroles') {
4639: next if (grep(/^\Q$role\E$/,@privroles));
4640: } else {
4641: my $possdoms = [$domain];
4642: if (ref($roledoms) eq 'ARRAY') {
4643: push(@{$possdoms},@{$roledoms});
4644: }
4645: if (&privileged($username,$domain,$possdoms,\@privroles)) {
4646: if (!$nothide{$username.':'.$domain}) {
4647: next;
4648: }
4649: }
4650: }
4651: }
4652: if ($withsec) {
4653: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4654: $tstart.':'.$tend;
4655: } else {
4656: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4657: }
4658: }
4659: return %returnhash;
4660: }
4661:
4662: sub get_all_adhocroles {
4663: my ($dom) = @_;
4664: my @roles_by_num = ();
4665: my %domdefaults = &get_domain_defaults($dom);
4666: my (%description,%access_in_dom,%access_info);
4667: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
4668: my $count = 0;
4669: my %domcurrent = %{$domdefaults{'adhocroles'}};
4670: my %ordered;
4671: foreach my $role (sort(keys(%domcurrent))) {
4672: my ($order,$desc,$access_in_dom);
4673: if (ref($domcurrent{$role}) eq 'HASH') {
4674: $order = $domcurrent{$role}{'order'};
4675: $desc = $domcurrent{$role}{'desc'};
4676: $access_in_dom{$role} = $domcurrent{$role}{'access'};
4677: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
4678: }
4679: if ($order eq '') {
4680: $order = $count;
4681: }
4682: $ordered{$order} = $role;
4683: if ($desc ne '') {
4684: $description{$role} = $desc;
4685: } else {
4686: $description{$role}= $role;
4687: }
4688: $count++;
4689: }
4690: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
4691: push(@roles_by_num,$ordered{$item});
4692: }
4693: }
4694: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
4695: }
4696:
4697: sub get_my_adhocroles {
4698: my ($cid,$checkreg) = @_;
4699: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
4700: if ($env{'request.course.id'} eq $cid) {
4701: $cdom = $env{'course.'.$cid.'.domain'};
4702: $cnum = $env{'course.'.$cid.'.num'};
4703: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
4704: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
4705: $cdom = $1;
4706: $cnum = $2;
4707: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
4708: $cdom,$cnum);
4709: }
4710: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
4711: my $user = $env{'user.name'}.':'.$env{'user.domain'};
4712: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
4713: if ($rosterhash{$user} ne '') {
4714: my $type = (split(/:/,$rosterhash{$user}))[5];
4715: return ([],{}) if ($type eq 'auto');
4716: }
4717: }
4718: if (($cdom ne '') && ($cnum ne '')) {
4719: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
4720: my $then=$env{'user.login.time'};
4721: my $update=$env{'user.update.time'};
4722: if (!$update) {
4723: $update = $then;
4724: }
4725: my @liveroles;
4726: foreach my $role ('dh','da') {
4727: if ($env{"user.role.$role./$cdom/"}) {
4728: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
4729: my $limit = $update;
4730: if ($env{'request.role'} eq "$role./$cdom/") {
4731: $limit = $then;
4732: }
4733: my $activerole = 1;
4734: if ($tstart && $tstart>$limit) { $activerole = 0; }
4735: if ($tend && $tend <$limit) { $activerole = 0; }
4736: if ($activerole) {
4737: push(@liveroles,$role);
4738: }
4739: }
4740: }
4741: if (@liveroles) {
4742: if (&homeserver($cnum,$cdom) ne 'no_host') {
4743: my ($accessref,$accessinfo,%access_in_dom);
4744: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
4745: if (ref($roles_by_num) eq 'ARRAY') {
4746: if (@{$roles_by_num}) {
4747: my %settings;
4748: if ($env{'request.course.id'} eq $cid) {
4749: foreach my $envkey (keys(%env)) {
4750: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
4751: $settings{$1} = $env{$envkey};
4752: }
4753: }
4754: } else {
4755: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
4756: }
4757: my %setincrs;
4758: if ($settings{'internal.adhocaccess'}) {
4759: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
4760: }
4761: my @statuses;
4762: if ($env{'environment.inststatus'}) {
4763: @statuses = split(/,/,$env{'environment.inststatus'});
4764: }
4765: my $user = $env{'user.name'}.':'.$env{'user.domain'};
4766: if (ref($accessref) eq 'HASH') {
4767: %access_in_dom = %{$accessref};
4768: }
4769: foreach my $role (@{$roles_by_num}) {
4770: my ($curraccess,@okstatus,@personnel);
4771: if ($setincrs{$role}) {
4772: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
4773: if ($curraccess eq 'status') {
4774: @okstatus = split(/\&/,$rest);
4775: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4776: @personnel = split(/\&/,$rest);
4777: }
4778: } else {
4779: $curraccess = $access_in_dom{$role};
4780: if (ref($accessinfo) eq 'HASH') {
4781: if ($curraccess eq 'status') {
4782: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4783: @okstatus = @{$accessinfo->{$role}};
4784: }
4785: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4786: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4787: @personnel = @{$accessinfo->{$role}};
4788: }
4789: }
4790: }
4791: }
4792: if ($curraccess eq 'none') {
4793: next;
4794: } elsif ($curraccess eq 'all') {
4795: push(@possroles,$role);
4796: } elsif ($curraccess eq 'dh') {
4797: if (grep(/^dh$/,@liveroles)) {
4798: push(@possroles,$role);
4799: } else {
4800: next;
4801: }
4802: } elsif ($curraccess eq 'da') {
4803: if (grep(/^da$/,@liveroles)) {
4804: push(@possroles,$role);
4805: } else {
4806: next;
4807: }
4808: } elsif ($curraccess eq 'status') {
4809: if (@okstatus) {
4810: if (!@statuses) {
4811: if (grep(/^default$/,@okstatus)) {
4812: push(@possroles,$role);
4813: }
4814: } else {
4815: foreach my $status (@okstatus) {
4816: if (grep(/^\Q$status\E$/,@statuses)) {
4817: push(@possroles,$role);
4818: last;
4819: }
4820: }
4821: }
4822: }
4823: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4824: if (grep(/^\Q$user\E$/,@personnel)) {
4825: if ($curraccess eq 'exc') {
4826: push(@possroles,$role);
4827: }
4828: } elsif ($curraccess eq 'inc') {
4829: push(@possroles,$role);
4830: }
4831: }
4832: }
4833: }
4834: }
4835: }
4836: }
4837: }
4838: }
4839: unless (ref($description) eq 'HASH') {
4840: if (ref($roles_by_num) eq 'ARRAY') {
4841: my %desc;
4842: map { $desc{$_} = $_; } (@{$roles_by_num});
4843: $description = \%desc;
4844: } else {
4845: $description = {};
4846: }
4847: }
4848: return (\@possroles,$description);
4849: }
4850:
4851: # ----------------------------------------------------- Frontpage Announcements
4852: #
4853: #
4854:
4855: sub postannounce {
4856: my ($server,$text)=@_;
4857: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
4858: unless ($text=~/\w/) { $text=''; }
4859: return &reply('setannounce:'.&escape($text),$server);
4860: }
4861:
4862: sub getannounce {
4863:
4864: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
4865: my $announcement='';
4866: while (my $line = <$fh>) { $announcement .= $line; }
4867: close($fh);
4868: if ($announcement=~/\w/) {
4869: return
4870: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
4871: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
4872: } else {
4873: return '';
4874: }
4875: } else {
4876: return '';
4877: }
4878: }
4879:
4880: # ---------------------------------------------------------- Course ID routines
4881: # Deal with domain's nohist_courseid.db files
4882: #
4883:
4884: sub courseidput {
4885: my ($domain,$storehash,$coursehome,$caller) = @_;
4886: return unless (ref($storehash) eq 'HASH');
4887: my $outcome;
4888: if ($caller eq 'timeonly') {
4889: my $cids = '';
4890: foreach my $item (keys(%$storehash)) {
4891: $cids.=&escape($item).'&';
4892: }
4893: $cids=~s/\&$//;
4894: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4895: $coursehome);
4896: } else {
4897: my $items = '';
4898: foreach my $item (keys(%$storehash)) {
4899: $items.= &escape($item).'='.
4900: &freeze_escape($$storehash{$item}).'&';
4901: }
4902: $items=~s/\&$//;
4903: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4904: $coursehome);
4905: }
4906: if ($outcome eq 'unknown_cmd') {
4907: my $what;
4908: foreach my $cid (keys(%$storehash)) {
4909: $what .= &escape($cid).'=';
4910: foreach my $item ('description','inst_code','owner','type') {
4911: $what .= &escape($storehash->{$cid}{$item}).':';
4912: }
4913: $what =~ s/\:$/&/;
4914: }
4915: $what =~ s/\&$//;
4916: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4917: } else {
4918: return $outcome;
4919: }
4920: }
4921:
4922: sub courseiddump {
4923: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
4924: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
4925: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
4926: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
4927: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
4928: my $as_hash = 1;
4929: my %returnhash;
4930: if (!$domfilter) { $domfilter=''; }
4931: my %libserv = &all_library();
4932: foreach my $tryserver (keys(%libserv)) {
4933: if ( ( $hostidflag == 1
4934: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4935: || (!defined($hostidflag)) ) {
4936:
4937: if (($domfilter eq '') ||
4938: (&host_domain($tryserver) eq $domfilter)) {
4939: my $rep;
4940: if (grep { $_ eq $tryserver } current_machine_ids()) {
4941: $rep = LONCAPA::Lond::dump_course_id_handler(
4942: join(":", (&host_domain($tryserver), $sincefilter,
4943: &escape($descfilter), &escape($instcodefilter),
4944: &escape($ownerfilter), &escape($coursefilter),
4945: &escape($typefilter), &escape($regexp_ok),
4946: $as_hash, &escape($selfenrollonly),
4947: &escape($catfilter), $showhidden, $caller,
4948: &escape($cloner), &escape($cc_clone), $cloneonly,
4949: &escape($createdbefore), &escape($createdafter),
4950: &escape($creationcontext),$domcloner,$hasuniquecode,
4951: $reqcrsdom,&escape($reqinstcode))));
4952: } else {
4953: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4954: $sincefilter.':'.&escape($descfilter).':'.
4955: &escape($instcodefilter).':'.&escape($ownerfilter).
4956: ':'.&escape($coursefilter).':'.&escape($typefilter).
4957: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4958: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4959: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4960: &escape($cc_clone).':'.$cloneonly.':'.
4961: &escape($createdbefore).':'.&escape($createdafter).':'.
4962: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
4963: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
4964: }
4965:
4966: my @pairs=split(/\&/,$rep);
4967: foreach my $item (@pairs) {
4968: my ($key,$value)=split(/\=/,$item,2);
4969: $key = &unescape($key);
4970: next if ($key =~ /^error: 2 /);
4971: my $result = &thaw_unescape($value);
4972: if (ref($result) eq 'HASH') {
4973: $returnhash{$key}=$result;
4974: } else {
4975: my @responses = split(/:/,$value);
4976: my @items = ('description','inst_code','owner','type');
4977: for (my $i=0; $i<@responses; $i++) {
4978: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
4979: }
4980: }
4981: }
4982: }
4983: }
4984: }
4985: return %returnhash;
4986: }
4987:
4988: sub courselastaccess {
4989: my ($cdom,$cnum,$hostidref) = @_;
4990: my %returnhash;
4991: if ($cdom && $cnum) {
4992: my $chome = &homeserver($cnum,$cdom);
4993: if ($chome ne 'no_host') {
4994: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4995: &extract_lastaccess(\%returnhash,$rep);
4996: }
4997: } else {
4998: if (!$cdom) { $cdom=''; }
4999: my %libserv = &all_library();
5000: foreach my $tryserver (keys(%libserv)) {
5001: if (ref($hostidref) eq 'ARRAY') {
5002: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5003: }
5004: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5005: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5006: &extract_lastaccess(\%returnhash,$rep);
5007: }
5008: }
5009: }
5010: return %returnhash;
5011: }
5012:
5013: sub extract_lastaccess {
5014: my ($returnhash,$rep) = @_;
5015: if (ref($returnhash) eq 'HASH') {
5016: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5017: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5018: $rep eq '') {
5019: my @pairs=split(/\&/,$rep);
5020: foreach my $item (@pairs) {
5021: my ($key,$value)=split(/\=/,$item,2);
5022: $key = &unescape($key);
5023: next if ($key =~ /^error: 2 /);
5024: $returnhash->{$key} = &thaw_unescape($value);
5025: }
5026: }
5027: }
5028: return;
5029: }
5030:
5031: # ---------------------------------------------------------- DC e-mail
5032:
5033: sub dcmailput {
5034: my ($domain,$msgid,$message,$server)=@_;
5035: my $status = &Apache::lonnet::critical(
5036: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5037: &escape($message),$server);
5038: return $status;
5039: }
5040:
5041: sub dcmaildump {
5042: my ($dom,$startdate,$enddate,$senders) = @_;
5043: my %returnhash=();
5044:
5045: if (defined(&domain($dom,'primary'))) {
5046: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5047: &escape($enddate).':';
5048: my @esc_senders=map { &escape($_)} @$senders;
5049: $cmd.=&escape(join('&',@esc_senders));
5050: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
5051: my ($key,$value) = split(/\=/,$line,2);
5052: if (($key) && ($value)) {
5053: $returnhash{&unescape($key)} = &unescape($value);
5054: }
5055: }
5056: }
5057: return %returnhash;
5058: }
5059: # ---------------------------------------------------------- Domain roles
5060:
5061: sub get_domain_roles {
5062: my ($dom,$roles,$startdate,$enddate)=@_;
5063: if ((!defined($startdate)) || ($startdate eq '')) {
5064: $startdate = '.';
5065: }
5066: if ((!defined($enddate)) || ($enddate eq '')) {
5067: $enddate = '.';
5068: }
5069: my $rolelist;
5070: if (ref($roles) eq 'ARRAY') {
5071: $rolelist = join('&',@{$roles});
5072: }
5073: my %personnel = ();
5074:
5075: my %servers = &get_servers($dom,'library');
5076: foreach my $tryserver (keys(%servers)) {
5077: %{$personnel{$tryserver}}=();
5078: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5079: &escape($startdate).':'.
5080: &escape($enddate).':'.
5081: &escape($rolelist), $tryserver))) {
5082: my ($key,$value) = split(/\=/,$line,2);
5083: if (($key) && ($value)) {
5084: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5085: }
5086: }
5087: }
5088: return %personnel;
5089: }
5090:
5091: sub get_active_domroles {
5092: my ($dom,$roles) = @_;
5093: return () unless (ref($roles) eq 'ARRAY');
5094: my $now = time;
5095: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5096: my %domroles;
5097: foreach my $server (keys(%dompersonnel)) {
5098: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5099: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5100: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5101: }
5102: }
5103: return %domroles;
5104: }
5105:
5106: # ----------------------------------------------------------- Interval timing
5107:
5108: {
5109: # Caches needed for speedup of navmaps
5110: # We don't want to cache this for very long at all (5 seconds at most)
5111: #
5112: # The user for whom we cache
5113: my $cachedkey='';
5114: # The cached times for this user
5115: my %cachedtimes=();
5116: # When this was last done
5117: my $cachedtime='';
5118:
5119: sub load_all_first_access {
5120: my ($uname,$udom,$ignorecache)=@_;
5121: if (($cachedkey eq $uname.':'.$udom) &&
5122: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
5123: (!$ignorecache)) {
5124: return;
5125: }
5126: $cachedtime=time;
5127: $cachedkey=$uname.':'.$udom;
5128: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
5129: }
5130:
5131: sub get_first_access {
5132: my ($type,$argsymb,$argmap,$ignorecache)=@_;
5133: my ($symb,$courseid,$udom,$uname)=&whichuser();
5134: if ($argsymb) { $symb=$argsymb; }
5135: my ($map,$id,$res)=&decode_symb($symb);
5136: if ($argmap) { $map = $argmap; }
5137: if ($type eq 'course') {
5138: $res='course';
5139: } elsif ($type eq 'map') {
5140: $res=&symbread($map);
5141: } else {
5142: $res=$symb;
5143: }
5144: &load_all_first_access($uname,$udom,$ignorecache);
5145: return $cachedtimes{"$courseid\0$res"};
5146: }
5147:
5148: sub set_first_access {
5149: my ($type,$interval)=@_;
5150: my ($symb,$courseid,$udom,$uname)=&whichuser();
5151: my ($map,$id,$res)=&decode_symb($symb);
5152: if ($type eq 'course') {
5153: $res='course';
5154: } elsif ($type eq 'map') {
5155: $res=&symbread($map);
5156: } else {
5157: $res=$symb;
5158: }
5159: $cachedkey='';
5160: my $firstaccess=&get_first_access($type,$symb,$map);
5161: if (!$firstaccess) {
5162: my $start = time;
5163: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5164: $udom,$uname);
5165: if ($putres eq 'ok') {
5166: &put('timerinterval',{"$courseid\0$res"=>$interval},
5167: $udom,$uname);
5168: &appenv(
5169: {
5170: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5171: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5172: }
5173: );
5174: }
5175: return $putres;
5176: }
5177: return 'already_set';
5178: }
5179: }
5180:
5181: # --------------------------------------------- Set Expire Date for Spreadsheet
5182:
5183: sub expirespread {
5184: my ($uname,$udom,$stype,$usymb)=@_;
5185: my $cid=$env{'request.course.id'};
5186: if ($cid) {
5187: my $now=time;
5188: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
5189: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5190: $env{'course.'.$cid.'.num'}.
5191: ':nohist_expirationdates:'.
5192: &escape($key).'='.$now,
5193: $env{'course.'.$cid.'.home'})
5194: }
5195: return 'ok';
5196: }
5197:
5198: # ----------------------------------------------------- Devalidate Spreadsheets
5199:
5200: sub devalidate {
5201: my ($symb,$uname,$udom)=@_;
5202: my $cid=$env{'request.course.id'};
5203: if ($cid) {
5204: # delete the stored spreadsheets for
5205: # - the student level sheet of this user in course's homespace
5206: # - the assessment level sheet for this resource
5207: # for this user in user's homespace
5208: # - current conditional state info
5209: my $key=$uname.':'.$udom.':';
5210: my $status=
5211: &del('nohist_calculatedsheets',
5212: [$key.'studentcalc:'],
5213: $env{'course.'.$cid.'.domain'},
5214: $env{'course.'.$cid.'.num'})
5215: .' '.
5216: &del('nohist_calculatedsheets_'.$cid,
5217: [$key.'assesscalc:'.$symb],$udom,$uname);
5218: unless ($status eq 'ok ok') {
5219: &logthis('Could not devalidate spreadsheet '.
5220: $uname.' at '.$udom.' for '.
5221: $symb.': '.$status);
5222: }
5223: &delenv('user.state.'.$cid);
5224: }
5225: }
5226:
5227: sub get_scalar {
5228: my ($string,$end) = @_;
5229: my $value;
5230: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5231: $value = $1;
5232: } elsif ($$string =~ s/^([^&]*?)&//) {
5233: $value = $1;
5234: }
5235: return &unescape($value);
5236: }
5237:
5238: sub array2str {
5239: my (@array) = @_;
5240: my $result=&arrayref2str(\@array);
5241: $result=~s/^__ARRAY_REF__//;
5242: $result=~s/__END_ARRAY_REF__$//;
5243: return $result;
5244: }
5245:
5246: sub arrayref2str {
5247: my ($arrayref) = @_;
5248: my $result='__ARRAY_REF__';
5249: foreach my $elem (@$arrayref) {
5250: if(ref($elem) eq 'ARRAY') {
5251: $result.=&arrayref2str($elem).'&';
5252: } elsif(ref($elem) eq 'HASH') {
5253: $result.=&hashref2str($elem).'&';
5254: } elsif(ref($elem)) {
5255: #print("Got a ref of ".(ref($elem))." skipping.");
5256: } else {
5257: $result.=&escape($elem).'&';
5258: }
5259: }
5260: $result=~s/\&$//;
5261: $result .= '__END_ARRAY_REF__';
5262: return $result;
5263: }
5264:
5265: sub hash2str {
5266: my (%hash) = @_;
5267: my $result=&hashref2str(\%hash);
5268: $result=~s/^__HASH_REF__//;
5269: $result=~s/__END_HASH_REF__$//;
5270: return $result;
5271: }
5272:
5273: sub hashref2str {
5274: my ($hashref)=@_;
5275: my $result='__HASH_REF__';
5276: foreach my $key (sort(keys(%$hashref))) {
5277: if (ref($key) eq 'ARRAY') {
5278: $result.=&arrayref2str($key).'=';
5279: } elsif (ref($key) eq 'HASH') {
5280: $result.=&hashref2str($key).'=';
5281: } elsif (ref($key)) {
5282: $result.='=';
5283: #print("Got a ref of ".(ref($key))." skipping.");
5284: } else {
5285: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
5286: }
5287:
5288: if(ref($hashref->{$key}) eq 'ARRAY') {
5289: $result.=&arrayref2str($hashref->{$key}).'&';
5290: } elsif(ref($hashref->{$key}) eq 'HASH') {
5291: $result.=&hashref2str($hashref->{$key}).'&';
5292: } elsif(ref($hashref->{$key})) {
5293: $result.='&';
5294: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
5295: } else {
5296: $result.=&escape($hashref->{$key}).'&';
5297: }
5298: }
5299: $result=~s/\&$//;
5300: $result .= '__END_HASH_REF__';
5301: return $result;
5302: }
5303:
5304: sub str2hash {
5305: my ($string)=@_;
5306: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5307: return %$hash;
5308: }
5309:
5310: sub str2hashref {
5311: my ($string) = @_;
5312:
5313: my %hash;
5314:
5315: if($string !~ /^__HASH_REF__/) {
5316: if (! ($string eq '' || !defined($string))) {
5317: $hash{'error'}='Not hash reference';
5318: }
5319: return (\%hash, $string);
5320: }
5321:
5322: $string =~ s/^__HASH_REF__//;
5323:
5324: while($string !~ /^__END_HASH_REF__/) {
5325: #key
5326: my $key='';
5327: if($string =~ /^__HASH_REF__/) {
5328: ($key, $string)=&str2hashref($string);
5329: if(defined($key->{'error'})) {
5330: $hash{'error'}='Bad data';
5331: return (\%hash, $string);
5332: }
5333: } elsif($string =~ /^__ARRAY_REF__/) {
5334: ($key, $string)=&str2arrayref($string);
5335: if($key->[0] eq 'Array reference error') {
5336: $hash{'error'}='Bad data';
5337: return (\%hash, $string);
5338: }
5339: } else {
5340: $string =~ s/^(.*?)=//;
5341: $key=&unescape($1);
5342: }
5343: $string =~ s/^=//;
5344:
5345: #value
5346: my $value='';
5347: if($string =~ /^__HASH_REF__/) {
5348: ($value, $string)=&str2hashref($string);
5349: if(defined($value->{'error'})) {
5350: $hash{'error'}='Bad data';
5351: return (\%hash, $string);
5352: }
5353: } elsif($string =~ /^__ARRAY_REF__/) {
5354: ($value, $string)=&str2arrayref($string);
5355: if($value->[0] eq 'Array reference error') {
5356: $hash{'error'}='Bad data';
5357: return (\%hash, $string);
5358: }
5359: } else {
5360: $value=&get_scalar(\$string,'__END_HASH_REF__');
5361: }
5362: $string =~ s/^&//;
5363:
5364: $hash{$key}=$value;
5365: }
5366:
5367: $string =~ s/^__END_HASH_REF__//;
5368:
5369: return (\%hash, $string);
5370: }
5371:
5372: sub str2array {
5373: my ($string)=@_;
5374: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5375: return @$array;
5376: }
5377:
5378: sub str2arrayref {
5379: my ($string) = @_;
5380: my @array;
5381:
5382: if($string !~ /^__ARRAY_REF__/) {
5383: if (! ($string eq '' || !defined($string))) {
5384: $array[0]='Array reference error';
5385: }
5386: return (\@array, $string);
5387: }
5388:
5389: $string =~ s/^__ARRAY_REF__//;
5390:
5391: while($string !~ /^__END_ARRAY_REF__/) {
5392: my $value='';
5393: if($string =~ /^__HASH_REF__/) {
5394: ($value, $string)=&str2hashref($string);
5395: if(defined($value->{'error'})) {
5396: $array[0] ='Array reference error';
5397: return (\@array, $string);
5398: }
5399: } elsif($string =~ /^__ARRAY_REF__/) {
5400: ($value, $string)=&str2arrayref($string);
5401: if($value->[0] eq 'Array reference error') {
5402: $array[0] ='Array reference error';
5403: return (\@array, $string);
5404: }
5405: } else {
5406: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5407: }
5408: $string =~ s/^&//;
5409:
5410: push(@array, $value);
5411: }
5412:
5413: $string =~ s/^__END_ARRAY_REF__//;
5414:
5415: return (\@array, $string);
5416: }
5417:
5418: # -------------------------------------------------------------------Temp Store
5419:
5420: sub tmpreset {
5421: my ($symb,$namespace,$domain,$stuname) = @_;
5422: if (!$symb) {
5423: $symb=&symbread();
5424: if (!$symb) { $symb= $env{'request.url'}; }
5425: }
5426: $symb=escape($symb);
5427:
5428: if (!$namespace) { $namespace=$env{'request.state'}; }
5429: $namespace=~s/\//\_/g;
5430: $namespace=~s/\W//g;
5431:
5432: if (!$domain) { $domain=$env{'user.domain'}; }
5433: if (!$stuname) { $stuname=$env{'user.name'}; }
5434: if ($domain eq 'public' && $stuname eq 'public') {
5435: $stuname=$ENV{'REMOTE_ADDR'};
5436: }
5437: my $path=LONCAPA::tempdir();
5438: my %hash;
5439: if (tie(%hash,'GDBM_File',
5440: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
5441: &GDBM_WRCREAT(),0640)) {
5442: foreach my $key (keys(%hash)) {
5443: if ($key=~ /:$symb/) {
5444: delete($hash{$key});
5445: }
5446: }
5447: }
5448: }
5449:
5450: sub tmpstore {
5451: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5452:
5453: if (!$symb) {
5454: $symb=&symbread();
5455: if (!$symb) { $symb= $env{'request.url'}; }
5456: }
5457: $symb=escape($symb);
5458:
5459: if (!$namespace) {
5460: # I don't think we would ever want to store this for a course.
5461: # it seems this will only be used if we don't have a course.
5462: #$namespace=$env{'request.course.id'};
5463: #if (!$namespace) {
5464: $namespace=$env{'request.state'};
5465: #}
5466: }
5467: $namespace=~s/\//\_/g;
5468: $namespace=~s/\W//g;
5469: if (!$domain) { $domain=$env{'user.domain'}; }
5470: if (!$stuname) { $stuname=$env{'user.name'}; }
5471: if ($domain eq 'public' && $stuname eq 'public') {
5472: $stuname=$ENV{'REMOTE_ADDR'};
5473: }
5474: my $now=time;
5475: my %hash;
5476: my $path=LONCAPA::tempdir();
5477: if (tie(%hash,'GDBM_File',
5478: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
5479: &GDBM_WRCREAT(),0640)) {
5480: $hash{"version:$symb"}++;
5481: my $version=$hash{"version:$symb"};
5482: my $allkeys='';
5483: foreach my $key (keys(%$storehash)) {
5484: $allkeys.=$key.':';
5485: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
5486: }
5487: $hash{"$version:$symb:timestamp"}=$now;
5488: $allkeys.='timestamp';
5489: $hash{"$version:keys:$symb"}=$allkeys;
5490: if (untie(%hash)) {
5491: return 'ok';
5492: } else {
5493: return "error:$!";
5494: }
5495: } else {
5496: return "error:$!";
5497: }
5498: }
5499:
5500: # -----------------------------------------------------------------Temp Restore
5501:
5502: sub tmprestore {
5503: my ($symb,$namespace,$domain,$stuname) = @_;
5504:
5505: if (!$symb) {
5506: $symb=&symbread();
5507: if (!$symb) { $symb= $env{'request.url'}; }
5508: }
5509: $symb=escape($symb);
5510:
5511: if (!$namespace) { $namespace=$env{'request.state'}; }
5512:
5513: if (!$domain) { $domain=$env{'user.domain'}; }
5514: if (!$stuname) { $stuname=$env{'user.name'}; }
5515: if ($domain eq 'public' && $stuname eq 'public') {
5516: $stuname=$ENV{'REMOTE_ADDR'};
5517: }
5518: my %returnhash;
5519: $namespace=~s/\//\_/g;
5520: $namespace=~s/\W//g;
5521: my %hash;
5522: my $path=LONCAPA::tempdir();
5523: if (tie(%hash,'GDBM_File',
5524: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
5525: &GDBM_READER(),0640)) {
5526: my $version=$hash{"version:$symb"};
5527: $returnhash{'version'}=$version;
5528: my $scope;
5529: for ($scope=1;$scope<=$version;$scope++) {
5530: my $vkeys=$hash{"$scope:keys:$symb"};
5531: my @keys=split(/:/,$vkeys);
5532: my $key;
5533: $returnhash{"$scope:keys"}=$vkeys;
5534: foreach $key (@keys) {
5535: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5536: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5537: }
5538: }
5539: if (!(untie(%hash))) {
5540: return "error:$!";
5541: }
5542: } else {
5543: return "error:$!";
5544: }
5545: return %returnhash;
5546: }
5547:
5548: # ----------------------------------------------------------------------- Store
5549:
5550: sub store {
5551: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
5552: my $home='';
5553:
5554: if ($stuname) { $home=&homeserver($stuname,$domain); }
5555:
5556: $symb=&symbclean($symb);
5557: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
5558:
5559: if (!$domain) { $domain=$env{'user.domain'}; }
5560: if (!$stuname) { $stuname=$env{'user.name'}; }
5561:
5562: &devalidate($symb,$stuname,$domain);
5563:
5564: $symb=escape($symb);
5565: if (!$namespace) {
5566: unless ($namespace=$env{'request.course.id'}) {
5567: return '';
5568: }
5569: }
5570: if (!$home) { $home=$env{'user.home'}; }
5571:
5572: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5573: $$storehash{'host'}=$perlvar{'lonHostID'};
5574:
5575: my $namevalue='';
5576: foreach my $key (keys(%$storehash)) {
5577: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5578: }
5579: $namevalue=~s/\&$//;
5580: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
5581: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
5582: }
5583:
5584: # -------------------------------------------------------------- Critical Store
5585:
5586: sub cstore {
5587: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
5588: my $home='';
5589:
5590: if ($stuname) { $home=&homeserver($stuname,$domain); }
5591:
5592: $symb=&symbclean($symb);
5593: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
5594:
5595: if (!$domain) { $domain=$env{'user.domain'}; }
5596: if (!$stuname) { $stuname=$env{'user.name'}; }
5597:
5598: &devalidate($symb,$stuname,$domain);
5599:
5600: $symb=escape($symb);
5601: if (!$namespace) {
5602: unless ($namespace=$env{'request.course.id'}) {
5603: return '';
5604: }
5605: }
5606: if (!$home) { $home=$env{'user.home'}; }
5607:
5608: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5609: $$storehash{'host'}=$perlvar{'lonHostID'};
5610:
5611: my $namevalue='';
5612: foreach my $key (keys(%$storehash)) {
5613: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5614: }
5615: $namevalue=~s/\&$//;
5616: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
5617: return critical
5618: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
5619: }
5620:
5621: # --------------------------------------------------------------------- Restore
5622:
5623: sub restore {
5624: my ($symb,$namespace,$domain,$stuname) = @_;
5625: my $home='';
5626:
5627: if ($stuname) { $home=&homeserver($stuname,$domain); }
5628:
5629: if (!$symb) {
5630: return if ($namespace eq 'courserequests');
5631: unless ($symb=escape(&symbread())) { return ''; }
5632: } else {
5633: unless ($namespace eq 'courserequests') {
5634: $symb=&escape(&symbclean($symb));
5635: }
5636: }
5637: if (!$namespace) {
5638: unless ($namespace=$env{'request.course.id'}) {
5639: return '';
5640: }
5641: }
5642: if (!$domain) { $domain=$env{'user.domain'}; }
5643: if (!$stuname) { $stuname=$env{'user.name'}; }
5644: if (!$home) { $home=$env{'user.home'}; }
5645: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5646:
5647: my %returnhash=();
5648: foreach my $line (split(/\&/,$answer)) {
5649: my ($name,$value)=split(/\=/,$line);
5650: $returnhash{&unescape($name)}=&thaw_unescape($value);
5651: }
5652: my $version;
5653: for ($version=1;$version<=$returnhash{'version'};$version++) {
5654: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5655: $returnhash{$item}=$returnhash{$version.':'.$item};
5656: }
5657: }
5658: return %returnhash;
5659: }
5660:
5661: # ---------------------------------------------------------- Course Description
5662: #
5663: #
5664:
5665: sub coursedescription {
5666: my ($courseid,$args)=@_;
5667: $courseid=~s/^\///;
5668: $courseid=~s/\_/\//g;
5669: my ($cdomain,$cnum)=split(/\//,$courseid);
5670: my $chome=&homeserver($cnum,$cdomain);
5671: my $normalid=$cdomain.'_'.$cnum;
5672: # need to always cache even if we get errors otherwise we keep
5673: # trying and trying and trying to get the course description.
5674: my %envhash=();
5675: my %returnhash=();
5676:
5677: my $expiretime=600;
5678: if ($env{'request.course.id'} eq $normalid) {
5679: $expiretime=120;
5680: }
5681:
5682: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5683: if (!$args->{'freshen_cache'}
5684: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5685: foreach my $key (keys(%env)) {
5686: next if ($key !~ /^\Q$prefix\E(.*)/);
5687: my ($setting) = $1;
5688: $returnhash{$setting} = $env{$key};
5689: }
5690: return %returnhash;
5691: }
5692:
5693: # get the data again
5694:
5695: if (!$args->{'one_time'}) {
5696: $envhash{'course.'.$normalid.'.last_cache'}=time;
5697: }
5698:
5699: if ($chome ne 'no_host') {
5700: %returnhash=&dump('environment',$cdomain,$cnum);
5701: if (!exists($returnhash{'con_lost'})) {
5702: my $username = $env{'user.name'}; # Defult username
5703: if(defined $args->{'user'}) {
5704: $username = $args->{'user'};
5705: }
5706: $returnhash{'home'}= $chome;
5707: $returnhash{'domain'} = $cdomain;
5708: $returnhash{'num'} = $cnum;
5709: if (!defined($returnhash{'type'})) {
5710: $returnhash{'type'} = 'Course';
5711: }
5712: while (my ($name,$value) = each %returnhash) {
5713: $envhash{'course.'.$normalid.'.'.$name}=$value;
5714: }
5715: $returnhash{'url'}=&clutter($returnhash{'url'});
5716: $returnhash{'fn'}=LONCAPA::tempdir() .
5717: $username.'_'.$cdomain.'_'.$cnum;
5718: $envhash{'course.'.$normalid.'.home'}=$chome;
5719: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5720: $envhash{'course.'.$normalid.'.num'}=$cnum;
5721: }
5722: }
5723: if (!$args->{'one_time'}) {
5724: &appenv(\%envhash);
5725: }
5726: return %returnhash;
5727: }
5728:
5729: sub update_released_required {
5730: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5731: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5732: $cid = $env{'request.course.id'};
5733: $cdom = $env{'course.'.$cid.'.domain'};
5734: $cnum = $env{'course.'.$cid.'.num'};
5735: $chome = $env{'course.'.$cid.'.home'};
5736: }
5737: if ($needsrelease) {
5738: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5739: my $needsupdate;
5740: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5741: $needsupdate = 1;
5742: } else {
5743: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5744: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5745: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5746: $needsupdate = 1;
5747: }
5748: }
5749: if ($needsupdate) {
5750: my %needshash = (
5751: 'internal.releaserequired' => $needsrelease,
5752: );
5753: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5754: if ($putresult eq 'ok') {
5755: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5756: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5757: if (ref($crsinfo{$cid}) eq 'HASH') {
5758: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5759: &courseidput($cdom,\%crsinfo,$chome,'notime');
5760: }
5761: }
5762: }
5763: }
5764: return;
5765: }
5766:
5767: # -------------------------------------------------See if a user is privileged
5768:
5769: sub privileged {
5770: my ($username,$domain,$possdomains,$possroles)=@_;
5771: my $now = time;
5772: my $roles;
5773: if (ref($possroles) eq 'ARRAY') {
5774: $roles = $possroles;
5775: } else {
5776: $roles = ['dc','su'];
5777: }
5778: if (ref($possdomains) eq 'ARRAY') {
5779: my %privileged = &privileged_by_domain($possdomains,$roles);
5780: foreach my $dom (@{$possdomains}) {
5781: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5782: (ref($privileged{$dom}) eq 'HASH')) {
5783: foreach my $role (@{$roles}) {
5784: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5785: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5786: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5787: return 1 unless (($end && $end < $now) ||
5788: ($start && $start > $now));
5789: }
5790: }
5791: }
5792: }
5793: }
5794: } else {
5795: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5796: my $now = time;
5797:
5798: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
5799: my ($trole, $tend, $tstart) = split(/_/, $role);
5800: if (grep(/^\Q$trole\E$/,@{$roles})) {
5801: return 1 unless ($tend && $tend < $now)
5802: or ($tstart && $tstart > $now);
5803: }
5804: }
5805: }
5806: return 0;
5807: }
5808:
5809: sub privileged_by_domain {
5810: my ($domains,$roles) = @_;
5811: my %privileged = ();
5812: my $cachetime = 60*60*24;
5813: my $now = time;
5814: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5815: return %privileged;
5816: }
5817: foreach my $dom (@{$domains}) {
5818: next if (ref($privileged{$dom}) eq 'HASH');
5819: my $needroles;
5820: foreach my $role (@{$roles}) {
5821: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5822: if (defined($cached)) {
5823: if (ref($result) eq 'HASH') {
5824: $privileged{$dom}{$role} = $result;
5825: }
5826: } else {
5827: $needroles = 1;
5828: }
5829: }
5830: if ($needroles) {
5831: my %dompersonnel = &get_domain_roles($dom,$roles);
5832: $privileged{$dom} = {};
5833: foreach my $server (keys(%dompersonnel)) {
5834: if (ref($dompersonnel{$server}) eq 'HASH') {
5835: foreach my $item (keys(%{$dompersonnel{$server}})) {
5836: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5837: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5838: next if ($end && $end < $now);
5839: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5840: $dompersonnel{$server}{$item};
5841: }
5842: }
5843: }
5844: if (ref($privileged{$dom}) eq 'HASH') {
5845: foreach my $role (@{$roles}) {
5846: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5847: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5848: } else {
5849: my %hash = ();
5850: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5851: }
5852: }
5853: }
5854: }
5855: }
5856: return %privileged;
5857: }
5858:
5859: # -------------------------------------------------------- Get user privileges
5860:
5861: sub rolesinit {
5862: my ($domain, $username) = @_;
5863: my %userroles = ('user.login.time' => time);
5864: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5865:
5866: # firstaccess and timerinterval are related to timed maps/resources.
5867: # also, blocking can be triggered by an activating timer
5868: # it's saved in the user's %env.
5869: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5870: my %timerinterval = &dump('timerinterval', $domain, $username);
5871: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5872: %timerintchk, %timerintenv);
5873:
5874: foreach my $key (keys(%firstaccess)) {
5875: my ($cid, $rest) = split(/\0/, $key);
5876: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5877: }
5878:
5879: foreach my $key (keys(%timerinterval)) {
5880: my ($cid,$rest) = split(/\0/,$key);
5881: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5882: }
5883:
5884: my %allroles=();
5885: my %allgroups=();
5886:
5887: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
5888: my $role = $rolesdump{$area};
5889: $area =~ s/\_\w\w$//;
5890:
5891: my ($trole, $tend, $tstart, $group_privs);
5892:
5893: if ($role =~ /^cr/) {
5894: # Custom role, defined by a user
5895: # e.g., user.role.cr/msu/smith/mynewrole
5896: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5897: $trole = $1;
5898: ($tend, $tstart) = split('_', $2);
5899: } else {
5900: $trole = $role;
5901: }
5902: } elsif ($role =~ m|^gr/|) {
5903: # Role of member in a group, defined within a course/community
5904: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5905: ($trole, $tend, $tstart) = split(/_/, $role);
5906: next if $tstart eq '-1';
5907: ($trole, $group_privs) = split(/\//, $trole);
5908: $group_privs = &unescape($group_privs);
5909: } else {
5910: # Just a normal role, defined in roles.tab
5911: ($trole, $tend, $tstart) = split(/_/,$role);
5912: }
5913:
5914: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5915: $username);
5916: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5917:
5918: # role expired or not available yet?
5919: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5920: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5921:
5922: next if $area eq '' or $trole eq '';
5923:
5924: my $spec = "$trole.$area";
5925: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5926:
5927: if ($trole =~ /^cr\//) {
5928: # Custom role, defined by a user
5929: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5930: } elsif ($trole eq 'gr') {
5931: # Role of a member in a group, defined within a course/community
5932: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5933: next;
5934: } else {
5935: # Normal role, defined in roles.tab
5936: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5937: }
5938:
5939: my $cid = $tdomain.'_'.$trest;
5940: unless ($firstaccchk{$cid}) {
5941: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5942: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5943: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5944: $coursetimerstarts{$cid}{$item};
5945: }
5946: }
5947: $firstaccchk{$cid} = 1;
5948: }
5949: unless ($timerintchk{$cid}) {
5950: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5951: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5952: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5953: $coursetimerintervals{$cid}{$item};
5954: }
5955: }
5956: $timerintchk{$cid} = 1;
5957: }
5958: }
5959:
5960: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
5961: \%allroles, \%allgroups);
5962: $env{'user.adv'} = $userroles{'user.adv'};
5963: $env{'user.rar'} = $userroles{'user.rar'};
5964:
5965: return (\%userroles,\%firstaccenv,\%timerintenv);
5966: }
5967:
5968: sub set_arearole {
5969: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5970: unless ($nolog) {
5971: # log the associated role with the area
5972: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5973: }
5974: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
5975: }
5976:
5977: sub custom_roleprivs {
5978: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5979: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
5980: my $homsvr = &homeserver($rauthor,$rdomain);
5981: if (&hostname($homsvr) ne '') {
5982: my ($rdummy,$roledef)=
5983: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5984: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5985: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5986: if (defined($syspriv)) {
5987: if ($trest =~ /^$match_community$/) {
5988: $syspriv =~ s/bre\&S//;
5989: }
5990: $$allroles{'cm./'}.=':'.$syspriv;
5991: $$allroles{$spec.'./'}.=':'.$syspriv;
5992: }
5993: if ($tdomain ne '') {
5994: if (defined($dompriv)) {
5995: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5996: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5997: }
5998: if (($trest ne '') && (defined($coursepriv))) {
5999: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6000: my $rolename = $1;
6001: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6002: }
6003: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6004: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6005: }
6006: }
6007: }
6008: }
6009: }
6010:
6011: sub course_adhocrole_privs {
6012: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6013: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6014: if ($overrides{"internal.adhocpriv.$rolename"}) {
6015: my (%currprivs,%storeprivs);
6016: foreach my $item (split(/:/,$coursepriv)) {
6017: my ($priv,$restrict) = split(/\&/,$item);
6018: $currprivs{$priv} = $restrict;
6019: }
6020: my (%possadd,%possremove,%full);
6021: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6022: my ($priv,$restrict)=split(/\&/,$item);
6023: $full{$priv} = $restrict;
6024: }
6025: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6026: next if ($item eq '');
6027: my ($rule,$rest) = split(/=/,$item);
6028: next unless (($rule eq 'off') || ($rule eq 'on'));
6029: foreach my $priv (split(/:/,$rest)) {
6030: if ($priv ne '') {
6031: if ($rule eq 'off') {
6032: $possremove{$priv} = 1;
6033: } else {
6034: $possadd{$priv} = 1;
6035: }
6036: }
6037: }
6038: }
6039: foreach my $priv (sort(keys(%full))) {
6040: if (exists($currprivs{$priv})) {
6041: unless (exists($possremove{$priv})) {
6042: $storeprivs{$priv} = $currprivs{$priv};
6043: }
6044: } elsif (exists($possadd{$priv})) {
6045: $storeprivs{$priv} = $full{$priv};
6046: }
6047: }
6048: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6049: }
6050: return $coursepriv;
6051: }
6052:
6053: sub group_roleprivs {
6054: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6055: my $access = 1;
6056: my $now = time;
6057: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6058: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6059: if ($access) {
6060: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
6061: $$allgroups{$course}{$group} .=':'.$group_privs;
6062: }
6063: }
6064:
6065: sub standard_roleprivs {
6066: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6067: if (defined($pr{$trole.':s'})) {
6068: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6069: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6070: }
6071: if ($tdomain ne '') {
6072: if (defined($pr{$trole.':d'})) {
6073: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6074: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6075: }
6076: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6077: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6078: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6079: }
6080: }
6081: }
6082:
6083: sub set_userprivs {
6084: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
6085: my $author=0;
6086: my $adv=0;
6087: my $rar=0;
6088: my %grouproles = ();
6089: if (keys(%{$allgroups}) > 0) {
6090: my @groupkeys;
6091: foreach my $role (keys(%{$allroles})) {
6092: push(@groupkeys,$role);
6093: }
6094: if (ref($groups_roles) eq 'HASH') {
6095: foreach my $key (keys(%{$groups_roles})) {
6096: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6097: push(@groupkeys,$key);
6098: }
6099: }
6100: }
6101: if (@groupkeys > 0) {
6102: foreach my $role (@groupkeys) {
6103: my ($trole,$area,$sec,$extendedarea);
6104: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6105: $trole = $1;
6106: $area = $2;
6107: $sec = $3;
6108: $extendedarea = $area.$sec;
6109: if (exists($$allgroups{$area})) {
6110: foreach my $group (keys(%{$$allgroups{$area}})) {
6111: my $spec = $trole.'.'.$extendedarea;
6112: $grouproles{$spec.'.'.$area.'/'.$group} =
6113: $$allgroups{$area}{$group};
6114: }
6115: }
6116: }
6117: }
6118: }
6119: }
6120: foreach my $group (keys(%grouproles)) {
6121: $$allroles{$group} = $grouproles{$group};
6122: }
6123: foreach my $role (keys(%{$allroles})) {
6124: my %thesepriv;
6125: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
6126: foreach my $item (split(/:/,$$allroles{$role})) {
6127: if ($item ne '') {
6128: my ($privilege,$restrictions)=split(/&/,$item);
6129: if ($restrictions eq '') {
6130: $thesepriv{$privilege}='F';
6131: } elsif ($thesepriv{$privilege} ne 'F') {
6132: $thesepriv{$privilege}.=$restrictions;
6133: }
6134: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
6135: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
6136: }
6137: }
6138: my $thesestr='';
6139: foreach my $priv (sort(keys(%thesepriv))) {
6140: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6141: }
6142: $userroles->{'user.priv.'.$role} = $thesestr;
6143: }
6144: return ($author,$adv,$rar);
6145: }
6146:
6147: sub role_status {
6148: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
6149: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
6150: my ($one,$two) = split(m{\./},$rolekey,2);
6151: (undef,undef,$$role) = split(/\./,$one,3);
6152: unless (!defined($$role) || $$role eq '') {
6153: $$where = '/'.$two;
6154: $$trolecode=$$role.'.'.$$where;
6155: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6156: $$tstatus='is';
6157: if ($$tstart && $$tstart>$update) {
6158: $$tstatus='future';
6159: if ($$tstart<$now) {
6160: if ($$tstart && $$tstart>$refresh) {
6161: if (($$where ne '') && ($$role ne '')) {
6162: my (%allroles,%allgroups,$group_privs,
6163: %groups_roles,@rolecodes);
6164: my %userroles = (
6165: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6166: );
6167: @rolecodes = ('cm');
6168: my $spec=$$role.'.'.$$where;
6169: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6170: if ($$role =~ /^cr\//) {
6171: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
6172: push(@rolecodes,'cr');
6173: } elsif ($$role eq 'gr') {
6174: push(@rolecodes,$$role);
6175: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6176: $env{'user.name'});
6177: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
6178: (undef,my $group_privs) = split(/\//,$trole);
6179: $group_privs = &unescape($group_privs);
6180: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
6181: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
6182: &get_groups_roles($tdomain,$trest,
6183: \%course_roles,\@rolecodes,
6184: \%groups_roles);
6185: } else {
6186: push(@rolecodes,$$role);
6187: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6188: }
6189: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6190: \%groups_roles);
6191: &appenv(\%userroles,\@rolecodes);
6192: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
6193: }
6194: }
6195: $$tstatus = 'is';
6196: }
6197: }
6198: if ($$tend) {
6199: if ($$tend<$update) {
6200: $$tstatus='expired';
6201: } elsif ($$tend<$now) {
6202: $$tstatus='will_not';
6203: }
6204: }
6205: }
6206: }
6207: }
6208:
6209: sub get_groups_roles {
6210: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6211: return unless((ref($cdom_courseroles) eq 'HASH') &&
6212: (ref($rolecodes) eq 'ARRAY') &&
6213: (ref($groups_roles) eq 'HASH'));
6214: if (keys(%{$cdom_courseroles}) > 0) {
6215: my ($cnum) = ($rest =~ /^($match_courseid)/);
6216: if ($cdom ne '' && $cnum ne '') {
6217: foreach my $key (keys(%{$cdom_courseroles})) {
6218: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6219: my $crsrole = $1;
6220: my $crssec = $2;
6221: if ($crsrole =~ /^cr/) {
6222: unless (grep(/^cr$/,@{$rolecodes})) {
6223: push(@{$rolecodes},'cr');
6224: }
6225: } else {
6226: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6227: push(@{$rolecodes},$crsrole);
6228: }
6229: }
6230: my $rolekey = "$crsrole./$cdom/$cnum";
6231: if ($crssec ne '') {
6232: $rolekey .= "/$crssec";
6233: }
6234: $rolekey .= './';
6235: $groups_roles->{$rolekey} = $rolecodes;
6236: }
6237: }
6238: }
6239: }
6240: return;
6241: }
6242:
6243: sub delete_env_groupprivs {
6244: my ($where,$courseroles,$possroles) = @_;
6245: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6246: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6247: unless (ref($courseroles->{$udom}) eq 'HASH') {
6248: %{$courseroles->{$udom}} =
6249: &get_my_roles('','','userroles',['active'],
6250: $possroles,[$udom],1);
6251: }
6252: if (ref($courseroles->{$udom}) eq 'HASH') {
6253: foreach my $item (keys(%{$courseroles->{$udom}})) {
6254: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6255: my $area = '/'.$cdom.'/'.$cnum;
6256: my $privkey = "user.priv.$crsrole.$area";
6257: if ($crssec ne '') {
6258: $privkey .= '/'.$crssec;
6259: }
6260: $privkey .= ".$area/$group";
6261: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6262: }
6263: }
6264: return;
6265: }
6266:
6267: sub check_adhoc_privs {
6268: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
6269: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
6270: if ($sec) {
6271: $cckey .= '/'.$sec;
6272: }
6273: my $setprivs;
6274: if ($env{$cckey}) {
6275: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
6276: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
6277: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
6278: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
6279: $setprivs = 1;
6280: }
6281: } else {
6282: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
6283: $setprivs = 1;
6284: }
6285: return $setprivs;
6286: }
6287:
6288: sub set_adhoc_privileges {
6289: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
6290: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
6291: my $area = '/'.$dcdom.'/'.$pickedcourse;
6292: if ($sec ne '') {
6293: $area .= '/'.$sec;
6294: }
6295: my $spec = $role.'.'.$area;
6296: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
6297: $env{'user.name'},1);
6298: my %rolehash = ();
6299: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6300: my $rolename = $1;
6301: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
6302: my %domdef = &get_domain_defaults($dcdom);
6303: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6304: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6305: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6306: }
6307: }
6308: } else {
6309: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6310: }
6311: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
6312: &appenv(\%userroles,[$role,'cm']);
6313: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
6314: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
6315: &appenv( {'request.role' => $spec,
6316: 'request.role.domain' => $dcdom,
6317: 'request.course.sec' => $sec,
6318: }
6319: );
6320: my $tadv=0;
6321: if (&allowed('adv') eq 'F') { $tadv=1; }
6322: &appenv({'request.role.adv' => $tadv});
6323: }
6324: }
6325:
6326: # --------------------------------------------------------------- get interface
6327:
6328: sub get {
6329: my ($namespace,$storearr,$udomain,$uname)=@_;
6330: my $items='';
6331: foreach my $item (@$storearr) {
6332: $items.=&escape($item).'&';
6333: }
6334: $items=~s/\&$//;
6335: if (!$udomain) { $udomain=$env{'user.domain'}; }
6336: if (!$uname) { $uname=$env{'user.name'}; }
6337: my $uhome=&homeserver($uname,$udomain);
6338:
6339: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
6340: my @pairs=split(/\&/,$rep);
6341: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6342: return @pairs;
6343: }
6344: my %returnhash=();
6345: my $i=0;
6346: foreach my $item (@$storearr) {
6347: $returnhash{$item}=&thaw_unescape($pairs[$i]);
6348: $i++;
6349: }
6350: return %returnhash;
6351: }
6352:
6353: # --------------------------------------------------------------- del interface
6354:
6355: sub del {
6356: my ($namespace,$storearr,$udomain,$uname)=@_;
6357: my $items='';
6358: foreach my $item (@$storearr) {
6359: $items.=&escape($item).'&';
6360: }
6361:
6362: $items=~s/\&$//;
6363: if (!$udomain) { $udomain=$env{'user.domain'}; }
6364: if (!$uname) { $uname=$env{'user.name'}; }
6365: my $uhome=&homeserver($uname,$udomain);
6366: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
6367: }
6368:
6369: # -------------------------------------------------------------- dump interface
6370:
6371: sub unserialize {
6372: my ($rep, $escapedkeys) = @_;
6373:
6374: return {} if $rep =~ /^error/;
6375:
6376: my %returnhash=();
6377: foreach my $item (split(/\&/,$rep)) {
6378: my ($key, $value) = split(/=/, $item, 2);
6379: $key = unescape($key) unless $escapedkeys;
6380: next if $key =~ /^error: 2 /;
6381: $returnhash{$key} = &thaw_unescape($value);
6382: }
6383: #return %returnhash;
6384: return \%returnhash;
6385: }
6386:
6387: # see Lond::dump_with_regexp
6388: # if $escapedkeys hash keys won't get unescaped.
6389: sub dump {
6390: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
6391: if (!$udomain) { $udomain=$env{'user.domain'}; }
6392: if (!$uname) { $uname=$env{'user.name'}; }
6393: my $uhome=&homeserver($uname,$udomain);
6394:
6395: if ($regexp) {
6396: $regexp=&escape($regexp);
6397: } else {
6398: $regexp='.';
6399: }
6400: if (grep { $_ eq $uhome } current_machine_ids()) {
6401: # user is hosted on this machine
6402: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
6403: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
6404: return %{unserialize($reply, $escapedkeys)};
6405: }
6406: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
6407: my @pairs=split(/\&/,$rep);
6408: my %returnhash=();
6409: if (!($rep =~ /^error/ )) {
6410: foreach my $item (@pairs) {
6411: my ($key,$value)=split(/=/,$item,2);
6412: $key = unescape($key) unless $escapedkeys;
6413: #$key = &unescape($key);
6414: next if ($key =~ /^error: 2 /);
6415: $returnhash{$key}=&thaw_unescape($value);
6416: }
6417: }
6418: return %returnhash;
6419: }
6420:
6421:
6422: # --------------------------------------------------------- dumpstore interface
6423:
6424: sub dumpstore {
6425: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
6426: # same as dump but keys must be escaped. They may contain colon separated
6427: # lists of values that may themself contain colons (e.g. symbs).
6428: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
6429: }
6430:
6431: # -------------------------------------------------------------- keys interface
6432:
6433: sub getkeys {
6434: my ($namespace,$udomain,$uname)=@_;
6435: if (!$udomain) { $udomain=$env{'user.domain'}; }
6436: if (!$uname) { $uname=$env{'user.name'}; }
6437: my $uhome=&homeserver($uname,$udomain);
6438: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6439: my @keyarray=();
6440: foreach my $key (split(/\&/,$rep)) {
6441: next if ($key =~ /^error: 2 /);
6442: push(@keyarray,&unescape($key));
6443: }
6444: return @keyarray;
6445: }
6446:
6447: # --------------------------------------------------------------- currentdump
6448: sub currentdump {
6449: my ($courseid,$sdom,$sname)=@_;
6450: $courseid = $env{'request.course.id'} if (! defined($courseid));
6451: $sdom = $env{'user.domain'} if (! defined($sdom));
6452: $sname = $env{'user.name'} if (! defined($sname));
6453: my $uhome = &homeserver($sname,$sdom);
6454: my $rep;
6455:
6456: if (grep { $_ eq $uhome } current_machine_ids()) {
6457: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6458: $courseid)));
6459: } else {
6460: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6461: }
6462:
6463: return if ($rep =~ /^(error:|no_such_host)/);
6464: #
6465: my %returnhash=();
6466: #
6467: if ($rep eq 'unknown_cmd') {
6468: # an old lond will not know currentdump
6469: # Do a dump and make it look like a currentdump
6470: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
6471: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6472: my %hash = @tmp;
6473: @tmp=();
6474: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
6475: } else {
6476: my @pairs=split(/\&/,$rep);
6477: foreach my $pair (@pairs) {
6478: my ($key,$value)=split(/=/,$pair,2);
6479: my ($symb,$param) = split(/:/,$key);
6480: $returnhash{&unescape($symb)}->{&unescape($param)} =
6481: &thaw_unescape($value);
6482: }
6483: }
6484: return %returnhash;
6485: }
6486:
6487: sub convert_dump_to_currentdump{
6488: my %hash = %{shift()};
6489: my %returnhash;
6490: # Code ripped from lond, essentially. The only difference
6491: # here is the unescaping done by lonnet::dump(). Conceivably
6492: # we might run in to problems with parameter names =~ /^v\./
6493: while (my ($key,$value) = each(%hash)) {
6494: my ($v,$symb,$param) = split(/:/,$key);
6495: $symb = &unescape($symb);
6496: $param = &unescape($param);
6497: next if ($v eq 'version' || $symb eq 'keys');
6498: next if (exists($returnhash{$symb}) &&
6499: exists($returnhash{$symb}->{$param}) &&
6500: $returnhash{$symb}->{'v.'.$param} > $v);
6501: $returnhash{$symb}->{$param}=$value;
6502: $returnhash{$symb}->{'v.'.$param}=$v;
6503: }
6504: #
6505: # Remove all of the keys in the hashes which keep track of
6506: # the version of the parameter.
6507: while (my ($symb,$param_hash) = each(%returnhash)) {
6508: # use a foreach because we are going to delete from the hash.
6509: foreach my $key (keys(%$param_hash)) {
6510: delete($param_hash->{$key}) if ($key =~ /^v\./);
6511: }
6512: }
6513: return \%returnhash;
6514: }
6515:
6516: # ------------------------------------------------------ critical inc interface
6517:
6518: sub cinc {
6519: return &inc(@_,'critical');
6520: }
6521:
6522: # --------------------------------------------------------------- inc interface
6523:
6524: sub inc {
6525: my ($namespace,$store,$udomain,$uname,$critical) = @_;
6526: if (!$udomain) { $udomain=$env{'user.domain'}; }
6527: if (!$uname) { $uname=$env{'user.name'}; }
6528: my $uhome=&homeserver($uname,$udomain);
6529: my $items='';
6530: if (! ref($store)) {
6531: # got a single value, so use that instead
6532: $items = &escape($store).'=&';
6533: } elsif (ref($store) eq 'SCALAR') {
6534: $items = &escape($$store).'=&';
6535: } elsif (ref($store) eq 'ARRAY') {
6536: $items = join('=&',map {&escape($_);} @{$store});
6537: } elsif (ref($store) eq 'HASH') {
6538: while (my($key,$value) = each(%{$store})) {
6539: $items.= &escape($key).'='.&escape($value).'&';
6540: }
6541: }
6542: $items=~s/\&$//;
6543: if ($critical) {
6544: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
6545: } else {
6546: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
6547: }
6548: }
6549:
6550: # --------------------------------------------------------------- put interface
6551:
6552: sub put {
6553: my ($namespace,$storehash,$udomain,$uname)=@_;
6554: if (!$udomain) { $udomain=$env{'user.domain'}; }
6555: if (!$uname) { $uname=$env{'user.name'}; }
6556: my $uhome=&homeserver($uname,$udomain);
6557: my $items='';
6558: foreach my $item (keys(%$storehash)) {
6559: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
6560: }
6561: $items=~s/\&$//;
6562: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
6563: }
6564:
6565: # ------------------------------------------------------------ newput interface
6566:
6567: sub newput {
6568: my ($namespace,$storehash,$udomain,$uname)=@_;
6569: if (!$udomain) { $udomain=$env{'user.domain'}; }
6570: if (!$uname) { $uname=$env{'user.name'}; }
6571: my $uhome=&homeserver($uname,$udomain);
6572: my $items='';
6573: foreach my $key (keys(%$storehash)) {
6574: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6575: }
6576: $items=~s/\&$//;
6577: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
6578: }
6579:
6580: # --------------------------------------------------------- putstore interface
6581:
6582: sub putstore {
6583: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
6584: if (!$udomain) { $udomain=$env{'user.domain'}; }
6585: if (!$uname) { $uname=$env{'user.name'}; }
6586: my $uhome=&homeserver($uname,$udomain);
6587: my $items='';
6588: foreach my $key (keys(%$storehash)) {
6589: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6590: }
6591: $items=~s/\&$//;
6592: my $esc_symb=&escape($symb);
6593: my $esc_v=&escape($version);
6594: my $reply =
6595: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
6596: $uhome);
6597: if (($tolog) && ($reply eq 'ok')) {
6598: my $namevalue='';
6599: foreach my $key (keys(%{$storehash})) {
6600: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6601: }
6602: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
6603: '&host='.&escape($perlvar{'lonHostID'}).
6604: '&version='.$esc_v.
6605: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
6606: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
6607: }
6608: if ($reply eq 'unknown_cmd') {
6609: # gfall back to way things use to be done
6610: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
6611: $uname);
6612: }
6613: return $reply;
6614: }
6615:
6616: sub old_putstore {
6617: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
6618: if (!$udomain) { $udomain=$env{'user.domain'}; }
6619: if (!$uname) { $uname=$env{'user.name'}; }
6620: my $uhome=&homeserver($uname,$udomain);
6621: my %newstorehash;
6622: foreach my $item (keys(%$storehash)) {
6623: my $key = $version.':'.&escape($symb).':'.$item;
6624: $newstorehash{$key} = $storehash->{$item};
6625: }
6626: my $items='';
6627: my %allitems = ();
6628: foreach my $item (keys(%newstorehash)) {
6629: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
6630: my $key = $1.':keys:'.$2;
6631: $allitems{$key} .= $3.':';
6632: }
6633: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
6634: }
6635: foreach my $item (keys(%allitems)) {
6636: $allitems{$item} =~ s/\:$//;
6637: $items.= $item.'='.$allitems{$item}.'&';
6638: }
6639: $items=~s/\&$//;
6640: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
6641: }
6642:
6643: # ------------------------------------------------------ critical put interface
6644:
6645: sub cput {
6646: my ($namespace,$storehash,$udomain,$uname)=@_;
6647: if (!$udomain) { $udomain=$env{'user.domain'}; }
6648: if (!$uname) { $uname=$env{'user.name'}; }
6649: my $uhome=&homeserver($uname,$udomain);
6650: my $items='';
6651: foreach my $item (keys(%$storehash)) {
6652: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
6653: }
6654: $items=~s/\&$//;
6655: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
6656: }
6657:
6658: # -------------------------------------------------------------- eget interface
6659:
6660: sub eget {
6661: my ($namespace,$storearr,$udomain,$uname)=@_;
6662: my $items='';
6663: foreach my $item (@$storearr) {
6664: $items.=&escape($item).'&';
6665: }
6666: $items=~s/\&$//;
6667: if (!$udomain) { $udomain=$env{'user.domain'}; }
6668: if (!$uname) { $uname=$env{'user.name'}; }
6669: my $uhome=&homeserver($uname,$udomain);
6670: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
6671: my @pairs=split(/\&/,$rep);
6672: my %returnhash=();
6673: my $i=0;
6674: foreach my $item (@$storearr) {
6675: $returnhash{$item}=&thaw_unescape($pairs[$i]);
6676: $i++;
6677: }
6678: return %returnhash;
6679: }
6680:
6681: # ------------------------------------------------------------ tmpput interface
6682: sub tmpput {
6683: my ($storehash,$server,$context)=@_;
6684: my $items='';
6685: foreach my $item (keys(%$storehash)) {
6686: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
6687: }
6688: $items=~s/\&$//;
6689: if (defined($context)) {
6690: $items .= ':'.&escape($context);
6691: }
6692: return &reply("tmpput:$items",$server);
6693: }
6694:
6695: # ------------------------------------------------------------ tmpget interface
6696: sub tmpget {
6697: my ($token,$server)=@_;
6698: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6699: my $rep=&reply("tmpget:$token",$server);
6700: my %returnhash;
6701: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
6702: return %returnhash;
6703: }
6704: foreach my $item (split(/\&/,$rep)) {
6705: my ($key,$value)=split(/=/,$item);
6706: $returnhash{&unescape($key)}=&thaw_unescape($value);
6707: }
6708: return %returnhash;
6709: }
6710:
6711: # ------------------------------------------------------------ tmpdel interface
6712: sub tmpdel {
6713: my ($token,$server)=@_;
6714: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6715: return &reply("tmpdel:$token",$server);
6716: }
6717:
6718: # ------------------------------------------------------------ get_timebased_id
6719:
6720: sub get_timebased_id {
6721: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6722: $maxtries) = @_;
6723: my ($newid,$error,$dellock);
6724: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6725: return ('','ok','invalid call to get suffix');
6726: }
6727:
6728: # set defaults for any optional args for which values were not supplied
6729: if ($who eq '') {
6730: $who = $env{'user.name'}.':'.$env{'user.domain'};
6731: }
6732: if (!$locktries) {
6733: $locktries = 3;
6734: }
6735: if (!$maxtries) {
6736: $maxtries = 10;
6737: }
6738:
6739: if (($cdom eq '') || ($cnum eq '')) {
6740: if ($env{'request.course.id'}) {
6741: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6742: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6743: }
6744: if (($cdom eq '') || ($cnum eq '')) {
6745: return ('','ok','call to get suffix not in course context');
6746: }
6747: }
6748:
6749: # construct locking item
6750: my $lockhash = {
6751: $prefix."\0".'locked_'.$keyid => $who,
6752: };
6753: my $tries = 0;
6754:
6755: # attempt to get lock on nohist_$namespace file
6756: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6757: while (($gotlock ne 'ok') && $tries <$locktries) {
6758: $tries ++;
6759: sleep 1;
6760: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6761: }
6762:
6763: # attempt to get unique identifier, based on current timestamp
6764: if ($gotlock eq 'ok') {
6765: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6766: my $id = time;
6767: $newid = $id;
6768: if ($idtype eq 'addcode') {
6769: $newid .= &sixnum_code();
6770: }
6771: my $idtries = 0;
6772: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6773: if ($idtype eq 'concat') {
6774: $newid = $id.$idtries;
6775: } elsif ($idtype eq 'addcode') {
6776: $newid = $newid.&sixnum_code();
6777: } else {
6778: $newid ++;
6779: }
6780: $idtries ++;
6781: }
6782: if (!exists($inuse{$prefix."\0".$newid})) {
6783: my %new_item = (
6784: $prefix."\0".$newid => $who,
6785: );
6786: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6787: $cdom,$cnum);
6788: if ($putresult ne 'ok') {
6789: undef($newid);
6790: $error = 'error saving new item: '.$putresult;
6791: }
6792: } else {
6793: undef($newid);
6794: $error = ('error: no unique suffix available for the new item ');
6795: }
6796: # remove lock
6797: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6798: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6799: } else {
6800: $error = "error: could not obtain lockfile\n";
6801: $dellock = 'ok';
6802: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6803: $dellock = 'nolock';
6804: }
6805: }
6806: return ($newid,$dellock,$error);
6807: }
6808:
6809: sub sixnum_code {
6810: my $code;
6811: for (0..6) {
6812: $code .= int( rand(9) );
6813: }
6814: return $code;
6815: }
6816:
6817: # -------------------------------------------------- portfolio access checking
6818:
6819: sub portfolio_access {
6820: my ($requrl,$clientip) = @_;
6821: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
6822: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
6823: if ($result) {
6824: my %setters;
6825: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6826: my ($startblock,$endblock) =
6827: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6828: if ($startblock && $endblock) {
6829: return 'B';
6830: }
6831: } else {
6832: my ($startblock,$endblock) =
6833: &Apache::loncommon::blockcheck(\%setters,'port');
6834: if ($startblock && $endblock) {
6835: return 'B';
6836: }
6837: }
6838: }
6839: if ($result eq 'ok') {
6840: return 'F';
6841: } elsif ($result =~ /^[^:]+:guest_/) {
6842: return 'A';
6843: }
6844: return '';
6845: }
6846:
6847: sub get_portfolio_access {
6848: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
6849:
6850: if (!ref($access_hash)) {
6851: my $current_perms = &get_portfile_permissions($udom,$unum);
6852: my %access_controls = &get_access_controls($current_perms,$group,
6853: $file_name);
6854: $access_hash = $access_controls{$file_name};
6855: }
6856:
6857: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
6858: my $now = time;
6859: if (ref($access_hash) eq 'HASH') {
6860: foreach my $key (keys(%{$access_hash})) {
6861: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6862: if ($start > $now) {
6863: next;
6864: }
6865: if ($end && $end<$now) {
6866: next;
6867: }
6868: if ($scope eq 'public') {
6869: $public = $key;
6870: last;
6871: } elsif ($scope eq 'guest') {
6872: $guest = $key;
6873: } elsif ($scope eq 'domains') {
6874: push(@domains,$key);
6875: } elsif ($scope eq 'users') {
6876: push(@users,$key);
6877: } elsif ($scope eq 'course') {
6878: push(@courses,$key);
6879: } elsif ($scope eq 'group') {
6880: push(@groups,$key);
6881: } elsif ($scope eq 'ip') {
6882: push(@ips,$key);
6883: }
6884: }
6885: if ($public) {
6886: return 'ok';
6887: } elsif (@ips > 0) {
6888: my $allowed;
6889: foreach my $ipkey (@ips) {
6890: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6891: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6892: $allowed = 1;
6893: last;
6894: }
6895: }
6896: }
6897: if ($allowed) {
6898: return 'ok';
6899: }
6900: }
6901: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6902: if ($guest) {
6903: return $guest;
6904: }
6905: } else {
6906: if (@domains > 0) {
6907: foreach my $domkey (@domains) {
6908: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6909: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6910: return 'ok';
6911: }
6912: }
6913: }
6914: }
6915: if (@users > 0) {
6916: foreach my $userkey (@users) {
6917: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6918: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6919: if (ref($item) eq 'HASH') {
6920: if (($item->{'uname'} eq $env{'user.name'}) &&
6921: ($item->{'udom'} eq $env{'user.domain'})) {
6922: return 'ok';
6923: }
6924: }
6925: }
6926: }
6927: }
6928: }
6929: my %roleshash;
6930: my @courses_and_groups = @courses;
6931: push(@courses_and_groups,@groups);
6932: if (@courses_and_groups > 0) {
6933: my (%allgroups,%allroles);
6934: my ($start,$end,$role,$sec,$group);
6935: foreach my $envkey (%env) {
6936: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
6937: my $cid = $2.'_'.$3;
6938: if ($1 eq 'gr') {
6939: $group = $4;
6940: $allgroups{$cid}{$group} = $env{$envkey};
6941: } else {
6942: if ($4 eq '') {
6943: $sec = 'none';
6944: } else {
6945: $sec = $4;
6946: }
6947: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6948: }
6949: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
6950: my $cid = $2.'_'.$3;
6951: if ($4 eq '') {
6952: $sec = 'none';
6953: } else {
6954: $sec = $4;
6955: }
6956: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6957: }
6958: }
6959: if (keys(%allroles) == 0) {
6960: return;
6961: }
6962: foreach my $key (@courses_and_groups) {
6963: my %content = %{$$access_hash{$key}};
6964: my $cnum = $content{'number'};
6965: my $cdom = $content{'domain'};
6966: my $cid = $cdom.'_'.$cnum;
6967: if (!exists($allroles{$cid})) {
6968: next;
6969: }
6970: foreach my $role_id (keys(%{$content{'roles'}})) {
6971: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6972: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6973: my @status = @{$content{'roles'}{$role_id}{'access'}};
6974: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6975: foreach my $role (keys(%{$allroles{$cid}})) {
6976: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6977: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6978: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6979: if (grep/^all$/,@sections) {
6980: return 'ok';
6981: } else {
6982: if (grep/^$sec$/,@sections) {
6983: return 'ok';
6984: }
6985: }
6986: }
6987: }
6988: if (keys(%{$allgroups{$cid}}) == 0) {
6989: if (grep/^none$/,@groups) {
6990: return 'ok';
6991: }
6992: } else {
6993: if (grep/^all$/,@groups) {
6994: return 'ok';
6995: }
6996: foreach my $group (keys(%{$allgroups{$cid}})) {
6997: if (grep/^$group$/,@groups) {
6998: return 'ok';
6999: }
7000: }
7001: }
7002: }
7003: }
7004: }
7005: }
7006: }
7007: if ($guest) {
7008: return $guest;
7009: }
7010: }
7011: }
7012: return;
7013: }
7014:
7015: sub course_group_datechecker {
7016: my ($dates,$now,$status) = @_;
7017: my ($start,$end) = split(/\./,$dates);
7018: if (!$start && !$end) {
7019: return 'ok';
7020: }
7021: if (grep/^active$/,@{$status}) {
7022: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7023: return 'ok';
7024: }
7025: }
7026: if (grep/^previous$/,@{$status}) {
7027: if ($end > $now ) {
7028: return 'ok';
7029: }
7030: }
7031: if (grep/^future$/,@{$status}) {
7032: if ($start > $now) {
7033: return 'ok';
7034: }
7035: }
7036: return;
7037: }
7038:
7039: sub parse_portfolio_url {
7040: my ($url) = @_;
7041:
7042: my ($type,$udom,$unum,$group,$file_name);
7043:
7044: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
7045: $type = 1;
7046: $udom = $1;
7047: $unum = $2;
7048: $file_name = $3;
7049: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
7050: $type = 2;
7051: $udom = $1;
7052: $unum = $2;
7053: $group = $3;
7054: $file_name = $3.'/'.$4;
7055: }
7056: if (wantarray) {
7057: return ($type,$udom,$unum,$file_name,$group);
7058: }
7059: return $type;
7060: }
7061:
7062: sub is_portfolio_url {
7063: my ($url) = @_;
7064: return scalar(&parse_portfolio_url($url));
7065: }
7066:
7067: sub is_portfolio_file {
7068: my ($file) = @_;
7069: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
7070: return 1;
7071: }
7072: return;
7073: }
7074:
7075: sub usertools_access {
7076: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
7077: my ($access,%tools);
7078: if ($context eq '') {
7079: $context = 'tools';
7080: }
7081: if ($context eq 'requestcourses') {
7082: %tools = (
7083: official => 1,
7084: unofficial => 1,
7085: community => 1,
7086: textbook => 1,
7087: placement => 1,
7088: );
7089: } elsif ($context eq 'requestauthor') {
7090: %tools = (
7091: requestauthor => 1,
7092: );
7093: } else {
7094: %tools = (
7095: aboutme => 1,
7096: blog => 1,
7097: webdav => 1,
7098: portfolio => 1,
7099: );
7100: }
7101: return if (!defined($tools{$tool}));
7102:
7103: if (($udom eq '') || ($uname eq '')) {
7104: $udom = $env{'user.domain'};
7105: $uname = $env{'user.name'};
7106: }
7107:
7108: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7109: if ($action ne 'reload') {
7110: if ($context eq 'requestcourses') {
7111: return $env{'environment.canrequest.'.$tool};
7112: } elsif ($context eq 'requestauthor') {
7113: return $env{'environment.canrequest.author'};
7114: } else {
7115: return $env{'environment.availabletools.'.$tool};
7116: }
7117: }
7118: }
7119:
7120: my ($toolstatus,$inststatus,$envkey);
7121: if ($context eq 'requestauthor') {
7122: $envkey = $context;
7123: } else {
7124: $envkey = $context.'.'.$tool;
7125: }
7126:
7127: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7128: ($action ne 'reload')) {
7129: $toolstatus = $env{'environment.'.$envkey};
7130: $inststatus = $env{'environment.inststatus'};
7131: } else {
7132: if (ref($userenvref) eq 'HASH') {
7133: $toolstatus = $userenvref->{$envkey};
7134: $inststatus = $userenvref->{'inststatus'};
7135: } else {
7136: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7137: $toolstatus = $userenv{$envkey};
7138: $inststatus = $userenv{'inststatus'};
7139: }
7140: }
7141:
7142: if ($toolstatus ne '') {
7143: if ($toolstatus) {
7144: $access = 1;
7145: } else {
7146: $access = 0;
7147: }
7148: return $access;
7149: }
7150:
7151: my ($is_adv,%domdef);
7152: if (ref($is_advref) eq 'HASH') {
7153: $is_adv = $is_advref->{'is_adv'};
7154: } else {
7155: $is_adv = &is_advanced_user($udom,$uname);
7156: }
7157: if (ref($domdefref) eq 'HASH') {
7158: %domdef = %{$domdefref};
7159: } else {
7160: %domdef = &get_domain_defaults($udom);
7161: }
7162: if (ref($domdef{$tool}) eq 'HASH') {
7163: if ($is_adv) {
7164: if ($domdef{$tool}{'_LC_adv'} ne '') {
7165: if ($domdef{$tool}{'_LC_adv'}) {
7166: $access = 1;
7167: } else {
7168: $access = 0;
7169: }
7170: return $access;
7171: }
7172: }
7173: if ($inststatus ne '') {
7174: my ($hasaccess,$hasnoaccess);
7175: foreach my $affiliation (split(/:/,$inststatus)) {
7176: if ($domdef{$tool}{$affiliation} ne '') {
7177: if ($domdef{$tool}{$affiliation}) {
7178: $hasaccess = 1;
7179: } else {
7180: $hasnoaccess = 1;
7181: }
7182: }
7183: }
7184: if ($hasaccess || $hasnoaccess) {
7185: if ($hasaccess) {
7186: $access = 1;
7187: } elsif ($hasnoaccess) {
7188: $access = 0;
7189: }
7190: return $access;
7191: }
7192: } else {
7193: if ($domdef{$tool}{'default'} ne '') {
7194: if ($domdef{$tool}{'default'}) {
7195: $access = 1;
7196: } elsif ($domdef{$tool}{'default'} == 0) {
7197: $access = 0;
7198: }
7199: return $access;
7200: }
7201: }
7202: } else {
7203: if (($context eq 'tools') && ($tool ne 'webdav')) {
7204: $access = 1;
7205: } else {
7206: $access = 0;
7207: }
7208: return $access;
7209: }
7210: }
7211:
7212: sub is_course_owner {
7213: my ($cdom,$cnum,$udom,$uname) = @_;
7214: if (($udom eq '') || ($uname eq '')) {
7215: $udom = $env{'user.domain'};
7216: $uname = $env{'user.name'};
7217: }
7218: unless (($udom eq '') || ($uname eq '')) {
7219: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7220: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7221: return 1;
7222: } else {
7223: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7224: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7225: return 1;
7226: }
7227: }
7228: }
7229: }
7230: return;
7231: }
7232:
7233: sub is_advanced_user {
7234: my ($udom,$uname) = @_;
7235: if ($udom ne '' && $uname ne '') {
7236: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7237: if (wantarray) {
7238: return ($env{'user.adv'},$env{'user.author'});
7239: } else {
7240: return $env{'user.adv'};
7241: }
7242: }
7243: }
7244: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7245: my %allroles;
7246: my ($is_adv,$is_author);
7247: foreach my $role (keys(%roleshash)) {
7248: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7249: my $area = '/'.$tdomain.'/'.$trest;
7250: if ($sec ne '') {
7251: $area .= '/'.$sec;
7252: }
7253: if (($area ne '') && ($trole ne '')) {
7254: my $spec=$trole.'.'.$area;
7255: if ($trole =~ /^cr\//) {
7256: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7257: } elsif ($trole ne 'gr') {
7258: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7259: }
7260: if ($trole eq 'au') {
7261: $is_author = 1;
7262: }
7263: }
7264: }
7265: foreach my $role (keys(%allroles)) {
7266: last if ($is_adv);
7267: foreach my $item (split(/:/,$allroles{$role})) {
7268: if ($item ne '') {
7269: my ($privilege,$restrictions)=split(/&/,$item);
7270: if ($privilege eq 'adv') {
7271: $is_adv = 1;
7272: last;
7273: }
7274: }
7275: }
7276: }
7277: if (wantarray) {
7278: return ($is_adv,$is_author);
7279: }
7280: return $is_adv;
7281: }
7282:
7283: sub check_can_request {
7284: my ($dom,$can_request,$request_domains) = @_;
7285: my $canreq = 0;
7286: my ($types,$typename) = &Apache::loncommon::course_types();
7287: my @options = ('approval','validate','autolimit');
7288: my $optregex = join('|',@options);
7289: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7290: foreach my $type (@{$types}) {
7291: if (&usertools_access($env{'user.name'},
7292: $env{'user.domain'},
7293: $type,undef,'requestcourses')) {
7294: $canreq ++;
7295: if (ref($request_domains) eq 'HASH') {
7296: push(@{$request_domains->{$type}},$env{'user.domain'});
7297: }
7298: if ($dom eq $env{'user.domain'}) {
7299: $can_request->{$type} = 1;
7300: }
7301: }
7302: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
7303: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7304: if (@curr > 0) {
7305: foreach my $item (@curr) {
7306: if (ref($request_domains) eq 'HASH') {
7307: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7308: if ($otherdom ne '') {
7309: if (ref($request_domains->{$type}) eq 'ARRAY') {
7310: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7311: push(@{$request_domains->{$type}},$otherdom);
7312: }
7313: } else {
7314: push(@{$request_domains->{$type}},$otherdom);
7315: }
7316: }
7317: }
7318: }
7319: unless($dom eq $env{'user.domain'}) {
7320: $canreq ++;
7321: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7322: $can_request->{$type} = 1;
7323: }
7324: }
7325: }
7326: }
7327: }
7328: }
7329: return $canreq;
7330: }
7331:
7332: # ---------------------------------------------- Custom access rule evaluation
7333:
7334: sub customaccess {
7335: my ($priv,$uri)=@_;
7336: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
7337: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
7338: $udom = &LONCAPA::clean_domain($udom);
7339: $ucrs = &LONCAPA::clean_username($ucrs);
7340: my $access=0;
7341: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
7342: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7343: if ($type eq 'user') {
7344: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7345: my ($tdom,$tuname)=split(m{/},$scope);
7346: if ($tdom) {
7347: if ($tdom ne $env{'user.domain'}) { next; }
7348: }
7349: if ($tuname) {
7350: if ($tuname ne $env{'user.name'}) { next; }
7351: }
7352: $access=($effect eq 'allow');
7353: last;
7354: }
7355: } else {
7356: if ($role) {
7357: if ($role ne $urole) { next; }
7358: }
7359: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7360: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7361: if ($tdom) {
7362: if ($tdom ne $udom) { next; }
7363: }
7364: if ($tcrs) {
7365: if ($tcrs ne $ucrs) { next; }
7366: }
7367: if ($tsec) {
7368: if ($tsec ne $usec) { next; }
7369: }
7370: $access=($effect eq 'allow');
7371: last;
7372: }
7373: if ($realm eq '' && $role eq '') {
7374: $access=($effect eq 'allow');
7375: }
7376: }
7377: }
7378: return $access;
7379: }
7380:
7381: # ------------------------------------------------- Check for a user privilege
7382:
7383: sub allowed {
7384: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
7385: my $ver_orguri=$uri;
7386: $uri=&deversion($uri);
7387: my $orguri=$uri;
7388: $uri=&declutter($uri);
7389:
7390: if ($priv eq 'evb') {
7391: # Evade communication block restrictions for specified role in a course
7392: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7393: return $1;
7394: } else {
7395: return;
7396: }
7397: }
7398:
7399: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
7400: # Free bre access to adm and meta resources
7401: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$}))
7402: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7403: && ($priv eq 'bre')) {
7404: return 'F';
7405: }
7406:
7407: # Free bre access to user's own portfolio contents
7408: my ($space,$domain,$name,@dir)=split('/',$uri);
7409: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
7410: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
7411: my %setters;
7412: my ($startblock,$endblock) =
7413: &Apache::loncommon::blockcheck(\%setters,'port');
7414: if ($startblock && $endblock) {
7415: return 'B';
7416: } else {
7417: return 'F';
7418: }
7419: }
7420:
7421: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
7422: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7423: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7424: if (exists($env{'request.course.id'})) {
7425: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7426: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7427: if (($domain eq $cdom) && ($name eq $cnum)) {
7428: my $courseprivid=$env{'request.course.id'};
7429: $courseprivid=~s/\_/\//;
7430: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7431: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7432: return $1;
7433: } else {
7434: if ($env{'request.course.sec'}) {
7435: $courseprivid.='/'.$env{'request.course.sec'};
7436: }
7437: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7438: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7439: return $2;
7440: }
7441: }
7442: }
7443: }
7444: }
7445:
7446: # Free bre to public access
7447:
7448: if ($priv eq 'bre') {
7449: my $copyright=&metadata($uri,'copyright');
7450: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
7451: return 'F';
7452: }
7453: if ($copyright eq 'priv') {
7454: $uri=~/([^\/]+)\/([^\/]+)\//;
7455: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
7456: return '';
7457: }
7458: }
7459: if ($copyright eq 'domain') {
7460: $uri=~/([^\/]+)\/([^\/]+)\//;
7461: unless (($env{'user.domain'} eq $1) ||
7462: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
7463: return '';
7464: }
7465: }
7466: if ($env{'request.role'}=~ /li\.\//) {
7467: # Library role, so allow browsing of resources in this domain.
7468: return 'F';
7469: }
7470: if ($copyright eq 'custom') {
7471: unless (&customaccess($priv,$uri)) { return ''; }
7472: }
7473: }
7474: # Domain coordinator is trying to create a course
7475: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
7476: # uri is the requested domain in this case.
7477: # comparison to 'request.role.domain' shows if the user has selected
7478: # a role of dc for the domain in question.
7479: return 'F' if ($uri eq $env{'request.role.domain'});
7480: }
7481:
7482: my $thisallowed='';
7483: my $statecond=0;
7484: my $courseprivid='';
7485:
7486: my $ownaccess;
7487: # Community Coordinator or Assistant Co-author browsing resource space.
7488: if (($priv eq 'bro') && ($env{'user.author'})) {
7489: if ($uri eq '') {
7490: $ownaccess = 1;
7491: } else {
7492: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
7493: my $udom = $env{'user.domain'};
7494: my $uname = $env{'user.name'};
7495: if ($uri =~ m{^\Q$udom\E/?$}) {
7496: $ownaccess = 1;
7497: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
7498: unless ($uri =~ m{\.\./}) {
7499: $ownaccess = 1;
7500: }
7501: } elsif (($udom ne 'public') && ($uname ne 'public')) {
7502: my $now = time;
7503: if ($uri =~ m{^([^/]+)/?$}) {
7504: my $adom = $1;
7505: foreach my $key (keys(%env)) {
7506: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
7507: my ($start,$end) = split('.',$env{$key});
7508: if (($now >= $start) && (!$end || $end < $now)) {
7509: $ownaccess = 1;
7510: last;
7511: }
7512: }
7513: }
7514: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
7515: my $adom = $1;
7516: my $aname = $2;
7517: foreach my $role ('ca','aa') {
7518: if ($env{"user.role.$role./$adom/$aname"}) {
7519: my ($start,$end) =
7520: split('.',$env{"user.role.$role./$adom/$aname"});
7521: if (($now >= $start) && (!$end || $end < $now)) {
7522: $ownaccess = 1;
7523: last;
7524: }
7525: }
7526: }
7527: }
7528: }
7529: }
7530: }
7531: }
7532:
7533: # Course
7534:
7535: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
7536: unless (($priv eq 'bro') && (!$ownaccess)) {
7537: $thisallowed.=$1;
7538: }
7539: }
7540:
7541: # Domain
7542:
7543: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
7544: =~/\Q$priv\E\&([^\:]*)/) {
7545: unless (($priv eq 'bro') && (!$ownaccess)) {
7546: $thisallowed.=$1;
7547: }
7548: }
7549:
7550: # User who is not author or co-author might still be able to edit
7551: # resource of an author in the domain (e.g., if Domain Coordinator).
7552: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
7553: (&allowed('mdc',$env{'request.course.id'}))) {
7554: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
7555: $thisallowed.=$1;
7556: }
7557: }
7558:
7559: # Course: uri itself is a course
7560: my $courseuri=$uri;
7561: $courseuri=~s/\_(\d)/\/$1/;
7562: $courseuri=~s/^([^\/])/\/$1/;
7563:
7564: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
7565: =~/\Q$priv\E\&([^\:]*)/) {
7566: unless (($priv eq 'bro') && (!$ownaccess)) {
7567: $thisallowed.=$1;
7568: }
7569: }
7570:
7571: # URI is an uploaded document for this course, default permissions don't matter
7572: # not allowing 'edit' access (editupload) to uploaded course docs
7573: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
7574: $thisallowed='';
7575: my ($match)=&is_on_map($uri);
7576: if ($match) {
7577: if ($env{'user.priv.'.$env{'request.role'}.'./'}
7578: =~/\Q$priv\E\&([^\:]*)/) {
7579: my $value = $1;
7580: if ($noblockcheck) {
7581: $thisallowed.=$value;
7582: } else {
7583: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7584: if (@blockers > 0) {
7585: $thisallowed = 'B';
7586: } else {
7587: $thisallowed.=$value;
7588: }
7589: }
7590: }
7591: } else {
7592: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
7593: if ($refuri) {
7594: if ($refuri =~ m|^/adm/|) {
7595: $thisallowed='F';
7596: } else {
7597: $refuri=&declutter($refuri);
7598: my ($match) = &is_on_map($refuri);
7599: if ($match) {
7600: if ($noblockcheck) {
7601: $thisallowed='F';
7602: } else {
7603: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7604: if (@blockers > 0) {
7605: $thisallowed = 'B';
7606: } else {
7607: $thisallowed='F';
7608: }
7609: }
7610: }
7611: }
7612: }
7613: }
7614: }
7615:
7616: if ($priv eq 'bre'
7617: && $thisallowed ne 'F'
7618: && $thisallowed ne '2'
7619: && &is_portfolio_url($uri)) {
7620: $thisallowed = &portfolio_access($uri,$clientip);
7621: }
7622:
7623: # Full access at system, domain or course-wide level? Exit.
7624: if ($thisallowed=~/F/) {
7625: return 'F';
7626: }
7627:
7628: # If this is generating or modifying users, exit with special codes
7629:
7630: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
7631: if (($priv eq 'cca') || ($priv eq 'caa')) {
7632: my ($audom,$auname)=split('/',$uri);
7633: # no author name given, so this just checks on the general right to make a co-author in this domain
7634: unless ($auname) { return $thisallowed; }
7635: # an author name is given, so we are about to actually make a co-author for a certain account
7636: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
7637: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
7638: ($audom ne $env{'request.role.domain'}))) { return ''; }
7639: }
7640: return $thisallowed;
7641: }
7642: #
7643: # Gathered so far: system, domain and course wide privileges
7644: #
7645: # Course: See if uri or referer is an individual resource that is part of
7646: # the course
7647:
7648: if ($env{'request.course.id'}) {
7649:
7650: $courseprivid=$env{'request.course.id'};
7651: if ($env{'request.course.sec'}) {
7652: $courseprivid.='/'.$env{'request.course.sec'};
7653: }
7654: $courseprivid=~s/\_/\//;
7655: my $checkreferer=1;
7656: my ($match,$cond)=&is_on_map($uri);
7657: if ($match) {
7658: $statecond=$cond;
7659: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
7660: =~/\Q$priv\E\&([^\:]*)/) {
7661: my $value = $1;
7662: if ($priv eq 'bre') {
7663: if ($noblockcheck) {
7664: $thisallowed.=$value;
7665: } else {
7666: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7667: if (@blockers > 0) {
7668: $thisallowed = 'B';
7669: } else {
7670: $thisallowed.=$value;
7671: }
7672: }
7673: } else {
7674: $thisallowed.=$value;
7675: }
7676: $checkreferer=0;
7677: }
7678: }
7679:
7680: if ($checkreferer) {
7681: my $refuri=$env{'httpref.'.$orguri};
7682: unless ($refuri) {
7683: foreach my $key (keys(%env)) {
7684: if ($key=~/^httpref\..*\*/) {
7685: my $pattern=$key;
7686: $pattern=~s/^httpref\.\/res\///;
7687: $pattern=~s/\*/\[\^\/\]\+/g;
7688: $pattern=~s/\//\\\//g;
7689: if ($orguri=~/$pattern/) {
7690: $refuri=$env{$key};
7691: }
7692: }
7693: }
7694: }
7695:
7696: if ($refuri) {
7697: $refuri=&declutter($refuri);
7698: my ($match,$cond)=&is_on_map($refuri);
7699: if ($match) {
7700: my $refstatecond=$cond;
7701: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
7702: =~/\Q$priv\E\&([^\:]*)/) {
7703: my $value = $1;
7704: if ($priv eq 'bre') {
7705: if ($noblockcheck) {
7706: $thisallowed.=$value;
7707: } else {
7708: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7709: if (@blockers > 0) {
7710: $thisallowed = 'B';
7711: } else {
7712: $thisallowed.=$value;
7713: }
7714: }
7715: } else {
7716: $thisallowed.=$value;
7717: }
7718: $uri=$refuri;
7719: $statecond=$refstatecond;
7720: }
7721: }
7722: }
7723: }
7724: }
7725:
7726: #
7727: # Gathered now: all privileges that could apply, and condition number
7728: #
7729: #
7730: # Full or no access?
7731: #
7732:
7733: if ($thisallowed=~/F/) {
7734: return 'F';
7735: }
7736:
7737: unless ($thisallowed) {
7738: return '';
7739: }
7740:
7741: # Restrictions exist, deal with them
7742: #
7743: # C:according to course preferences
7744: # R:according to resource settings
7745: # L:unless locked
7746: # X:according to user session state
7747: #
7748:
7749: # Possibly locked functionality, check all courses
7750: # Locks might take effect only after 10 minutes cache expiration for other
7751: # courses, and 2 minutes for current course
7752:
7753: my $envkey;
7754: if ($thisallowed=~/L/) {
7755: foreach $envkey (keys(%env)) {
7756: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7757: my $courseid=$2;
7758: my $roleid=$1.'.'.$2;
7759: $courseid=~s/^\///;
7760: my $expiretime=600;
7761: if ($env{'request.role'} eq $roleid) {
7762: $expiretime=120;
7763: }
7764: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7765: my $prefix='course.'.$cdom.'_'.$cnum.'.';
7766: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
7767: &coursedescription($courseid,{'freshen_cache' => 1});
7768: }
7769: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7770: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7771: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7772: &log($env{'user.domain'},$env{'user.name'},
7773: $env{'user.home'},
7774: 'Locked by res: '.$priv.' for '.$uri.' due to '.
7775: $cdom.'/'.$cnum.'/'.$csec.' expire '.
7776: $env{$prefix.'priv.'.$priv.'.lock.expire'});
7777: return '';
7778: }
7779: }
7780: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7781: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7782: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7783: &log($env{'user.domain'},$env{'user.name'},
7784: $env{'user.home'},
7785: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
7786: $cdom.'/'.$cnum.'/'.$csec.' expire '.
7787: $env{$prefix.'priv.'.$priv.'.lock.expire'});
7788: return '';
7789: }
7790: }
7791: }
7792: }
7793: }
7794:
7795: #
7796: # Rest of the restrictions depend on selected course
7797: #
7798:
7799: unless ($env{'request.course.id'}) {
7800: if ($thisallowed eq 'A') {
7801: return 'A';
7802: } elsif ($thisallowed eq 'B') {
7803: return 'B';
7804: } else {
7805: return '1';
7806: }
7807: }
7808:
7809: #
7810: # Now user is definitely in a course
7811: #
7812:
7813:
7814: # Course preferences
7815:
7816: if ($thisallowed=~/C/) {
7817: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7818: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7819: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
7820: =~/\Q$rolecode\E/) {
7821: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
7822: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7823: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7824: $env{'request.course.id'});
7825: }
7826: return '';
7827: }
7828:
7829: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
7830: =~/\Q$unamedom\E/) {
7831: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
7832: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7833: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7834: $env{'request.course.id'});
7835: }
7836: return '';
7837: }
7838: }
7839:
7840: # Resource preferences
7841:
7842: if ($thisallowed=~/R/) {
7843: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7844: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
7845: if (($priv ne 'pch') && ($priv ne 'plc')) {
7846: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7847: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7848: }
7849: return '';
7850: }
7851: }
7852:
7853: # Restricted by state or randomout?
7854:
7855: if ($thisallowed=~/X/) {
7856: if ($env{'acc.randomout'}) {
7857: if (!$symb) { $symb=&symbread($uri,1); }
7858: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
7859: return '';
7860: }
7861: }
7862: if (&condval($statecond)) {
7863: return '2';
7864: } else {
7865: return '';
7866: }
7867: }
7868:
7869: if ($thisallowed eq 'A') {
7870: return 'A';
7871: } elsif ($thisallowed eq 'B') {
7872: return 'B';
7873: }
7874: return 'F';
7875: }
7876:
7877: # ------------------------------------------- Check construction space access
7878:
7879: sub constructaccess {
7880: my ($url,$setpriv)=@_;
7881:
7882: # We do not allow editing of previous versions of files
7883: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7884:
7885: # Get username and domain from URL
7886: my ($ownername,$ownerdomain,$ownerhome);
7887:
7888: ($ownerdomain,$ownername) =
7889: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
7890:
7891: # The URL does not really point to any authorspace, forget it
7892: unless (($ownername) && ($ownerdomain)) { return ''; }
7893:
7894: # Now we need to see if the user has access to the authorspace of
7895: # $ownername at $ownerdomain
7896:
7897: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7898: # Real author for this?
7899: $ownerhome = $env{'user.home'};
7900: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7901: return ($ownername,$ownerdomain,$ownerhome);
7902: }
7903: } else {
7904: # Co-author for this?
7905: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7906: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7907: $ownerhome = &homeserver($ownername,$ownerdomain);
7908: return ($ownername,$ownerdomain,$ownerhome);
7909: }
7910: if ($env{'request.course.id'}) {
7911: if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
7912: ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
7913: if (&allowed('mdc',$env{'request.course.id'})) {
7914: $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
7915: return ($ownername,$ownerdomain,$ownerhome);
7916: }
7917: }
7918: }
7919: }
7920:
7921: # We don't have any access right now. If we are not possibly going to do anything about this,
7922: # we might as well leave
7923: unless ($setpriv) { return ''; }
7924:
7925: # Backdoor access?
7926: my $allowed=&allowed('eco',$ownerdomain);
7927: # Nope
7928: unless ($allowed) { return ''; }
7929: # Looks like we may have access, but could be locked by the owner of the construction space
7930: if ($allowed eq 'U') {
7931: my %blocked=&get('environment',['domcoord.author'],
7932: $ownerdomain,$ownername);
7933: # Is blocked by owner
7934: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7935: }
7936: if (($allowed eq 'F') || ($allowed eq 'U')) {
7937: # Grant temporary access
7938: my $then=$env{'user.login.time'};
7939: my $update=$env{'user.update.time'};
7940: if (!$update) { $update = $then; }
7941: my $refresh=$env{'user.refresh.time'};
7942: if (!$refresh) { $refresh = $update; }
7943: my $now = time;
7944: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7945: $now,'ca','constructaccess');
7946: $ownerhome = &homeserver($ownername,$ownerdomain);
7947: return($ownername,$ownerdomain,$ownerhome);
7948: }
7949: # No business here
7950: return '';
7951: }
7952:
7953: # ----------------------------------------------------------- Content Blocking
7954:
7955: {
7956: # Caches for faster Course Contents display where content blocking
7957: # is in operation (i.e., interval param set) for timed quiz.
7958: #
7959: # User for whom data are being temporarily cached.
7960: my $cacheduser='';
7961: # Cached blockers for this user (a hash of blocking items).
7962: my %cachedblockers=();
7963: # When the data were last cached.
7964: my $cachedlast='';
7965:
7966: sub load_all_blockers {
7967: my ($uname,$udom,$blocks)=@_;
7968: if (($uname ne '') && ($udom ne '')) {
7969: if (($cacheduser eq $uname.':'.$udom) &&
7970: (abs($cachedlast-time)<5)) {
7971: return;
7972: }
7973: }
7974: $cachedlast=time;
7975: $cacheduser=$uname.':'.$udom;
7976: %cachedblockers = &get_commblock_resources($blocks);
7977: }
7978:
7979: sub get_comm_blocks {
7980: my ($cdom,$cnum) = @_;
7981: if ($cdom eq '' || $cnum eq '') {
7982: return unless ($env{'request.course.id'});
7983: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7984: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7985: }
7986: my %commblocks;
7987: my $hashid=$cdom.'_'.$cnum;
7988: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7989: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7990: %commblocks = %{$blocksref};
7991: } else {
7992: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7993: my $cachetime = 600;
7994: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7995: }
7996: return %commblocks;
7997: }
7998:
7999: sub get_commblock_resources {
8000: my ($blocks) = @_;
8001: my %blockers = ();
8002: return %blockers unless ($env{'request.course.id'});
8003: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
8004: my %commblocks;
8005: if (ref($blocks) eq 'HASH') {
8006: %commblocks = %{$blocks};
8007: } else {
8008: %commblocks = &get_comm_blocks();
8009: }
8010: return %blockers unless (keys(%commblocks) > 0);
8011: my $navmap = Apache::lonnavmaps::navmap->new();
8012: return %blockers unless (ref($navmap));
8013: my $now = time;
8014: foreach my $block (keys(%commblocks)) {
8015: if ($block =~ /^(\d+)____(\d+)$/) {
8016: my ($start,$end) = ($1,$2);
8017: if ($start <= $now && $end >= $now) {
8018: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8019: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8020: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8021: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8022: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8023: }
8024: }
8025: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8026: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8027: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
8028: }
8029: }
8030: }
8031: }
8032: }
8033: } elsif ($block =~ /^firstaccess____(.+)$/) {
8034: my $item = $1;
8035: my @to_test;
8036: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8037: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8038: my @interval;
8039: my $type = 'map';
8040: if ($item eq 'course') {
8041: $type = 'course';
8042: @interval=&EXT("resource.0.interval");
8043: } else {
8044: if ($item =~ /___\d+___/) {
8045: $type = 'resource';
8046: @interval=&EXT("resource.0.interval",$item);
8047: if (ref($navmap)) {
8048: my $res = $navmap->getBySymb($item);
8049: push(@to_test,$res);
8050: }
8051: } else {
8052: my $mapsymb = &symbread($item,1);
8053: if ($mapsymb) {
8054: if (ref($navmap)) {
8055: my $mapres = $navmap->getBySymb($mapsymb);
8056: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
8057: foreach my $res (@to_test) {
8058: my $symb = $res->symb();
8059: next if ($symb eq $mapsymb);
8060: if ($symb ne '') {
8061: @interval=&EXT("resource.0.interval",$symb);
8062: if ($interval[1] eq 'map') {
8063: last;
8064: }
8065: }
8066: }
8067: }
8068: }
8069: }
8070: }
8071: if ($interval[0] =~ /^(\d+)/) {
8072: my $timelimit = $1;
8073: my $first_access;
8074: if ($type eq 'resource') {
8075: $first_access=&get_first_access($interval[1],$item);
8076: } elsif ($type eq 'map') {
8077: $first_access=&get_first_access($interval[1],undef,$item);
8078: } else {
8079: $first_access=&get_first_access($interval[1]);
8080: }
8081: if ($first_access) {
8082: my $timesup = $first_access+$timelimit;
8083: if ($timesup > $now) {
8084: my $activeblock;
8085: foreach my $res (@to_test) {
8086: if ($res->answerable()) {
8087: $activeblock = 1;
8088: last;
8089: }
8090: }
8091: if ($activeblock) {
8092: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8093: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8094: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8095: }
8096: }
8097: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8098: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8099: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
8100: }
8101: }
8102: }
8103: }
8104: }
8105: }
8106: }
8107: }
8108: }
8109: }
8110: return %blockers;
8111: }
8112:
8113: sub has_comm_blocking {
8114: my ($priv,$symb,$uri,$blocks) = @_;
8115: my @blockers;
8116: return unless ($env{'request.course.id'});
8117: return unless ($priv eq 'bre');
8118: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
8119: return if ($env{'request.state'} eq 'construct');
8120: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
8121: return unless (keys(%cachedblockers) > 0);
8122: my (%possibles,@symbs);
8123: if (!$symb) {
8124: $symb = &symbread($uri,1,1,1,\%possibles);
8125: }
8126: if ($symb) {
8127: @symbs = ($symb);
8128: } elsif (keys(%possibles)) {
8129: @symbs = keys(%possibles);
8130: }
8131: my $noblock;
8132: foreach my $symb (@symbs) {
8133: last if ($noblock);
8134: my ($map,$resid,$resurl)=&decode_symb($symb);
8135: foreach my $block (keys(%cachedblockers)) {
8136: if ($block =~ /^firstaccess____(.+)$/) {
8137: my $item = $1;
8138: if (($item eq $map) || ($item eq $symb)) {
8139: $noblock = 1;
8140: last;
8141: }
8142: }
8143: if (ref($cachedblockers{$block}) eq 'HASH') {
8144: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
8145: if ($cachedblockers{$block}{'resources'}{$symb}) {
8146: unless (grep(/^\Q$block\E$/,@blockers)) {
8147: push(@blockers,$block);
8148: }
8149: }
8150: }
8151: }
8152: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
8153: if ($cachedblockers{$block}{'maps'}{$map}) {
8154: unless (grep(/^\Q$block\E$/,@blockers)) {
8155: push(@blockers,$block);
8156: }
8157: }
8158: }
8159: }
8160: }
8161: return if ($noblock);
8162: return @blockers;
8163: }
8164: }
8165:
8166: # -------------------------------- Deversion and split uri into path an filename
8167:
8168: #
8169: # Removes the version from a URI and
8170: # splits it in to its filename and path to the filename.
8171: # Seems like File::Basename could have done this more clearly.
8172: # Parameters:
8173: # $uri - input URI
8174: # Returns:
8175: # Two element list consisting of
8176: # $pathname - the URI up to and excluding the trailing /
8177: # $filename - The part of the URI following the last /
8178: # NOTE:
8179: # Another realization of this is simply:
8180: # use File::Basename;
8181: # ...
8182: # $uri = shift;
8183: # $filename = basename($uri);
8184: # $path = dirname($uri);
8185: # return ($filename, $path);
8186: #
8187: # The implementation below is probably faster however.
8188: #
8189: sub split_uri_for_cond {
8190: my $uri=&deversion(&declutter(shift));
8191: my @uriparts=split(/\//,$uri);
8192: my $filename=pop(@uriparts);
8193: my $pathname=join('/',@uriparts);
8194: return ($pathname,$filename);
8195: }
8196: # --------------------------------------------------- Is a resource on the map?
8197:
8198: sub is_on_map {
8199: my ($pathname,$filename) = &split_uri_for_cond(shift);
8200: #Trying to find the conditional for the file
8201: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
8202: /\&\Q$filename\E\:([\d\|]+)\&/);
8203: if ($match) {
8204: return (1,$1);
8205: } else {
8206: return (0,0);
8207: }
8208: }
8209:
8210: # --------------------------------------------------------- Get symb from alias
8211:
8212: sub get_symb_from_alias {
8213: my $symb=shift;
8214: my ($map,$resid,$url)=&decode_symb($symb);
8215: # Already is a symb
8216: if ($url) { return $symb; }
8217: # Must be an alias
8218: my $aliassymb='';
8219: my %bighash;
8220: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8221: &GDBM_READER(),0640)) {
8222: my $rid=$bighash{'mapalias_'.$symb};
8223: if ($rid) {
8224: my ($mapid,$resid)=split(/\./,$rid);
8225: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8226: $resid,$bighash{'src_'.$rid});
8227: }
8228: untie %bighash;
8229: }
8230: return $aliassymb;
8231: }
8232:
8233: # ----------------------------------------------------------------- Define Role
8234:
8235: sub definerole {
8236: if (allowed('mcr','/')) {
8237: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
8238: foreach my $role (split(':',$sysrole)) {
8239: my ($crole,$cqual)=split(/\&/,$role);
8240: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8241: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8242: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
8243: return "refused:s:$crole&$cqual";
8244: }
8245: }
8246: }
8247: foreach my $role (split(':',$domrole)) {
8248: my ($crole,$cqual)=split(/\&/,$role);
8249: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8250: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8251: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
8252: return "refused:d:$crole&$cqual";
8253: }
8254: }
8255: }
8256: foreach my $role (split(':',$courole)) {
8257: my ($crole,$cqual)=split(/\&/,$role);
8258: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8259: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8260: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
8261: return "refused:c:$crole&$cqual";
8262: }
8263: }
8264: }
8265: my $uhome;
8266: if (($uname ne '') && ($udom ne '')) {
8267: $uhome = &homeserver($uname,$udom);
8268: return $uhome if ($uhome eq 'no_host');
8269: } else {
8270: $uname = $env{'user.name'};
8271: $udom = $env{'user.domain'};
8272: $uhome = $env{'user.home'};
8273: }
8274: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
8275: "$udom:$uname:rolesdef_$rolename=".
8276: escape($sysrole.'_'.$domrole.'_'.$courole);
8277: return reply($command,$uhome);
8278: } else {
8279: return 'refused';
8280: }
8281: }
8282:
8283: # ---------------- Make a metadata query against the network of library servers
8284:
8285: sub metadata_query {
8286: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
8287: my %rhash;
8288: my %libserv = &all_library();
8289: my @server_list = (defined($server_array) ? @$server_array
8290: : keys(%libserv) );
8291: for my $server (@server_list) {
8292: my $domains = '';
8293: if (ref($domains_hash) eq 'HASH') {
8294: $domains = $domains_hash->{$server};
8295: }
8296: unless ($custom or $customshow) {
8297: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
8298: $rhash{$server}=$reply;
8299: }
8300: else {
8301: my $reply=&reply("querysend:".&escape($query).':'.
8302: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
8303: $server);
8304: $rhash{$server}=$reply;
8305: }
8306: }
8307: return \%rhash;
8308: }
8309:
8310: # ----------------------------------------- Send log queries and wait for reply
8311:
8312: sub log_query {
8313: my ($uname,$udom,$query,%filters)=@_;
8314: my $uhome=&homeserver($uname,$udom);
8315: if ($uhome eq 'no_host') { return 'error: no_host'; }
8316: my $uhost=&hostname($uhome);
8317: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
8318: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8319: $uhome);
8320: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
8321: return get_query_reply($queryid);
8322: }
8323:
8324: # -------------------------- Update MySQL table for portfolio file
8325:
8326: sub update_portfolio_table {
8327: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
8328: if ($group ne '') {
8329: $file_name =~s /^\Q$group\E//;
8330: }
8331: my $homeserver = &homeserver($uname,$udom);
8332: my $queryid=
8333: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8334: ':'.&escape($file_name).':'.$action,$homeserver);
8335: my $reply = &get_query_reply($queryid);
8336: return $reply;
8337: }
8338:
8339: # -------------------------- Update MySQL allusers table
8340:
8341: sub update_allusers_table {
8342: my ($uname,$udom,$names) = @_;
8343: my $homeserver = &homeserver($uname,$udom);
8344: my $queryid=
8345: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8346: 'lastname='.&escape($names->{'lastname'}).'%%'.
8347: 'firstname='.&escape($names->{'firstname'}).'%%'.
8348: 'middlename='.&escape($names->{'middlename'}).'%%'.
8349: 'generation='.&escape($names->{'generation'}).'%%'.
8350: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8351: 'id='.&escape($names->{'id'}),$homeserver);
8352: return;
8353: }
8354:
8355: # ------- Request retrieval of institutional classlists for course(s)
8356:
8357: sub fetch_enrollment_query {
8358: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
8359: my ($homeserver,$sleep,$loopmax);
8360: my $maxtries = 1;
8361: if ($context eq 'automated') {
8362: $homeserver = $perlvar{'lonHostID'};
8363: $sleep = 2;
8364: $loopmax = 100;
8365: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
8366: } else {
8367: $homeserver = &homeserver($cnum,$dom);
8368: }
8369: my $host=&hostname($homeserver);
8370: my $cmd = '';
8371: foreach my $affiliate (keys(%{$affiliatesref})) {
8372: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
8373: }
8374: $cmd =~ s/%%$//;
8375: $cmd = &escape($cmd);
8376: my $query = 'fetchenrollment';
8377: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
8378: unless ($queryid=~/^\Q$host\E\_/) {
8379: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
8380: return 'error: '.$queryid;
8381: }
8382: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
8383: my $tries = 1;
8384: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8385: $reply = &get_query_reply($queryid,$sleep,$loopmax);
8386: $tries ++;
8387: }
8388: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8389: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8390: } else {
8391: my @responses = split(/:/,$reply);
8392: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
8393: foreach my $line (@responses) {
8394: my ($key,$value) = split(/=/,$line,2);
8395: $$replyref{$key} = $value;
8396: }
8397: } else {
8398: my $pathname = LONCAPA::tempdir();
8399: foreach my $line (@responses) {
8400: my ($key,$value) = split(/=/,$line);
8401: $$replyref{$key} = $value;
8402: if ($value > 0) {
8403: foreach my $item (@{$$affiliatesref{$key}}) {
8404: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
8405: my $destname = $pathname.'/'.$filename;
8406: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
8407: if ($xml_classlist =~ /^error/) {
8408: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
8409: } else {
8410: if ( open(FILE,">$destname") ) {
8411: print FILE &unescape($xml_classlist);
8412: close(FILE);
8413: } else {
8414: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
8415: }
8416: }
8417: }
8418: }
8419: }
8420: }
8421: return 'ok';
8422: }
8423: return 'error';
8424: }
8425:
8426: sub get_query_reply {
8427: my ($queryid,$sleep,$loopmax) = @_;;
8428: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
8429: $sleep = 0.2;
8430: }
8431: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
8432: $loopmax = 100;
8433: }
8434: my $replyfile=LONCAPA::tempdir().$queryid;
8435: my $reply='';
8436: for (1..$loopmax) {
8437: sleep($sleep);
8438: if (-e $replyfile.'.end') {
8439: if (open(my $fh,$replyfile)) {
8440: $reply = join('',<$fh>);
8441: close($fh);
8442: } else { return 'error: reply_file_error'; }
8443: return &unescape($reply);
8444: }
8445: }
8446: return 'timeout:'.$queryid;
8447: }
8448:
8449: sub courselog_query {
8450: #
8451: # possible filters:
8452: # url: url or symb
8453: # username
8454: # domain
8455: # action: view, submit, grade
8456: # start: timestamp
8457: # end: timestamp
8458: #
8459: my (%filters)=@_;
8460: unless ($env{'request.course.id'}) { return 'no_course'; }
8461: if ($filters{'url'}) {
8462: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
8463: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
8464: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
8465: }
8466: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8467: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
8468: return &log_query($cname,$cdom,'courselog',%filters);
8469: }
8470:
8471: sub userlog_query {
8472: #
8473: # possible filters:
8474: # action: log check role
8475: # start: timestamp
8476: # end: timestamp
8477: #
8478: my ($uname,$udom,%filters)=@_;
8479: return &log_query($uname,$udom,'userlog',%filters);
8480: }
8481:
8482: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
8483:
8484: sub auto_run {
8485: my ($cnum,$cdom) = @_;
8486: my $response = 0;
8487: my $settings;
8488: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
8489: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
8490: $settings = $domconfig{'autoenroll'};
8491: if ($settings->{'run'} eq '1') {
8492: $response = 1;
8493: }
8494: } else {
8495: my $homeserver;
8496: if (&is_course($cdom,$cnum)) {
8497: $homeserver = &homeserver($cnum,$cdom);
8498: } else {
8499: $homeserver = &domain($cdom,'primary');
8500: }
8501: if ($homeserver ne 'no_host') {
8502: $response = &reply('autorun:'.$cdom,$homeserver);
8503: }
8504: }
8505: return $response;
8506: }
8507:
8508: sub auto_get_sections {
8509: my ($cnum,$cdom,$inst_coursecode) = @_;
8510: my $homeserver;
8511: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8512: $homeserver = &homeserver($cnum,$cdom);
8513: }
8514: if (!defined($homeserver)) {
8515: if ($cdom =~ /^$match_domain$/) {
8516: $homeserver = &domain($cdom,'primary');
8517: }
8518: }
8519: my @secs;
8520: if (defined($homeserver)) {
8521: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
8522: unless ($response eq 'refused') {
8523: @secs = split(/:/,$response);
8524: }
8525: }
8526: return @secs;
8527: }
8528:
8529: sub auto_new_course {
8530: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
8531: my $homeserver = &homeserver($cnum,$cdom);
8532: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
8533: return $response;
8534: }
8535:
8536: sub auto_validate_courseID {
8537: my ($cnum,$cdom,$inst_course_id) = @_;
8538: my $homeserver = &homeserver($cnum,$cdom);
8539: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
8540: return $response;
8541: }
8542:
8543: sub auto_validate_instcode {
8544: my ($cnum,$cdom,$instcode,$owner) = @_;
8545: my ($homeserver,$response);
8546: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8547: $homeserver = &homeserver($cnum,$cdom);
8548: }
8549: if (!defined($homeserver)) {
8550: if ($cdom =~ /^$match_domain$/) {
8551: $homeserver = &domain($cdom,'primary');
8552: }
8553: }
8554: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
8555: &escape($instcode).':'.&escape($owner),$homeserver));
8556: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
8557: return ($outcome,$description,$defaultcredits);
8558: }
8559:
8560: sub auto_create_password {
8561: my ($cnum,$cdom,$authparam,$udom) = @_;
8562: my ($homeserver,$response);
8563: my $create_passwd = 0;
8564: my $authchk = '';
8565: if ($udom =~ /^$match_domain$/) {
8566: $homeserver = &domain($udom,'primary');
8567: }
8568: if ($homeserver eq '') {
8569: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8570: $homeserver = &homeserver($cnum,$cdom);
8571: }
8572: }
8573: if ($homeserver eq '') {
8574: $authchk = 'nodomain';
8575: } else {
8576: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
8577: if ($response eq 'refused') {
8578: $authchk = 'refused';
8579: } else {
8580: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
8581: }
8582: }
8583: return ($authparam,$create_passwd,$authchk);
8584: }
8585:
8586: sub auto_photo_permission {
8587: my ($cnum,$cdom,$students) = @_;
8588: my $homeserver = &homeserver($cnum,$cdom);
8589: my ($outcome,$perm_reqd,$conditions) =
8590: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
8591: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8592: return (undef,undef);
8593: }
8594: return ($outcome,$perm_reqd,$conditions);
8595: }
8596:
8597: sub auto_checkphotos {
8598: my ($uname,$udom,$pid) = @_;
8599: my $homeserver = &homeserver($uname,$udom);
8600: my ($result,$resulttype);
8601: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
8602: &escape($uname).':'.&escape($pid),
8603: $homeserver));
8604: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8605: return (undef,undef);
8606: }
8607: if ($outcome) {
8608: ($result,$resulttype) = split(/:/,$outcome);
8609: }
8610: return ($result,$resulttype);
8611: }
8612:
8613: sub auto_photochoice {
8614: my ($cnum,$cdom) = @_;
8615: my $homeserver = &homeserver($cnum,$cdom);
8616: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
8617: &escape($cdom),
8618: $homeserver)));
8619: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8620: return (undef,undef);
8621: }
8622: return ($update,$comment);
8623: }
8624:
8625: sub auto_photoupdate {
8626: my ($affiliatesref,$dom,$cnum,$photo) = @_;
8627: my $homeserver = &homeserver($cnum,$dom);
8628: my $host=&hostname($homeserver);
8629: my $cmd = '';
8630: my $maxtries = 1;
8631: foreach my $affiliate (keys(%{$affiliatesref})) {
8632: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
8633: }
8634: $cmd =~ s/%%$//;
8635: $cmd = &escape($cmd);
8636: my $query = 'institutionalphotos';
8637: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
8638: unless ($queryid=~/^\Q$host\E\_/) {
8639: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
8640: return 'error: '.$queryid;
8641: }
8642: my $reply = &get_query_reply($queryid);
8643: my $tries = 1;
8644: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8645: $reply = &get_query_reply($queryid);
8646: $tries ++;
8647: }
8648: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8649: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8650: } else {
8651: my @responses = split(/:/,$reply);
8652: my $outcome = shift(@responses);
8653: foreach my $item (@responses) {
8654: my ($key,$value) = split(/=/,$item);
8655: $$photo{$key} = $value;
8656: }
8657: return $outcome;
8658: }
8659: return 'error';
8660: }
8661:
8662: sub auto_instcode_format {
8663: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
8664: $cat_order) = @_;
8665: my $courses = '';
8666: my @homeservers;
8667: if ($caller eq 'global') {
8668: my %servers = &get_servers($codedom,'library');
8669: foreach my $tryserver (keys(%servers)) {
8670: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8671: push(@homeservers,$tryserver);
8672: }
8673: }
8674: } elsif ($caller eq 'requests') {
8675: if ($codedom =~ /^$match_domain$/) {
8676: my $chome = &domain($codedom,'primary');
8677: unless ($chome eq 'no_host') {
8678: push(@homeservers,$chome);
8679: }
8680: }
8681: } else {
8682: push(@homeservers,&homeserver($caller,$codedom));
8683: }
8684: foreach my $code (keys(%{$instcodes})) {
8685: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
8686: }
8687: chop($courses);
8688: my $ok_response = 0;
8689: my $response;
8690: while (@homeservers > 0 && $ok_response == 0) {
8691: my $server = shift(@homeservers);
8692: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
8693: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
8694: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
8695: split(/:/,$response);
8696: %{$codes} = (%{$codes},&str2hash($codes_str));
8697: push(@{$codetitles},&str2array($codetitles_str));
8698: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
8699: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
8700: $ok_response = 1;
8701: }
8702: }
8703: if ($ok_response) {
8704: return 'ok';
8705: } else {
8706: return $response;
8707: }
8708: }
8709:
8710: sub auto_instcode_defaults {
8711: my ($domain,$returnhash,$code_order) = @_;
8712: my @homeservers;
8713:
8714: my %servers = &get_servers($domain,'library');
8715: foreach my $tryserver (keys(%servers)) {
8716: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8717: push(@homeservers,$tryserver);
8718: }
8719: }
8720:
8721: my $response;
8722: foreach my $server (@homeservers) {
8723: $response=&reply('autoinstcodedefaults:'.$domain,$server);
8724: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8725:
8726: foreach my $pair (split(/\&/,$response)) {
8727: my ($name,$value)=split(/\=/,$pair);
8728: if ($name eq 'code_order') {
8729: @{$code_order} = split(/\&/,&unescape($value));
8730: } else {
8731: $returnhash->{&unescape($name)}=&unescape($value);
8732: }
8733: }
8734: return 'ok';
8735: }
8736:
8737: return $response;
8738: }
8739:
8740: sub auto_possible_instcodes {
8741: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
8742: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
8743: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8744: return;
8745: }
8746: my (@homeservers,$uhome);
8747: if (defined(&domain($domain,'primary'))) {
8748: $uhome=&domain($domain,'primary');
8749: push(@homeservers,&domain($domain,'primary'));
8750: } else {
8751: my %servers = &get_servers($domain,'library');
8752: foreach my $tryserver (keys(%servers)) {
8753: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8754: push(@homeservers,$tryserver);
8755: }
8756: }
8757: }
8758: my $response;
8759: foreach my $server (@homeservers) {
8760: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8761: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8762: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8763: split(':',$response);
8764: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8765: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
8766: foreach my $item (split('&',$cat_title)) {
8767: my ($name,$value)=split('=',$item);
8768: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
8769: }
8770: foreach my $item (split('&',$cat_order)) {
8771: my ($name,$value)=split('=',$item);
8772: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
8773: }
8774: return 'ok';
8775: }
8776: return $response;
8777: }
8778:
8779: sub auto_courserequest_checks {
8780: my ($dom) = @_;
8781: my ($homeserver,%validations);
8782: if ($dom =~ /^$match_domain$/) {
8783: $homeserver = &domain($dom,'primary');
8784: }
8785: unless ($homeserver eq 'no_host') {
8786: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8787: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8788: my @items = split(/&/,$response);
8789: foreach my $item (@items) {
8790: my ($key,$value) = split('=',$item);
8791: $validations{&unescape($key)} = &thaw_unescape($value);
8792: }
8793: }
8794: }
8795: return %validations;
8796: }
8797:
8798: sub auto_courserequest_validation {
8799: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
8800: my ($homeserver,$response);
8801: if ($dom =~ /^$match_domain$/) {
8802: $homeserver = &domain($dom,'primary');
8803: }
8804: unless ($homeserver eq 'no_host') {
8805: my $customdata;
8806: if (ref($custominfo) eq 'HASH') {
8807: $customdata = &freeze_escape($custominfo);
8808: }
8809: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
8810: ':'.&escape($crstype).':'.&escape($inststatuslist).
8811: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8812: $customdata,$homeserver));
8813: }
8814: return $response;
8815: }
8816:
8817: sub auto_validate_class_sec {
8818: my ($cdom,$cnum,$owners,$inst_class) = @_;
8819: my $homeserver = &homeserver($cnum,$cdom);
8820: my $ownerlist;
8821: if (ref($owners) eq 'ARRAY') {
8822: $ownerlist = join(',',@{$owners});
8823: } else {
8824: $ownerlist = $owners;
8825: }
8826: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
8827: &escape($ownerlist).':'.$cdom,$homeserver);
8828: return $response;
8829: }
8830:
8831: sub auto_crsreq_update {
8832: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
8833: $code,$accessstart,$accessend,$inbound) = @_;
8834: my ($homeserver,%crsreqresponse);
8835: if ($cdom =~ /^$match_domain$/) {
8836: $homeserver = &domain($cdom,'primary');
8837: }
8838: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8839: my $info;
8840: if (ref($inbound) eq 'HASH') {
8841: $info = &freeze_escape($inbound);
8842: }
8843: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8844: ':'.&escape($action).':'.&escape($ownername).':'.
8845: &escape($ownerdomain).':'.&escape($fullname).':'.
8846: &escape($title).':'.&escape($code).':'.
8847: &escape($accessstart).':'.&escape($accessend).':'.$info,
8848: $homeserver);
8849: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8850: my @items = split(/&/,$response);
8851: foreach my $item (@items) {
8852: my ($key,$value) = split('=',$item);
8853: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8854: }
8855: }
8856: }
8857: return \%crsreqresponse;
8858: }
8859:
8860: sub auto_export_grades {
8861: my ($cdom,$cnum,$inforef,$gradesref) = @_;
8862: my ($homeserver,%exportresponse);
8863: if ($cdom =~ /^$match_domain$/) {
8864: $homeserver = &domain($cdom,'primary');
8865: }
8866: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8867: my $info;
8868: if (ref($inforef) eq 'HASH') {
8869: $info = &freeze_escape($inforef);
8870: }
8871: if (ref($gradesref) eq 'HASH') {
8872: my $grades = &freeze_escape($gradesref);
8873: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
8874: $info.':'.$grades,$homeserver);
8875: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
8876: my @items = split(/&/,$response);
8877: foreach my $item (@items) {
8878: my ($key,$value) = split('=',$item);
8879: $exportresponse{&unescape($key)} = &thaw_unescape($value);
8880: }
8881: }
8882: }
8883: }
8884: return \%exportresponse;
8885: }
8886:
8887: sub check_instcode_cloning {
8888: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8889: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8890: return;
8891: }
8892: my $canclone;
8893: if (@{$code_order} > 0) {
8894: my $instcoderegexp ='^';
8895: my @clonecodes = split(/\&/,$cloner);
8896: foreach my $item (@{$code_order}) {
8897: if (grep(/^\Q$item\E=/,@clonecodes)) {
8898: foreach my $pair (@clonecodes) {
8899: my ($key,$val) = split(/\=/,$pair,2);
8900: $val = &unescape($val);
8901: if ($key eq $item) {
8902: $instcoderegexp .= '('.$val.')';
8903: last;
8904: }
8905: }
8906: } else {
8907: $instcoderegexp .= $codedefaults->{$item};
8908: }
8909: }
8910: $instcoderegexp .= '$';
8911: my (@from,@to);
8912: eval {
8913: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8914: (@to) = ($clonetocode =~ /$instcoderegexp/);
8915: };
8916: if ((@from > 0) && (@to > 0)) {
8917: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8918: if (!@diffs) {
8919: $canclone = 1;
8920: }
8921: }
8922: }
8923: return $canclone;
8924: }
8925:
8926: sub default_instcode_cloning {
8927: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8928: my (%codedefaults,@code_order,$canclone);
8929: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8930: %codedefaults = %{$codedefaultsref};
8931: @code_order = @{$codeorderref};
8932: } elsif ($clonedom) {
8933: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8934: }
8935: if (($domdefclone) && (@code_order)) {
8936: my @clonecodes = split(/\+/,$domdefclone);
8937: my $instcoderegexp ='^';
8938: foreach my $item (@code_order) {
8939: if (grep(/^\Q$item\E$/,@clonecodes)) {
8940: $instcoderegexp .= '('.$codedefaults{$item}.')';
8941: } else {
8942: $instcoderegexp .= $codedefaults{$item};
8943: }
8944: }
8945: $instcoderegexp .= '$';
8946: my (@from,@to);
8947: eval {
8948: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8949: (@to) = ($clonetocode =~ /$instcoderegexp/);
8950: };
8951: if ((@from > 0) && (@to > 0)) {
8952: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8953: if (!@diffs) {
8954: $canclone = 1;
8955: }
8956: }
8957: }
8958: return $canclone;
8959: }
8960:
8961: # ------------------------------------------------------- Course Group routines
8962:
8963: sub get_coursegroups {
8964: my ($cdom,$cnum,$group,$namespace) = @_;
8965: return(&dump($namespace,$cdom,$cnum,$group));
8966: }
8967:
8968: sub modify_coursegroup {
8969: my ($cdom,$cnum,$groupsettings) = @_;
8970: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8971: }
8972:
8973: sub toggle_coursegroup_status {
8974: my ($cdom,$cnum,$group,$action) = @_;
8975: my ($from_namespace,$to_namespace);
8976: if ($action eq 'delete') {
8977: $from_namespace = 'coursegroups';
8978: $to_namespace = 'deleted_groups';
8979: } else {
8980: $from_namespace = 'deleted_groups';
8981: $to_namespace = 'coursegroups';
8982: }
8983: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
8984: if (my $tmp = &error(%curr_group)) {
8985: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8986: return ('read error',$tmp);
8987: } else {
8988: my %savedsettings = %curr_group;
8989: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
8990: my $deloutcome;
8991: if ($result eq 'ok') {
8992: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
8993: } else {
8994: return ('write error',$result);
8995: }
8996: if ($deloutcome eq 'ok') {
8997: return 'ok';
8998: } else {
8999: return ('delete error',$deloutcome);
9000: }
9001: }
9002: }
9003:
9004: sub modify_group_roles {
9005: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
9006: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
9007: my $role = 'gr/'.&escape($userprivs);
9008: my ($uname,$udom) = split(/:/,$user);
9009: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
9010: if ($result eq 'ok') {
9011: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
9012: }
9013: return $result;
9014: }
9015:
9016: sub modify_coursegroup_membership {
9017: my ($cdom,$cnum,$membership) = @_;
9018: my $result = &put('groupmembership',$membership,$cdom,$cnum);
9019: return $result;
9020: }
9021:
9022: sub get_active_groups {
9023: my ($udom,$uname,$cdom,$cnum) = @_;
9024: my $now = time;
9025: my %groups = ();
9026: foreach my $key (keys(%env)) {
9027: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
9028: my ($start,$end) = split(/\./,$env{$key});
9029: if (($end!=0) && ($end<$now)) { next; }
9030: if (($start!=0) && ($start>$now)) { next; }
9031: if ($1 eq $cdom && $2 eq $cnum) {
9032: $groups{$3} = $env{$key} ;
9033: }
9034: }
9035: }
9036: return %groups;
9037: }
9038:
9039: sub get_group_membership {
9040: my ($cdom,$cnum,$group) = @_;
9041: return(&dump('groupmembership',$cdom,$cnum,$group));
9042: }
9043:
9044: sub get_users_groups {
9045: my ($udom,$uname,$courseid) = @_;
9046: my @usersgroups;
9047: my $cachetime=1800;
9048:
9049: my $hashid="$udom:$uname:$courseid";
9050: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
9051: if (defined($cached)) {
9052: @usersgroups = split(/:/,$grouplist);
9053: } else {
9054: $grouplist = '';
9055: my $courseurl = &courseid_to_courseurl($courseid);
9056: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
9057: my $access_end = $env{'course.'.$courseid.
9058: '.default_enrollment_end_date'};
9059: my $now = time;
9060: foreach my $key (keys(%roleshash)) {
9061: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
9062: my $group = $1;
9063: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
9064: my $start = $2;
9065: my $end = $1;
9066: if ($start == -1) { next; } # deleted from group
9067: if (($start!=0) && ($start>$now)) { next; }
9068: if (($end!=0) && ($end<$now)) {
9069: if ($access_end && $access_end < $now) {
9070: if ($access_end - $end < 86400) {
9071: push(@usersgroups,$group);
9072: }
9073: }
9074: next;
9075: }
9076: push(@usersgroups,$group);
9077: }
9078: }
9079: }
9080: @usersgroups = &sort_course_groups($courseid,@usersgroups);
9081: $grouplist = join(':',@usersgroups);
9082: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
9083: }
9084: return @usersgroups;
9085: }
9086:
9087: sub devalidate_getgroups_cache {
9088: my ($udom,$uname,$cdom,$cnum)=@_;
9089: my $courseid = $cdom.'_'.$cnum;
9090:
9091: my $hashid="$udom:$uname:$courseid";
9092: &devalidate_cache_new('getgroups',$hashid);
9093: }
9094:
9095: # ------------------------------------------------------------------ Plain Text
9096:
9097: sub plaintext {
9098: my ($short,$type,$cid,$forcedefault) = @_;
9099: if ($short =~ m{^cr/}) {
9100: return (split('/',$short))[-1];
9101: }
9102: if (!defined($cid)) {
9103: $cid = $env{'request.course.id'};
9104: }
9105: my %rolenames = (
9106: Course => 'std',
9107: Community => 'alt1',
9108: Placement => 'std',
9109: );
9110: if ($cid ne '') {
9111: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
9112: unless ($forcedefault) {
9113: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
9114: &Apache::lonlocal::mt_escape(\$roletext);
9115: return &Apache::lonlocal::mt($roletext);
9116: }
9117: }
9118: }
9119: if ((defined($type)) && (defined($rolenames{$type})) &&
9120: (defined($rolenames{$type})) &&
9121: (defined($prp{$short}{$rolenames{$type}}))) {
9122: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
9123: } elsif ($cid ne '') {
9124: my $crstype = $env{'course.'.$cid.'.type'};
9125: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
9126: (defined($prp{$short}{$rolenames{$crstype}}))) {
9127: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
9128: }
9129: }
9130: return &Apache::lonlocal::mt($prp{$short}{'std'});
9131: }
9132:
9133: # ----------------------------------------------------------------- Assign Role
9134:
9135: sub assignrole {
9136: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
9137: $context)=@_;
9138: my $mrole;
9139: if ($role =~ /^cr\//) {
9140: my $cwosec=$url;
9141: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
9142: unless (&allowed('ccr',$cwosec)) {
9143: my $refused = 1;
9144: if ($context eq 'requestcourses') {
9145: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
9146: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
9147: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
9148: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9149: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9150: if ($crsenv{'internal.courseowner'} eq
9151: $env{'user.name'}.':'.$env{'user.domain'}) {
9152: $refused = '';
9153: }
9154: }
9155: }
9156: }
9157: }
9158: if ($refused) {
9159: &logthis('Refused custom assignrole: '.
9160: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
9161: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
9162: return 'refused';
9163: }
9164: }
9165: $mrole='cr';
9166: } elsif ($role =~ /^gr\//) {
9167: my $cwogrp=$url;
9168: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
9169: unless (&allowed('mdg',$cwogrp)) {
9170: &logthis('Refused group assignrole: '.
9171: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
9172: $env{'user.name'}.' at '.$env{'user.domain'});
9173: return 'refused';
9174: }
9175: $mrole='gr';
9176: } else {
9177: my $cwosec=$url;
9178: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
9179: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
9180: my $refused;
9181: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
9182: if (!(&allowed('c'.$role,$url))) {
9183: $refused = 1;
9184: }
9185: } else {
9186: $refused = 1;
9187: }
9188: if ($refused) {
9189: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9190: if (!$selfenroll && $context eq 'course') {
9191: my %crsenv;
9192: if ($role eq 'cc' || $role eq 'co') {
9193: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9194: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
9195: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
9196: if ($crsenv{'internal.courseowner'} eq
9197: $env{'user.name'}.':'.$env{'user.domain'}) {
9198: $refused = '';
9199: }
9200: }
9201: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
9202: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
9203: if ($crsenv{'internal.courseowner'} eq
9204: $env{'user.name'}.':'.$env{'user.domain'}) {
9205: $refused = '';
9206: }
9207: }
9208: }
9209: }
9210: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
9211: $refused = '';
9212: } elsif ($context eq 'requestcourses') {
9213: my @possroles = ('st','ta','ep','in','cc','co');
9214: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
9215: my $wrongcc;
9216: if ($cnum =~ /^$match_community$/) {
9217: $wrongcc = 1 if ($role eq 'cc');
9218: } else {
9219: $wrongcc = 1 if ($role eq 'co');
9220: }
9221: unless ($wrongcc) {
9222: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9223: if ($crsenv{'internal.courseowner'} eq
9224: $env{'user.name'}.':'.$env{'user.domain'}) {
9225: $refused = '';
9226: }
9227: }
9228: }
9229: } elsif ($context eq 'requestauthor') {
9230: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
9231: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
9232: if ($env{'environment.requestauthor'} eq 'automatic') {
9233: $refused = '';
9234: } else {
9235: my %domdefaults = &get_domain_defaults($udom);
9236: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
9237: my $checkbystatus;
9238: if ($env{'user.adv'}) {
9239: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9240: if ($disposition eq 'automatic') {
9241: $refused = '';
9242: } elsif ($disposition eq '') {
9243: $checkbystatus = 1;
9244: }
9245: } else {
9246: $checkbystatus = 1;
9247: }
9248: if ($checkbystatus) {
9249: if ($env{'environment.inststatus'}) {
9250: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9251: foreach my $type (@inststatuses) {
9252: if (($type ne '') &&
9253: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9254: $refused = '';
9255: }
9256: }
9257: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9258: $refused = '';
9259: }
9260: }
9261: }
9262: }
9263: }
9264: }
9265: if ($refused) {
9266: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9267: ' '.$role.' '.$end.' '.$start.' by '.
9268: $env{'user.name'}.' at '.$env{'user.domain'});
9269: return 'refused';
9270: }
9271: }
9272: } elsif ($role eq 'au') {
9273: if ($url ne '/'.$udom.'/') {
9274: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9275: ' to assign author role for '.$uname.':'.$udom.
9276: ' in domain: '.$url.' refused (wrong domain).');
9277: return 'refused';
9278: }
9279: }
9280: $mrole=$role;
9281: }
9282: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
9283: "$udom:$uname:$url".'_'."$mrole=$role";
9284: if ($end) { $command.='_'.$end; }
9285: if ($start) {
9286: if ($end) {
9287: $command.='_'.$start;
9288: } else {
9289: $command.='_0_'.$start;
9290: }
9291: }
9292: my $origstart = $start;
9293: my $origend = $end;
9294: my $delflag;
9295: # actually delete
9296: if ($deleteflag) {
9297: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
9298: # modify command to delete the role
9299: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
9300: "$udom:$uname:$url".'_'."$mrole";
9301: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
9302: # set start and finish to negative values for userrolelog
9303: $start=-1;
9304: $end=-1;
9305: $delflag = 1;
9306: }
9307: }
9308: # send command
9309: my $answer=&reply($command,&homeserver($uname,$udom));
9310: # log new user role if status is ok
9311: if ($answer eq 'ok') {
9312: &userrolelog($role,$uname,$udom,$url,$start,$end);
9313: if (($role eq 'cc') || ($role eq 'in') ||
9314: ($role eq 'ep') || ($role eq 'ad') ||
9315: ($role eq 'ta') || ($role eq 'st') ||
9316: ($role=~/^cr/) || ($role eq 'gr') ||
9317: ($role eq 'co')) {
9318: # for course roles, perform group memberships changes triggered by role change.
9319: unless ($role =~ /^gr/) {
9320: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
9321: $origstart,$selfenroll,$context);
9322: }
9323: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9324: $selfenroll,$context);
9325: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
9326: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
9327: ($role eq 'da')) {
9328: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9329: $context);
9330: } elsif (($role eq 'ca') || ($role eq 'aa')) {
9331: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9332: $context);
9333: }
9334: if ($role eq 'cc') {
9335: &autoupdate_coowners($url,$end,$start,$uname,$udom);
9336: }
9337: }
9338: return $answer;
9339: }
9340:
9341: sub autoupdate_coowners {
9342: my ($url,$end,$start,$uname,$udom) = @_;
9343: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
9344: if (($cdom ne '') && ($cnum ne '')) {
9345: my $now = time;
9346: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
9347: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
9348: my %coursehash = &coursedescription($cdom.'_'.$cnum);
9349: my $instcode = $coursehash{'internal.coursecode'};
9350: if ($instcode ne '') {
9351: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
9352: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
9353: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
9354: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
9355: if ($result eq 'valid') {
9356: if ($coursehash{'internal.co-owners'}) {
9357: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9358: push(@newcoowners,$coowner);
9359: }
9360: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
9361: push(@newcoowners,$uname.':'.$udom);
9362: }
9363: @newcoowners = sort(@newcoowners);
9364: } else {
9365: push(@newcoowners,$uname.':'.$udom);
9366: }
9367: } else {
9368: if ($coursehash{'internal.co-owners'}) {
9369: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9370: unless ($coowner eq $uname.':'.$udom) {
9371: push(@newcoowners,$coowner);
9372: }
9373: }
9374: unless (@newcoowners > 0) {
9375: $delcoowners = 1;
9376: $coowners = '';
9377: }
9378: }
9379: }
9380: if (@newcoowners || $delcoowners) {
9381: &store_coowners($cdom,$cnum,$coursehash{'home'},
9382: $delcoowners,@newcoowners);
9383: }
9384: }
9385: }
9386: }
9387: }
9388: }
9389: }
9390:
9391: sub store_coowners {
9392: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
9393: my $cid = $cdom.'_'.$cnum;
9394: my ($coowners,$delresult,$putresult);
9395: if (@newcoowners) {
9396: $coowners = join(',',@newcoowners);
9397: my %coownershash = (
9398: 'internal.co-owners' => $coowners,
9399: );
9400: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
9401: if ($putresult eq 'ok') {
9402: if ($env{'course.'.$cid.'.num'} eq $cnum) {
9403: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
9404: }
9405: }
9406: }
9407: if ($delcoowners) {
9408: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
9409: if ($delresult eq 'ok') {
9410: if ($env{'course.'.$cid.'.internal.co-owners'}) {
9411: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
9412: }
9413: }
9414: }
9415: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
9416: my %crsinfo =
9417: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
9418: if (ref($crsinfo{$cid}) eq 'HASH') {
9419: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
9420: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
9421: }
9422: }
9423: }
9424:
9425: # -------------------------------------------------- Modify user authentication
9426: # Overrides without validation
9427:
9428: sub modifyuserauth {
9429: my ($udom,$uname,$umode,$upass)=@_;
9430: my $uhome=&homeserver($uname,$udom);
9431: unless (&allowed('mau',$udom)) { return 'refused'; }
9432: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
9433: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9434: ' in domain '.$env{'request.role.domain'});
9435: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
9436: &escape($upass),$uhome);
9437: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
9438: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
9439: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
9440: &log($udom,,$uname,$uhome,
9441: 'Authentication changed by '.$env{'user.domain'}.', '.
9442: $env{'user.name'}.', '.$umode.
9443: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
9444: unless ($reply eq 'ok') {
9445: &logthis('Authentication mode error: '.$reply);
9446: return 'error: '.$reply;
9447: }
9448: return 'ok';
9449: }
9450:
9451: # --------------------------------------------------------------- Modify a user
9452:
9453: sub modifyuser {
9454: my ($udom, $uname, $uid,
9455: $umode, $upass, $first,
9456: $middle, $last, $gene,
9457: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
9458: $udom= &LONCAPA::clean_domain($udom);
9459: $uname=&LONCAPA::clean_username($uname);
9460: my $showcandelete = 'none';
9461: if (ref($candelete) eq 'ARRAY') {
9462: if (@{$candelete} > 0) {
9463: $showcandelete = join(', ',@{$candelete});
9464: }
9465: }
9466: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
9467: $umode.', '.$first.', '.$middle.', '.
9468: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
9469: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
9470: ' desiredhome not specified').
9471: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9472: ' in domain '.$env{'request.role.domain'});
9473: my $uhome=&homeserver($uname,$udom,'true');
9474: my $newuser;
9475: if ($uhome eq 'no_host') {
9476: $newuser = 1;
9477: }
9478: # ----------------------------------------------------------------- Create User
9479: if (($uhome eq 'no_host') &&
9480: (($umode && $upass) || ($umode eq 'localauth'))) {
9481: my $unhome='';
9482: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
9483: $unhome = $desiredhome;
9484: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
9485: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
9486: } else { # load balancing routine for determining $unhome
9487: my $loadm=10000000;
9488: my %servers = &get_servers($udom,'library');
9489: foreach my $tryserver (keys(%servers)) {
9490: my $answer=reply('load',$tryserver);
9491: if (($answer=~/\d+/) && ($answer<$loadm)) {
9492: $loadm=$answer;
9493: $unhome=$tryserver;
9494: }
9495: }
9496: }
9497: if (($unhome eq '') || ($unhome eq 'no_host')) {
9498: return 'error: unable to find a home server for '.$uname.
9499: ' in domain '.$udom;
9500: }
9501: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
9502: &escape($upass),$unhome);
9503: unless ($reply eq 'ok') {
9504: return 'error: '.$reply;
9505: }
9506: $uhome=&homeserver($uname,$udom,'true');
9507: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
9508: return 'error: unable verify users home machine.';
9509: }
9510: } # End of creation of new user
9511: # ---------------------------------------------------------------------- Add ID
9512: if ($uid) {
9513: $uid=~tr/A-Z/a-z/;
9514: my %uidhash=&idrget($udom,$uname);
9515: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
9516: && (!$forceid)) {
9517: unless ($uid eq $uidhash{$uname}) {
9518: return 'error: user id "'.$uid.'" does not match '.
9519: 'current user id "'.$uidhash{$uname}.'".';
9520: }
9521: } else {
9522: &idput($udom,{$uname => $uid},$uhome,'ids');
9523: }
9524: }
9525: # -------------------------------------------------------------- Add names, etc
9526: my @tmp=&get('environment',
9527: ['firstname','middlename','lastname','generation','id',
9528: 'permanentemail','inststatus'],
9529: $udom,$uname);
9530: my (%names,%oldnames);
9531: if ($tmp[0] =~ m/^error:.*/) {
9532: %names=();
9533: } else {
9534: %names = @tmp;
9535: %oldnames = %names;
9536: }
9537: #
9538: # If name, email and/or uid are blank (e.g., because an uploaded file
9539: # of users did not contain them), do not overwrite existing values
9540: # unless field is in $candelete array ref.
9541: #
9542:
9543: my @fields = ('firstname','middlename','lastname','generation',
9544: 'permanentemail','id');
9545: my %newvalues;
9546: if (ref($candelete) eq 'ARRAY') {
9547: foreach my $field (@fields) {
9548: if (grep(/^\Q$field\E$/,@{$candelete})) {
9549: if ($field eq 'firstname') {
9550: $names{$field} = $first;
9551: } elsif ($field eq 'middlename') {
9552: $names{$field} = $middle;
9553: } elsif ($field eq 'lastname') {
9554: $names{$field} = $last;
9555: } elsif ($field eq 'generation') {
9556: $names{$field} = $gene;
9557: } elsif ($field eq 'permanentemail') {
9558: $names{$field} = $email;
9559: } elsif ($field eq 'id') {
9560: $names{$field} = $uid;
9561: }
9562: }
9563: }
9564: }
9565: if ($first) { $names{'firstname'} = $first; }
9566: if (defined($middle)) { $names{'middlename'} = $middle; }
9567: if ($last) { $names{'lastname'} = $last; }
9568: if (defined($gene)) { $names{'generation'} = $gene; }
9569: if ($email) {
9570: $email=~s/[^\w\@\.\-\,]//gs;
9571: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
9572: }
9573: if ($uid) { $names{'id'} = $uid; }
9574: if (defined($inststatus)) {
9575: $names{'inststatus'} = '';
9576: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
9577: if (ref($usertypes) eq 'HASH') {
9578: my @okstatuses;
9579: foreach my $item (split(/:/,$inststatus)) {
9580: if (defined($usertypes->{$item})) {
9581: push(@okstatuses,$item);
9582: }
9583: }
9584: if (@okstatuses) {
9585: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
9586: }
9587: }
9588: }
9589: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
9590: $umode.', '.$first.', '.$middle.', '.
9591: $last.', '.$gene.', '.$email.', '.$inststatus;
9592: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
9593: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
9594: } else {
9595: $logmsg .= ' during self creation';
9596: }
9597: my $changed;
9598: if ($newuser) {
9599: $changed = 1;
9600: } else {
9601: foreach my $field (@fields) {
9602: if ($names{$field} ne $oldnames{$field}) {
9603: $changed = 1;
9604: last;
9605: }
9606: }
9607: }
9608: unless ($changed) {
9609: $logmsg = 'No changes in user information needed for: '.$logmsg;
9610: &logthis($logmsg);
9611: return 'ok';
9612: }
9613: my $reply = &put('environment', \%names, $udom,$uname);
9614: if ($reply ne 'ok') {
9615: return 'error: '.$reply;
9616: }
9617: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
9618: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
9619: }
9620: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
9621: &devalidate_cache_new('namescache',$uname.':'.$udom);
9622: $logmsg = 'Success modifying user '.$logmsg;
9623: &logthis($logmsg);
9624: return 'ok';
9625: }
9626:
9627: # -------------------------------------------------------------- Modify student
9628:
9629: sub modifystudent {
9630: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
9631: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
9632: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
9633: if (!$cid) {
9634: unless ($cid=$env{'request.course.id'}) {
9635: return 'not_in_class';
9636: }
9637: }
9638: # --------------------------------------------------------------- Make the user
9639: my $reply=&modifyuser
9640: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
9641: $desiredhome,$email,$inststatus);
9642: unless ($reply eq 'ok') { return $reply; }
9643: # This will cause &modify_student_enrollment to get the uid from the
9644: # student's environment
9645: $uid = undef if (!$forceid);
9646: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
9647: $gene,$usec,$end,$start,$type,$locktype,
9648: $cid,$selfenroll,$context,$credits,$instsec);
9649: return $reply;
9650: }
9651:
9652: sub modify_student_enrollment {
9653: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
9654: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
9655: my ($cdom,$cnum,$chome);
9656: if (!$cid) {
9657: unless ($cid=$env{'request.course.id'}) {
9658: return 'not_in_class';
9659: }
9660: $cdom=$env{'course.'.$cid.'.domain'};
9661: $cnum=$env{'course.'.$cid.'.num'};
9662: } else {
9663: ($cdom,$cnum)=split(/_/,$cid);
9664: }
9665: $chome=$env{'course.'.$cid.'.home'};
9666: if (!$chome) {
9667: $chome=&homeserver($cnum,$cdom);
9668: }
9669: if (!$chome) { return 'unknown_course'; }
9670: # Make sure the user exists
9671: my $uhome=&homeserver($uname,$udom);
9672: if (($uhome eq '') || ($uhome eq 'no_host')) {
9673: return 'error: no such user';
9674: }
9675: # Get student data if we were not given enough information
9676: if (!defined($first) || $first eq '' ||
9677: !defined($last) || $last eq '' ||
9678: !defined($uid) || $uid eq '' ||
9679: !defined($middle) || $middle eq '' ||
9680: !defined($gene) || $gene eq '') {
9681: # They did not supply us with enough data to enroll the student, so
9682: # we need to pick up more information.
9683: my %tmp = &get('environment',
9684: ['firstname','middlename','lastname', 'generation','id']
9685: ,$udom,$uname);
9686:
9687: #foreach my $key (keys(%tmp)) {
9688: # &logthis("key $key = ".$tmp{$key});
9689: #}
9690: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
9691: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
9692: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
9693: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
9694: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
9695: }
9696: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
9697: my $user = "$uname:$udom";
9698: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
9699: my $reply=cput('classlist',
9700: {$user =>
9701: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
9702: $cdom,$cnum);
9703: if (($reply eq 'ok') || ($reply eq 'delayed')) {
9704: &devalidate_getsection_cache($udom,$uname,$cid);
9705: } else {
9706: return 'error: '.$reply;
9707: }
9708: # Add student role to user
9709: my $uurl='/'.$cid;
9710: $uurl=~s/\_/\//g;
9711: if ($usec) {
9712: $uurl.='/'.$usec;
9713: }
9714: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
9715: $selfenroll,$context);
9716: if ($result ne 'ok') {
9717: if ($old_entry{$user} ne '') {
9718: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
9719: } else {
9720: $reply = &del('classlist',[$user],$cdom,$cnum);
9721: }
9722: }
9723: return $result;
9724: }
9725:
9726: sub format_name {
9727: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
9728: my $name;
9729: if ($first ne 'lastname') {
9730: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
9731: } else {
9732: if ($lastname=~/\S/) {
9733: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
9734: $name=~s/\s+,/,/;
9735: } else {
9736: $name.= $firstname.' '.$middlename.' '.$generation;
9737: }
9738: }
9739: $name=~s/^\s+//;
9740: $name=~s/\s+$//;
9741: $name=~s/\s+/ /g;
9742: return $name;
9743: }
9744:
9745: # ------------------------------------------------- Write to course preferences
9746:
9747: sub writecoursepref {
9748: my ($courseid,%prefs)=@_;
9749: $courseid=~s/^\///;
9750: $courseid=~s/\_/\//g;
9751: my ($cdomain,$cnum)=split(/\//,$courseid);
9752: my $chome=homeserver($cnum,$cdomain);
9753: if (($chome eq '') || ($chome eq 'no_host')) {
9754: return 'error: no such course';
9755: }
9756: my $cstring='';
9757: foreach my $pref (keys(%prefs)) {
9758: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
9759: }
9760: $cstring=~s/\&$//;
9761: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
9762: }
9763:
9764: # ---------------------------------------------------------- Make/modify course
9765:
9766: sub createcourse {
9767: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
9768: $course_owner,$crstype,$cnum,$context,$category)=@_;
9769: $url=&declutter($url);
9770: my $cid='';
9771: if ($context eq 'requestcourses') {
9772: my $can_create = 0;
9773: my ($ownername,$ownerdom) = split(':',$course_owner);
9774: if ($udom eq $ownerdom) {
9775: if (&usertools_access($ownername,$ownerdom,$category,undef,
9776: $context)) {
9777: $can_create = 1;
9778: }
9779: } else {
9780: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
9781: $category);
9782: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
9783: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
9784: if (@curr > 0) {
9785: my @options = qw(approval validate autolimit);
9786: my $optregex = join('|',@options);
9787: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9788: $can_create = 1;
9789: }
9790: }
9791: }
9792: }
9793: if ($can_create) {
9794: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9795: unless (&allowed('ccc',$udom)) {
9796: return 'refused';
9797: }
9798: }
9799: } else {
9800: return 'refused';
9801: }
9802: } elsif (!&allowed('ccc',$udom)) {
9803: return 'refused';
9804: }
9805: # --------------------------------------------------------------- Get Unique ID
9806: my $uname;
9807: if ($cnum =~ /^$match_courseid$/) {
9808: my $chome=&homeserver($cnum,$udom,'true');
9809: if (($chome eq '') || ($chome eq 'no_host')) {
9810: $uname = $cnum;
9811: } else {
9812: $uname = &generate_coursenum($udom,$crstype);
9813: }
9814: } else {
9815: $uname = &generate_coursenum($udom,$crstype);
9816: }
9817: return $uname if ($uname =~ /^error/);
9818: # -------------------------------------------------- Check supplied server name
9819: if (!defined($course_server)) {
9820: if (defined(&domain($udom,'primary'))) {
9821: $course_server = &domain($udom,'primary');
9822: } else {
9823: $course_server = $env{'user.home'};
9824: }
9825: }
9826: my %host_servers =
9827: &Apache::lonnet::get_servers($udom,'library');
9828: unless ($host_servers{$course_server}) {
9829: return 'error: invalid home server for course: '.$course_server;
9830: }
9831: # ------------------------------------------------------------- Make the course
9832: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
9833: $course_server);
9834: unless ($reply eq 'ok') { return 'error: '.$reply; }
9835: my $uhome=&homeserver($uname,$udom,'true');
9836: if (($uhome eq '') || ($uhome eq 'no_host')) {
9837: return 'error: no such course';
9838: }
9839: # ----------------------------------------------------------------- Course made
9840: # log existence
9841: my $now = time;
9842: my $newcourse = {
9843: $udom.'_'.$uname => {
9844: description => $description,
9845: inst_code => $inst_code,
9846: owner => $course_owner,
9847: type => $crstype,
9848: creator => $env{'user.name'}.':'.
9849: $env{'user.domain'},
9850: created => $now,
9851: context => $context,
9852: },
9853: };
9854: &courseidput($udom,$newcourse,$uhome,'notime');
9855: # set toplevel url
9856: my $topurl=$url;
9857: unless ($nonstandard) {
9858: # ------------------------------------------ For standard courses, make top url
9859: my $mapurl=&clutter($url);
9860: if ($mapurl eq '/res/') { $mapurl=''; }
9861: $env{'form.initmap'}=(<<ENDINITMAP);
9862: <map>
9863: <resource id="1" type="start"></resource>
9864: <resource id="2" src="$mapurl"></resource>
9865: <resource id="3" type="finish"></resource>
9866: <link index="1" from="1" to="2"></link>
9867: <link index="2" from="2" to="3"></link>
9868: </map>
9869: ENDINITMAP
9870: $topurl=&declutter(
9871: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
9872: );
9873: }
9874: # ----------------------------------------------------------- Write preferences
9875: &writecoursepref($udom.'_'.$uname,
9876: ('description' => $description,
9877: 'url' => $topurl,
9878: 'internal.creator' => $env{'user.name'}.':'.
9879: $env{'user.domain'},
9880: 'internal.created' => $now,
9881: 'internal.creationcontext' => $context)
9882: );
9883: return '/'.$udom.'/'.$uname;
9884: }
9885:
9886: # ------------------------------------------------------------------- Create ID
9887: sub generate_coursenum {
9888: my ($udom,$crstype) = @_;
9889: my $domdesc = &domain($udom);
9890: return 'error: invalid domain' if ($domdesc eq '');
9891: my $first;
9892: if ($crstype eq 'Community') {
9893: $first = '0';
9894: } else {
9895: $first = int(1+rand(9));
9896: }
9897: my $uname=$first.
9898: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9899: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9900: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9901: # ----------------------------------------------- Make sure that does not exist
9902: my $uhome=&homeserver($uname,$udom,'true');
9903: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9904: if ($crstype eq 'Community') {
9905: $first = '0';
9906: } else {
9907: $first = int(1+rand(9));
9908: }
9909: $uname=$first.
9910: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9911: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9912: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9913: $uhome=&homeserver($uname,$udom,'true');
9914: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9915: return 'error: unable to generate unique course-ID';
9916: }
9917: }
9918: return $uname;
9919: }
9920:
9921: sub is_course {
9922: my ($cdom, $cnum) = scalar(@_) == 1 ?
9923: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9924:
9925: return unless $cdom and $cnum;
9926:
9927: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9928: '.');
9929:
9930: return unless(exists($courses{$cdom.'_'.$cnum}));
9931: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
9932: }
9933:
9934: sub store_userdata {
9935: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
9936: my $result;
9937: if ($datakey ne '') {
9938: if (ref($storehash) eq 'HASH') {
9939: if ($udom eq '' || $uname eq '') {
9940: $udom = $env{'user.domain'};
9941: $uname = $env{'user.name'};
9942: }
9943: my $uhome=&homeserver($uname,$udom);
9944: if (($uhome eq '') || ($uhome eq 'no_host')) {
9945: $result = 'error: no_host';
9946: } else {
9947: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9948: $storehash->{'host'} = $perlvar{'lonHostID'};
9949:
9950: my $namevalue='';
9951: foreach my $key (keys(%{$storehash})) {
9952: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9953: }
9954: $namevalue=~s/\&$//;
9955: unless ($namespace eq 'courserequests') {
9956: $datakey = &escape($datakey);
9957: }
9958: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9959: $namevalue,$uhome);
9960: }
9961: } else {
9962: $result = 'error: data to store was not a hash reference';
9963: }
9964: } else {
9965: $result= 'error: invalid requestkey';
9966: }
9967: return $result;
9968: }
9969:
9970: # ---------------------------------------------------------- Assign Custom Role
9971:
9972: sub assigncustomrole {
9973: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
9974: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
9975: $end,$start,$deleteflag,$selfenroll,$context);
9976: }
9977:
9978: # ----------------------------------------------------------------- Revoke Role
9979:
9980: sub revokerole {
9981: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
9982: my $now=time;
9983: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
9984: }
9985:
9986: # ---------------------------------------------------------- Revoke Custom Role
9987:
9988: sub revokecustomrole {
9989: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
9990: my $now=time;
9991: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
9992: $deleteflag,$selfenroll,$context);
9993: }
9994:
9995: # ------------------------------------------------------------ Disk usage
9996: sub diskusage {
9997: my ($udom,$uname,$directorypath,$getpropath)=@_;
9998: $directorypath =~ s/\/$//;
9999: my $listing=&reply('du2:'.&escape($directorypath).':'
10000: .&escape($getpropath).':'.&escape($uname).':'
10001: .&escape($udom),homeserver($uname,$udom));
10002: if ($listing eq 'unknown_cmd') {
10003: if ($getpropath) {
10004: $directorypath = &propath($udom,$uname).'/'.$directorypath;
10005: }
10006: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10007: }
10008: return $listing;
10009: }
10010:
10011: sub is_locked {
10012: my ($file_name, $domain, $user, $which) = @_;
10013: my @check;
10014: my $is_locked;
10015: push (@check,$file_name);
10016: my %locked = &get('file_permissions',\@check,
10017: $env{'user.domain'},$env{'user.name'});
10018: my ($tmp)=keys(%locked);
10019: if ($tmp=~/^error:/) { undef(%locked); }
10020:
10021: if (ref($locked{$file_name}) eq 'ARRAY') {
10022: $is_locked = 'false';
10023: foreach my $entry (@{$locked{$file_name}}) {
10024: if (ref($entry) eq 'ARRAY') {
10025: $is_locked = 'true';
10026: if (ref($which) eq 'ARRAY') {
10027: push(@{$which},$entry);
10028: } else {
10029: last;
10030: }
10031: }
10032: }
10033: } else {
10034: $is_locked = 'false';
10035: }
10036: return $is_locked;
10037: }
10038:
10039: sub declutter_portfile {
10040: my ($file) = @_;
10041: $file =~ s{^(/portfolio/|portfolio/)}{/};
10042: return $file;
10043: }
10044:
10045: # ------------------------------------------------------------- Mark as Read Only
10046:
10047: sub mark_as_readonly {
10048: my ($domain,$user,$files,$what) = @_;
10049: my %current_permissions = &dump('file_permissions',$domain,$user);
10050: my ($tmp)=keys(%current_permissions);
10051: if ($tmp=~/^error:/) { undef(%current_permissions); }
10052: foreach my $file (@{$files}) {
10053: $file = &declutter_portfile($file);
10054: push(@{$current_permissions{$file}},$what);
10055: }
10056: &put('file_permissions',\%current_permissions,$domain,$user);
10057: return;
10058: }
10059:
10060: # ------------------------------------------------------------Save Selected Files
10061:
10062: sub save_selected_files {
10063: my ($user, $path, @files) = @_;
10064: my $filename = $user."savedfiles";
10065: my @other_files = &files_not_in_path($user, $path);
10066: open (OUT, '>'.$tmpdir.$filename);
10067: foreach my $file (@files) {
10068: print (OUT $env{'form.currentpath'}.$file."\n");
10069: }
10070: foreach my $file (@other_files) {
10071: print (OUT $file."\n");
10072: }
10073: close (OUT);
10074: return 'ok';
10075: }
10076:
10077: sub clear_selected_files {
10078: my ($user) = @_;
10079: my $filename = $user."savedfiles";
10080: open (OUT, '>'.LONCAPA::tempdir().$filename);
10081: print (OUT undef);
10082: close (OUT);
10083: return ("ok");
10084: }
10085:
10086: sub files_in_path {
10087: my ($user, $path) = @_;
10088: my $filename = $user."savedfiles";
10089: my %return_files;
10090: open (IN, '<'.LONCAPA::tempdir().$filename);
10091: while (my $line_in = <IN>) {
10092: chomp ($line_in);
10093: my @paths_and_file = split (m!/!, $line_in);
10094: my $file_part = pop (@paths_and_file);
10095: my $path_part = join ('/', @paths_and_file);
10096: $path_part.='/';
10097: my $path_and_file = $path_part.$file_part;
10098: if ($path_part eq $path) {
10099: $return_files{$file_part}= 'selected';
10100: }
10101: }
10102: close (IN);
10103: return (\%return_files);
10104: }
10105:
10106: # called in portfolio select mode, to show files selected NOT in current directory
10107: sub files_not_in_path {
10108: my ($user, $path) = @_;
10109: my $filename = $user."savedfiles";
10110: my @return_files;
10111: my $path_part;
10112: open(IN, '<'.LONCAPA::.$filename);
10113: while (my $line = <IN>) {
10114: #ok, I know it's clunky, but I want it to work
10115: my @paths_and_file = split(m|/|, $line);
10116: my $file_part = pop(@paths_and_file);
10117: chomp($file_part);
10118: my $path_part = join('/', @paths_and_file);
10119: $path_part .= '/';
10120: my $path_and_file = $path_part.$file_part;
10121: if ($path_part ne $path) {
10122: push(@return_files, ($path_and_file));
10123: }
10124: }
10125: close(OUT);
10126: return (@return_files);
10127: }
10128:
10129: #------------------------------Submitted/Handedback Portfolio Files Versioning
10130:
10131: sub portfiles_versioning {
10132: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10133: my $portfolio_root = '/userfiles/portfolio';
10134: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10135: foreach my $file (@{$portfiles}) {
10136: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10137: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10138: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10139: my $getpropath = 1;
10140: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10141: $stu_name,$getpropath);
10142: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10143: my $new_answer =
10144: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10145: if ($new_answer ne 'problem getting file') {
10146: push(@{$versioned_portfiles}, $directory.$new_answer);
10147: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10148: [$symb,$env{'request.course.id'},'graded']);
10149: }
10150: }
10151: }
10152:
10153: sub get_next_version {
10154: my ($answer_name, $answer_ext, $dir_list) = @_;
10155: my $version;
10156: if (ref($dir_list) eq 'ARRAY') {
10157: foreach my $row (@{$dir_list}) {
10158: my ($file) = split(/\&/,$row,2);
10159: my ($file_name,$file_version,$file_ext) =
10160: &file_name_version_ext($file);
10161: if (($file_name eq $answer_name) &&
10162: ($file_ext eq $answer_ext)) {
10163: # gets here if filename and extension match,
10164: # regardless of version
10165: if ($file_version ne '') {
10166: # a versioned file is found so save it for later
10167: if ($file_version > $version) {
10168: $version = $file_version;
10169: }
10170: }
10171: }
10172: }
10173: }
10174: $version ++;
10175: return($version);
10176: }
10177:
10178: sub version_selected_portfile {
10179: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10180: my ($answer_name,$answer_ver,$answer_ext) =
10181: &file_name_version_ext($file_name);
10182: my $new_answer;
10183: $env{'form.copy'} =
10184: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10185: if($env{'form.copy'} eq '-1') {
10186: $new_answer = 'problem getting file';
10187: } else {
10188: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10189: my $copy_result =
10190: &finishuserfileupload($stu_name,$domain,'copy',
10191: '/portfolio'.$directory.$new_answer);
10192: }
10193: undef($env{'form.copy'});
10194: return ($new_answer);
10195: }
10196:
10197: sub file_name_version_ext {
10198: my ($file)=@_;
10199: my @file_parts = split(/\./, $file);
10200: my ($name,$version,$ext);
10201: if (@file_parts > 1) {
10202: $ext=pop(@file_parts);
10203: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10204: $version=pop(@file_parts);
10205: }
10206: $name=join('.',@file_parts);
10207: } else {
10208: $name=join('.',@file_parts);
10209: }
10210: return($name,$version,$ext);
10211: }
10212:
10213: #----------------------------------------------Get portfolio file permissions
10214:
10215: sub get_portfile_permissions {
10216: my ($domain,$user) = @_;
10217: my %current_permissions = &dump('file_permissions',$domain,$user);
10218: my ($tmp)=keys(%current_permissions);
10219: if ($tmp=~/^error:/) { undef(%current_permissions); }
10220: return \%current_permissions;
10221: }
10222:
10223: #---------------------------------------------Get portfolio file access controls
10224:
10225: sub get_access_controls {
10226: my ($current_permissions,$group,$file) = @_;
10227: my %access;
10228: my $real_file = $file;
10229: $file =~ s/\.meta$//;
10230: if (defined($file)) {
10231: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10232: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10233: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10234: }
10235: }
10236: } else {
10237: foreach my $key (keys(%{$current_permissions})) {
10238: if ($key =~ /\0accesscontrol$/) {
10239: if (defined($group)) {
10240: if ($key !~ m-^\Q$group\E/-) {
10241: next;
10242: }
10243: }
10244: my ($fullpath) = split(/\0/,$key);
10245: if (ref($$current_permissions{$key}) eq 'HASH') {
10246: foreach my $control (keys(%{$$current_permissions{$key}})) {
10247: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10248: }
10249: }
10250: }
10251: }
10252: }
10253: return %access;
10254: }
10255:
10256: sub modify_access_controls {
10257: my ($file_name,$changes,$domain,$user)=@_;
10258: my ($outcome,$deloutcome);
10259: my %store_permissions;
10260: my %new_values;
10261: my %new_control;
10262: my %translation;
10263: my @deletions = ();
10264: my $now = time;
10265: if (exists($$changes{'activate'})) {
10266: if (ref($$changes{'activate'}) eq 'HASH') {
10267: my @newitems = sort(keys(%{$$changes{'activate'}}));
10268: my $numnew = scalar(@newitems);
10269: for (my $i=0; $i<$numnew; $i++) {
10270: my $newkey = $newitems[$i];
10271: my $newid = &Apache::loncommon::get_cgi_id();
10272: if ($newkey =~ /^\d+:/) {
10273: $newkey =~ s/^(\d+)/$newid/;
10274: $translation{$1} = $newid;
10275: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10276: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10277: $translation{$1} = $newid;
10278: }
10279: $new_values{$file_name."\0".$newkey} =
10280: $$changes{'activate'}{$newitems[$i]};
10281: $new_control{$newkey} = $now;
10282: }
10283: }
10284: }
10285: my %todelete;
10286: my %changed_items;
10287: foreach my $action ('delete','update') {
10288: if (exists($$changes{$action})) {
10289: if (ref($$changes{$action}) eq 'HASH') {
10290: foreach my $key (keys(%{$$changes{$action}})) {
10291: my ($itemnum) = ($key =~ /^([^:]+):/);
10292: if ($action eq 'delete') {
10293: $todelete{$itemnum} = 1;
10294: } else {
10295: $changed_items{$itemnum} = $key;
10296: }
10297: }
10298: }
10299: }
10300: }
10301: # get lock on access controls for file.
10302: my $lockhash = {
10303: $file_name."\0".'locked_access_records' => $env{'user.name'}.
10304: ':'.$env{'user.domain'},
10305: };
10306: my $tries = 0;
10307: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10308:
10309: while (($gotlock ne 'ok') && $tries < 10) {
10310: $tries ++;
10311: sleep(0.1);
10312: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10313: }
10314: if ($gotlock eq 'ok') {
10315: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10316: my ($tmp)=keys(%curr_permissions);
10317: if ($tmp=~/^error:/) { undef(%curr_permissions); }
10318: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10319: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10320: if (ref($curr_controls) eq 'HASH') {
10321: foreach my $control_item (keys(%{$curr_controls})) {
10322: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10323: if (defined($todelete{$itemnum})) {
10324: push(@deletions,$file_name."\0".$control_item);
10325: } else {
10326: if (defined($changed_items{$itemnum})) {
10327: $new_control{$changed_items{$itemnum}} = $now;
10328: push(@deletions,$file_name."\0".$control_item);
10329: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10330: } else {
10331: $new_control{$control_item} = $$curr_controls{$control_item};
10332: }
10333: }
10334: }
10335: }
10336: }
10337: my ($group);
10338: if (&is_course($domain,$user)) {
10339: ($group,my $file) = split(/\//,$file_name,2);
10340: }
10341: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10342: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10343: $outcome = &put('file_permissions',\%new_values,$domain,$user);
10344: # remove lock
10345: my @del_lock = ($file_name."\0".'locked_access_records');
10346: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10347: my $sqlresult =
10348: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10349: $group);
10350: } else {
10351: $outcome = "error: could not obtain lockfile\n";
10352: }
10353: return ($outcome,$deloutcome,\%new_values,\%translation);
10354: }
10355:
10356: sub make_public_indefinitely {
10357: my (@requrl) = @_;
10358: return &automated_portfile_access('public',\@requrl);
10359: }
10360:
10361: sub automated_portfile_access {
10362: my ($accesstype,$addsref,$delsref,$info) = @_;
10363: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
10364: return 'invalid';
10365: }
10366: my %urls;
10367: if (ref($addsref) eq 'ARRAY') {
10368: foreach my $requrl (@{$addsref}) {
10369: if (&is_portfolio_url($requrl)) {
10370: unless (exists($urls{$requrl})) {
10371: $urls{$requrl} = 'add';
10372: }
10373: }
10374: }
10375: }
10376: if (ref($delsref) eq 'ARRAY') {
10377: foreach my $requrl (@{$delsref}) {
10378: if (&is_portfolio_url($requrl)) {
10379: unless (exists($urls{$requrl})) {
10380: $urls{$requrl} = 'delete';
10381: }
10382: }
10383: }
10384: }
10385: unless (keys(%urls)) {
10386: return 'invalid';
10387: }
10388: my $ip;
10389: if ($accesstype eq 'ip') {
10390: if (ref($info) eq 'HASH') {
10391: if ($info->{'ip'} ne '') {
10392: $ip = $info->{'ip'};
10393: }
10394: }
10395: if ($ip eq '') {
10396: return 'invalid';
10397: }
10398: }
10399: my $errors;
10400: my $now = time;
10401: my %current_perms;
10402: foreach my $requrl (sort(keys(%urls))) {
10403: my $action;
10404: if ($urls{$requrl} eq 'add') {
10405: $action = 'activate';
10406: } else {
10407: $action = 'none';
10408: }
10409: my $aclnum = 0;
10410: my (undef,$udom,$unum,$file_name,$group) =
10411: &parse_portfolio_url($requrl);
10412: unless (exists($current_perms{$unum.':'.$udom})) {
10413: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
10414: }
10415: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
10416: $group,$file_name);
10417: foreach my $key (keys(%{$access_controls{$file_name}})) {
10418: my ($num,$scope,$end,$start) =
10419: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10420: if ($scope eq $accesstype) {
10421: if (($start <= $now) && ($end == 0)) {
10422: if ($accesstype eq 'ip') {
10423: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
10424: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
10425: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
10426: if ($urls{$requrl} eq 'add') {
10427: $action = 'none';
10428: last;
10429: } else {
10430: $action = 'delete';
10431: $aclnum = $num;
10432: last;
10433: }
10434: }
10435: }
10436: }
10437: } elsif ($accesstype eq 'public') {
10438: if ($urls{$requrl} eq 'add') {
10439: $action = 'none';
10440: last;
10441: } else {
10442: $action = 'delete';
10443: $aclnum = $num;
10444: last;
10445: }
10446: }
10447: } elsif ($accesstype eq 'public') {
10448: $action = 'update';
10449: $aclnum = $num;
10450: last;
10451: }
10452: }
10453: }
10454: if ($action eq 'none') {
10455: next;
10456: } else {
10457: my %changes;
10458: my $newend = 0;
10459: my $newstart = $now;
10460: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
10461: $changes{$action}{$newkey} = {
10462: type => $accesstype,
10463: time => {
10464: start => $newstart,
10465: end => $newend,
10466: },
10467: };
10468: if ($accesstype eq 'ip') {
10469: $changes{$action}{$newkey}{'ip'} = [$ip];
10470: }
10471: my ($outcome,$deloutcome,$new_values,$translation) =
10472: &modify_access_controls($file_name,\%changes,$udom,$unum);
10473: unless ($outcome eq 'ok') {
10474: $errors .= $outcome.' ';
10475: }
10476: }
10477: }
10478: if ($errors) {
10479: $errors =~ s/\s$//;
10480: return $errors;
10481: } else {
10482: return 'ok';
10483: }
10484: }
10485:
10486: #------------------------------------------------------Get Marked as Read Only
10487:
10488: sub get_marked_as_readonly {
10489: my ($domain,$user,$what,$group) = @_;
10490: my $current_permissions = &get_portfile_permissions($domain,$user);
10491: my @readonly_files;
10492: my $cmp1=$what;
10493: if (ref($what)) { $cmp1=join('',@{$what}) };
10494: while (my ($file_name,$value) = each(%{$current_permissions})) {
10495: if (defined($group)) {
10496: if ($file_name !~ m-^\Q$group\E/-) {
10497: next;
10498: }
10499: }
10500: if (ref($value) eq "ARRAY"){
10501: foreach my $stored_what (@{$value}) {
10502: my $cmp2=$stored_what;
10503: if (ref($stored_what) eq 'ARRAY') {
10504: $cmp2=join('',@{$stored_what});
10505: }
10506: if ($cmp1 eq $cmp2) {
10507: push(@readonly_files, $file_name);
10508: last;
10509: } elsif (!defined($what)) {
10510: push(@readonly_files, $file_name);
10511: last;
10512: }
10513: }
10514: }
10515: }
10516: return @readonly_files;
10517: }
10518: #-----------------------------------------------------------Get Marked as Read Only Hash
10519:
10520: sub get_marked_as_readonly_hash {
10521: my ($current_permissions,$group,$what) = @_;
10522: my %readonly_files;
10523: while (my ($file_name,$value) = each(%{$current_permissions})) {
10524: if (defined($group)) {
10525: if ($file_name !~ m-^\Q$group\E/-) {
10526: next;
10527: }
10528: }
10529: if (ref($value) eq "ARRAY"){
10530: foreach my $stored_what (@{$value}) {
10531: if (ref($stored_what) eq 'ARRAY') {
10532: foreach my $lock_descriptor(@{$stored_what}) {
10533: if ($lock_descriptor eq 'graded') {
10534: $readonly_files{$file_name} = 'graded';
10535: } elsif ($lock_descriptor eq 'handback') {
10536: $readonly_files{$file_name} = 'handback';
10537: } else {
10538: if (!exists($readonly_files{$file_name})) {
10539: $readonly_files{$file_name} = 'locked';
10540: }
10541: }
10542: }
10543: }
10544: }
10545: }
10546: }
10547: return %readonly_files;
10548: }
10549: # ------------------------------------------------------------ Unmark as Read Only
10550:
10551: sub unmark_as_readonly {
10552: # unmarks $file_name (if $file_name is defined), or all files locked by $what
10553: # for portfolio submissions, $what contains [$symb,$crsid]
10554: my ($domain,$user,$what,$file_name,$group) = @_;
10555: $file_name = &declutter_portfile($file_name);
10556: my $symb_crs = $what;
10557: if (ref($what)) { $symb_crs=join('',@$what); }
10558: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
10559: my ($tmp)=keys(%current_permissions);
10560: if ($tmp=~/^error:/) { undef(%current_permissions); }
10561: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
10562: foreach my $file (@readonly_files) {
10563: my $clean_file = &declutter_portfile($file);
10564: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
10565: my $current_locks = $current_permissions{$file};
10566: my @new_locks;
10567: my @del_keys;
10568: if (ref($current_locks) eq "ARRAY"){
10569: foreach my $locker (@{$current_locks}) {
10570: my $compare=$locker;
10571: if (ref($locker) eq 'ARRAY') {
10572: $compare=join('',@{$locker});
10573: if ($compare ne $symb_crs) {
10574: push(@new_locks, $locker);
10575: }
10576: }
10577: }
10578: if (scalar(@new_locks) > 0) {
10579: $current_permissions{$file} = \@new_locks;
10580: } else {
10581: push(@del_keys, $file);
10582: &del('file_permissions',\@del_keys, $domain, $user);
10583: delete($current_permissions{$file});
10584: }
10585: }
10586: }
10587: &put('file_permissions',\%current_permissions,$domain,$user);
10588: return;
10589: }
10590:
10591: # ------------------------------------------------------------ Directory lister
10592:
10593: sub dirlist {
10594: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
10595: $uri=~s/^\///;
10596: $uri=~s/\/$//;
10597: my ($udom, $uname);
10598: if ($getuserdir) {
10599: $udom = $userdomain;
10600: $uname = $username;
10601: } else {
10602: (undef,$udom,$uname)=split(/\//,$uri);
10603: if(defined($userdomain)) {
10604: $udom = $userdomain;
10605: }
10606: if(defined($username)) {
10607: $uname = $username;
10608: }
10609: }
10610: my ($dirRoot,$listing,@listing_results);
10611:
10612: $dirRoot = $perlvar{'lonDocRoot'};
10613: if (defined($getpropath)) {
10614: $dirRoot = &propath($udom,$uname);
10615: $dirRoot =~ s/\/$//;
10616: } elsif (defined($getuserdir)) {
10617: my $subdir=$uname.'__';
10618: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10619: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10620: ."/$udom/$subdir/$uname";
10621: } elsif (defined($alternateRoot)) {
10622: $dirRoot = $alternateRoot;
10623: }
10624:
10625: if($udom) {
10626: if($uname) {
10627: my $uhome = &homeserver($uname,$udom);
10628: if ($uhome eq 'no_host') {
10629: return ([],'no_host');
10630: }
10631: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
10632: .$getuserdir.':'.&escape($dirRoot)
10633: .':'.&escape($uname).':'.&escape($udom),$uhome);
10634: if ($listing eq 'unknown_cmd') {
10635: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
10636: } else {
10637: @listing_results = map { &unescape($_); } split(/:/,$listing);
10638: }
10639: if ($listing eq 'unknown_cmd') {
10640: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
10641: @listing_results = split(/:/,$listing);
10642: } else {
10643: @listing_results = map { &unescape($_); } split(/:/,$listing);
10644: }
10645: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10646: ($listing eq 'rejected') || ($listing eq 'refused') ||
10647: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10648: return ([],$listing);
10649: } else {
10650: return (\@listing_results);
10651: }
10652: } elsif(!$alternateRoot) {
10653: my (%allusers,%listerror);
10654: my %servers = &get_servers($udom,'library');
10655: foreach my $tryserver (keys(%servers)) {
10656: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10657: &escape($udom),$tryserver);
10658: if ($listing eq 'unknown_cmd') {
10659: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10660: $udom, $tryserver);
10661: } else {
10662: @listing_results = map { &unescape($_); } split(/:/,$listing);
10663: }
10664: if ($listing eq 'unknown_cmd') {
10665: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10666: $udom, $tryserver);
10667: @listing_results = split(/:/,$listing);
10668: } else {
10669: @listing_results =
10670: map { &unescape($_); } split(/:/,$listing);
10671: }
10672: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10673: ($listing eq 'rejected') || ($listing eq 'refused') ||
10674: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10675: $listerror{$tryserver} = $listing;
10676: } else {
10677: foreach my $line (@listing_results) {
10678: my ($entry) = split(/&/,$line,2);
10679: $allusers{$entry} = 1;
10680: }
10681: }
10682: }
10683: my @alluserslist=();
10684: foreach my $user (sort(keys(%allusers))) {
10685: push(@alluserslist,$user.'&user');
10686: }
10687:
10688: if (!%listerror) {
10689: # no errors
10690: return (\@alluserslist);
10691: } elsif (scalar(keys(%servers)) == 1) {
10692: # one library server, one error
10693: my ($key) = keys(%listerror);
10694: return (\@alluserslist, $listerror{$key});
10695: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10696: # con_lost indicates that we might miss data from at least one
10697: # library server
10698: return (\@alluserslist, 'con_lost');
10699: } else {
10700: # multiple library servers and no con_lost -> data should be
10701: # complete.
10702: return (\@alluserslist);
10703: }
10704:
10705: } else {
10706: return ([],'missing username');
10707: }
10708: } elsif(!defined($getpropath)) {
10709: my $path = $perlvar{'lonDocRoot'}.'/res/';
10710: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10711: return (\@all_domains);
10712: } else {
10713: return ([],'missing domain');
10714: }
10715: }
10716:
10717: # --------------------------------------------- GetFileTimestamp
10718: # This function utilizes dirlist and returns the date stamp for
10719: # when it was last modified. It will also return an error of -1
10720: # if an error occurs
10721:
10722: sub GetFileTimestamp {
10723: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
10724: $studentDomain = &LONCAPA::clean_domain($studentDomain);
10725: $studentName = &LONCAPA::clean_username($studentName);
10726: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10727: undef,$getuserdir);
10728: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10729: return -1;
10730: }
10731: if (ref($fileref) eq 'ARRAY') {
10732: my @stats = split('&',$fileref->[0]);
10733: # @stats contains first the filename, then the stat output
10734: return $stats[10]; # so this is 10 instead of 9.
10735: } else {
10736: return -1;
10737: }
10738: }
10739:
10740: sub stat_file {
10741: my ($uri) = @_;
10742: $uri = &clutter_with_no_wrapper($uri);
10743:
10744: my ($udom,$uname,$file);
10745: if ($uri =~ m-^/(uploaded|editupload)/-) {
10746: ($udom,$uname,$file) =
10747: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
10748: $file = 'userfiles/'.$file;
10749: }
10750: if ($uri =~ m-^/res/-) {
10751: ($udom,$uname) =
10752: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
10753: $file = $uri;
10754: }
10755:
10756: if (!$udom || !$uname || !$file) {
10757: # unable to handle the uri
10758: return ();
10759: }
10760: my $getpropath;
10761: if ($file =~ /^userfiles\//) {
10762: $getpropath = 1;
10763: }
10764: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10765: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10766: return ();
10767: } else {
10768: if (ref($listref) eq 'ARRAY') {
10769: my @stats = split('&',$listref->[0]);
10770: shift(@stats); #filename is first
10771: return @stats;
10772: }
10773: }
10774: return ();
10775: }
10776:
10777: # --------------------------------------------------------- recursedirs
10778: # Recursive function to traverse either a specific user's Authoring Space
10779: # or corresponding Published Resource Space, and populate the hash ref:
10780: # $dirhashref with URLs of all directories, and if $filehashref hash
10781: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
10782: # or .rights files in resource space, and .meta, .save, .log, and .bak
10783: # files in Authoring Space.
10784: #
10785: # Inputs:
10786: #
10787: # $is_home - true if current server is home server for user's space
10788: # $context - either: priv, or res respectively for Authoring or Resource Space.
10789: # $docroot - Document root (i.e., /home/httpd/html
10790: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
10791: # $relpath - Current path (relative to top level).
10792: # $dirhashref - reference to hash to populate with URLs of directories (Required)
10793: # $filehashref - reference to hash to populate with URLs of files (Optional)
10794: #
10795: # Returns: nothing
10796: #
10797: # Side Effects: populates $dirhashref, and $filehashref (if provided).
10798: #
10799: # Currently used by interface/londocs.pm to create linked select boxes for
10800: # directory and filename to import a Course "Author" resource into a course, and
10801: # also to create linked select boxes for Authoring Space and Directory to choose
10802: # save location for creation of a new "standard" problem from the Course Editor.
10803: #
10804:
10805: sub recursedirs {
10806: my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
10807: return unless (ref($dirhashref) eq 'HASH');
10808: my $currpath = $docroot.$toppath;
10809: if ($relpath) {
10810: $currpath .= "/$relpath";
10811: }
10812: my $savefile;
10813: if (ref($filehashref)) {
10814: $savefile = 1;
10815: }
10816: if ($is_home) {
10817: if (opendir(my $dirh,$currpath)) {
10818: foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
10819: next if ($item eq '');
10820: if (-d "$currpath/$item") {
10821: my $newpath;
10822: if ($relpath) {
10823: $newpath = "$relpath/$item";
10824: } else {
10825: $newpath = $item;
10826: }
10827: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10828: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10829: } elsif ($savefile) {
10830: if ($context eq 'priv') {
10831: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10832: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10833: }
10834: } else {
10835: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
10836: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10837: }
10838: }
10839: }
10840: }
10841: closedir($dirh);
10842: }
10843: } else {
10844: my ($dirlistref,$listerror) =
10845: &dirlist($toppath.$relpath);
10846: my @dir_lines;
10847: my $dirptr=16384;
10848: if (ref($dirlistref) eq 'ARRAY') {
10849: foreach my $dir_line (sort
10850: {
10851: my ($afile)=split('&',$a,2);
10852: my ($bfile)=split('&',$b,2);
10853: return (lc($afile) cmp lc($bfile));
10854: } (@{$dirlistref})) {
10855: my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
10856: split(/\&/,$dir_line,16);
10857: $item =~ s/\s+$//;
10858: next if (($item =~ /^\.\.?$/) || ($obs));
10859: if ($dirptr&$testdir) {
10860: my $newpath;
10861: if ($relpath) {
10862: $newpath = "$relpath/$item";
10863: } else {
10864: $relpath = '/';
10865: $newpath = $item;
10866: }
10867: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10868: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10869: } elsif ($savefile) {
10870: if ($context eq 'priv') {
10871: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10872: $filehashref->{$relpath}{$item} = 1;
10873: }
10874: } else {
10875: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
10876: $filehashref->{$relpath}{$item} = 1;
10877: }
10878: }
10879: }
10880: }
10881: }
10882: }
10883: return;
10884: }
10885:
10886: # -------------------------------------------------------- Value of a Condition
10887:
10888: # gets the value of a specific preevaluated condition
10889: # stored in the string $env{user.state.<cid>}
10890: # or looks up a condition reference in the bighash and if if hasn't
10891: # already been evaluated recurses into docondval to get the value of
10892: # the condition, then memoizing it to
10893: # $env{user.state.<cid>.<condition>}
10894: sub directcondval {
10895: my $number=shift;
10896: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
10897: &Apache::lonuserstate::evalstate();
10898: }
10899: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10900: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10901: } elsif ($number =~ /^_/) {
10902: my $sub_condition;
10903: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10904: &GDBM_READER(),0640)) {
10905: $sub_condition=$bighash{'conditions'.$number};
10906: untie(%bighash);
10907: }
10908: my $value = &docondval($sub_condition);
10909: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
10910: return $value;
10911: }
10912: if ($env{'user.state.'.$env{'request.course.id'}}) {
10913: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
10914: } else {
10915: return 2;
10916: }
10917: }
10918:
10919: # get the collection of conditions for this resource
10920: sub condval {
10921: my $condidx=shift;
10922: my $allpathcond='';
10923: foreach my $cond (split(/\|/,$condidx)) {
10924: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10925: $allpathcond.=
10926: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10927: }
10928: }
10929: $allpathcond=~s/\|$//;
10930: return &docondval($allpathcond);
10931: }
10932:
10933: #evaluates an expression of conditions
10934: sub docondval {
10935: my ($allpathcond) = @_;
10936: my $result=0;
10937: if ($env{'request.course.id'}
10938: && defined($allpathcond)) {
10939: my $operand='|';
10940: my @stack;
10941: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10942: if ($chunk eq '(') {
10943: push @stack,($operand,$result);
10944: } elsif ($chunk eq ')') {
10945: my $before=pop @stack;
10946: if (pop @stack eq '&') {
10947: $result=$result>$before?$before:$result;
10948: } else {
10949: $result=$result>$before?$result:$before;
10950: }
10951: } elsif (($chunk eq '&') || ($chunk eq '|')) {
10952: $operand=$chunk;
10953: } else {
10954: my $new=directcondval($chunk);
10955: if ($operand eq '&') {
10956: $result=$result>$new?$new:$result;
10957: } else {
10958: $result=$result>$new?$result:$new;
10959: }
10960: }
10961: }
10962: }
10963: return $result;
10964: }
10965:
10966: # ---------------------------------------------------- Devalidate courseresdata
10967:
10968: sub devalidatecourseresdata {
10969: my ($coursenum,$coursedomain)=@_;
10970: my $hashid=$coursenum.':'.$coursedomain;
10971: &devalidate_cache_new('courseres',$hashid);
10972: }
10973:
10974:
10975: # --------------------------------------------------- Course Resourcedata Query
10976: #
10977: # Parameters:
10978: # $coursenum - Number of the course.
10979: # $coursedomain - Domain at which the course was created.
10980: # Returns:
10981: # A hash of the course parameters along (I think) with timestamps
10982: # and version info.
10983:
10984: sub get_courseresdata {
10985: my ($coursenum,$coursedomain)=@_;
10986: my $coursehom=&homeserver($coursenum,$coursedomain);
10987: my $hashid=$coursenum.':'.$coursedomain;
10988: my ($result,$cached)=&is_cached_new('courseres',$hashid);
10989: my %dumpreply;
10990: unless (defined($cached)) {
10991: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
10992: $result=\%dumpreply;
10993: my ($tmp) = keys(%dumpreply);
10994: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10995: &do_cache_new('courseres',$hashid,$result,600);
10996: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10997: return $tmp;
10998: } elsif ($tmp =~ /^(error)/) {
10999: $result=undef;
11000: &do_cache_new('courseres',$hashid,$result,600);
11001: }
11002: }
11003: return $result;
11004: }
11005:
11006: sub devalidateuserresdata {
11007: my ($uname,$udom)=@_;
11008: my $hashid="$udom:$uname";
11009: &devalidate_cache_new('userres',$hashid);
11010: }
11011:
11012: sub get_userresdata {
11013: my ($uname,$udom)=@_;
11014: #most student don\'t have any data set, check if there is some data
11015: if (&EXT_cache_status($udom,$uname)) { return undef; }
11016:
11017: my $hashid="$udom:$uname";
11018: my ($result,$cached)=&is_cached_new('userres',$hashid);
11019: if (!defined($cached)) {
11020: my %resourcedata=&dump('resourcedata',$udom,$uname);
11021: $result=\%resourcedata;
11022: &do_cache_new('userres',$hashid,$result,600);
11023: }
11024: my ($tmp)=keys(%$result);
11025: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11026: return $result;
11027: }
11028: #error 2 occurs when the .db doesn't exist
11029: if ($tmp!~/error: 2 /) {
11030: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11031: &logthis("<font color=\"blue\">WARNING:".
11032: " Trying to get resource data for ".
11033: $uname." at ".$udom.": ".
11034: $tmp."</font>");
11035: }
11036: } elsif ($tmp=~/error: 2 /) {
11037: #&EXT_cache_set($udom,$uname);
11038: &do_cache_new('userres',$hashid,undef,600);
11039: undef($tmp); # not really an error so don't send it back
11040: }
11041: return $tmp;
11042: }
11043: #----------------------------------------------- resdata - return resource data
11044: # Purpose:
11045: # Return resource data for either users or for a course.
11046: # Parameters:
11047: # $name - Course/user name.
11048: # $domain - Name of the domain the user/course is registered on.
11049: # $type - Type of thing $name is (must be 'course' or 'user')
11050: # $mapp - decluttered URL of enclosing map
11051: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
11052: # $recurseup - Ref to array of map URLs, starting with map containing
11053: # $mapp up through hierarchy of nested maps to top level map.
11054: # $courseid - CourseID (first part of param identifier).
11055: # $modifier - Middle part of param identifier.
11056: # $what - Last part of param identifier.
11057: # @which - Array of names of resources desired.
11058: # Returns:
11059: # The value of the first reasource in @which that is found in the
11060: # resource hash.
11061: # Exceptional Conditions:
11062: # If the $type passed in is not valid (not the string 'course' or
11063: # 'user', an undefined reference is returned.
11064: # If none of the resources are found, an undef is returned
11065: sub resdata {
11066: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11067: $modifier,$what,@which)=@_;
11068: my $result;
11069: if ($type eq 'course') {
11070: $result=&get_courseresdata($name,$domain);
11071: } elsif ($type eq 'user') {
11072: $result=&get_userresdata($name,$domain);
11073: }
11074: if (!ref($result)) { return $result; }
11075: foreach my $item (@which) {
11076: if ($item->[1] eq 'course') {
11077: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11078: unless ($$recursed) {
11079: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11080: $$recursed = 1;
11081: }
11082: foreach my $item (@${recurseup}) {
11083: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11084: last if (defined($result->{$norecursechk}));
11085: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11086: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11087: }
11088: }
11089: }
11090: if (defined($result->{$item->[0]})) {
11091: return [$result->{$item->[0]},$item->[1]];
11092: }
11093: }
11094: return undef;
11095: }
11096:
11097: sub get_domain_ltitools {
11098: my ($cdom) = @_;
11099: my %ltitools;
11100: my ($result,$cached)=&is_cached_new('ltitools',$cdom);
11101: if (defined($cached)) {
11102: if (ref($result) eq 'HASH') {
11103: %ltitools = %{$result};
11104: }
11105: } else {
11106: my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
11107: if (ref($domconfig{'ltitools'}) eq 'HASH') {
11108: %ltitools = %{$domconfig{'ltitools'}};
11109: my %encdomconfig = &get_dom('encconfig',['ltitools'],$cdom);
11110: if (ref($encdomconfig{'ltitools'}) eq 'HASH') {
11111: foreach my $id (keys(%ltitools)) {
11112: if (ref($encdomconfig{'ltitools'}{$id}) eq 'HASH') {
11113: foreach my $item ('key','secret') {
11114: $ltitools{$id}{$item} = $encdomconfig{'ltitools'}{$id}{$item};
11115: }
11116: }
11117: }
11118: }
11119: }
11120: my $cachetime = 24*60*60;
11121: &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
11122: }
11123: return %ltitools;
11124: }
11125:
11126: sub get_numsuppfiles {
11127: my ($cnum,$cdom,$ignorecache)=@_;
11128: my $hashid=$cnum.':'.$cdom;
11129: my ($suppcount,$cached);
11130: unless ($ignorecache) {
11131: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11132: }
11133: unless (defined($cached)) {
11134: my $chome=&homeserver($cnum,$cdom);
11135: unless ($chome eq 'no_host') {
11136: ($suppcount,my $errors) = (0,0);
11137: my $suppmap = 'supplemental.sequence';
11138: ($suppcount,$errors) =
11139: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11140: }
11141: &do_cache_new('suppcount',$hashid,$suppcount,600);
11142: }
11143: return $suppcount;
11144: }
11145:
11146: #
11147: # EXT resource caching routines
11148: #
11149:
11150: {
11151: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11152: #
11153: # The course for which we cache
11154: my $cachedmapkey='';
11155: # The cached recursive maps for this course
11156: my %cachedmaps=();
11157: # When this was last done
11158: my $cachedmaptime='';
11159:
11160: sub clear_EXT_cache_status {
11161: &delenv('cache.EXT.');
11162: }
11163:
11164: sub EXT_cache_status {
11165: my ($target_domain,$target_user) = @_;
11166: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11167: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11168: # We know already the user has no data
11169: return 1;
11170: } else {
11171: return 0;
11172: }
11173: }
11174:
11175: sub EXT_cache_set {
11176: my ($target_domain,$target_user) = @_;
11177: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11178: #&appenv({$cachename => time});
11179: }
11180:
11181: # --------------------------------------------------------- Value of a Variable
11182: sub EXT {
11183:
11184: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11185: unless ($varname) { return ''; }
11186: #get real user name/domain, courseid and symb
11187: my $courseid;
11188: my $publicuser;
11189: if ($symbparm) {
11190: $symbparm=&get_symb_from_alias($symbparm);
11191: }
11192: if (!($uname && $udom)) {
11193: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11194: if (!$symbparm) { $symbparm=$cursymb; }
11195: } else {
11196: $courseid=$env{'request.course.id'};
11197: }
11198: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11199: my $rest;
11200: if (defined($therest[0])) {
11201: $rest=join('.',@therest);
11202: } else {
11203: $rest='';
11204: }
11205:
11206: my $qualifierrest=$qualifier;
11207: if ($rest) { $qualifierrest.='.'.$rest; }
11208: my $spacequalifierrest=$space;
11209: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11210: if ($realm eq 'user') {
11211: # --------------------------------------------------------------- user.resource
11212: if ($space eq 'resource') {
11213: if ( (defined($Apache::lonhomework::parsing_a_problem)
11214: || defined($Apache::lonhomework::parsing_a_task))
11215: &&
11216: ($symbparm eq &symbread()) ) {
11217: # if we are in the middle of processing the resource the
11218: # get the value we are planning on committing
11219: if (defined($Apache::lonhomework::results{$qualifierrest})) {
11220: return $Apache::lonhomework::results{$qualifierrest};
11221: } else {
11222: return $Apache::lonhomework::history{$qualifierrest};
11223: }
11224: } else {
11225: my %restored;
11226: if ($publicuser || $env{'request.state'} eq 'construct') {
11227: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11228: } else {
11229: %restored=&restore($symbparm,$courseid,$udom,$uname);
11230: }
11231: return $restored{$qualifierrest};
11232: }
11233: # ----------------------------------------------------------------- user.access
11234: } elsif ($space eq 'access') {
11235: # FIXME - not supporting calls for a specific user
11236: return &allowed($qualifier,$rest);
11237: # ------------------------------------------ user.preferences, user.environment
11238: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11239: if (($uname eq $env{'user.name'}) &&
11240: ($udom eq $env{'user.domain'})) {
11241: return $env{join('.',('environment',$qualifierrest))};
11242: } else {
11243: my %returnhash;
11244: if (!$publicuser) {
11245: %returnhash=&userenvironment($udom,$uname,
11246: $qualifierrest);
11247: }
11248: return $returnhash{$qualifierrest};
11249: }
11250: # ----------------------------------------------------------------- user.course
11251: } elsif ($space eq 'course') {
11252: # FIXME - not supporting calls for a specific user
11253: return $env{join('.',('request.course',$qualifier))};
11254: # ------------------------------------------------------------------- user.role
11255: } elsif ($space eq 'role') {
11256: # FIXME - not supporting calls for a specific user
11257: my ($role,$where)=split(/\./,$env{'request.role'});
11258: if ($qualifier eq 'value') {
11259: return $role;
11260: } elsif ($qualifier eq 'extent') {
11261: return $where;
11262: }
11263: # ----------------------------------------------------------------- user.domain
11264: } elsif ($space eq 'domain') {
11265: return $udom;
11266: # ------------------------------------------------------------------- user.name
11267: } elsif ($space eq 'name') {
11268: return $uname;
11269: # ---------------------------------------------------- Any other user namespace
11270: } else {
11271: my %reply;
11272: if (!$publicuser) {
11273: %reply=&get($space,[$qualifierrest],$udom,$uname);
11274: }
11275: return $reply{$qualifierrest};
11276: }
11277: } elsif ($realm eq 'query') {
11278: # ---------------------------------------------- pull stuff out of query string
11279: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11280: [$spacequalifierrest]);
11281: return $env{'form.'.$spacequalifierrest};
11282: } elsif ($realm eq 'request') {
11283: # ------------------------------------------------------------- request.browser
11284: if ($space eq 'browser') {
11285: return $env{'browser.'.$qualifier};
11286: # ------------------------------------------------------------ request.filename
11287: } else {
11288: return $env{'request.'.$spacequalifierrest};
11289: }
11290: } elsif ($realm eq 'course') {
11291: # ---------------------------------------------------------- course.description
11292: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11293: } elsif ($realm eq 'resource') {
11294:
11295: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11296: if (!$symbparm) { $symbparm=&symbread(); }
11297: }
11298:
11299: if ($qualifier eq '') {
11300: if ($space eq 'title') {
11301: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11302: return &gettitle($symbparm);
11303: }
11304:
11305: if ($space eq 'map') {
11306: my ($map) = &decode_symb($symbparm);
11307: return &symbread($map);
11308: }
11309: if ($space eq 'maptitle') {
11310: my ($map) = &decode_symb($symbparm);
11311: return &gettitle($map);
11312: }
11313: if ($space eq 'filename') {
11314: if ($symbparm) {
11315: return &clutter((&decode_symb($symbparm))[2]);
11316: }
11317: return &hreflocation('',$env{'request.filename'});
11318: }
11319:
11320: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11321: if ($space eq 'visibleparts') {
11322: my $navmap = Apache::lonnavmaps::navmap->new();
11323: my $item;
11324: if (ref($navmap)) {
11325: my $res = $navmap->getBySymb($symbparm);
11326: my $parts = $res->parts();
11327: if (ref($parts) eq 'ARRAY') {
11328: $item = join(',',@{$parts});
11329: }
11330: undef($navmap);
11331: }
11332: return $item;
11333: }
11334: }
11335: }
11336:
11337: my ($section, $group, @groups, @recurseup, $recursed);
11338: my ($courselevelm,$courseleveli,$courselevel,$mapp);
11339: if (($courseid eq '') && ($cid)) {
11340: $courseid = $cid;
11341: }
11342: if (($symbparm && $courseid) &&
11343: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
11344:
11345: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11346:
11347: # ----------------------------------------------------- Cascading lookup scheme
11348: my $symbp=$symbparm;
11349: $mapp=&deversion((&decode_symb($symbp))[0]);
11350: my $symbparm=$symbp.'.'.$spacequalifierrest;
11351: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
11352: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11353: if (($env{'user.name'} eq $uname) &&
11354: ($env{'user.domain'} eq $udom)) {
11355: $section=$env{'request.course.sec'};
11356: @groups = split(/:/,$env{'request.course.groups'});
11357: @groups=&sort_course_groups($courseid,@groups);
11358: } else {
11359: if (! defined($usection)) {
11360: $section=&getsection($udom,$uname,$courseid);
11361: } else {
11362: $section = $usection;
11363: }
11364: @groups = &get_users_groups($udom,$uname,$courseid);
11365: }
11366:
11367: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11368: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11369: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
11370: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11371:
11372: $courselevel=$courseid.'.'.$spacequalifierrest;
11373: my $courselevelr=$courseid.'.'.$symbparm;
11374: $courseleveli=$courseid.'.'.$recurseparm;
11375: $courselevelm=$courseid.'.'.$mapparm;
11376:
11377: # ----------------------------------------------------------- first, check user
11378:
11379: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
11380: \@recurseup,$courseid,'.',$spacequalifierrest,
11381: ([$courselevelr,'resource'],
11382: [$courselevelm,'map' ],
11383: [$courseleveli,'map' ],
11384: [$courselevel, 'course' ]));
11385: if (defined($userreply)) { return &get_reply($userreply); }
11386:
11387: # ------------------------------------------------ second, check some of course
11388: my $coursereply;
11389: if (@groups > 0) {
11390: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11391: $recurseparm,$mapparm,$spacequalifierrest,
11392: $mapp,\$recursed,\@recurseup);
11393: if (defined($coursereply)) { return &get_reply($coursereply); }
11394: }
11395:
11396: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11397: $env{'course.'.$courseid.'.domain'},
11398: 'course',$mapp,\$recursed,\@recurseup,
11399: $courseid,'.['.$section.'].',$spacequalifierrest,
11400: ([$seclevelr, 'resource'],
11401: [$seclevelm, 'map' ],
11402: [$secleveli, 'map' ],
11403: [$seclevel, 'course' ],
11404: [$courselevelr,'resource']));
11405: if (defined($coursereply)) { return &get_reply($coursereply); }
11406:
11407: # ------------------------------------------------------ third, check map parms
11408: my %parmhash=();
11409: my $thisparm='';
11410: if (tie(%parmhash,'GDBM_File',
11411: $env{'request.course.fn'}.'_parms.db',
11412: &GDBM_READER(),0640)) {
11413: $thisparm=$parmhash{$symbparm};
11414: untie(%parmhash);
11415: }
11416: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
11417: }
11418: # ------------------------------------------ fourth, look in resource metadata
11419:
11420: my $what = $spacequalifierrest;
11421: $what=~s/\./\_/;
11422: my $filename;
11423: if (!$symbparm) { $symbparm=&symbread(); }
11424: if ($symbparm) {
11425: $filename=(&decode_symb($symbparm))[2];
11426: } else {
11427: $filename=$env{'request.filename'};
11428: }
11429: my $metadata=&metadata($filename,$what);
11430: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11431: $metadata=&metadata($filename,'parameter_'.$what);
11432: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11433:
11434: # ----------------------------------------------- fifth, look in rest of course
11435: if ($symbparm && defined($courseid) &&
11436: $courseid eq $env{'request.course.id'}) {
11437: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11438: $env{'course.'.$courseid.'.domain'},
11439: 'course',$mapp,\$recursed,\@recurseup,
11440: $courseid,'.',$spacequalifierrest,
11441: ([$courselevelm,'map' ],
11442: [$courseleveli,'map' ],
11443: [$courselevel, 'course']));
11444: if (defined($coursereply)) { return &get_reply($coursereply); }
11445: }
11446: # ------------------------------------------------------------------ Cascade up
11447: unless ($space eq '0') {
11448: my @parts=split(/_/,$space);
11449: my $id=pop(@parts);
11450: my $part=join('_',@parts);
11451: if ($part eq '') { $part='0'; }
11452: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
11453: $symbparm,$udom,$uname,$section,1);
11454: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
11455: }
11456: if ($recurse) { return undef; }
11457: my $pack_def=&packages_tab_default($filename,$varname);
11458: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
11459: # ---------------------------------------------------- Any other user namespace
11460: } elsif ($realm eq 'environment') {
11461: # ----------------------------------------------------------------- environment
11462: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11463: return $env{'environment.'.$spacequalifierrest};
11464: } else {
11465: if ($uname eq 'anonymous' && $udom eq '') {
11466: return '';
11467: }
11468: my %returnhash=&userenvironment($udom,$uname,
11469: $spacequalifierrest);
11470: return $returnhash{$spacequalifierrest};
11471: }
11472: } elsif ($realm eq 'system') {
11473: # ----------------------------------------------------------------- system.time
11474: if ($space eq 'time') {
11475: return time;
11476: }
11477: } elsif ($realm eq 'server') {
11478: # ----------------------------------------------------------------- system.time
11479: if ($space eq 'name') {
11480: return $ENV{'SERVER_NAME'};
11481: }
11482: }
11483: return '';
11484: }
11485:
11486: sub get_reply {
11487: my ($reply_value) = @_;
11488: if (ref($reply_value) eq 'ARRAY') {
11489: if (wantarray) {
11490: return @$reply_value;
11491: }
11492: return $reply_value->[0];
11493: } else {
11494: return $reply_value;
11495: }
11496: }
11497:
11498: sub check_group_parms {
11499: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
11500: $recursed,$recurseupref) = @_;
11501: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
11502: [$what,'course']);
11503: my $coursereply;
11504: foreach my $group (@{$groups}) {
11505: my @groupitems = ();
11506: foreach my $level (@levels) {
11507: my $item = $courseid.'.['.$group.'].'.$level->[0];
11508: push(@groupitems,[$item,$level->[1]]);
11509: }
11510: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11511: $env{'course.'.$courseid.'.domain'},
11512: 'course',$mapp,$recursed,$recurseupref,
11513: $courseid,'.['.$group.'].',$what,
11514: @groupitems);
11515: last if (defined($coursereply));
11516: }
11517: return $coursereply;
11518: }
11519:
11520: sub get_map_hierarchy {
11521: my ($mapname,$courseid) = @_;
11522: my @recurseup = ();
11523: if ($mapname) {
11524: if (($cachedmapkey eq $courseid) &&
11525: (abs($cachedmaptime-time)<5)) {
11526: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
11527: return @{$cachedmaps{$mapname}};
11528: }
11529: }
11530: my $navmap = Apache::lonnavmaps::navmap->new();
11531: if (ref($navmap)) {
11532: @recurseup = $navmap->recurseup_maps($mapname);
11533: undef($navmap);
11534: $cachedmaps{$mapname} = \@recurseup;
11535: $cachedmaptime=time;
11536: $cachedmapkey=$courseid;
11537: }
11538: }
11539: return @recurseup;
11540: }
11541:
11542: }
11543:
11544: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
11545: my ($courseid,@groups) = @_;
11546: @groups = sort(@groups);
11547: return @groups;
11548: }
11549:
11550: sub packages_tab_default {
11551: my ($uri,$varname)=@_;
11552: my (undef,$part,$name)=split(/\./,$varname);
11553:
11554: my (@extension,@specifics,$do_default);
11555: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
11556: my ($pack_type,$pack_part)=split(/_/,$package,2);
11557: if ($pack_type eq 'default') {
11558: $do_default=1;
11559: } elsif ($pack_type eq 'extension') {
11560: push(@extension,[$package,$pack_type,$pack_part]);
11561: } elsif ($pack_part eq $part || $pack_type eq 'part') {
11562: # only look at packages defaults for packages that this id is
11563: push(@specifics,[$package,$pack_type,$pack_part]);
11564: }
11565: }
11566: # first look for a package that matches the requested part id
11567: foreach my $package (@specifics) {
11568: my (undef,$pack_type,$pack_part)=@{$package};
11569: next if ($pack_part ne $part);
11570: if (defined($packagetab{"$pack_type&$name&default"})) {
11571: return $packagetab{"$pack_type&$name&default"};
11572: }
11573: }
11574: # look for any possible matching non extension_ package
11575: foreach my $package (@specifics) {
11576: my (undef,$pack_type,$pack_part)=@{$package};
11577: if (defined($packagetab{"$pack_type&$name&default"})) {
11578: return $packagetab{"$pack_type&$name&default"};
11579: }
11580: if ($pack_type eq 'part') { $pack_part='0'; }
11581: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11582: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
11583: }
11584: }
11585: # look for any posible extension_ match
11586: foreach my $package (@extension) {
11587: my ($package,$pack_type)=@{$package};
11588: if (defined($packagetab{"$pack_type&$name&default"})) {
11589: return $packagetab{"$pack_type&$name&default"};
11590: }
11591: if (defined($packagetab{$package."&$name&default"})) {
11592: return $packagetab{$package."&$name&default"};
11593: }
11594: }
11595: # look for a global default setting
11596: if ($do_default && defined($packagetab{"default&$name&default"})) {
11597: return $packagetab{"default&$name&default"};
11598: }
11599: return undef;
11600: }
11601:
11602: sub add_prefix_and_part {
11603: my ($prefix,$part)=@_;
11604: my $keyroot;
11605: if (defined($prefix) && $prefix !~ /^__/) {
11606: # prefix that has a part already
11607: $keyroot=$prefix;
11608: } elsif (defined($prefix)) {
11609: # prefix that is missing a part
11610: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11611: } else {
11612: # no prefix at all
11613: if (defined($part)) { $keyroot='_'.$part; }
11614: }
11615: return $keyroot;
11616: }
11617:
11618: # ---------------------------------------------------------------- Get metadata
11619:
11620: my %metaentry;
11621: my %importedpartids;
11622: sub metadata {
11623: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
11624: $uri=&declutter($uri);
11625: # if it is a non metadata possible uri return quickly
11626: if (($uri eq '') ||
11627: (($uri =~ m|^/*adm/|) &&
11628: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
11629: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
11630: return undef;
11631: }
11632: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
11633: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
11634: return undef;
11635: }
11636: my $filename=$uri;
11637: $uri=~s/\.meta$//;
11638: #
11639: # Is the metadata already cached?
11640: # Look at timestamp of caching
11641: # Everything is cached by the main uri, libraries are never directly cached
11642: #
11643: if (!defined($liburi)) {
11644: my ($result,$cached)=&is_cached_new('meta',$uri);
11645: if (defined($cached)) { return $result->{':'.$what}; }
11646: }
11647: {
11648: # Imported parts would go here
11649: my %importedids=();
11650: my @origfileimportpartids=();
11651: my $importedparts=0;
11652: #
11653: # Is this a recursive call for a library?
11654: #
11655: # if (! exists($metacache{$uri})) {
11656: # $metacache{$uri}={};
11657: # }
11658: my $cachetime = 60*60;
11659: if ($liburi) {
11660: $liburi=&declutter($liburi);
11661: $filename=$liburi;
11662: } else {
11663: &devalidate_cache_new('meta',$uri);
11664: undef(%metaentry);
11665: }
11666: my %metathesekeys=();
11667: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
11668: my $metastring;
11669: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
11670: my $which = &hreflocation('','/'.($liburi || $uri));
11671: $metastring =
11672: &Apache::lonnet::ssi_body($which,
11673: ('grade_target' => 'meta'));
11674: $cachetime = 1; # only want this cached in the child not long term
11675: } elsif (($uri !~ m -^(editupload)/-) &&
11676: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
11677: my $file=&filelocation('',&clutter($filename));
11678: #push(@{$metaentry{$uri.'.file'}},$file);
11679: $metastring=&getfile($file);
11680: }
11681: my $parser=HTML::LCParser->new(\$metastring);
11682: my $token;
11683: undef %metathesekeys;
11684: while ($token=$parser->get_token) {
11685: if ($token->[0] eq 'S') {
11686: if (defined($token->[2]->{'package'})) {
11687: #
11688: # This is a package - get package info
11689: #
11690: my $package=$token->[2]->{'package'};
11691: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11692: if (defined($token->[2]->{'id'})) {
11693: $keyroot.='_'.$token->[2]->{'id'};
11694: }
11695: if ($metaentry{':packages'}) {
11696: $metaentry{':packages'}.=','.$package.$keyroot;
11697: } else {
11698: $metaentry{':packages'}=$package.$keyroot;
11699: }
11700: foreach my $pack_entry (keys(%packagetab)) {
11701: my $part=$keyroot;
11702: $part=~s/^\_//;
11703: if ($pack_entry=~/^\Q$package\E\&/ ||
11704: $pack_entry=~/^\Q$package\E_0\&/) {
11705: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
11706: # ignore package.tab specified default values
11707: # here &package_tab_default() will fetch those
11708: if ($subp eq 'default') { next; }
11709: my $value=$packagetab{$pack_entry};
11710: my $unikey;
11711: if ($pack =~ /_0$/) {
11712: $unikey='parameter_0_'.$name;
11713: $part=0;
11714: } else {
11715: $unikey='parameter'.$keyroot.'_'.$name;
11716: }
11717: if ($subp eq 'display') {
11718: $value.=' [Part: '.$part.']';
11719: }
11720: $metaentry{':'.$unikey.'.part'}=$part;
11721: $metathesekeys{$unikey}=1;
11722: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11723: $metaentry{':'.$unikey.'.'.$subp}=$value;
11724: }
11725: if (defined($metaentry{':'.$unikey.'.default'})) {
11726: $metaentry{':'.$unikey}=
11727: $metaentry{':'.$unikey.'.default'};
11728: }
11729: }
11730: }
11731: } else {
11732: #
11733: # This is not a package - some other kind of start tag
11734: #
11735: my $entry=$token->[1];
11736: my $unikey='';
11737:
11738: if ($entry eq 'import') {
11739: #
11740: # Importing a library here
11741: #
11742: my $location=$parser->get_text('/import');
11743: my $dir=$filename;
11744: $dir=~s|[^/]*$||;
11745: $location=&filelocation($dir,$location);
11746:
11747: my $importmode=$token->[2]->{'importmode'};
11748: if ($importmode eq 'problem') {
11749: # Import as problem/response
11750: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11751: } elsif ($importmode eq 'part') {
11752: # Import as part(s)
11753: $importedparts=1;
11754: # We need to get the original file and the imported file to get the part order correct
11755: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11756: # Load and inspect original file
11757: if ($#origfileimportpartids<0) {
11758: undef(%importedpartids);
11759: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11760: my $origfile=&getfile($origfilelocation);
11761: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11762: }
11763:
11764: # Load and inspect imported file
11765: my $impfile=&getfile($location);
11766: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11767: if ($#impfilepartids>=0) {
11768: # This problem had parts
11769: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
11770: } else {
11771: # Importing by turning a single problem into a problem part
11772: # It gets the import-tags ID as part-ID
11773: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
11774: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
11775: }
11776: } else {
11777: # Normal import
11778: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11779: if (defined($token->[2]->{'id'})) {
11780: $unikey.='_'.$token->[2]->{'id'};
11781: }
11782: }
11783:
11784: if ($depthcount<20) {
11785: my $metadata =
11786: &metadata($uri,'keys', $location,$unikey,
11787: $depthcount+1);
11788: foreach my $meta (split(',',$metadata)) {
11789: $metaentry{':'.$meta}=$metaentry{':'.$meta};
11790: $metathesekeys{$meta}=1;
11791: }
11792:
11793: }
11794: } else {
11795: #
11796: # Not importing, some other kind of non-package, non-library start tag
11797: #
11798: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11799: if (defined($token->[2]->{'id'})) {
11800: $unikey.='_'.$token->[2]->{'id'};
11801: }
11802: if (defined($token->[2]->{'name'})) {
11803: $unikey.='_'.$token->[2]->{'name'};
11804: }
11805: $metathesekeys{$unikey}=1;
11806: foreach my $param (@{$token->[3]}) {
11807: $metaentry{':'.$unikey.'.'.$param} =
11808: $token->[2]->{$param};
11809: }
11810: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
11811: my $default=$metaentry{':'.$unikey.'.default'};
11812: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11813: # only ws inside the tag, and not in default, so use default
11814: # as value
11815: $metaentry{':'.$unikey}=$default;
11816: } elsif ( $internaltext =~ /\S/ ) {
11817: # something interesting inside the tag
11818: $metaentry{':'.$unikey}=$internaltext;
11819: } else {
11820: # no interesting values, don't set a default
11821: }
11822: # end of not-a-package not-a-library import
11823: }
11824: # end of not-a-package start tag
11825: }
11826: # the next is the end of "start tag"
11827: }
11828: }
11829: my ($extension) = ($uri =~ /\.(\w+)$/);
11830: $extension = lc($extension);
11831: if ($extension eq 'htm') { $extension='html'; }
11832:
11833: foreach my $key (keys(%packagetab)) {
11834: #no specific packages #how's our extension
11835: if ($key!~/^extension_\Q$extension\E&/) { next; }
11836: &metadata_create_package_def($uri,$key,'extension_'.$extension,
11837: \%metathesekeys);
11838: }
11839:
11840: if (!exists($metaentry{':packages'})
11841: || $packagetab{"import_defaults&extension_$extension"}) {
11842: foreach my $key (keys(%packagetab)) {
11843: #no specific packages well let's get default then
11844: if ($key!~/^default&/) { next; }
11845: &metadata_create_package_def($uri,$key,'default',
11846: \%metathesekeys);
11847: }
11848: }
11849: # are there custom rights to evaluate
11850: if ($metaentry{':copyright'} eq 'custom') {
11851:
11852: #
11853: # Importing a rights file here
11854: #
11855: unless ($depthcount) {
11856: my $location=$metaentry{':customdistributionfile'};
11857: my $dir=$filename;
11858: $dir=~s|[^/]*$||;
11859: $location=&filelocation($dir,$location);
11860: my $rights_metadata =
11861: &metadata($uri,'keys',$location,'_rights',
11862: $depthcount+1);
11863: foreach my $rights (split(',',$rights_metadata)) {
11864: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11865: $metathesekeys{$rights}=1;
11866: }
11867: }
11868: }
11869: # uniqifiy package listing
11870: my %seen;
11871: my @uniq_packages =
11872: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11873: $metaentry{':packages'} = join(',',@uniq_packages);
11874:
11875: if ($importedparts) {
11876: # We had imported parts and need to rebuild partorder
11877: $metaentry{':partorder'}='';
11878: $metathesekeys{'partorder'}=1;
11879: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
11880: if ($origfileimportpartids[$index] eq 'part') {
11881: # original part, part of the problem
11882: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
11883: } else {
11884: # we have imported parts at this position
11885: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
11886: }
11887: }
11888: $metaentry{':partorder'}=~s/^\,//;
11889: }
11890:
11891: $metaentry{':keys'} = join(',',keys(%metathesekeys));
11892: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
11893: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
11894: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
11895: # this is the end of "was not already recently cached
11896: }
11897: return $metaentry{':'.$what};
11898: }
11899:
11900: sub metadata_create_package_def {
11901: my ($uri,$key,$package,$metathesekeys)=@_;
11902: my ($pack,$name,$subp)=split(/\&/,$key);
11903: if ($subp eq 'default') { next; }
11904:
11905: if (defined($metaentry{':packages'})) {
11906: $metaentry{':packages'}.=','.$package;
11907: } else {
11908: $metaentry{':packages'}=$package;
11909: }
11910: my $value=$packagetab{$key};
11911: my $unikey;
11912: $unikey='parameter_0_'.$name;
11913: $metaentry{':'.$unikey.'.part'}=0;
11914: $$metathesekeys{$unikey}=1;
11915: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11916: $metaentry{':'.$unikey.'.'.$subp}=$value;
11917: }
11918: if (defined($metaentry{':'.$unikey.'.default'})) {
11919: $metaentry{':'.$unikey}=
11920: $metaentry{':'.$unikey.'.default'};
11921: }
11922: }
11923:
11924: sub metadata_generate_part0 {
11925: my ($metadata,$metacache,$uri) = @_;
11926: my %allnames;
11927: foreach my $metakey (keys(%$metadata)) {
11928: if ($metakey=~/^parameter\_(.*)/) {
11929: my $part=$$metacache{':'.$metakey.'.part'};
11930: my $name=$$metacache{':'.$metakey.'.name'};
11931: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
11932: $allnames{$name}=$part;
11933: }
11934: }
11935: }
11936: foreach my $name (keys(%allnames)) {
11937: $$metadata{"parameter_0_$name"}=1;
11938: my $key=":parameter_0_$name";
11939: $$metacache{"$key.part"}='0';
11940: $$metacache{"$key.name"}=$name;
11941: $$metacache{"$key.type"}=$$metacache{':parameter_'.
11942: $allnames{$name}.'_'.$name.
11943: '.type'};
11944: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
11945: '.display'};
11946: my $expr='[Part: '.$allnames{$name}.']';
11947: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
11948: $$metacache{"$key.display"}=$olddis;
11949: }
11950: }
11951:
11952: # ------------------------------------------------------ Devalidate title cache
11953:
11954: sub devalidate_title_cache {
11955: my ($url)=@_;
11956: if (!$env{'request.course.id'}) { return; }
11957: my $symb=&symbread($url);
11958: if (!$symb) { return; }
11959: my $key=$env{'request.course.id'}."\0".$symb;
11960: &devalidate_cache_new('title',$key);
11961: }
11962:
11963: # ------------------------------------------------- Get the title of a course
11964:
11965: sub current_course_title {
11966: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
11967: }
11968: # ------------------------------------------------- Get the title of a resource
11969:
11970: sub gettitle {
11971: my $urlsymb=shift;
11972: my $symb=&symbread($urlsymb);
11973: if ($symb) {
11974: my $key=$env{'request.course.id'}."\0".$symb;
11975: my ($result,$cached)=&is_cached_new('title',$key);
11976: if (defined($cached)) {
11977: return $result;
11978: }
11979: my ($map,$resid,$url)=&decode_symb($symb);
11980: my $title='';
11981: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
11982: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
11983: } else {
11984: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11985: &GDBM_READER(),0640)) {
11986: my $mapid=$bighash{'map_pc_'.&clutter($map)};
11987: $title=$bighash{'title_'.$mapid.'.'.$resid};
11988: untie(%bighash);
11989: }
11990: }
11991: $title=~s/\&colon\;/\:/gs;
11992: if ($title) {
11993: # Remember both $symb and $title for dynamic metadata
11994: $accesshash{$symb.'___crstitle'}=$title;
11995: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
11996: # Cache this title and then return it
11997: return &do_cache_new('title',$key,$title,600);
11998: }
11999: $urlsymb=$url;
12000: }
12001: my $title=&metadata($urlsymb,'title');
12002: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
12003: return $title;
12004: }
12005:
12006: sub get_slot {
12007: my ($which,$cnum,$cdom)=@_;
12008: if (!$cnum || !$cdom) {
12009: (undef,my $courseid)=&whichuser();
12010: $cdom=$env{'course.'.$courseid.'.domain'};
12011: $cnum=$env{'course.'.$courseid.'.num'};
12012: }
12013: my $key=join("\0",'slots',$cdom,$cnum,$which);
12014: my %slotinfo;
12015: if (exists($remembered{$key})) {
12016: $slotinfo{$which} = $remembered{$key};
12017: } else {
12018: %slotinfo=&get('slots',[$which],$cdom,$cnum);
12019: &Apache::lonhomework::showhash(%slotinfo);
12020: my ($tmp)=keys(%slotinfo);
12021: if ($tmp=~/^error:/) { return (); }
12022: $remembered{$key} = $slotinfo{$which};
12023: }
12024: if (ref($slotinfo{$which}) eq 'HASH') {
12025: return %{$slotinfo{$which}};
12026: }
12027: return $slotinfo{$which};
12028: }
12029:
12030: sub get_reservable_slots {
12031: my ($cnum,$cdom,$uname,$udom) = @_;
12032: my $now = time;
12033: my $reservable_info;
12034: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12035: if (exists($remembered{$key})) {
12036: $reservable_info = $remembered{$key};
12037: } else {
12038: my %resv;
12039: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12040: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12041: $reservable_info = \%resv;
12042: $remembered{$key} = $reservable_info;
12043: }
12044: return $reservable_info;
12045: }
12046:
12047: sub get_course_slots {
12048: my ($cnum,$cdom) = @_;
12049: my $hashid=$cnum.':'.$cdom;
12050: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12051: if (defined($cached)) {
12052: if (ref($result) eq 'HASH') {
12053: return %{$result};
12054: }
12055: } else {
12056: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12057: my ($tmp) = keys(%slots);
12058: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12059: &do_cache_new('allslots',$hashid,\%slots,600);
12060: return %slots;
12061: }
12062: }
12063: return;
12064: }
12065:
12066: sub devalidate_slots_cache {
12067: my ($cnum,$cdom)=@_;
12068: my $hashid=$cnum.':'.$cdom;
12069: &devalidate_cache_new('allslots',$hashid);
12070: }
12071:
12072: sub get_coursechange {
12073: my ($cdom,$cnum) = @_;
12074: if ($cdom eq '' || $cnum eq '') {
12075: return unless ($env{'request.course.id'});
12076: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12077: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12078: }
12079: my $hashid=$cdom.'_'.$cnum;
12080: my ($change,$cached)=&is_cached_new('crschange',$hashid);
12081: if ((defined($cached)) && ($change ne '')) {
12082: return $change;
12083: } else {
12084: my %crshash;
12085: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12086: if ($crshash{'internal.contentchange'} eq '') {
12087: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12088: if ($change eq '') {
12089: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12090: $change = $crshash{'internal.created'};
12091: }
12092: } else {
12093: $change = $crshash{'internal.contentchange'};
12094: }
12095: my $cachetime = 600;
12096: &do_cache_new('crschange',$hashid,$change,$cachetime);
12097: }
12098: return $change;
12099: }
12100:
12101: sub devalidate_coursechange_cache {
12102: my ($cnum,$cdom)=@_;
12103: my $hashid=$cnum.':'.$cdom;
12104: &devalidate_cache_new('crschange',$hashid);
12105: }
12106:
12107: # ------------------------------------------------- Update symbolic store links
12108:
12109: sub symblist {
12110: my ($mapname,%newhash)=@_;
12111: $mapname=&deversion(&declutter($mapname));
12112: my %hash;
12113: if (($env{'request.course.fn'}) && (%newhash)) {
12114: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12115: &GDBM_WRCREAT(),0640)) {
12116: foreach my $url (keys(%newhash)) {
12117: next if ($url eq 'last_known'
12118: && $env{'form.no_update_last_known'});
12119: $hash{declutter($url)}=&encode_symb($mapname,
12120: $newhash{$url}->[1],
12121: $newhash{$url}->[0]);
12122: }
12123: if (untie(%hash)) {
12124: return 'ok';
12125: }
12126: }
12127: }
12128: return 'error';
12129: }
12130:
12131: # --------------------------------------------------------------- Verify a symb
12132:
12133: sub symbverify {
12134: my ($symb,$thisurl,$encstate)=@_;
12135: my $thisfn=$thisurl;
12136: $thisfn=&declutter($thisfn);
12137: # direct jump to resource in page or to a sequence - will construct own symbs
12138: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12139: # check URL part
12140: my ($map,$resid,$url)=&decode_symb($symb);
12141:
12142: unless ($url eq $thisfn) { return 0; }
12143:
12144: $symb=&symbclean($symb);
12145: $thisurl=&deversion($thisurl);
12146: $thisfn=&deversion($thisfn);
12147:
12148: my %bighash;
12149: my $okay=0;
12150:
12151: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12152: &GDBM_READER(),0640)) {
12153: my $noclutter;
12154: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12155: $thisurl =~ s/\?.+$//;
12156: if ($map =~ m{^uploaded/.+\.page$}) {
12157: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12158: $thisurl =~ s{^\Qhttp://https://\E}{https://};
12159: $noclutter = 1;
12160: }
12161: }
12162: my $ids;
12163: if ($noclutter) {
12164: $ids=$bighash{'ids_'.$thisurl};
12165: } else {
12166: $ids=$bighash{'ids_'.&clutter($thisurl)};
12167: }
12168: unless ($ids) {
12169: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
12170: $ids=$bighash{$idkey};
12171: }
12172: if ($ids) {
12173: # ------------------------------------------------------------------- Has ID(s)
12174: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12175: $symb =~ s/\?.+$//;
12176: }
12177: foreach my $id (split(/\,/,$ids)) {
12178: my ($mapid,$resid)=split(/\./,$id);
12179: if (
12180: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12181: eq $symb) {
12182: if (ref($encstate)) {
12183: $$encstate = $bighash{'encrypted_'.$id};
12184: }
12185: if (($env{'request.role.adv'}) ||
12186: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12187: ($thisurl eq '/adm/navmaps')) {
12188: $okay=1;
12189: last;
12190: }
12191: }
12192: }
12193: }
12194: untie(%bighash);
12195: }
12196: return $okay;
12197: }
12198:
12199: # --------------------------------------------------------------- Clean-up symb
12200:
12201: sub symbclean {
12202: my $symb=shift;
12203: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12204: # remove version from map
12205: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
12206:
12207: # remove version from URL
12208: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
12209:
12210: # remove wrapper
12211:
12212: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
12213: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
12214: return $symb;
12215: }
12216:
12217: # ---------------------------------------------- Split symb to find map and url
12218:
12219: sub encode_symb {
12220: my ($map,$resid,$url)=@_;
12221: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12222: }
12223:
12224: sub decode_symb {
12225: my $symb=shift;
12226: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12227: my ($map,$resid,$url)=split(/___/,$symb);
12228: return (&fixversion($map),$resid,&fixversion($url));
12229: }
12230:
12231: sub fixversion {
12232: my $fn=shift;
12233: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
12234: my %bighash;
12235: my $uri=&clutter($fn);
12236: my $key=$env{'request.course.id'}.'_'.$uri;
12237: # is this cached?
12238: my ($result,$cached)=&is_cached_new('courseresversion',$key);
12239: if (defined($cached)) { return $result; }
12240: # unfortunately not cached, or expired
12241: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12242: &GDBM_READER(),0640)) {
12243: if ($bighash{'version_'.$uri}) {
12244: my $version=$bighash{'version_'.$uri};
12245: unless (($version eq 'mostrecent') ||
12246: ($version==&getversion($uri))) {
12247: $uri=~s/\.(\w+)$/\.$version\.$1/;
12248: }
12249: }
12250: untie %bighash;
12251: }
12252: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
12253: }
12254:
12255: sub deversion {
12256: my $url=shift;
12257: $url=~s/\.\d+\.(\w+)$/\.$1/;
12258: return $url;
12259: }
12260:
12261: # ------------------------------------------------------ Return symb list entry
12262:
12263: sub symbread {
12264: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
12265: my $cache_str='request.symbread.cached.'.$thisfn;
12266: if (defined($env{$cache_str})) {
12267: if ($ignorecachednull) {
12268: return $env{$cache_str} unless ($env{$cache_str} eq '');
12269: } else {
12270: return $env{$cache_str};
12271: }
12272: }
12273: # no filename provided? try from environment
12274: unless ($thisfn) {
12275: if ($env{'request.symb'}) {
12276: return $env{$cache_str}=&symbclean($env{'request.symb'});
12277: }
12278: $thisfn=$env{'request.filename'};
12279: }
12280: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12281: # is that filename actually a symb? Verify, clean, and return
12282: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
12283: if (&symbverify($thisfn,$1)) {
12284: return $env{$cache_str}=&symbclean($thisfn);
12285: }
12286: }
12287: $thisfn=declutter($thisfn);
12288: my %hash;
12289: my %bighash;
12290: my $syval='';
12291: if (($env{'request.course.fn'}) && ($thisfn)) {
12292: my $targetfn = $thisfn;
12293: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
12294: $targetfn = 'adm/wrapper/'.$thisfn;
12295: }
12296: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12297: $targetfn=$1;
12298: }
12299: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12300: &GDBM_READER(),0640)) {
12301: $syval=$hash{$targetfn};
12302: untie(%hash);
12303: }
12304: # ---------------------------------------------------------- There was an entry
12305: if ($syval) {
12306: #unless ($syval=~/\_\d+$/) {
12307: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
12308: #&appenv({'request.ambiguous' => $thisfn});
12309: #return $env{$cache_str}='';
12310: #}
12311: #$syval.=$1;
12312: #}
12313: } else {
12314: # ------------------------------------------------------- Was not in symb table
12315: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12316: &GDBM_READER(),0640)) {
12317: # ---------------------------------------------- Get ID(s) for current resource
12318: my $ids=$bighash{'ids_'.&clutter($thisfn)};
12319: unless ($ids) {
12320: $ids=$bighash{'ids_/'.$thisfn};
12321: }
12322: unless ($ids) {
12323: # alias?
12324: $ids=$bighash{'mapalias_'.$thisfn};
12325: }
12326: if ($ids) {
12327: # ------------------------------------------------------------------- Has ID(s)
12328: my @possibilities=split(/\,/,$ids);
12329: if ($#possibilities==0) {
12330: # ----------------------------------------------- There is only one possibility
12331: my ($mapid,$resid)=split(/\./,$ids);
12332: $syval=&encode_symb($bighash{'map_id_'.$mapid},
12333: $resid,$thisfn);
12334: if (ref($possibles) eq 'HASH') {
12335: $possibles->{$syval} = 1;
12336: }
12337: if ($checkforblock) {
12338: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
12339: if (@blockers) {
12340: $syval = '';
12341: return;
12342: }
12343: }
12344: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12345: # ------------------------------------------ There is more than one possibility
12346: my $realpossible=0;
12347: foreach my $id (@possibilities) {
12348: my $file=$bighash{'src_'.$id};
12349: my $canaccess;
12350: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12351: $canaccess = 1;
12352: } else {
12353: $canaccess = &allowed('bre',$file);
12354: }
12355: if ($canaccess) {
12356: my ($mapid,$resid)=split(/\./,$id);
12357: if ($bighash{'map_type_'.$mapid} ne 'page') {
12358: my $poss_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',$poss_syval,$file);
12365: unless (@blockers > 0) {
12366: $syval = $poss_syval;
12367: $realpossible++;
12368: }
12369: } else {
12370: $syval = $poss_syval;
12371: $realpossible++;
12372: }
12373: }
12374: }
12375: }
12376: if ($realpossible!=1) { $syval=''; }
12377: } else {
12378: $syval='';
12379: }
12380: }
12381: untie(%bighash);
12382: }
12383: }
12384: if ($syval) {
12385: return $env{$cache_str}=$syval;
12386: }
12387: }
12388: &appenv({'request.ambiguous' => $thisfn});
12389: return $env{$cache_str}='';
12390: }
12391:
12392: # ---------------------------------------------------------- Return random seed
12393:
12394: sub numval {
12395: my $txt=shift;
12396: $txt=~tr/A-J/0-9/;
12397: $txt=~tr/a-j/0-9/;
12398: $txt=~tr/K-T/0-9/;
12399: $txt=~tr/k-t/0-9/;
12400: $txt=~tr/U-Z/0-5/;
12401: $txt=~tr/u-z/0-5/;
12402: $txt=~s/\D//g;
12403: if ($_64bit) { if ($txt > 2**32) { return -1; } }
12404: return int($txt);
12405: }
12406:
12407: sub numval2 {
12408: my $txt=shift;
12409: $txt=~tr/A-J/0-9/;
12410: $txt=~tr/a-j/0-9/;
12411: $txt=~tr/K-T/0-9/;
12412: $txt=~tr/k-t/0-9/;
12413: $txt=~tr/U-Z/0-5/;
12414: $txt=~tr/u-z/0-5/;
12415: $txt=~s/\D//g;
12416: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12417: my $total;
12418: foreach my $val (@txts) { $total+=$val; }
12419: if ($_64bit) { if ($total > 2**32) { return -1; } }
12420: return int($total);
12421: }
12422:
12423: sub numval3 {
12424: use integer;
12425: my $txt=shift;
12426: $txt=~tr/A-J/0-9/;
12427: $txt=~tr/a-j/0-9/;
12428: $txt=~tr/K-T/0-9/;
12429: $txt=~tr/k-t/0-9/;
12430: $txt=~tr/U-Z/0-5/;
12431: $txt=~tr/u-z/0-5/;
12432: $txt=~s/\D//g;
12433: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12434: my $total;
12435: foreach my $val (@txts) { $total+=$val; }
12436: if ($_64bit) { $total=(($total<<32)>>32); }
12437: return $total;
12438: }
12439:
12440: sub digest {
12441: my ($data)=@_;
12442: my $digest=&Digest::MD5::md5($data);
12443: my ($a,$b,$c,$d)=unpack("iiii",$digest);
12444: my ($e,$f);
12445: {
12446: use integer;
12447: $e=($a+$b);
12448: $f=($c+$d);
12449: if ($_64bit) {
12450: $e=(($e<<32)>>32);
12451: $f=(($f<<32)>>32);
12452: }
12453: }
12454: if (wantarray) {
12455: return ($e,$f);
12456: } else {
12457: my $g;
12458: {
12459: use integer;
12460: $g=($e+$f);
12461: if ($_64bit) {
12462: $g=(($g<<32)>>32);
12463: }
12464: }
12465: return $g;
12466: }
12467: }
12468:
12469: sub latest_rnd_algorithm_id {
12470: return '64bit5';
12471: }
12472:
12473: sub get_rand_alg {
12474: my ($courseid)=@_;
12475: if (!$courseid) { $courseid=(&whichuser())[1]; }
12476: if ($courseid) {
12477: return $env{"course.$courseid.rndseed"};
12478: }
12479: return &latest_rnd_algorithm_id();
12480: }
12481:
12482: sub validCODE {
12483: my ($CODE)=@_;
12484: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12485: return 0;
12486: }
12487:
12488: sub getCODE {
12489: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
12490: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12491: defined($Apache::lonhomework::parsing_a_task) ) &&
12492: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
12493: return $Apache::lonhomework::history{'resource.CODE'};
12494: }
12495: return undef;
12496: }
12497: #
12498: # Determines the random seed for a specific context:
12499: #
12500: # parameters:
12501: # symb - in course context the symb for the seed.
12502: # course_id - The course id of the form domain_coursenum.
12503: # domain - Domain for the user.
12504: # course - Course for the user.
12505: # cenv - environment of the course.
12506: #
12507: # NOTE:
12508: # All parameters are picked out of the environment if missing
12509: # or not defined.
12510: # If a symb cannot be determined the current time is used instead.
12511: #
12512: # For a given well defined symb, courside, domain, username,
12513: # and course environment, the seed is reproducible.
12514: #
12515: sub rndseed {
12516: my ($symb,$courseid,$domain,$username, $cenv)=@_;
12517: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
12518: if (!defined($symb)) {
12519: unless ($symb=$wsymb) { return time; }
12520: }
12521: if (!defined $courseid) {
12522: $courseid=$wcourseid;
12523: }
12524: if (!defined $domain) { $domain=$wdomain; }
12525: if (!defined $username) { $username=$wusername }
12526:
12527: my $which;
12528: if (defined($cenv->{'rndseed'})) {
12529: $which = $cenv->{'rndseed'};
12530: } else {
12531: $which =&get_rand_alg($courseid);
12532: }
12533: if (defined(&getCODE())) {
12534:
12535: if ($which eq '64bit5') {
12536: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12537: } elsif ($which eq '64bit4') {
12538: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12539: } else {
12540: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12541: }
12542: } elsif ($which eq '64bit5') {
12543: return &rndseed_64bit5($symb,$courseid,$domain,$username);
12544: } elsif ($which eq '64bit4') {
12545: return &rndseed_64bit4($symb,$courseid,$domain,$username);
12546: } elsif ($which eq '64bit3') {
12547: return &rndseed_64bit3($symb,$courseid,$domain,$username);
12548: } elsif ($which eq '64bit2') {
12549: return &rndseed_64bit2($symb,$courseid,$domain,$username);
12550: } elsif ($which eq '64bit') {
12551: return &rndseed_64bit($symb,$courseid,$domain,$username);
12552: }
12553: return &rndseed_32bit($symb,$courseid,$domain,$username);
12554: }
12555:
12556: sub rndseed_32bit {
12557: my ($symb,$courseid,$domain,$username)=@_;
12558: {
12559: use integer;
12560: my $symbchck=unpack("%32C*",$symb) << 27;
12561: my $symbseed=numval($symb) << 22;
12562: my $namechck=unpack("%32C*",$username) << 17;
12563: my $nameseed=numval($username) << 12;
12564: my $domainseed=unpack("%32C*",$domain) << 7;
12565: my $courseseed=unpack("%32C*",$courseid);
12566: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
12567: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12568: #&logthis("rndseed :$num:$symb");
12569: if ($_64bit) { $num=(($num<<32)>>32); }
12570: return $num;
12571: }
12572: }
12573:
12574: sub rndseed_64bit {
12575: my ($symb,$courseid,$domain,$username)=@_;
12576: {
12577: use integer;
12578: my $symbchck=unpack("%32S*",$symb) << 21;
12579: my $symbseed=numval($symb) << 10;
12580: my $namechck=unpack("%32S*",$username);
12581:
12582: my $nameseed=numval($username) << 21;
12583: my $domainseed=unpack("%32S*",$domain) << 10;
12584: my $courseseed=unpack("%32S*",$courseid);
12585:
12586: my $num1=$symbchck+$symbseed+$namechck;
12587: my $num2=$nameseed+$domainseed+$courseseed;
12588: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12589: #&logthis("rndseed :$num:$symb");
12590: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12591: return "$num1,$num2";
12592: }
12593: }
12594:
12595: sub rndseed_64bit2 {
12596: my ($symb,$courseid,$domain,$username)=@_;
12597: {
12598: use integer;
12599: # strings need to be an even # of cahracters long, it it is odd the
12600: # last characters gets thrown away
12601: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12602: my $symbseed=numval($symb) << 10;
12603: my $namechck=unpack("%32S*",$username.' ');
12604:
12605: my $nameseed=numval($username) << 21;
12606: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12607: my $courseseed=unpack("%32S*",$courseid.' ');
12608:
12609: my $num1=$symbchck+$symbseed+$namechck;
12610: my $num2=$nameseed+$domainseed+$courseseed;
12611: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12612: #&logthis("rndseed :$num:$symb");
12613: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12614: return "$num1,$num2";
12615: }
12616: }
12617:
12618: sub rndseed_64bit3 {
12619: my ($symb,$courseid,$domain,$username)=@_;
12620: {
12621: use integer;
12622: # strings need to be an even # of cahracters long, it it is odd the
12623: # last characters gets thrown away
12624: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12625: my $symbseed=numval2($symb) << 10;
12626: my $namechck=unpack("%32S*",$username.' ');
12627:
12628: my $nameseed=numval2($username) << 21;
12629: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12630: my $courseseed=unpack("%32S*",$courseid.' ');
12631:
12632: my $num1=$symbchck+$symbseed+$namechck;
12633: my $num2=$nameseed+$domainseed+$courseseed;
12634: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12635: #&logthis("rndseed :$num1:$num2:$_64bit");
12636: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12637:
12638: return "$num1:$num2";
12639: }
12640: }
12641:
12642: sub rndseed_64bit4 {
12643: my ($symb,$courseid,$domain,$username)=@_;
12644: {
12645: use integer;
12646: # strings need to be an even # of cahracters long, it it is odd the
12647: # last characters gets thrown away
12648: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12649: my $symbseed=numval3($symb) << 10;
12650: my $namechck=unpack("%32S*",$username.' ');
12651:
12652: my $nameseed=numval3($username) << 21;
12653: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12654: my $courseseed=unpack("%32S*",$courseid.' ');
12655:
12656: my $num1=$symbchck+$symbseed+$namechck;
12657: my $num2=$nameseed+$domainseed+$courseseed;
12658: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12659: #&logthis("rndseed :$num1:$num2:$_64bit");
12660: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12661:
12662: return "$num1:$num2";
12663: }
12664: }
12665:
12666: sub rndseed_64bit5 {
12667: my ($symb,$courseid,$domain,$username)=@_;
12668: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12669: return "$num1:$num2";
12670: }
12671:
12672: sub rndseed_CODE_64bit {
12673: my ($symb,$courseid,$domain,$username)=@_;
12674: {
12675: use integer;
12676: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12677: my $symbseed=numval2($symb);
12678: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12679: my $CODEseed=numval(&getCODE());
12680: my $courseseed=unpack("%32S*",$courseid.' ');
12681: my $num1=$symbseed+$CODEchck;
12682: my $num2=$CODEseed+$courseseed+$symbchck;
12683: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12684: #&logthis("rndseed :$num1:$num2:$symb");
12685: if ($_64bit) { $num1=(($num1<<32)>>32); }
12686: if ($_64bit) { $num2=(($num2<<32)>>32); }
12687: return "$num1:$num2";
12688: }
12689: }
12690:
12691: sub rndseed_CODE_64bit4 {
12692: my ($symb,$courseid,$domain,$username)=@_;
12693: {
12694: use integer;
12695: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12696: my $symbseed=numval3($symb);
12697: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12698: my $CODEseed=numval3(&getCODE());
12699: my $courseseed=unpack("%32S*",$courseid.' ');
12700: my $num1=$symbseed+$CODEchck;
12701: my $num2=$CODEseed+$courseseed+$symbchck;
12702: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12703: #&logthis("rndseed :$num1:$num2:$symb");
12704: if ($_64bit) { $num1=(($num1<<32)>>32); }
12705: if ($_64bit) { $num2=(($num2<<32)>>32); }
12706: return "$num1:$num2";
12707: }
12708: }
12709:
12710: sub rndseed_CODE_64bit5 {
12711: my ($symb,$courseid,$domain,$username)=@_;
12712: my $code = &getCODE();
12713: my ($num1,$num2)=&digest("$symb,$courseid,$code");
12714: return "$num1:$num2";
12715: }
12716:
12717: sub setup_random_from_rndseed {
12718: my ($rndseed)=@_;
12719: if ($rndseed =~/([,:])/) {
12720: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12721: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12722: &Math::Random::random_set_seed_from_phrase($rndseed);
12723: } else {
12724: &Math::Random::random_set_seed($num1,$num2);
12725: }
12726: } else {
12727: &Math::Random::random_set_seed_from_phrase($rndseed);
12728: }
12729: }
12730:
12731: sub latest_receipt_algorithm_id {
12732: return 'receipt3';
12733: }
12734:
12735: sub recunique {
12736: my $fucourseid=shift;
12737: my $unique;
12738: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12739: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
12740: $unique=$env{"course.$fucourseid.internal.encseed"};
12741: } else {
12742: $unique=$perlvar{'lonReceipt'};
12743: }
12744: return unpack("%32C*",$unique);
12745: }
12746:
12747: sub recprefix {
12748: my $fucourseid=shift;
12749: my $prefix;
12750: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12751: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
12752: $prefix=$env{"course.$fucourseid.internal.encpref"};
12753: } else {
12754: $prefix=$perlvar{'lonHostID'};
12755: }
12756: return unpack("%32C*",$prefix);
12757: }
12758:
12759: sub ireceipt {
12760: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
12761:
12762: my $return =&recprefix($fucourseid).'-';
12763:
12764: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12765: $env{'request.state'} eq 'construct') {
12766: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12767: return $return;
12768: }
12769:
12770: my $cuname=unpack("%32C*",$funame);
12771: my $cudom=unpack("%32C*",$fudom);
12772: my $cucourseid=unpack("%32C*",$fucourseid);
12773: my $cusymb=unpack("%32C*",$fusymb);
12774: my $cunique=&recunique($fucourseid);
12775: my $cpart=unpack("%32S*",$part);
12776: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12777:
12778: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
12779:
12780: $return.= ($cunique%$cuname+
12781: $cunique%$cudom+
12782: $cusymb%$cuname+
12783: $cusymb%$cudom+
12784: $cucourseid%$cuname+
12785: $cucourseid%$cudom+
12786: $cpart%$cuname+
12787: $cpart%$cudom);
12788: } else {
12789: $return.= ($cunique%$cuname+
12790: $cunique%$cudom+
12791: $cusymb%$cuname+
12792: $cusymb%$cudom+
12793: $cucourseid%$cuname+
12794: $cucourseid%$cudom);
12795: }
12796: return $return;
12797: }
12798:
12799: sub receipt {
12800: my ($part)=@_;
12801: my ($symb,$courseid,$domain,$name) = &whichuser();
12802: return &ireceipt($name,$domain,$courseid,$symb,$part);
12803: }
12804:
12805: sub whichuser {
12806: my ($passedsymb)=@_;
12807: my ($symb,$courseid,$domain,$name,$publicuser);
12808: if (defined($env{'form.grade_symb'})) {
12809: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12810: my $allowed=&allowed('vgr',$tmp_courseid);
12811: if (!$allowed &&
12812: exists($env{'request.course.sec'}) &&
12813: $env{'request.course.sec'} !~ /^\s*$/) {
12814: $allowed=&allowed('vgr',$tmp_courseid.
12815: '/'.$env{'request.course.sec'});
12816: }
12817: if ($allowed) {
12818: ($symb)=&get_env_multiple('form.grade_symb');
12819: $courseid=$tmp_courseid;
12820: ($domain)=&get_env_multiple('form.grade_domain');
12821: ($name)=&get_env_multiple('form.grade_username');
12822: return ($symb,$courseid,$domain,$name,$publicuser);
12823: }
12824: }
12825: if (!$passedsymb) {
12826: $symb=&symbread();
12827: } else {
12828: $symb=$passedsymb;
12829: }
12830: $courseid=$env{'request.course.id'};
12831: $domain=$env{'user.domain'};
12832: $name=$env{'user.name'};
12833: if ($name eq 'public' && $domain eq 'public') {
12834: if (!defined($env{'form.username'})) {
12835: $env{'form.username'}.=time.rand(10000000);
12836: }
12837: $name.=$env{'form.username'};
12838: }
12839: return ($symb,$courseid,$domain,$name,$publicuser);
12840:
12841: }
12842:
12843: # ------------------------------------------------------------ Serves up a file
12844: # returns either the contents of the file or
12845: # -1 if the file doesn't exist
12846: #
12847: # if the target is a file that was uploaded via DOCS,
12848: # a check will be made to see if a current copy exists on the local server,
12849: # if it does this will be served, otherwise a copy will be retrieved from
12850: # the home server for the course and stored in /home/httpd/html/userfiles on
12851: # the local server.
12852:
12853: sub getfile {
12854: my ($file) = @_;
12855: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
12856: &repcopy($file);
12857: return &readfile($file);
12858: }
12859:
12860: sub repcopy_userfile {
12861: my ($file)=@_;
12862: my $londocroot = $perlvar{'lonDocRoot'};
12863: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
12864: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
12865: my ($cdom,$cnum,$filename) =
12866: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
12867: my $uri="/uploaded/$cdom/$cnum/$filename";
12868: if (-e "$file") {
12869: # we already have a local copy, check it out
12870: my @fileinfo = stat($file);
12871: my $rtncode;
12872: my $info;
12873: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
12874: if ($lwpresp ne 'ok') {
12875: # there is no such file anymore, even though we had a local copy
12876: if ($rtncode eq '404') {
12877: unlink($file);
12878: }
12879: return -1;
12880: }
12881: if ($info < $fileinfo[9]) {
12882: # nice, the file we have is up-to-date, just say okay
12883: return 'ok';
12884: } else {
12885: # the file is outdated, get rid of it
12886: unlink($file);
12887: }
12888: }
12889: # one way or the other, at this point, we don't have the file
12890: # construct the correct path for the file
12891: my @parts = ($cdom,$cnum);
12892: if ($filename =~ m|^(.+)/[^/]+$|) {
12893: push @parts, split(/\//,$1);
12894: }
12895: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
12896: foreach my $part (@parts) {
12897: $path .= '/'.$part;
12898: if (!-e $path) {
12899: mkdir($path,0770);
12900: }
12901: }
12902: # now the path exists for sure
12903: # get a user agent
12904: my $transferfile=$file.'.in.transfer';
12905: # FIXME: this should flock
12906: if (-e $transferfile) { return 'ok'; }
12907: my $request;
12908: $uri=~s/^\///;
12909: my $homeserver = &homeserver($cnum,$cdom);
12910: my $protocol = $protocol{$homeserver};
12911: $protocol = 'http' if ($protocol ne 'https');
12912: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
12913: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
12914: # did it work?
12915: if ($response->is_error()) {
12916: unlink($transferfile);
12917: &logthis("Userfile repcopy failed for $uri");
12918: return -1;
12919: }
12920: # worked, rename the transfer file
12921: rename($transferfile,$file);
12922: return 'ok';
12923: }
12924:
12925: sub tokenwrapper {
12926: my $uri=shift;
12927: $uri=~s|^https?\://([^/]+)||;
12928: $uri=~s|^/||;
12929: $env{'user.environment'}=~/\/([^\/]+)\.id/;
12930: my $token=$1;
12931: my (undef,$udom,$uname,$file)=split('/',$uri,4);
12932: if ($udom && $uname && $file) {
12933: $file=~s|(\?\.*)*$||;
12934: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
12935: my $homeserver = &homeserver($uname,$udom);
12936: my $protocol = $protocol{$homeserver};
12937: $protocol = 'http' if ($protocol ne 'https');
12938: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
12939: (($uri=~/\?/)?'&':'?').'token='.$token.
12940: '&tokenissued='.$perlvar{'lonHostID'};
12941: } else {
12942: return '/adm/notfound.html';
12943: }
12944: }
12945:
12946: # call with reqtype HEAD: get last modification time
12947: # call with reqtype GET: get the file contents
12948: # Do not call this with reqtype GET for large files! It loads everything into memory
12949: #
12950: sub getuploaded {
12951: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
12952: $uri=~s/^\///;
12953: my $homeserver = &homeserver($cnum,$cdom);
12954: my $protocol = $protocol{$homeserver};
12955: $protocol = 'http' if ($protocol ne 'https');
12956: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
12957: my $request=new HTTP::Request($reqtype,$uri);
12958: my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
12959: $$rtncode = $response->code;
12960: if (! $response->is_success()) {
12961: return 'failed';
12962: }
12963: if ($reqtype eq 'HEAD') {
12964: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
12965: } elsif ($reqtype eq 'GET') {
12966: $$info = $response->content;
12967: }
12968: return 'ok';
12969: }
12970:
12971: sub readfile {
12972: my $file = shift;
12973: if ( (! -e $file ) || ($file eq '') ) { return -1; };
12974: my $fh;
12975: open($fh,"<$file");
12976: my $a='';
12977: while (my $line = <$fh>) { $a .= $line; }
12978: return $a;
12979: }
12980:
12981: sub filelocation {
12982: my ($dir,$file) = @_;
12983: my $location;
12984: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
12985:
12986: if ($file =~ m-^/adm/-) {
12987: $file=~s-^/adm/wrapper/-/-;
12988: $file=~s-^/adm/coursedocs/showdoc/-/-;
12989: }
12990:
12991: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
12992: $location = $file;
12993: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
12994: my ($udom,$uname,$filename)=
12995: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
12996: my $home=&homeserver($uname,$udom);
12997: my $is_me=0;
12998: my @ids=¤t_machine_ids();
12999: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13000: if ($is_me) {
13001: $location=propath($udom,$uname).'/userfiles/'.$filename;
13002: } else {
13003: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13004: $udom.'/'.$uname.'/'.$filename;
13005: }
13006: } elsif ($file =~ m-^/adm/-) {
13007: $location = $perlvar{'lonDocRoot'}.'/'.$file;
13008: } else {
13009: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13010: $file=~s:^/(res|priv)/:/:;
13011: my $space=$1;
13012: if ( !( $file =~ m:^/:) ) {
13013: $location = $dir. '/'.$file;
13014: } else {
13015: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13016: }
13017: }
13018: $location=~s://+:/:g; # remove duplicate /
13019: while ($location=~m{/\.\./}) {
13020: if ($location =~ m{/[^/]+/\.\./}) {
13021: $location=~ s{/[^/]+/\.\./}{/}g;
13022: } else {
13023: $location=~ s{/\.\./}{/}g;
13024: }
13025: } #remove dir/..
13026: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13027: return $location;
13028: }
13029:
13030: sub hreflocation {
13031: my ($dir,$file)=@_;
13032: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13033: $file=filelocation($dir,$file);
13034: } elsif ($file=~m-^/adm/-) {
13035: $file=~s-^/adm/wrapper/-/-;
13036: $file=~s-^/adm/coursedocs/showdoc/-/-;
13037: }
13038: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13039: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13040: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13041: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13042: {/uploaded/$1/$2/}x;
13043: }
13044: if ($file=~ m{^/userfiles/}) {
13045: $file =~ s{^/userfiles/}{/uploaded/};
13046: }
13047: return $file;
13048: }
13049:
13050:
13051:
13052:
13053:
13054: sub current_machine_domains {
13055: return &machine_domains(&hostname($perlvar{'lonHostID'}));
13056: }
13057:
13058: sub machine_domains {
13059: my ($hostname) = @_;
13060: my @domains;
13061: my %hostname = &all_hostnames();
13062: while( my($id, $name) = each(%hostname)) {
13063: # &logthis("-$id-$name-$hostname-");
13064: if ($hostname eq $name) {
13065: push(@domains,&host_domain($id));
13066: }
13067: }
13068: return @domains;
13069: }
13070:
13071: sub current_machine_ids {
13072: return &machine_ids(&hostname($perlvar{'lonHostID'}));
13073: }
13074:
13075: sub machine_ids {
13076: my ($hostname) = @_;
13077: $hostname ||= &hostname($perlvar{'lonHostID'});
13078: my @ids;
13079: my %name_to_host = &all_names();
13080: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13081: return @{ $name_to_host{$hostname} };
13082: }
13083: return;
13084: }
13085:
13086: sub additional_machine_domains {
13087: my @domains;
13088: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
13089: while( my $line = <$fh>) {
13090: $line =~ s/\s//g;
13091: push(@domains,$line);
13092: }
13093: return @domains;
13094: }
13095:
13096: sub default_login_domain {
13097: my $domain = $perlvar{'lonDefDomain'};
13098: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13099: foreach my $posdom (¤t_machine_domains(),
13100: &additional_machine_domains()) {
13101: if (lc($posdom) eq lc($testdomain)) {
13102: $domain=$posdom;
13103: last;
13104: }
13105: }
13106: return $domain;
13107: }
13108:
13109: # ------------------------------------------------------------- Declutters URLs
13110:
13111: sub declutter {
13112: my $thisfn=shift;
13113: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13114: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13115: $thisfn=~s{^/home/httpd/html}{};
13116: }
13117: $thisfn=~s/^\///;
13118: $thisfn=~s|^adm/wrapper/||;
13119: $thisfn=~s|^adm/coursedocs/showdoc/||;
13120: $thisfn=~s/^res\///;
13121: $thisfn=~s/^priv\///;
13122: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13123: $thisfn=~s/\?.+$//;
13124: }
13125: return $thisfn;
13126: }
13127:
13128: # ------------------------------------------------------------- Clutter up URLs
13129:
13130: sub clutter {
13131: my $thisfn='/'.&declutter(shift);
13132: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
13133: || $thisfn =~ m{^/adm/(includes|pages)} ) {
13134: $thisfn='/res'.$thisfn;
13135: }
13136: if ($thisfn !~m|^/adm|) {
13137: if ($thisfn =~ m|^/ext/|) {
13138: $thisfn='/adm/wrapper'.$thisfn;
13139: } else {
13140: my ($ext) = ($thisfn =~ /\.(\w+)$/);
13141: my $embstyle=&Apache::loncommon::fileembstyle($ext);
13142: if ($embstyle eq 'ssi'
13143: || ($embstyle eq 'hdn')
13144: || ($embstyle eq 'rat')
13145: || ($embstyle eq 'prv')
13146: || ($embstyle eq 'ign')) {
13147: #do nothing with these
13148: } elsif (($embstyle eq 'img')
13149: || ($embstyle eq 'emb')
13150: || ($embstyle eq 'wrp')) {
13151: $thisfn='/adm/wrapper'.$thisfn;
13152: } elsif ($embstyle eq 'unk'
13153: && $thisfn!~/\.(sequence|page)$/) {
13154: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
13155: } else {
13156: # &logthis("Got a blank emb style");
13157: }
13158: }
13159: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
13160: $thisfn='/adm/wrapper'.$thisfn;
13161: }
13162: return $thisfn;
13163: }
13164:
13165: sub clutter_with_no_wrapper {
13166: my $uri = &clutter(shift);
13167: if ($uri =~ m-^/adm/-) {
13168: $uri =~ s-^/adm/wrapper/-/-;
13169: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
13170: }
13171: return $uri;
13172: }
13173:
13174: sub freeze_escape {
13175: my ($value)=@_;
13176: if (ref($value)) {
13177: $value=&nfreeze($value);
13178: return '__FROZEN__'.&escape($value);
13179: }
13180: return &escape($value);
13181: }
13182:
13183:
13184: sub thaw_unescape {
13185: my ($value)=@_;
13186: if ($value =~ /^__FROZEN__/) {
13187: substr($value,0,10,undef);
13188: $value=&unescape($value);
13189: return &thaw($value);
13190: }
13191: return &unescape($value);
13192: }
13193:
13194: sub correct_line_ends {
13195: my ($result)=@_;
13196: $$result =~s/\r\n/\n/mg;
13197: $$result =~s/\r/\n/mg;
13198: }
13199: # ================================================================ Main Program
13200:
13201: sub goodbye {
13202: &logthis("Starting Shut down");
13203: #not converted to using infrastruture and probably shouldn't be
13204: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
13205: #converted
13206: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
13207: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13208: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13209: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
13210: #1.1 only
13211: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13212: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13213: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13214: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13215: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
13216: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13217: &logthis(sprintf("%-20s is %s",'hits',$hits));
13218: &flushcourselogs();
13219: &logthis("Shutting down");
13220: }
13221:
13222: sub get_dns {
13223: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
13224: if (!$ignore_cache) {
13225: my ($content,$cached)=
13226: &Apache::lonnet::is_cached_new('dns',$url);
13227: if ($cached) {
13228: &$func($content,$hashref);
13229: return;
13230: }
13231: }
13232:
13233: my %alldns;
13234: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
13235: foreach my $dns (<$config>) {
13236: next if ($dns !~ /^\^(\S*)/x);
13237: my $line = $1;
13238: my ($host,$protocol) = split(/:/,$line);
13239: if ($protocol ne 'https') {
13240: $protocol = 'http';
13241: }
13242: $alldns{$host} = $protocol;
13243: }
13244: while (%alldns) {
13245: my ($dns) = sort { $b cmp $a } keys(%alldns);
13246: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13247: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
13248: delete($alldns{$dns});
13249: next if ($response->is_error());
13250: my @content = split("\n",$response->content);
13251: unless ($nocache) {
13252: &do_cache_new('dns',$url,\@content,30*24*60*60);
13253: }
13254: &$func(\@content,$hashref);
13255: return;
13256: }
13257: close($config);
13258: my $which = (split('/',$url))[3];
13259: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13260: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
13261: my @content = <$config>;
13262: &$func(\@content,$hashref);
13263: return;
13264: }
13265:
13266: # ------------------------------------------------------Get DNS checksums file
13267: sub parse_dns_checksums_tab {
13268: my ($lines,$hashref) = @_;
13269: my $lonhost = $perlvar{'lonHostID'};
13270: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
13271: my $loncaparev = &get_server_loncaparev($machine_dom);
13272: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13273: my $webconfdir = '/etc/httpd/conf';
13274: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13275: $webconfdir = '/etc/apache2';
13276: } elsif ($distro =~ /^sles(\d+)$/) {
13277: if ($1 >= 10) {
13278: $webconfdir = '/etc/apache2';
13279: }
13280: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13281: if ($1 >= 10.0) {
13282: $webconfdir = '/etc/apache2';
13283: }
13284: }
13285: my ($release,$timestamp) = split(/\-/,$loncaparev);
13286: my (%chksum,%revnum);
13287: if (ref($lines) eq 'ARRAY') {
13288: chomp(@{$lines});
13289: my $version = shift(@{$lines});
13290: if ($version eq $release) {
13291: foreach my $line (@{$lines}) {
13292: my ($file,$version,$shasum) = split(/,/,$line);
13293: if ($file =~ m{^/etc/httpd/conf}) {
13294: if ($webconfdir eq '/etc/apache2') {
13295: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13296: }
13297: }
13298: $chksum{$file} = $shasum;
13299: $revnum{$file} = $version;
13300: }
13301: if (ref($hashref) eq 'HASH') {
13302: %{$hashref} = (
13303: sums => \%chksum,
13304: versions => \%revnum,
13305: );
13306: }
13307: }
13308: }
13309: return;
13310: }
13311:
13312: sub fetch_dns_checksums {
13313: my %checksums;
13314: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
13315: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
13316: my ($release,$timestamp) = split(/\-/,$loncaparev);
13317: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
13318: \%checksums);
13319: return \%checksums;
13320: }
13321:
13322: # ------------------------------------------------------------ Read domain file
13323: {
13324: my $loaded;
13325: my %domain;
13326:
13327: sub parse_domain_tab {
13328: my ($lines) = @_;
13329: foreach my $line (@$lines) {
13330: next if ($line =~ /^(\#|\s*$ )/x);
13331:
13332: chomp($line);
13333: my ($name,@elements) = split(/:/,$line,9);
13334: my %this_domain;
13335: foreach my $field ('description', 'auth_def', 'auth_arg_def',
13336: 'lang_def', 'city', 'longi', 'lati',
13337: 'primary') {
13338: $this_domain{$field} = shift(@elements);
13339: }
13340: $domain{$name} = \%this_domain;
13341: }
13342: }
13343:
13344: sub reset_domain_info {
13345: undef($loaded);
13346: undef(%domain);
13347: }
13348:
13349: sub load_domain_tab {
13350: my ($ignore_cache,$nocache) = @_;
13351: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
13352: my $fh;
13353: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
13354: my @lines = <$fh>;
13355: &parse_domain_tab(\@lines);
13356: }
13357: close($fh);
13358: $loaded = 1;
13359: }
13360:
13361: sub domain {
13362: &load_domain_tab() if (!$loaded);
13363:
13364: my ($name,$what) = @_;
13365: return if ( !exists($domain{$name}) );
13366:
13367: if (!$what) {
13368: return $domain{$name}{'description'};
13369: }
13370: return $domain{$name}{$what};
13371: }
13372:
13373: sub domain_info {
13374: &load_domain_tab() if (!$loaded);
13375: return %domain;
13376: }
13377:
13378: }
13379:
13380:
13381: # ------------------------------------------------------------- Read hosts file
13382: {
13383: my %hostname;
13384: my %hostdom;
13385: my %libserv;
13386: my $loaded;
13387: my %name_to_host;
13388: my %internetdom;
13389: my %LC_dns_serv;
13390:
13391: sub parse_hosts_tab {
13392: my ($file) = @_;
13393: foreach my $configline (@$file) {
13394: next if ($configline =~ /^(\#|\s*$ )/x);
13395: chomp($configline);
13396: if ($configline =~ /^\^/) {
13397: if ($configline =~ /^\^([\w.\-]+)/) {
13398: $LC_dns_serv{$1} = 1;
13399: }
13400: next;
13401: }
13402: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
13403: $name=~s/\s//g;
13404: if ($id && $domain && $role && $name) {
13405: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13406: my $curr = $hostname{$id};
13407: my $skip;
13408: if (ref($name_to_host{$curr}) eq 'ARRAY') {
13409: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13410: $skip = 1;
13411: } else {
13412: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13413: }
13414: }
13415: unless ($skip) {
13416: push(@{$name_to_host{$name}},$id);
13417: }
13418: } else {
13419: push(@{$name_to_host{$name}},$id);
13420: }
13421: $hostname{$id}=$name;
13422: $hostdom{$id}=$domain;
13423: if ($role eq 'library') { $libserv{$id}=$name; }
13424: if (defined($protocol)) {
13425: if ($protocol eq 'https') {
13426: $protocol{$id} = $protocol;
13427: } else {
13428: $protocol{$id} = 'http';
13429: }
13430: } else {
13431: $protocol{$id} = 'http';
13432: }
13433: if (defined($intdom)) {
13434: $internetdom{$id} = $intdom;
13435: }
13436: }
13437: }
13438: }
13439:
13440: sub reset_hosts_info {
13441: &purge_remembered();
13442: &reset_domain_info();
13443: &reset_hosts_ip_info();
13444: undef(%internetdom);
13445: undef(%name_to_host);
13446: undef(%hostname);
13447: undef(%hostdom);
13448: undef(%libserv);
13449: undef($loaded);
13450: }
13451:
13452: sub load_hosts_tab {
13453: my ($ignore_cache,$nocache) = @_;
13454: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
13455: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
13456: my @config = <$config>;
13457: &parse_hosts_tab(\@config);
13458: close($config);
13459: $loaded=1;
13460: }
13461:
13462: sub hostname {
13463: &load_hosts_tab() if (!$loaded);
13464:
13465: my ($lonid) = @_;
13466: return $hostname{$lonid};
13467: }
13468:
13469: sub all_hostnames {
13470: &load_hosts_tab() if (!$loaded);
13471:
13472: return %hostname;
13473: }
13474:
13475: sub all_names {
13476: my ($ignore_cache,$nocache) = @_;
13477: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
13478:
13479: return %name_to_host;
13480: }
13481:
13482: sub all_host_domain {
13483: &load_hosts_tab() if (!$loaded);
13484: return %hostdom;
13485: }
13486:
13487: sub all_host_intdom {
13488: &load_hosts_tab() if (!$loaded);
13489: return %internetdom;
13490: }
13491:
13492: sub is_library {
13493: &load_hosts_tab() if (!$loaded);
13494:
13495: return exists($libserv{$_[0]});
13496: }
13497:
13498: sub all_library {
13499: &load_hosts_tab() if (!$loaded);
13500:
13501: return %libserv;
13502: }
13503:
13504: sub unique_library {
13505: #2x reverse removes all hostnames that appear more than once
13506: my %unique = reverse &all_library();
13507: return reverse %unique;
13508: }
13509:
13510: sub get_servers {
13511: &load_hosts_tab() if (!$loaded);
13512:
13513: my ($domain,$type) = @_;
13514: my %possible_hosts = ($type eq 'library') ? %libserv
13515: : %hostname;
13516: my %result;
13517: if (ref($domain) eq 'ARRAY') {
13518: while ( my ($host,$hostname) = each(%possible_hosts)) {
13519: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
13520: $result{$host} = $hostname;
13521: }
13522: }
13523: } else {
13524: while ( my ($host,$hostname) = each(%possible_hosts)) {
13525: if ($hostdom{$host} eq $domain) {
13526: $result{$host} = $hostname;
13527: }
13528: }
13529: }
13530: return %result;
13531: }
13532:
13533: sub get_unique_servers {
13534: my %unique = reverse &get_servers(@_);
13535: return reverse %unique;
13536: }
13537:
13538: sub host_domain {
13539: &load_hosts_tab() if (!$loaded);
13540:
13541: my ($lonid) = @_;
13542: return $hostdom{$lonid};
13543: }
13544:
13545: sub all_domains {
13546: &load_hosts_tab() if (!$loaded);
13547:
13548: my %seen;
13549: my @uniq = grep(!$seen{$_}++, values(%hostdom));
13550: return @uniq;
13551: }
13552:
13553: sub internet_dom {
13554: &load_hosts_tab() if (!$loaded);
13555:
13556: my ($lonid) = @_;
13557: return $internetdom{$lonid};
13558: }
13559:
13560: sub is_LC_dns {
13561: &load_hosts_tab() if (!$loaded);
13562:
13563: my ($hostname) = @_;
13564: return exists($LC_dns_serv{$hostname});
13565: }
13566:
13567: }
13568:
13569: {
13570: my %iphost;
13571: my %name_to_ip;
13572: my %lonid_to_ip;
13573:
13574: sub get_hosts_from_ip {
13575: my ($ip) = @_;
13576: my %iphosts = &get_iphost();
13577: if (ref($iphosts{$ip})) {
13578: return @{$iphosts{$ip}};
13579: }
13580: return;
13581: }
13582:
13583: sub reset_hosts_ip_info {
13584: undef(%iphost);
13585: undef(%name_to_ip);
13586: undef(%lonid_to_ip);
13587: }
13588:
13589: sub get_host_ip {
13590: my ($lonid) = @_;
13591: if (exists($lonid_to_ip{$lonid})) {
13592: return $lonid_to_ip{$lonid};
13593: }
13594: my $name=&hostname($lonid);
13595: my $ip = gethostbyname($name);
13596: return if (!$ip || length($ip) ne 4);
13597: $ip=inet_ntoa($ip);
13598: $name_to_ip{$name} = $ip;
13599: $lonid_to_ip{$lonid} = $ip;
13600: return $ip;
13601: }
13602:
13603: sub get_iphost {
13604: my ($ignore_cache,$nocache) = @_;
13605:
13606: if (!$ignore_cache) {
13607: if (%iphost) {
13608: return %iphost;
13609: }
13610: my ($ip_info,$cached)=
13611: &Apache::lonnet::is_cached_new('iphost','iphost');
13612: if ($cached) {
13613: %iphost = %{$ip_info->[0]};
13614: %name_to_ip = %{$ip_info->[1]};
13615: %lonid_to_ip = %{$ip_info->[2]};
13616: return %iphost;
13617: }
13618: }
13619:
13620: # get yesterday's info for fallback
13621: my %old_name_to_ip;
13622: my ($ip_info,$cached)=
13623: &Apache::lonnet::is_cached_new('iphost','iphost');
13624: if ($cached) {
13625: %old_name_to_ip = %{$ip_info->[1]};
13626: }
13627:
13628: my %name_to_host = &all_names($ignore_cache,$nocache);
13629: foreach my $name (keys(%name_to_host)) {
13630: my $ip;
13631: if (!exists($name_to_ip{$name})) {
13632: $ip = gethostbyname($name);
13633: if (!$ip || length($ip) ne 4) {
13634: if (defined($old_name_to_ip{$name})) {
13635: $ip = $old_name_to_ip{$name};
13636: &logthis("Can't find $name defaulting to old $ip");
13637: } else {
13638: &logthis("Name $name no IP found");
13639: next;
13640: }
13641: } else {
13642: $ip=inet_ntoa($ip);
13643: }
13644: $name_to_ip{$name} = $ip;
13645: } else {
13646: $ip = $name_to_ip{$name};
13647: }
13648: foreach my $id (@{ $name_to_host{$name} }) {
13649: $lonid_to_ip{$id} = $ip;
13650: }
13651: push(@{$iphost{$ip}},@{$name_to_host{$name}});
13652: }
13653: unless ($nocache) {
13654: &do_cache_new('iphost','iphost',
13655: [\%iphost,\%name_to_ip,\%lonid_to_ip],
13656: 48*60*60);
13657: }
13658:
13659: return %iphost;
13660: }
13661:
13662: #
13663: # Given a DNS returns the loncapa host name for that DNS
13664: #
13665: sub host_from_dns {
13666: my ($dns) = @_;
13667: my @hosts;
13668: my $ip;
13669:
13670: if (exists($name_to_ip{$dns})) {
13671: $ip = $name_to_ip{$dns};
13672: }
13673: if (!$ip) {
13674: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13675: if (length($ip) == 4) {
13676: $ip = &IO::Socket::inet_ntoa($ip);
13677: }
13678: }
13679: if ($ip) {
13680: @hosts = get_hosts_from_ip($ip);
13681: return $hosts[0];
13682: }
13683: return undef;
13684: }
13685:
13686: sub get_internet_names {
13687: my ($lonid) = @_;
13688: return if ($lonid eq '');
13689: my ($idnref,$cached)=
13690: &Apache::lonnet::is_cached_new('internetnames',$lonid);
13691: if ($cached) {
13692: return $idnref;
13693: }
13694: my $ip = &get_host_ip($lonid);
13695: my @hosts = &get_hosts_from_ip($ip);
13696: my %iphost = &get_iphost();
13697: my (@idns,%seen);
13698: foreach my $id (@hosts) {
13699: my $dom = &host_domain($id);
13700: my $prim_id = &domain($dom,'primary');
13701: my $prim_ip = &get_host_ip($prim_id);
13702: next if ($seen{$prim_ip});
13703: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
13704: foreach my $id (@{$iphost{$prim_ip}}) {
13705: my $intdom = &internet_dom($id);
13706: unless (grep(/^\Q$intdom\E$/,@idns)) {
13707: push(@idns,$intdom);
13708: }
13709: }
13710: }
13711: $seen{$prim_ip} = 1;
13712: }
13713: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
13714: }
13715:
13716: }
13717:
13718: sub all_loncaparevs {
13719: 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);
13720: }
13721:
13722: # ---------------------------------------------------------- Read loncaparev table
13723: {
13724: sub load_loncaparevs {
13725: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
13726: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
13727: while (my $configline=<$config>) {
13728: chomp($configline);
13729: my ($hostid,$loncaparev)=split(/:/,$configline);
13730: $loncaparevs{$hostid}=$loncaparev;
13731: }
13732: close($config);
13733: }
13734: }
13735: }
13736: }
13737:
13738: # ---------------------------------------------------------- Read serverhostID table
13739: {
13740: sub load_serverhomeIDs {
13741: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
13742: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
13743: while (my $configline=<$config>) {
13744: chomp($configline);
13745: my ($name,$id)=split(/:/,$configline);
13746: $serverhomeIDs{$name}=$id;
13747: }
13748: close($config);
13749: }
13750: }
13751: }
13752: }
13753:
13754:
13755: BEGIN {
13756:
13757: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13758: unless ($readit) {
13759: {
13760: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13761: %perlvar = (%perlvar,%{$configvars});
13762: }
13763:
13764:
13765: # ------------------------------------------------------ Read spare server file
13766: {
13767: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
13768:
13769: while (my $configline=<$config>) {
13770: chomp($configline);
13771: if ($configline) {
13772: my ($host,$type) = split(':',$configline,2);
13773: if (!defined($type) || $type eq '') { $type = 'default' };
13774: push(@{ $spareid{$type} }, $host);
13775: }
13776: }
13777: close($config);
13778: }
13779: # ------------------------------------------------------------ Read permissions
13780: {
13781: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
13782:
13783: while (my $configline=<$config>) {
13784: chomp($configline);
13785: if ($configline) {
13786: my ($role,$perm)=split(/ /,$configline);
13787: if ($perm ne '') { $pr{$role}=$perm; }
13788: }
13789: }
13790: close($config);
13791: }
13792:
13793: # -------------------------------------------- Read plain texts for permissions
13794: {
13795: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
13796:
13797: while (my $configline=<$config>) {
13798: chomp($configline);
13799: if ($configline) {
13800: my ($short,@plain)=split(/:/,$configline);
13801: %{$prp{$short}} = ();
13802: if (@plain > 0) {
13803: $prp{$short}{'std'} = $plain[0];
13804: for (my $i=1; $i<@plain; $i++) {
13805: $prp{$short}{'alt'.$i} = $plain[$i];
13806: }
13807: }
13808: }
13809: }
13810: close($config);
13811: }
13812:
13813: # ---------------------------------------------------------- Read package table
13814: {
13815: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
13816:
13817: while (my $configline=<$config>) {
13818: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
13819: chomp($configline);
13820: my ($short,$plain)=split(/:/,$configline);
13821: my ($pack,$name)=split(/\&/,$short);
13822: if ($plain ne '') {
13823: $packagetab{$pack.'&'.$name.'&name'}=$name;
13824: $packagetab{$short}=$plain;
13825: }
13826: }
13827: close($config);
13828: }
13829:
13830: # ---------------------------------------------------------- Read loncaparev table
13831:
13832: &load_loncaparevs();
13833:
13834: # ---------------------------------------------------------- Read serverhostID table
13835:
13836: &load_serverhomeIDs();
13837:
13838: # ---------------------------------------------------------- Read releaseslist XML
13839: {
13840: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
13841: if (-e $file) {
13842: my $parser = HTML::LCParser->new($file);
13843: while (my $token = $parser->get_token()) {
13844: if ($token->[0] eq 'S') {
13845: my $item = $token->[1];
13846: my $name = $token->[2]{'name'};
13847: my $value = $token->[2]{'value'};
13848: my $valuematch = $token->[2]{'valuematch'};
13849: my $namematch = $token->[2]{'namematch'};
13850: if ($item eq 'parameter') {
13851: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
13852: my $release = $parser->get_text();
13853: $release =~ s/(^\s*|\s*$ )//gx;
13854: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
13855: }
13856: } elsif ($item ne '' && $name ne '') {
13857: my $release = $parser->get_text();
13858: $release =~ s/(^\s*|\s*$ )//gx;
13859: $needsrelease{$item.':'.$name.':'.$value} = $release;
13860: }
13861: }
13862: }
13863: }
13864: }
13865:
13866: # ---------------------------------------------------------- Read managers table
13867: {
13868: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
13869: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
13870: while (my $configline=<$config>) {
13871: chomp($configline);
13872: next if ($configline =~ /^\#/);
13873: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
13874: $managerstab{$configline} = 1;
13875: }
13876: }
13877: close($config);
13878: }
13879: }
13880: }
13881:
13882: # ------------- set up temporary directory
13883: {
13884: $tmpdir = LONCAPA::tempdir();
13885:
13886: }
13887:
13888: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
13889: 'compress_threshold'=> 20_000,
13890: });
13891:
13892: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
13893: $dumpcount=0;
13894: $locknum=0;
13895:
13896: &logtouch();
13897: &logthis('<font color="yellow">INFO: Read configuration</font>');
13898: $readit=1;
13899: {
13900: use integer;
13901: my $test=(2**32)+1;
13902: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
13903: &logthis(" Detected 64bit platform ($_64bit)");
13904: }
13905: }
13906: }
13907:
13908: 1;
13909: __END__
13910:
13911: =pod
13912:
13913: =head1 NAME
13914:
13915: Apache::lonnet - Subroutines to ask questions about things in the network.
13916:
13917: =head1 SYNOPSIS
13918:
13919: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
13920:
13921: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
13922:
13923: Common parameters:
13924:
13925: =over 4
13926:
13927: =item *
13928:
13929: $uname : an internal username (if $cname expecting a course Id specifically)
13930:
13931: =item *
13932:
13933: $udom : a domain (if $cdom expecting a course's domain specifically)
13934:
13935: =item *
13936:
13937: $symb : a resource instance identifier
13938:
13939: =item *
13940:
13941: $namespace : the name of a .db file that contains the data needed or
13942: being set.
13943:
13944: =back
13945:
13946: =head1 OVERVIEW
13947:
13948: lonnet provides subroutines which interact with the
13949: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
13950: about classes, users, and resources.
13951:
13952: For many of these objects you can also use this to store data about
13953: them or modify them in various ways.
13954:
13955: =head2 Symbs
13956:
13957: To identify a specific instance of a resource, LON-CAPA uses symbols
13958: or "symbs"X<symb>. These identifiers are built from the URL of the
13959: map, the resource number of the resource in the map, and the URL of
13960: the resource itself. The latter is somewhat redundant, but might help
13961: if maps change.
13962:
13963: An example is
13964:
13965: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
13966:
13967: The respective map entry is
13968:
13969: <resource id="19" src="/res/msu/korte/tests/part12.problem"
13970: title="Problem 2">
13971: </resource>
13972:
13973: Symbs are used by the random number generator, as well as to store and
13974: restore data specific to a certain instance of for example a problem.
13975:
13976: =head2 Storing And Retrieving Data
13977:
13978: X<store()>X<cstore()>X<restore()>Three of the most important functions
13979: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
13980: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
13981: is is the non-critical message twin of cstore. These functions are for
13982: handlers to store a perl hash to a user's permanent data space in an
13983: easy manner, and to retrieve it again on another call. It is expected
13984: that a handler would use this once at the beginning to retrieve data,
13985: and then again once at the end to send only the new data back.
13986:
13987: The data is stored in the user's data directory on the user's
13988: homeserver under the ID of the course.
13989:
13990: The hash that is returned by restore will have all of the previous
13991: value for all of the elements of the hash.
13992:
13993: Example:
13994:
13995: #creating a hash
13996: my %hash;
13997: $hash{'foo'}='bar';
13998:
13999: #storing it
14000: &Apache::lonnet::cstore(\%hash);
14001:
14002: #changing a value
14003: $hash{'foo'}='notbar';
14004:
14005: #adding a new value
14006: $hash{'bar'}='foo';
14007: &Apache::lonnet::cstore(\%hash);
14008:
14009: #retrieving the hash
14010: my %history=&Apache::lonnet::restore();
14011:
14012: #print the hash
14013: foreach my $key (sort(keys(%history))) {
14014: print("\%history{$key} = $history{$key}");
14015: }
14016:
14017: Will print out:
14018:
14019: %history{1:foo} = bar
14020: %history{1:keys} = foo:timestamp
14021: %history{1:timestamp} = 990455579
14022: %history{2:bar} = foo
14023: %history{2:foo} = notbar
14024: %history{2:keys} = foo:bar:timestamp
14025: %history{2:timestamp} = 990455580
14026: %history{bar} = foo
14027: %history{foo} = notbar
14028: %history{timestamp} = 990455580
14029: %history{version} = 2
14030:
14031: Note that the special hash entries C<keys>, C<version> and
14032: C<timestamp> were added to the hash. C<version> will be equal to the
14033: total number of versions of the data that have been stored. The
14034: C<timestamp> attribute will be the UNIX time the hash was
14035: stored. C<keys> is available in every historical section to list which
14036: keys were added or changed at a specific historical revision of a
14037: hash.
14038:
14039: B<Warning>: do not store the hash that restore returns directly. This
14040: will cause a mess since it will restore the historical keys as if the
14041: were new keys. I.E. 1:foo will become 1:1:foo etc.
14042:
14043: Calling convention:
14044:
14045: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
14046: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
14047:
14048: For more detailed information, see lonnet specific documentation.
14049:
14050: =head1 RETURN MESSAGES
14051:
14052: =over 4
14053:
14054: =item * B<con_lost>: unable to contact remote host
14055:
14056: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14057: when the connection is brought back up
14058:
14059: =item * B<con_failed>: unable to contact remote host and unable to save message
14060: for later delivery
14061:
14062: =item * B<error:>: an error a occurred, a description of the error follows the :
14063:
14064: =item * B<no_such_host>: unable to fund a host associated with the user/domain
14065: that was requested
14066:
14067: =back
14068:
14069: =head1 PUBLIC SUBROUTINES
14070:
14071: =head2 Session Environment Functions
14072:
14073: =over 4
14074:
14075: =item *
14076: X<appenv()>
14077: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
14078: the user envirnoment file, and will be restored for each access this
14079: user makes during this session, also modifies the %env for the current
14080: process. Optional rolesarrayref - if defined contains a reference to an array
14081: of roles which are exempt from the restriction on modifying user.role entries
14082: in the user's environment.db and in %env.
14083:
14084: =item *
14085: X<delenv()>
14086: B<delenv($delthis,$regexp)>: removes all items from the session
14087: environment file that begin with $delthis. If the
14088: optional second arg - $regexp - is true, $delthis is treated as a
14089: regular expression, otherwise \Q$delthis\E is used.
14090: The values are also deleted from the current processes %env.
14091:
14092: =item * get_env_multiple($name)
14093:
14094: gets $name from the %env hash, it seemlessly handles the cases where multiple
14095: values may be defined and end up as an array ref.
14096:
14097: returns an array of values
14098:
14099: =back
14100:
14101: =head2 User Information
14102:
14103: =over 4
14104:
14105: =item *
14106: X<queryauthenticate()>
14107: B<queryauthenticate($uname,$udom)>: try to determine user's current
14108: authentication scheme
14109:
14110: =item *
14111: X<authenticate()>
14112: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
14113: authenticate user from domain's lib servers (first use the current
14114: one). C<$upass> should be the users password.
14115: $checkdefauth is optional (value is 1 if a check should be made to
14116: authenticate user using default authentication method, and allow
14117: account creation if username does not have account in the domain).
14118: $clientcancheckhost is optional (value is 1 if checking whether the
14119: server can host will occur on the client side in lonauth.pm).
14120:
14121: =item *
14122: X<homeserver()>
14123: B<homeserver($uname,$udom)>: find the server which has
14124: the user's directory and files (there must be only one), this caches
14125: the answer, and also caches if there is a borken connection.
14126:
14127: =item *
14128: X<idget()>
14129: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
14130: a list of student/employee IDs or clicker IDs
14131: (student/employee IDs are a unique resource in a domain, there must be
14132: only 1 ID per username, and only 1 username per ID in a specific domain).
14133: clickerIDs are not necessarily unique, as students might share clickers.
14134: (returns hash: id=>name,id=>name)
14135:
14136: =item *
14137: X<idrget()>
14138: B<idrget($udom,@unames)>: find the IDs behind a list of
14139: usernames (returns hash: name=>id,name=>id)
14140:
14141: =item *
14142: X<idput()>
14143: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
14144: names and associated student/employee IDs or clicker IDs.
14145:
14146: =item *
14147: X<iddel()>
14148: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
14149: student/employee ID or clicker ID username look-ups from domain.
14150: The homeserver ($uhome) and namespace ($namespace) are optional.
14151: If no $uhome is provided, it will be determined usig &homeserver()
14152: for each user. If no $namespace is provided, the default is ids.
14153:
14154: =item *
14155: X<updateclickers()>
14156: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
14157: clicker ID-to-username look-ups in clickers.db on library server.
14158: Permitted actions are add or del (i.e., add or delete). The
14159: clickers.db contains clickerID as keys (escaped), and each corresponding
14160: value is an escaped comma-separated list of usernames (for whom the
14161: library server is the homeserver), who registered that particular ID.
14162: If $critical is true, the update will be sent via &critical, otherwise
14163: &reply() will be used.
14164:
14165: =item *
14166: X<rolesinit()>
14167: B<rolesinit($udom,$username)>: get user privileges.
14168: returns user role, first access and timer interval hashes
14169:
14170: =item *
14171: X<privileged()>
14172: B<privileged($username,$domain)>: returns a true if user has a
14173: privileged and active role (i.e. su or dc), false otherwise.
14174:
14175: =item *
14176: X<getsection()>
14177: B<getsection($udom,$uname,$cname)>: finds the section of student in the
14178: course $cname, return section name/number or '' for "not in course"
14179: and '-1' for "no section"
14180:
14181: =item *
14182: X<userenvironment()>
14183: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
14184: passed in @what from the requested user's environment, returns a hash
14185:
14186: =item *
14187: X<userlog_query()>
14188: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14189: activity.log file. %filters defines filters applied when parsing the
14190: log file. These can be start or end timestamps, or the type of action
14191: - log to look for Login or Logout events, check for Checkin or
14192: Checkout, role for role selection. The response is in the form
14193: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
14194: escaped strings of the action recorded in the activity.log file.
14195:
14196: =back
14197:
14198: =head2 User Roles
14199:
14200: =over 4
14201:
14202: =item *
14203:
14204: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
14205: returns codes for allowed actions.
14206:
14207: The first argument is required, all others are optional.
14208:
14209: $priv is the privilege being checked.
14210: $uri contains additional information about what is being checked for access (e.g.,
14211: URL, course ID etc.).
14212: $symb is the unique resource instance identifier in a course; if needed,
14213: but not provided, it will be retrieved via a call to &symbread().
14214: $role is the role for which a priv is being checked (only used if priv is evb).
14215: $clientip is the user's IP address (only used when checking for access to portfolio
14216: files).
14217: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
14218: prevents recursive calls to &allowed.
14219:
14220: F: full access
14221: U,I,K: authentication modes (cxx only)
14222: '': forbidden
14223: 1: user needs to choose course
14224: 2: browse allowed
14225: A: passphrase authentication needed
14226: B: access temporarily blocked because of a blocking event in a course.
14227:
14228: =item *
14229:
14230: constructaccess($url,$setpriv) : check for access to construction space URL
14231:
14232: See if the owner domain and name in the URL match those in the
14233: expected environment. If so, return three element list
14234: ($ownername,$ownerdomain,$ownerhome).
14235:
14236: Otherwise return the null string.
14237:
14238: If second argument 'setpriv' is true, it assigns the privileges,
14239: and returns the same three element list, unless the owner has
14240: blocked "ad hoc" Domain Coordinator access to the Author Space,
14241: in which case the null string is returned.
14242:
14243: =item *
14244:
14245: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14246: define a custom role rolename set privileges in format of lonTabs/roles.tab
14247: for system, domain, and course level. $uname and $udom are optional (current
14248: user's username and domain will be used when either of $uname or $udom are absent.
14249:
14250: =item *
14251:
14252: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
14253: (rolesplain.tab); plain text explanation of a user role term.
14254: $type is Course (default) or Community.
14255: If $forcedefault evaluates to true, text returned will be default
14256: text for $type. Otherwise, if this is a course, the text returned
14257: will be a custom name for the role (if defined in the course's
14258: environment). If no custom name is defined the default is returned.
14259:
14260: =item *
14261:
14262: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
14263: All arguments are optional. Returns a hash of a roles, either for
14264: co-author/assistant author roles for a user's Construction Space
14265: (default), or if $context is 'userroles', roles for the user himself,
14266: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14267: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14268: For each key, value is set to colon-separated start and end times for
14269: the role. If no username and domain are specified, will default to
14270: current user/domain. Types, roles, and roledoms are references to arrays
14271: of role statuses (active, future or previous), roles
14272: (e.g., cc,in, st etc.) and domains of the roles which can be used
14273: to restrict the list of roles reported. If no array ref is
14274: provided for types, will default to return only active roles.
14275:
14276: =item *
14277:
14278: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14279: user: $uname:$udom has a role in the course: $cdom_$cnum.
14280:
14281: Additional optional arguments are: $type (if role checking is to be restricted
14282: to certain user status types -- previous (expired roles), active (currently
14283: available roles) or future (roles available in the future), and
14284: $hideprivileged -- if true will not report course roles for users who
14285: have active Domain Coordinator role in course's domain or in additional
14286: domains (specified in 'Domains to check for privileged users' in course
14287: environment -- set via: Course Settings -> Classlists and staff listing).
14288:
14289: =item *
14290:
14291: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14292: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14293: $possdomains and $possroles are optional array refs -- to domains to check and
14294: roles to check. If $possdomains is not specified, a dump will be done of the
14295: users' roles.db to check for a dc or su role in any domain. This can be
14296: time consuming if &privileged is called repeatedly (e.g., when displaying a
14297: classlist), so in such cases, supplying a $possdomains array is preferred, as
14298: this then allows &privileged_by_domain() to be used, which caches the identity
14299: of privileged users, eliminating the need for repeated calls to &dump().
14300:
14301: =item *
14302:
14303: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14304: where the outer hash keys are domains specified in the $possdomains array ref,
14305: next inner hash keys are privileged roles specified in the $roles array ref,
14306: and the innermost hash contains key = value pairs for username:domain = end:start
14307: for active or future "privileged" users with that role in that domain. To avoid
14308: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14309: innerhash are cached using priv_$role and $dom as the identifiers.
14310:
14311: =back
14312:
14313: =head2 User Modification
14314:
14315: =over 4
14316:
14317: =item *
14318:
14319: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
14320: user for the level given by URL. Optional start and end dates (leave empty
14321: string or zero for "no date")
14322:
14323: =item *
14324:
14325: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14326: change a users, password, possible return values are: ok,
14327: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14328: refused
14329:
14330: =item *
14331:
14332: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
14333:
14334: =item *
14335:
14336: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14337: $forceid,$desiredhome,$email,$inststatus,$candelete) :
14338:
14339: will update user information (firstname,middlename,lastname,generation,
14340: permanentemail), and if forceid is true, student/employee ID also.
14341: A user's institutional affiliation(s) can also be updated.
14342: User information fields will not be overwritten with empty entries
14343: unless the field is included in the $candelete array reference.
14344: This array is included when a single user is modified via "Manage Users",
14345: or when Autoupdate.pl is run by cron in a domain.
14346:
14347: =item *
14348:
14349: modifystudent
14350:
14351: modify a student's enrollment and identification information.
14352: The course id is resolved based on the current user's environment.
14353: This means the invoking user must be a course coordinator or otherwise
14354: associated with a course.
14355:
14356: This call is essentially a wrapper for lonnet::modifyuser and
14357: lonnet::modify_student_enrollment
14358:
14359: Inputs:
14360:
14361: =over 4
14362:
14363: =item B<$udom> Student's loncapa domain
14364:
14365: =item B<$uname> Student's loncapa login name
14366:
14367: =item B<$uid> Student/Employee ID
14368:
14369: =item B<$umode> Student's authentication mode
14370:
14371: =item B<$upass> Student's password
14372:
14373: =item B<$first> Student's first name
14374:
14375: =item B<$middle> Student's middle name
14376:
14377: =item B<$last> Student's last name
14378:
14379: =item B<$gene> Student's generation
14380:
14381: =item B<$usec> Student's section in course
14382:
14383: =item B<$end> Unix time of the roles expiration
14384:
14385: =item B<$start> Unix time of the roles start date
14386:
14387: =item B<$forceid> If defined, allow $uid to be changed
14388:
14389: =item B<$desiredhome> server to use as home server for student
14390:
14391: =item B<$email> Student's permanent e-mail address
14392:
14393: =item B<$type> Type of enrollment (auto or manual)
14394:
14395: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
14396:
14397: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
14398:
14399: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
14400:
14401: =item B<$context> role change context (shown in User Management Logs display in a course)
14402:
14403: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14404:
14405: =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.
14406:
14407: =back
14408:
14409: =item *
14410:
14411: modify_student_enrollment
14412:
14413: Change a student's enrollment status in a class. The environment variable
14414: 'role.request.course' must be defined for this function to proceed.
14415:
14416: Inputs:
14417:
14418: =over 4
14419:
14420: =item $udom, student's domain
14421:
14422: =item $uname, student's name
14423:
14424: =item $uid, student's user id
14425:
14426: =item $first, student's first name
14427:
14428: =item $middle
14429:
14430: =item $last
14431:
14432: =item $gene
14433:
14434: =item $usec
14435:
14436: =item $end
14437:
14438: =item $start
14439:
14440: =item $type
14441:
14442: =item $locktype
14443:
14444: =item $cid
14445:
14446: =item $selfenroll
14447:
14448: =item $context
14449:
14450: =item $credits, number of credits student will earn from this class
14451:
14452: =item $instsec, institutional course section code for student
14453:
14454: =back
14455:
14456:
14457: =item *
14458:
14459: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14460: custom role; give a custom role to a user for the level given by URL. Specify
14461: name and domain of role author, and role name
14462:
14463: =item *
14464:
14465: revokerole($udom,$uname,$url,$role) : revoke a role for url
14466:
14467: =item *
14468:
14469: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14470:
14471: =back
14472:
14473: =head2 Course Infomation
14474:
14475: =over 4
14476:
14477: =item *
14478:
14479: coursedescription($courseid,$options) : returns a hash of information about the
14480: specified course id, including all environment settings for the
14481: course, the description of the course will be in the hash under the
14482: key 'description'
14483:
14484: $options is an optional parameter that if supplied is a hash reference that controls
14485: what how this function works. It has the following key/values:
14486:
14487: =over 4
14488:
14489: =item freshen_cache
14490:
14491: If defined, and the environment cache for the course is valid, it is
14492: returned in the returned hash.
14493:
14494: =item one_time
14495:
14496: If defined, the last cache time is set to _now_
14497:
14498: =item user
14499:
14500: If defined, the supplied username is used instead of the current user.
14501:
14502:
14503: =back
14504:
14505: =item *
14506:
14507: resdata($name,$domain,$type,@which) : request for current parameter
14508: setting for a specific $type, where $type is either 'course' or 'user',
14509: @what should be a list of parameters to ask about. This routine caches
14510: answers for 10 minutes.
14511:
14512: =item *
14513:
14514: get_courseresdata($courseid, $domain) : dump the entire course resource
14515: data base, returning a hash that is keyed by the resource name and has
14516: values that are the resource value. I believe that the timestamps and
14517: versions are also returned.
14518:
14519: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14520: supplemental content area. This routine caches the number of files for
14521: 10 minutes.
14522:
14523: =back
14524:
14525: =head2 Course Modification
14526:
14527: =over 4
14528:
14529: =item *
14530:
14531: writecoursepref($courseid,%prefs) : write preferences (environment
14532: database) for a course
14533:
14534: =item *
14535:
14536: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14537:
14538: =item *
14539:
14540: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
14541:
14542: =item *
14543:
14544: is_course($courseid), is_course($cdom, $cnum)
14545:
14546: Accepts either a combined $courseid (in the form of domain_courseid) or the
14547: two component version $cdom, $cnum. It checks if the specified course exists.
14548:
14549: Returns:
14550: undef if the course doesn't exist, otherwise
14551: in scalar context the combined courseid.
14552: in list context the two components of the course identifier, domain and
14553: courseid.
14554:
14555: =back
14556:
14557: =head2 Resource Subroutines
14558:
14559: =over 4
14560:
14561: =item *
14562:
14563: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
14564:
14565: =item *
14566:
14567: repcopy($filename) : subscribes to the requested file, and attempts to
14568: replicate from the owning library server, Might return
14569: 'unavailable', 'not_found', 'forbidden', 'ok', or
14570: 'bad_request', also attempts to grab the metadata for the
14571: resource. Expects the local filesystem pathname
14572: (/home/httpd/html/res/....)
14573:
14574: =back
14575:
14576: =head2 Resource Information
14577:
14578: =over 4
14579:
14580: =item *
14581:
14582: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
14583: and returns the value of a variety of different possible values,
14584: $varname should be a request string, and the other parameters can be
14585: used to specify who and what one is asking about. Ordinarily, $cid
14586: does not need to be specified, as it is retrived from
14587: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14588: within lonuserstate::loadmap() when initializing a course, before
14589: $env{'request.course.id'} has been set, so it needs to be provided
14590: in that one case.
14591:
14592: Possible values for $varname are environment.lastname (or other item
14593: from the envirnment hash), user.name (or someother aspect about the
14594: user), resource.0.maxtries (or some other part and parameter of a
14595: resource)
14596:
14597: =item *
14598:
14599: directcondval($number) : get current value of a condition; reads from a state
14600: string
14601:
14602: =item *
14603:
14604: condval($condidx) : value of condition index based on state
14605:
14606: =item *
14607:
14608: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14609: resource's metadata, $what should be either a specific key, or either
14610: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14611: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
14612:
14613: this function automatically caches all requests
14614:
14615: =item *
14616:
14617: metadata_query($query,$custom,$customshow) : make a metadata query against the
14618: network of library servers; returns file handle of where SQL and regex results
14619: will be stored for query
14620:
14621: =item *
14622:
14623: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
14624: return symbolic list entry (all arguments optional).
14625:
14626: Args: filename is the filename (including path) for the file for which a symb
14627: is required; donotrecurse, if true will prevent calls to allowed() being made
14628: to check access status if more than one resource was found in the bighash
14629: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
14630: a randompick); ignorecachednull, if true will prevent a symb of '' being
14631: returned if $env{$cache_str} is defined as ''; checkforblock if true will
14632: cause possible symbs to be checked to determine if they are subject to content
14633: blocking, if so they will not be included as possible symbs; possibles is a
14634: ref to a hash, which, as a side effect, will be populated with all possible
14635: symbs (content blocking not tested).
14636:
14637: returns the data handle
14638:
14639: =item *
14640:
14641: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
14642: and is a possible symb for the URL in $thisfn, and if is an encrypted
14643: resource that the user accessed using /enc/ returns a 1 on success, 0
14644: on failure, user must be in a course, as it assumes the existence of
14645: the course initial hash, and uses $env('request.course.id'}. The third
14646: arg is an optional reference to a scalar. If this arg is passed in the
14647: call to symbverify, it will be set to 1 if the symb has been set to be
14648: encrypted; otherwise it will be null.
14649:
14650: =item *
14651:
14652: symbclean($symb) : removes versions numbers from a symb, returns the
14653: cleaned symb
14654:
14655: =item *
14656:
14657: is_on_map($uri) : checks if the $uri is somewhere on the current
14658: course map, user must be in a course for it to work.
14659:
14660: =item *
14661:
14662: numval($salt) : return random seed value (addend for rndseed)
14663:
14664: =item *
14665:
14666: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
14667: a random seed, all arguments are optional, if they aren't sent it uses the
14668: environment to derive them. Note: if symb isn't sent and it can't get one
14669: from &symbread it will use the current time as its return value
14670:
14671: =item *
14672:
14673: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
14674: unfakeable, receipt
14675:
14676: =item *
14677:
14678: receipt() : API to ireceipt working off of env values; given out to users
14679:
14680: =item *
14681:
14682: countacc($url) : count the number of accesses to a given URL
14683:
14684: =item *
14685:
14686: 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
14687:
14688: =item *
14689:
14690: 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)
14691:
14692: =item *
14693:
14694: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
14695:
14696: =item *
14697:
14698: devalidate($symb) : devalidate temporary spreadsheet calculations,
14699: forcing spreadsheet to reevaluate the resource scores next time.
14700:
14701: =item *
14702:
14703: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
14704: when viewing in course context.
14705:
14706: input: six args -- filename (decluttered), course number, course domain,
14707: url, symb (if registered) and group (if this is a
14708: group item -- e.g., bulletin board, group page etc.).
14709:
14710: output: array of five scalars --
14711: $cfile -- url for file editing if editable on current server
14712: $home -- homeserver of resource (i.e., for author if published,
14713: or course if uploaded.).
14714: $switchserver -- 1 if server switch will be needed.
14715: $forceedit -- 1 if icon/link should be to go to edit mode
14716: $forceview -- 1 if icon/link should be to go to view mode
14717:
14718: =item *
14719:
14720: is_course_upload($file,$cnum,$cdom)
14721:
14722: Used in course context to determine if current file was uploaded to
14723: the course (i.e., would be found in /userfiles/docs on the course's
14724: homeserver.
14725:
14726: input: 3 args -- filename (decluttered), course number and course domain.
14727: output: boolean -- 1 if file was uploaded.
14728:
14729: =back
14730:
14731: =head2 Storing/Retreiving Data
14732:
14733: =over 4
14734:
14735: =item *
14736:
14737: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
14738: permanently for this url; hashref needs to be given and should be a \%hashname;
14739: the remaining args aren't required and if they aren't passed or are '' they will
14740: be derived from the env (with the exception of $laststore, which is an
14741: optional arg used when a user's submission is stored in grading).
14742: $laststore is $version=$timestamp, where $version is the most recent version
14743: number retrieved for the corresponding $symb in the $namespace db file, and
14744: $timestamp is the timestamp for that transaction (UNIX time).
14745: $laststore is currently only passed when cstore() is called by
14746: structuretags::finalize_storage().
14747:
14748: =item *
14749:
14750: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
14751: but uses critical subroutine
14752:
14753: =item *
14754:
14755: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
14756: all args are optional
14757:
14758: =item *
14759:
14760: dumpstore($namespace,$udom,$uname,$regexp,$range) :
14761: dumps the complete (or key matching regexp) namespace into a hash
14762: ($udom, $uname, $regexp, $range are optional) for a namespace that is
14763: normally &store()ed into
14764:
14765: $range should be either an integer '100' (give me the first 100
14766: matching records)
14767: or be two integers sperated by a - with no spaces
14768: '30-50' (give me the 30th through the 50th matching
14769: records)
14770:
14771:
14772: =item *
14773:
14774: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
14775: replaces a &store() version of data with a replacement set of data
14776: for a particular resource in a namespace passed in the $storehash hash
14777: reference. If $tolog is true, the transaction is logged in the courselog
14778: with an action=PUTSTORE.
14779:
14780: =item *
14781:
14782: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
14783: works very similar to store/cstore, but all data is stored in a
14784: temporary location and can be reset using tmpreset, $storehash should
14785: be a hash reference, returns nothing on success
14786:
14787: =item *
14788:
14789: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
14790: similar to restore, but all data is stored in a temporary location and
14791: can be reset using tmpreset. Returns a hash of values on success,
14792: error string otherwise.
14793:
14794: =item *
14795:
14796: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
14797: deltes all keys for $symb form the temporary storage hash.
14798:
14799: =item *
14800:
14801: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14802: reference filled in from namesp ($udom and $uname are optional)
14803:
14804: =item *
14805:
14806: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
14807: namesp ($udom and $uname are optional)
14808:
14809: =item *
14810:
14811: dump($namespace,$udom,$uname,$regexp,$range) :
14812: dumps the complete (or key matching regexp) namespace into a hash
14813: ($udom, $uname, $regexp, $range are optional)
14814:
14815: $range should be either an integer '100' (give me the first 100
14816: matching records)
14817: or be two integers sperated by a - with no spaces
14818: '30-50' (give me the 30th through the 50th matching
14819: records)
14820: =item *
14821:
14822: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
14823: $store can be a scalar, an array reference, or if the amount to be
14824: incremented is > 1, a hash reference.
14825:
14826: ($udom and $uname are optional)
14827:
14828: =item *
14829:
14830: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
14831: ($udom and $uname are optional)
14832:
14833: =item *
14834:
14835: cput($namespace,$storehash,$udom,$uname) : critical put
14836: ($udom and $uname are optional)
14837:
14838: =item *
14839:
14840: newput($namespace,$storehash,$udom,$uname) :
14841:
14842: Attempts to store the items in the $storehash, but only if they don't
14843: currently exist, if this succeeds you can be certain that you have
14844: successfully created a new key value pair in the $namespace db.
14845:
14846:
14847: Args:
14848: $namespace: name of database to store values to
14849: $storehash: hashref to store to the db
14850: $udom: (optional) domain of user containing the db
14851: $uname: (optional) name of user caontaining the db
14852:
14853: Returns:
14854: 'ok' -> succeeded in storing all keys of $storehash
14855: 'key_exists: <key>' -> failed to anything out of $storehash, as at
14856: least <key> already existed in the db (other
14857: requested keys may also already exist)
14858: 'error: <msg>' -> unable to tie the DB or other error occurred
14859: 'con_lost' -> unable to contact request server
14860: 'refused' -> action was not allowed by remote machine
14861:
14862:
14863: =item *
14864:
14865: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14866: reference filled in from namesp (encrypts the return communication)
14867: ($udom and $uname are optional)
14868:
14869: =item *
14870:
14871: log($udom,$name,$home,$message) : write to permanent log for user; use
14872: critical subroutine
14873:
14874: =item *
14875:
14876: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
14877: array reference filled in from namespace found in domain level on either
14878: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
14879:
14880: =item *
14881:
14882: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
14883: domain level either on specified domain server ($uhome) or primary domain
14884: server ($udom and $uhome are optional)
14885:
14886: =item *
14887:
14888: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
14889: for: authentication, language, quotas, timezone, date locale, and portal URL in
14890: the target domain.
14891:
14892: May also include additional key => value pairs for the following groups:
14893:
14894: =over
14895:
14896: =item
14897: disk quotas (MB allocated by default to portfolios and authoring spaces).
14898:
14899: =over
14900:
14901: =item defaultquota, authorquota
14902:
14903: =back
14904:
14905: =item
14906: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
14907: portfolio for users).
14908:
14909: =over
14910:
14911: =item
14912: aboutme, blog, webdav, portfolio
14913:
14914: =back
14915:
14916: =item
14917: requestcourses: ability to request courses, and how requests are processed.
14918:
14919: =over
14920:
14921: =item
14922: official, unofficial, community, textbook, placement
14923:
14924: =back
14925:
14926: =item
14927: inststatus: types of institutional affiliation, and order in which they are displayed.
14928:
14929: =over
14930:
14931: =item
14932: inststatustypes, inststatusorder, inststatusguest
14933:
14934: =back
14935:
14936: =item
14937: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
14938: for course's uploaded content.
14939:
14940: =over
14941:
14942: =item
14943: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
14944: communityquota, textbookquota, placementquota
14945:
14946: =back
14947:
14948: =item
14949: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
14950: on your servers.
14951:
14952: =over
14953:
14954: =item
14955: remotesessions, hostedsessions
14956:
14957: =back
14958:
14959: =back
14960:
14961: In cases where a domain coordinator has never used the "Set Domain Configuration"
14962: utility to create a configuration.db file on a domain's primary library server
14963: only the following domain defaults: auth_def, auth_arg_def, lang_def
14964: -- corresponding values are authentication type (internal, krb4, krb5,
14965: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
14966: will be available. Values are retrieved from cache (if current), unless the
14967: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
14968: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
14969:
14970: Typical usage:
14971:
14972: %domdefaults = &get_domain_defaults($target_domain);
14973:
14974: =back
14975:
14976: =head2 Network Status Functions
14977:
14978: =over 4
14979:
14980: =item *
14981:
14982: dirlist() : return directory list based on URI (first arg).
14983:
14984: Inputs: 1 required, 5 optional.
14985:
14986: =over
14987:
14988: =item
14989: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
14990:
14991: =item
14992: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
14993:
14994: =item
14995: $username - username of user/course to be listed. Extracted from $uri if absent.
14996:
14997: =item
14998: $getpropath - boolean: 1 if prepend path using &propath().
14999:
15000: =item
15001: $getuserdir - boolean: 1 if prepend path for "userfiles".
15002:
15003: =item
15004: $alternateRoot - path to prepend in place of path from $uri.
15005:
15006: =back
15007:
15008: Returns: Array of up to two items.
15009:
15010: =over
15011:
15012: a reference to an array of files/subdirectories
15013:
15014: =over
15015:
15016: Each element in the array of files/subdirectories is a & separated list of
15017: item name and the result of running stat on the item. If dirlist was requested
15018: for a file instead of a directory, the item name will be ''. For a directory
15019: listing, if the item is a metadata file, the element will end &N&M
15020: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15021: default copyright set (1).
15022:
15023: =back
15024:
15025: a scalar containing error condition (if encountered).
15026:
15027: =over
15028:
15029: =item
15030: no_host (no homeserver identified for $username:$domain).
15031:
15032: =item
15033: no_such_host (server contacted for listing not identified as valid host).
15034:
15035: =item
15036: con_lost (connection to remote server failed).
15037:
15038: =item
15039: refused (invalid $username:$domain received on lond side).
15040:
15041: =item
15042: no_such_dir (directory at specified path on lond side does not exist).
15043:
15044: =item
15045: empty (directory at specified path on lond side is empty).
15046:
15047: =over
15048:
15049: This is currently not encountered because the &ls3, &ls2,
15050: &ls (_handler) routines on the lond side do not filter out
15051: . and .. from a directory listing.
15052:
15053: =back
15054:
15055: =back
15056:
15057: =back
15058:
15059: =item *
15060:
15061: spareserver() : find server with least workload from spare.tab
15062:
15063:
15064: =item *
15065:
15066: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15067: if there is no corresponding loncapa host.
15068:
15069: =back
15070:
15071:
15072: =head2 Apache Request
15073:
15074: =over 4
15075:
15076: =item *
15077:
15078: ssi($url,%hash) : server side include, does a complete request cycle on url to
15079: localhost, posts hash
15080:
15081: =back
15082:
15083: =head2 Data to String to Data
15084:
15085: =over 4
15086:
15087: =item *
15088:
15089: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15090: and '&' separators, supports elements that are arrayrefs and hashrefs
15091:
15092: =item *
15093:
15094: hashref2str($hashref) : convert a hashref into a string complete with
15095: escaping and '=' and '&' separators, supports elements that are
15096: arrayrefs and hashrefs
15097:
15098: =item *
15099:
15100: arrayref2str($arrayref) : convert an arrayref into a string complete
15101: with escaping and '&' separators, supports elements that are arrayrefs
15102: and hashrefs
15103:
15104: =item *
15105:
15106: str2hash($string) : convert string to hash using unescaping and
15107: splitting on '=' and '&', supports elements that are arrayrefs and
15108: hashrefs
15109:
15110: =item *
15111:
15112: str2array($string) : convert string to hash using unescaping and
15113: splitting on '&', supports elements that are arrayrefs and hashrefs
15114:
15115: =back
15116:
15117: =head2 Logging Routines
15118:
15119:
15120: These routines allow one to make log messages in the lonnet.log and
15121: lonnet.perm logfiles.
15122:
15123: =over 4
15124:
15125: =item *
15126:
15127: logtouch() : make sure the logfile, lonnet.log, exists
15128:
15129: =item *
15130:
15131: logthis() : append message to the normal lonnet.log file, it gets
15132: preiodically rolled over and deleted.
15133:
15134: =item *
15135:
15136: logperm() : append a permanent message to lonnet.perm.log, this log
15137: file never gets deleted by any automated portion of the system, only
15138: messages of critical importance should go in here.
15139:
15140:
15141: =back
15142:
15143: =head2 General File Helper Routines
15144:
15145: =over 4
15146:
15147: =item *
15148:
15149: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15150: (a) files in /uploaded
15151: (i) If a local copy of the file exists -
15152: compares modification date of local copy with last-modified date for
15153: definitive version stored on home server for course. If local copy is
15154: stale, requests a new version from the home server and stores it.
15155: If the original has been removed from the home server, then local copy
15156: is unlinked.
15157: (ii) If local copy does not exist -
15158: requests the file from the home server and stores it.
15159:
15160: If $caller is 'uploadrep':
15161: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15162: for request for files originally uploaded via DOCS.
15163: - returns 'ok' if fresh local copy now available, -1 otherwise.
15164:
15165: Otherwise:
15166: This indicates a call from the content generation phase of the request.
15167: - returns the entire contents of the file or -1.
15168:
15169: (b) files in /res
15170: - returns the entire contents of a file or -1;
15171: it properly subscribes to and replicates the file if neccessary.
15172:
15173:
15174: =item *
15175:
15176: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15177: reference
15178:
15179: returns either a stat() list of data about the file or an empty list
15180: if the file doesn't exist or couldn't find out about it (connection
15181: problems or user unknown)
15182:
15183: =item *
15184:
15185: filelocation($dir,$file) : returns file system location of a file
15186: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15187: directory that relative $file lookups are to looked in ($dir of /a/dir
15188: and a file of ../bob will become /a/bob)
15189:
15190: =item *
15191:
15192: hreflocation($dir,$file) : returns file system location or a URL; same as
15193: filelocation except for hrefs
15194:
15195: =item *
15196:
15197: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15198: also removes beginning /home/httpd/html unless /priv/ follows it.
15199:
15200: =back
15201:
15202: =head2 Usererfile file routines (/uploaded*)
15203:
15204: =over 4
15205:
15206: =item *
15207:
15208: userfileupload(): main rotine for putting a file in a user or course's
15209: filespace, arguments are,
15210:
15211: formname - required - this is the name of the element in $env where the
15212: filename, and the contents of the file to create/modifed exist
15213: the filename is in $env{'form.'.$formname.'.filename'} and the
15214: contents of the file is located in $env{'form.'.$formname}
15215: context - if coursedoc, store the file in the course of the active role
15216: of the current user;
15217: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15218: if 'canceloverwrite': delete file in tmp/overwrites directory
15219: subdir - required - subdirectory to put the file in under ../userfiles/
15220: if undefined, it will be placed in "unknown"
15221:
15222: (This routine calls clean_filename() to remove any dangerous
15223: characters from the filename, and then calls finuserfileupload() to
15224: complete the transaction)
15225:
15226: returns either the url of the uploaded file (/uploaded/....) if successful
15227: and /adm/notfound.html if unsuccessful
15228:
15229: =item *
15230:
15231: clean_filename(): routine for cleaing a filename up for storage in
15232: userfile space, argument is:
15233:
15234: filename - proposed filename
15235:
15236: returns: the new clean filename
15237:
15238: =item *
15239:
15240: finishuserfileupload(): routine that creates and sends the file to
15241: userspace, probably shouldn't be called directly
15242:
15243: docuname: username or courseid of destination for the file
15244: docudom: domain of user/course of destination for the file
15245: formname: same as for userfileupload()
15246: fname: filename (including subdirectories) for the file
15247: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15248: allfiles: reference to hash used to store objects found by parser
15249: codebase: reference to hash used for codebases of java objects found by parser
15250: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15251: thumbheight: height (pixels) of thumbnail to be created for uploaded image
15252: resizewidth: width to be used to resize image using resizeImage from ImageMagick
15253: resizeheight: height to be used to resize image using resizeImage from ImageMagick
15254: context: if 'overwrite', will move the uploaded file from its temporary location to
15255: userfiles to facilitate overwriting a previously uploaded file with same name.
15256: mimetype: reference to scalar to accommodate mime type determined
15257: from File::MMagic if $parser = parse.
15258:
15259: returns either the url of the uploaded file (/uploaded/....) if successful
15260: and /adm/notfound.html if unsuccessful (or an error message if context
15261: was 'overwrite').
15262:
15263:
15264: =item *
15265:
15266: renameuserfile(): renames an existing userfile to a new name
15267:
15268: Args:
15269: docuname: username or courseid of destination for the file
15270: docudom: domain of user/course of destination for the file
15271: old: current file name (including any subdirs under userfiles)
15272: new: desired file name (including any subdirs under userfiles)
15273:
15274: =item *
15275:
15276: mkdiruserfile(): creates a directory is a userfiles dir
15277:
15278: Args:
15279: docuname: username or courseid of destination for the file
15280: docudom: domain of user/course of destination for the file
15281: dir: dir to create (including any subdirs under userfiles)
15282:
15283: =item *
15284:
15285: removeuserfile(): removes a file that exists in userfiles
15286:
15287: Args:
15288: docuname: username or courseid of destination for the file
15289: docudom: domain of user/course of destination for the file
15290: fname: filname to delete (including any subdirs under userfiles)
15291:
15292: =item *
15293:
15294: removeuploadedurl(): convience function for removeuserfile()
15295:
15296: Args:
15297: url: a full /uploaded/... url to delete
15298:
15299: =item *
15300:
15301: get_portfile_permissions():
15302: Args:
15303: domain: domain of user or course contain the portfolio files
15304: user: name of user or num of course contain the portfolio files
15305: Returns:
15306: hashref of a dump of the proper file_permissions.db
15307:
15308:
15309: =item *
15310:
15311: get_access_controls():
15312:
15313: Args:
15314: current_permissions: the hash ref returned from get_portfile_permissions()
15315: group: (optional) the group you want the files associated with
15316: file: (optional) the file you want access info on
15317:
15318: Returns:
15319: a hash (keys are file names) of hashes containing
15320: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15321: values are XML containing access control settings (see below)
15322:
15323: Internal notes:
15324:
15325: access controls are stored in file_permissions.db as key=value pairs.
15326: key -> path to file/file_name\0uniqueID:scope_end_start
15327: where scope -> public,guest,course,group,domains or users.
15328: end -> UNIX time for end of access (0 -> no end date)
15329: start -> UNIX time for start of access
15330:
15331: value -> XML description of access control
15332: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15333: <start></start>
15334: <end></end>
15335:
15336: <password></password> for scope type = guest
15337:
15338: <domain></domain> for scope type = course or group
15339: <number></number>
15340: <roles id="">
15341: <role></role>
15342: <access></access>
15343: <section></section>
15344: <group></group>
15345: </roles>
15346:
15347: <dom></dom> for scope type = domains
15348:
15349: <users> for scope type = users
15350: <user>
15351: <uname></uname>
15352: <udom></udom>
15353: </user>
15354: </users>
15355: </scope>
15356:
15357: Access data is also aggregated for each file in an additional key=value pair:
15358: key -> path to file/file_name\0accesscontrol
15359: value -> reference to hash
15360: hash contains key = value pairs
15361: where key = uniqueID:scope_end_start
15362: value = UNIX time record was last updated
15363:
15364: Used to improve speed of look-ups of access controls for each file.
15365:
15366: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15367:
15368: =item *
15369:
15370: modify_access_controls():
15371:
15372: Modifies access controls for a portfolio file
15373: Args
15374: 1. file name
15375: 2. reference to hash of required changes,
15376: 3. domain
15377: 4. username
15378: where domain,username are the domain of the portfolio owner
15379: (either a user or a course)
15380:
15381: Returns:
15382: 1. result of additions or updates ('ok' or 'error', with error message).
15383: 2. result of deletions ('ok' or 'error', with error message).
15384: 3. reference to hash of any new or updated access controls.
15385: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15386: key = integer (inbound ID)
15387: value = uniqueID
15388:
15389: =item *
15390:
15391: get_timebased_id():
15392:
15393: Attempts to get a unique timestamp-based suffix for use with items added to a
15394: course via the Course Editor (e.g., folders, composite pages,
15395: group bulletin boards).
15396:
15397: Args: (first three required; six others optional)
15398:
15399: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15400: docssequence, or name of group
15401:
15402: 2. keyid (alphanumeric): name of temporary locking key in hash,
15403: e.g., num, boardids
15404:
15405: 3. namespace: name of gdbm file used to store suffixes already assigned;
15406: file will be named nohist_namespace.db
15407:
15408: 4. cdom: domain of course; default is current course domain from %env
15409:
15410: 5. cnum: course number; default is current course number from %env
15411:
15412: 6. idtype: set to concat if an additional digit is to be appended to the
15413: unix timestamp to form the suffix, if the plain timestamp is already
15414: in use. Default is to not do this, but simply increment the unix
15415: timestamp by 1 until a unique key is obtained.
15416:
15417: 7. who: holder of locking key; defaults to user:domain for user.
15418:
15419: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
15420: retrying); default is 3.
15421:
15422: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
15423:
15424: Returns:
15425:
15426: 1. suffix obtained (numeric)
15427:
15428: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15429:
15430: 3. error: contains (localized) error message if an error occurred.
15431:
15432:
15433: =back
15434:
15435: =head2 HTTP Helper Routines
15436:
15437: =over 4
15438:
15439: =item *
15440:
15441: escape() : unpack non-word characters into CGI-compatible hex codes
15442:
15443: =item *
15444:
15445: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15446:
15447: =back
15448:
15449: =head1 PRIVATE SUBROUTINES
15450:
15451: =head2 Underlying communication routines (Shouldn't call)
15452:
15453: =over 4
15454:
15455: =item *
15456:
15457: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15458:
15459: =item *
15460:
15461: reply() : uses subreply to send a message to remote machine, logs all failures
15462:
15463: =item *
15464:
15465: critical() : passes a critical message to another server; if cannot
15466: get through then place message in connection buffer directory and
15467: returns con_delayed, if incapable of saving message, returns
15468: con_failed
15469:
15470: =item *
15471:
15472: reconlonc() : tries to reconnect lonc client processes.
15473:
15474: =back
15475:
15476: =head2 Resource Access Logging
15477:
15478: =over 4
15479:
15480: =item *
15481:
15482: flushcourselogs() : flush (save) buffer logs and access logs
15483:
15484: =item *
15485:
15486: courselog($what) : save message for course in hash
15487:
15488: =item *
15489:
15490: courseacclog($what) : save message for course using &courselog(). Perform
15491: special processing for specific resource types (problems, exams, quizzes, etc).
15492:
15493: =item *
15494:
15495: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15496: as a PerlChildExitHandler
15497:
15498: =back
15499:
15500: =head2 Other
15501:
15502: =over 4
15503:
15504: =item *
15505:
15506: symblist($mapname,%newhash) : update symbolic storage links
15507:
15508: =back
15509:
15510: =cut
15511:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>