File:
[LON-CAPA] /
loncom /
lonnet /
perl /
lonnet.pm
Revision
1.1481:
download - view:
text,
annotated -
select for diffs
Mon Feb 14 02:48:53 2022 UTC (2 years, 5 months ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD
- Bug 6907
- Rename "LTI Provider" domain config item.
- Add three additional sections: "Encryption of shared secrets",
"Rules for shared secrets" and Link Protectors (domain).
- Keys used in domain for a particular library server may only be set in
a session on that server (and use Lond.pm and not lonc/lond).
- Min and max length and character requirements can be set for secrets used
for LTI-based link protection for deep-links.
1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.1481 2022/02/14 02:48:53 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: use CGI::Cookie;
77:
78: use Encode;
79:
80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
81: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
82: %managerstab $passwdmin);
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 Net::CIDR;
100: use Sys::Hostname::FQDN();
101: use LONCAPA qw(:DEFAULT :match);
102: use LONCAPA::Configuration;
103: use LONCAPA::lonmetadata;
104: use LONCAPA::Lond;
105: use LONCAPA::LWPReq;
106: use LONCAPA::transliterate;
107:
108: use File::Copy;
109:
110: my $readit;
111: my $max_connection_retries = 20; # Or some such value.
112:
113: require Exporter;
114:
115: our @ISA = qw (Exporter);
116: our @EXPORT = qw(%env);
117:
118:
119: # ------------------------------------ Logging (parameters, docs, slots, roles)
120: {
121: my $logid;
122: sub write_log {
123: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
124: if ($context eq 'course') {
125: if (($cnum eq '') || ($cdom eq '')) {
126: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
127: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
128: }
129: }
130: $logid ++;
131: my $now = time();
132: my $id=$now.'00000'.$$.'00000'.$logid;
133: my $ip = &get_requestor_ip();
134: my $logentry = {
135: $id => {
136: 'exe_uname' => $env{'user.name'},
137: 'exe_udom' => $env{'user.domain'},
138: 'exe_time' => $now,
139: 'exe_ip' => $ip,
140: 'delflag' => $delflag,
141: 'logentry' => $storehash,
142: 'uname' => $uname,
143: 'udom' => $udom,
144: }
145: };
146: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
147: }
148: }
149:
150: sub logtouch {
151: my $execdir=$perlvar{'lonDaemons'};
152: unless (-e "$execdir/logs/lonnet.log") {
153: open(my $fh,">>","$execdir/logs/lonnet.log");
154: close $fh;
155: }
156: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
157: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
158: }
159:
160: sub logthis {
161: my $message=shift;
162: my $execdir=$perlvar{'lonDaemons'};
163: my $now=time;
164: my $local=localtime($now);
165: if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
166: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
167: print $fh $logstring;
168: close($fh);
169: }
170: return 1;
171: }
172:
173: sub logperm {
174: my $message=shift;
175: my $execdir=$perlvar{'lonDaemons'};
176: my $now=time;
177: my $local=localtime($now);
178: if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
179: print $fh "$now:$message:$local\n";
180: close($fh);
181: }
182: return 1;
183: }
184:
185: sub create_connection {
186: my ($hostname,$lonid) = @_;
187: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
188: Type => SOCK_STREAM,
189: Timeout => 10);
190: return 0 if (!$client);
191: print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
192: my $result = <$client>;
193: chomp($result);
194: return 1 if ($result eq 'done');
195: return 0;
196: }
197:
198: sub get_server_timezone {
199: my ($cnum,$cdom) = @_;
200: my $home=&homeserver($cnum,$cdom);
201: if ($home ne 'no_host') {
202: my $cachetime = 24*3600;
203: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
204: if (defined($cached)) {
205: return $timezone;
206: } else {
207: my $timezone = &reply('servertimezone',$home);
208: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
209: }
210: }
211: }
212:
213: sub get_server_distarch {
214: my ($lonhost,$ignore_cache) = @_;
215: if (defined($lonhost)) {
216: if (!defined(&hostname($lonhost))) {
217: return;
218: }
219: my $cachetime = 12*3600;
220: if (!$ignore_cache) {
221: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
222: if (defined($cached)) {
223: return $distarch;
224: }
225: }
226: my $rep = &reply('serverdistarch',$lonhost);
227: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
228: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
229: $rep eq '') {
230: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
231: }
232: }
233: return;
234: }
235:
236: sub get_servercerts_info {
237: my ($lonhost,$hostname,$context) = @_;
238: return if ($lonhost eq '');
239: if ($hostname eq '') {
240: $hostname = &hostname($lonhost);
241: }
242: return if ($hostname eq '');
243: my ($rep,$uselocal);
244: if ($context eq 'install') {
245: $uselocal = 1;
246: } elsif (grep { $_ eq $lonhost } ¤t_machine_ids()) {
247: $uselocal = 1;
248: }
249: if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
250: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
251: if ($distro eq '') {
252: $uselocal = 0;
253: } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
254: if ($1 < 6) {
255: $uselocal = 0;
256: }
257: } elsif ($distro =~ /^(?:sles)(\d+)$/) {
258: if ($1 < 12) {
259: $uselocal = 0;
260: }
261: }
262: }
263: if ($uselocal) {
264: $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
265: } else {
266: $rep=&reply('servercerts',$lonhost);
267: }
268: my ($result,%returnhash);
269: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
270: ($rep eq 'unknown_cmd')) {
271: $result = $rep;
272: } else {
273: $result = 'ok';
274: my @pairs=split(/\&/,$rep);
275: foreach my $item (@pairs) {
276: my ($key,$value)=split(/=/,$item,2);
277: my $what = &unescape($key);
278: $returnhash{$what}=&thaw_unescape($value);
279: }
280: }
281: return ($result,\%returnhash);
282: }
283:
284: sub get_server_loncaparev {
285: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
286: if (defined($lonhost)) {
287: if (!defined(&hostname($lonhost))) {
288: undef($lonhost);
289: }
290: }
291: if (!defined($lonhost)) {
292: if (defined(&domain($dom,'primary'))) {
293: $lonhost=&domain($dom,'primary');
294: if ($lonhost eq 'no_host') {
295: undef($lonhost);
296: }
297: }
298: }
299: if (defined($lonhost)) {
300: my $cachetime = 12*3600;
301: if (!$ignore_cache) {
302: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
303: if (defined($cached)) {
304: return $loncaparev;
305: }
306: }
307: my ($answer,$loncaparev);
308: my @ids=¤t_machine_ids();
309: if (grep(/^\Q$lonhost\E$/,@ids)) {
310: $answer = $perlvar{'lonVersion'};
311: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
312: $loncaparev = $1;
313: }
314: } else {
315: $answer = &reply('serverloncaparev',$lonhost);
316: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
317: if ($caller eq 'loncron') {
318: my $hostname = &hostname($lonhost);
319: my $protocol = $protocol{$lonhost};
320: $protocol = 'http' if ($protocol ne 'https');
321: my $url = $protocol.'://'.$hostname.'/adm/about.html';
322: my $request=new HTTP::Request('GET',$url);
323: my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
324: unless ($response->is_error()) {
325: my $content = $response->content;
326: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
327: $loncaparev = $1;
328: }
329: }
330: } else {
331: $loncaparev = $loncaparevs{$lonhost};
332: }
333: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
334: $loncaparev = $1;
335: }
336: }
337: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
338: }
339: }
340:
341: sub get_server_homeID {
342: my ($hostname,$ignore_cache,$caller) = @_;
343: unless ($ignore_cache) {
344: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
345: if (defined($cached)) {
346: return $serverhomeID;
347: }
348: }
349: my $cachetime = 12*3600;
350: my $serverhomeID;
351: if ($caller eq 'loncron') {
352: my @machine_ids = &machine_ids($hostname);
353: foreach my $id (@machine_ids) {
354: my $response = &reply('serverhomeID',$id);
355: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
356: $serverhomeID = $response;
357: last;
358: }
359: }
360: if ($serverhomeID eq '') {
361: $serverhomeID = $machine_ids[-1];
362: }
363: } else {
364: $serverhomeID = $serverhomeIDs{$hostname};
365: }
366: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
367: }
368:
369: sub get_remote_globals {
370: my ($lonhost,$whathash,$ignore_cache) = @_;
371: my ($result,%returnhash,%whatneeded);
372: if (ref($whathash) eq 'HASH') {
373: foreach my $what (sort(keys(%{$whathash}))) {
374: my $hashid = $lonhost.'-'.$what;
375: my ($response,$cached);
376: unless ($ignore_cache) {
377: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
378: }
379: if (defined($cached)) {
380: $returnhash{$what} = $response;
381: } else {
382: $whatneeded{$what} = 1;
383: }
384: }
385: if (keys(%whatneeded) == 0) {
386: $result = 'ok';
387: } else {
388: my $requested = &freeze_escape(\%whatneeded);
389: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
390: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
391: ($rep eq 'unknown_cmd')) {
392: $result = $rep;
393: } else {
394: $result = 'ok';
395: my @pairs=split(/\&/,$rep);
396: foreach my $item (@pairs) {
397: my ($key,$value)=split(/=/,$item,2);
398: my $what = &unescape($key);
399: my $hashid = $lonhost.'-'.$what;
400: $returnhash{$what}=&thaw_unescape($value);
401: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
402: }
403: }
404: }
405: }
406: return ($result,\%returnhash);
407: }
408:
409: sub remote_devalidate_cache {
410: my ($lonhost,$cachekeys) = @_;
411: my $items;
412: return unless (ref($cachekeys) eq 'ARRAY');
413: my $cachestr = join('&',@{$cachekeys});
414: my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
415: return $response;
416: }
417:
418: # -------------------------------------------------- Non-critical communication
419: sub subreply {
420: my ($cmd,$server)=@_;
421: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
422: #
423: # With loncnew process trimming, there's a timing hole between lonc server
424: # process exit and the master server picking up the listen on the AF_UNIX
425: # socket. In that time interval, a lock file will exist:
426:
427: my $lockfile=$peerfile.".lock";
428: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
429: sleep(0.1);
430: }
431: # At this point, either a loncnew parent is listening or an old lonc
432: # or loncnew child is listening so we can connect or everything's dead.
433: #
434: # We'll give the connection a few tries before abandoning it. If
435: # connection is not possible, we'll con_lost back to the client.
436: #
437: my $client;
438: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
439: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
440: Type => SOCK_STREAM,
441: Timeout => 10);
442: if ($client) {
443: last; # Connected!
444: } else {
445: &create_connection(&hostname($server),$server);
446: }
447: sleep(0.1); # Try again later if failed connection.
448: }
449: my $answer;
450: if ($client) {
451: print $client "sethost:$server:$cmd\n";
452: $answer=<$client>;
453: if (!$answer) { $answer="con_lost"; }
454: chomp($answer);
455: } else {
456: $answer = 'con_lost'; # Failed connection.
457: }
458: return $answer;
459: }
460:
461: sub reply {
462: my ($cmd,$server)=@_;
463: unless (defined(&hostname($server))) { return 'no_such_host'; }
464: my $answer=subreply($cmd,$server);
465: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
466: my $logged = $cmd;
467: if ($cmd =~ /^encrypt:([^:]+):/) {
468: my $subcmd = $1;
469: if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
470: ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
471: ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades') ||
472: ($subcmd eq 'put')) {
473: (undef,undef,my @rest) = split(/:/,$cmd);
474: if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
475: splice(@rest,2,1,'Hidden');
476: } elsif ($subcmd eq 'passwd') {
477: splice(@rest,2,2,('Hidden','Hidden'));
478: } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
479: ($subcmd eq 'autoexportgrades') || ($subcmd eq 'put')) {
480: splice(@rest,3,1,'Hidden');
481: }
482: $logged = join(':',('encrypt:'.$subcmd,@rest));
483: }
484: }
485: &logthis("<font color=\"blue\">WARNING:".
486: " $logged to $server returned $answer</font>");
487: }
488: return $answer;
489: }
490:
491: # ----------------------------------------------------------- Send USR1 to lonc
492:
493: sub reconlonc {
494: my ($lonid) = @_;
495: if ($lonid) {
496: my $hostname = &hostname($lonid);
497: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
498: if ($hostname && -e $peerfile) {
499: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
500: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
501: Type => SOCK_STREAM,
502: Timeout => 10);
503: if ($client) {
504: print $client ("reset_retries\n");
505: my $answer=<$client>;
506: #reset just this one.
507: }
508: }
509: return;
510: }
511:
512: &logthis("Trying to reconnect lonc");
513: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
514: if (open(my $fh,"<",$loncfile)) {
515: my $loncpid=<$fh>;
516: chomp($loncpid);
517: if (kill 0 => $loncpid) {
518: &logthis("lonc at pid $loncpid responding, sending USR1");
519: kill USR1 => $loncpid;
520: sleep 1;
521: } else {
522: &logthis(
523: "<font color=\"blue\">WARNING:".
524: " lonc at pid $loncpid not responding, giving up</font>");
525: }
526: } else {
527: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
528: }
529: }
530:
531: # ------------------------------------------------------ Critical communication
532:
533: sub critical {
534: my ($cmd,$server)=@_;
535: unless (&hostname($server)) {
536: &logthis("<font color=\"blue\">WARNING:".
537: " Critical message to unknown server ($server)</font>");
538: return 'no_such_host';
539: }
540: my $answer=reply($cmd,$server);
541: if ($answer eq 'con_lost') {
542: &reconlonc($server);
543: my $answer=reply($cmd,$server);
544: if ($answer eq 'con_lost') {
545: my $now=time;
546: my $middlename=$cmd;
547: $middlename=substr($middlename,0,16);
548: $middlename=~s/\W//g;
549: my $dfilename=
550: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
551: $dumpcount++;
552: {
553: my $dfh;
554: if (open($dfh,">",$dfilename)) {
555: print $dfh "$cmd\n";
556: close($dfh);
557: }
558: }
559: sleep 1;
560: my $wcmd='';
561: {
562: my $dfh;
563: if (open($dfh,"<",$dfilename)) {
564: $wcmd=<$dfh>;
565: close($dfh);
566: }
567: }
568: chomp($wcmd);
569: if ($wcmd eq $cmd) {
570: &logthis("<font color=\"blue\">WARNING: ".
571: "Connection buffer $dfilename: $cmd</font>");
572: &logperm("D:$server:$cmd");
573: return 'con_delayed';
574: } else {
575: &logthis("<font color=\"red\">CRITICAL:"
576: ." Critical connection failed: $server $cmd</font>");
577: &logperm("F:$server:$cmd");
578: return 'con_failed';
579: }
580: }
581: }
582: return $answer;
583: }
584:
585: # ------------------------------------------- check if return value is an error
586:
587: sub error {
588: my ($result) = @_;
589: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
590: if ($2 == 2) { return undef; }
591: return $1;
592: }
593: return undef;
594: }
595:
596: sub convert_and_load_session_env {
597: my ($lonidsdir,$handle)=@_;
598: my @profile;
599: {
600: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
601: if (!$opened) {
602: return 0;
603: }
604: flock($idf,LOCK_SH);
605: @profile=<$idf>;
606: close($idf);
607: }
608: my %temp_env;
609: foreach my $line (@profile) {
610: if ($line !~ m/=/) {
611: return 0;
612: }
613: chomp($line);
614: my ($envname,$envvalue)=split(/=/,$line,2);
615: $temp_env{&unescape($envname)} = &unescape($envvalue);
616: }
617: unlink("$lonidsdir/$handle.id");
618: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
619: 0640)) {
620: %disk_env = %temp_env;
621: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
622: untie(%disk_env);
623: }
624: return 1;
625: }
626:
627: # ------------------------------------------- Transfer profile into environment
628: my $env_loaded;
629: sub transfer_profile_to_env {
630: my ($lonidsdir,$handle,$force_transfer) = @_;
631: if (!$force_transfer && $env_loaded) { return; }
632:
633: if (!defined($lonidsdir)) {
634: $lonidsdir = $perlvar{'lonIDsDir'};
635: }
636: if (!defined($handle)) {
637: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
638: }
639:
640: my $convert;
641: {
642: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
643: if (!$opened) {
644: return;
645: }
646: flock($idf,LOCK_SH);
647: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
648: &GDBM_READER(),0640)) {
649: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
650: untie(%disk_env);
651: } else {
652: $convert = 1;
653: }
654: }
655: if ($convert) {
656: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
657: &logthis("Failed to load session, or convert session.");
658: }
659: }
660:
661: my %remove;
662: while ( my $envname = each(%env) ) {
663: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
664: if ($time < time-300) {
665: $remove{$key}++;
666: }
667: }
668: }
669:
670: $env{'user.environment'} = "$lonidsdir/$handle.id";
671: $env_loaded=1;
672: foreach my $expired_key (keys(%remove)) {
673: &delenv($expired_key);
674: }
675: }
676:
677: # ---------------------------------------------------- Check for valid session
678: sub check_for_valid_session {
679: my ($r,$name,$userhashref,$domref) = @_;
680: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
681: my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
682: if ($name eq 'lonDAV') {
683: $lonidsdir=$r->dir_config('lonDAVsessDir');
684: } else {
685: $lonidsdir=$r->dir_config('lonIDsDir');
686: if ($name eq '') {
687: $name = 'lonID';
688: }
689: }
690: if ($name eq 'lonID') {
691: $secure = 'lonSID';
692: $linkname = 'lonLinkID';
693: $pubname = 'lonPubID';
694: if (exists($cookies{$secure})) {
695: $lonid=$cookies{$secure};
696: } elsif (exists($cookies{$name})) {
697: $lonid=$cookies{$name};
698: } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
699: $lonid=$cookies{$linkname};
700: } elsif (exists($cookies{$pubname})) {
701: $lonid=$cookies{$pubname};
702: }
703: } else {
704: $lonid=$cookies{$name};
705: }
706: return undef if (!$lonid);
707:
708: my $handle=&LONCAPA::clean_handle($lonid->value);
709: if (-l "$lonidsdir/$handle.id") {
710: my $link = readlink("$lonidsdir/$handle.id");
711: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
712: $handle = $1;
713: }
714: }
715: if (!-e "$lonidsdir/$handle.id") {
716: if ((ref($domref)) && ($name eq 'lonID') &&
717: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
718: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
719: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
720: $$domref = $possudom;
721: }
722: }
723: return undef;
724: }
725:
726: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
727: return undef if (!$opened);
728:
729: flock($idf,LOCK_SH);
730: my %disk_env;
731: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
732: &GDBM_READER(),0640)) {
733: return undef;
734: }
735:
736: if (!defined($disk_env{'user.name'})
737: || !defined($disk_env{'user.domain'})) {
738: untie(%disk_env);
739: return undef;
740: }
741:
742: if (ref($userhashref) eq 'HASH') {
743: $userhashref->{'name'} = $disk_env{'user.name'};
744: $userhashref->{'domain'} = $disk_env{'user.domain'};
745: if ($disk_env{'request.role'}) {
746: $userhashref->{'role'} = $disk_env{'request.role'};
747: }
748: $userhashref->{'lti'} = $disk_env{'request.lti.login'};
749: if ($userhashref->{'lti'}) {
750: $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
751: $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
752: }
753: }
754: untie(%disk_env);
755:
756: return $handle;
757: }
758:
759: sub timed_flock {
760: my ($file,$lock_type) = @_;
761: my $failed=0;
762: eval {
763: local $SIG{__DIE__}='DEFAULT';
764: local $SIG{ALRM}=sub {
765: $failed=1;
766: die("failed lock");
767: };
768: alarm(13);
769: flock($file,$lock_type);
770: alarm(0);
771: };
772: if ($failed) {
773: return undef;
774: } else {
775: return 1;
776: }
777: }
778:
779: sub get_sessionfile_vars {
780: my ($handle,$lonidsdir,$storearr) = @_;
781: my %returnhash;
782: unless (ref($storearr) eq 'ARRAY') {
783: return %returnhash;
784: }
785: if (-l "$lonidsdir/$handle.id") {
786: my $link = readlink("$lonidsdir/$handle.id");
787: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
788: $handle = $1;
789: }
790: }
791: if ((-e "$lonidsdir/$handle.id") &&
792: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
793: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
794: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
795: if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
796: flock($idf,LOCK_SH);
797: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
798: &GDBM_READER(),0640)) {
799: foreach my $item (@{$storearr}) {
800: $returnhash{$item} = $disk_env{$item};
801: }
802: untie(%disk_env);
803: }
804: }
805: }
806: }
807: return %returnhash;
808: }
809:
810: # ---------------------------------------------------------- Append Environment
811:
812: sub appenv {
813: my ($newenv,$roles) = @_;
814: if (ref($newenv) eq 'HASH') {
815: foreach my $key (keys(%{$newenv})) {
816: my $refused = 0;
817: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
818: $refused = 1;
819: if (ref($roles) eq 'ARRAY') {
820: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
821: if (grep(/^\Q$role\E$/,@{$roles})) {
822: $refused = 0;
823: }
824: }
825: }
826: if ($refused) {
827: &logthis("<font color=\"blue\">WARNING: ".
828: "Attempt to modify environment ".$key." to ".$newenv->{$key}
829: .'</font>');
830: delete($newenv->{$key});
831: } else {
832: $env{$key}=$newenv->{$key};
833: }
834: }
835: my $lonids = $perlvar{'lonIDsDir'};
836: if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
837: my $opened = open(my $env_file,'+<',$env{'user.environment'});
838: if ($opened
839: && &timed_flock($env_file,LOCK_EX)
840: &&
841: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
842: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
843: while (my ($key,$value) = each(%{$newenv})) {
844: $disk_env{$key} = $value;
845: }
846: untie(%disk_env);
847: }
848: }
849: }
850: return 'ok';
851: }
852: # ----------------------------------------------------- Delete from Environment
853:
854: sub delenv {
855: my ($delthis,$regexp,$roles) = @_;
856: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
857: my $refused = 1;
858: if (ref($roles) eq 'ARRAY') {
859: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
860: if (grep(/^\Q$role\E$/,@{$roles})) {
861: $refused = 0;
862: }
863: }
864: if ($refused) {
865: &logthis("<font color=\"blue\">WARNING: ".
866: "Attempt to delete from environment ".$delthis);
867: return 'error';
868: }
869: }
870: my $opened = open(my $env_file,'+<',$env{'user.environment'});
871: if ($opened
872: && &timed_flock($env_file,LOCK_EX)
873: &&
874: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
875: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
876: foreach my $key (keys(%disk_env)) {
877: if ($regexp) {
878: if ($key=~/^$delthis/) {
879: delete($env{$key});
880: delete($disk_env{$key});
881: }
882: } else {
883: if ($key=~/^\Q$delthis\E/) {
884: delete($env{$key});
885: delete($disk_env{$key});
886: }
887: }
888: }
889: untie(%disk_env);
890: }
891: return 'ok';
892: }
893:
894: sub get_env_multiple {
895: my ($name) = @_;
896: my @values;
897: if (defined($env{$name})) {
898: # exists is it an array
899: if (ref($env{$name})) {
900: @values=@{ $env{$name} };
901: } else {
902: $values[0]=$env{$name};
903: }
904: }
905: return(@values);
906: }
907:
908: # ------------------------------------------------------------------- Locking
909:
910: sub set_lock {
911: my ($text)=@_;
912: $locknum++;
913: my $id=$$.'-'.$locknum;
914: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
915: 'session.lock.'.$id => $text});
916: return $id;
917: }
918:
919: sub get_locks {
920: my $num=0;
921: my %texts=();
922: foreach my $lock (split(/\,/,$env{'session.locks'})) {
923: if ($lock=~/\w/) {
924: $num++;
925: $texts{$lock}=$env{'session.lock.'.$lock};
926: }
927: }
928: return ($num,%texts);
929: }
930:
931: sub remove_lock {
932: my ($id)=@_;
933: my $newlocks='';
934: foreach my $lock (split(/\,/,$env{'session.locks'})) {
935: if (($lock=~/\w/) && ($lock ne $id)) {
936: $newlocks.=','.$lock;
937: }
938: }
939: &appenv({'session.locks' => $newlocks});
940: &delenv('session.lock.'.$id);
941: }
942:
943: sub remove_all_locks {
944: my $activelocks=$env{'session.locks'};
945: foreach my $lock (split(/\,/,$env{'session.locks'})) {
946: if ($lock=~/\w/) {
947: &remove_lock($lock);
948: }
949: }
950: }
951:
952:
953: # ------------------------------------------ Find out current server userload
954: sub userload {
955: my $numusers=0;
956: {
957: opendir(LONIDS,$perlvar{'lonIDsDir'});
958: my $filename;
959: my $curtime=time;
960: while ($filename=readdir(LONIDS)) {
961: next if ($filename eq '.' || $filename eq '..');
962: next if ($filename =~ /publicuser_\d+\.id/);
963: next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
964: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
965: if ($curtime-$mtime < 1800) { $numusers++; }
966: }
967: closedir(LONIDS);
968: }
969: my $userloadpercent=0;
970: my $maxuserload=$perlvar{'lonUserLoadLim'};
971: if ($maxuserload) {
972: $userloadpercent=100*$numusers/$maxuserload;
973: }
974: $userloadpercent=sprintf("%.2f",$userloadpercent);
975: return $userloadpercent;
976: }
977:
978: # ------------------------------ Find server with least workload from spare.tab
979:
980: sub spareserver {
981: my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
982: my $spare_server;
983: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
984: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
985: : $userloadpercent;
986: my ($uint_dom,$remotesessions);
987: if (($udom ne '') && (&domain($udom) ne '')) {
988: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
989: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
990: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
991: $remotesessions = $udomdefaults{'remotesessions'};
992: }
993: my $spareshash = &this_host_spares($udom);
994: if (ref($spareshash) eq 'HASH') {
995: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
996: foreach my $try_server (@{ $spareshash->{'primary'} }) {
997: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
998: $try_server));
999: ($spare_server, $lowest_load) =
1000: &compare_server_load($try_server, $spare_server, $lowest_load);
1001: }
1002: }
1003:
1004: my $found_server = ($spare_server ne '' && $lowest_load < 100);
1005:
1006: if (!$found_server) {
1007: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1008: foreach my $try_server (@{ $spareshash->{'default'} }) {
1009: next unless (&spare_can_host($udom,$uint_dom,
1010: $remotesessions,$try_server));
1011: ($spare_server, $lowest_load) =
1012: &compare_server_load($try_server, $spare_server, $lowest_load);
1013: }
1014: }
1015: }
1016: }
1017:
1018: if (!$want_server_name) {
1019: if (defined($spare_server)) {
1020: my $hostname = &hostname($spare_server);
1021: if (defined($hostname)) {
1022: my $protocol = 'http';
1023: if ($protocol{$spare_server} eq 'https') {
1024: $protocol = $protocol{$spare_server};
1025: }
1026: my $alias = &Apache::lonnet::use_proxy_alias($r,$spare_server);
1027: $hostname = $alias if ($alias ne '');
1028: $spare_server = $protocol.'://'.$hostname;
1029: }
1030: }
1031: }
1032: return $spare_server;
1033: }
1034:
1035: sub compare_server_load {
1036: my ($try_server, $spare_server, $lowest_load, $required) = @_;
1037:
1038: if ($required) {
1039: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
1040: my $remoterev = &get_server_loncaparev(undef,$try_server);
1041: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
1042: if (($major eq '' && $minor eq '') ||
1043: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
1044: return ($spare_server,$lowest_load);
1045: }
1046: }
1047:
1048: my $loadans = &reply('load', $try_server);
1049: my $userloadans = &reply('userload',$try_server);
1050:
1051: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1052: return ($spare_server, $lowest_load); #didn't get a number from the server
1053: }
1054:
1055: my $load;
1056: if ($loadans =~ /\d/) {
1057: if ($userloadans =~ /\d/) {
1058: #both are numbers, pick the bigger one
1059: $load = ($loadans > $userloadans) ? $loadans
1060: : $userloadans;
1061: } else {
1062: $load = $loadans;
1063: }
1064: } else {
1065: $load = $userloadans;
1066: }
1067:
1068: if (($load =~ /\d/) && ($load < $lowest_load)) {
1069: $spare_server = $try_server;
1070: $lowest_load = $load;
1071: }
1072: return ($spare_server,$lowest_load);
1073: }
1074:
1075: # --------------------------- ask offload servers if user already has a session
1076: sub find_existing_session {
1077: my ($udom,$uname) = @_;
1078: my $spareshash = &this_host_spares($udom);
1079: if (ref($spareshash) eq 'HASH') {
1080: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
1081: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1082: return $try_server if (&has_user_session($try_server, $udom, $uname));
1083: }
1084: }
1085: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1086: foreach my $try_server (@{ $spareshash->{'default'} }) {
1087: return $try_server if (&has_user_session($try_server, $udom, $uname));
1088: }
1089: }
1090: }
1091: return;
1092: }
1093:
1094: sub delusersession {
1095: my ($lonid,$udom,$uname) = @_;
1096: my $uprimary_id = &domain($udom,'primary');
1097: my $uintdom = &internet_dom($uprimary_id);
1098: my $intdom = &internet_dom($lonid);
1099: my $serverhomedom = &host_domain($lonid);
1100: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1101: return &reply(join(':','delusersession',
1102: map {&escape($_)} ($udom,$uname)),$lonid);
1103: }
1104: return;
1105: }
1106:
1107: # check if user's browser sent load balancer cookie and server still has session
1108: # and is not overloaded.
1109: sub check_for_balancer_cookie {
1110: my ($r,$update_mtime) = @_;
1111: my ($otherserver,$cookie);
1112: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1113: if (exists($cookies{'balanceID'})) {
1114: my $balid = $cookies{'balanceID'};
1115: $cookie=&LONCAPA::clean_handle($balid->value);
1116: my $balancedir=$r->dir_config('lonBalanceDir');
1117: if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
1118: if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
1119: my ($possudom,$possuname) = ($1,$2);
1120: my $has_session = 0;
1121: if ((&domain($possudom) ne '') &&
1122: (&homeserver($possuname,$possudom) ne 'no_host')) {
1123: my $try_server;
1124: my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
1125: if ($opened) {
1126: flock($idf,LOCK_SH);
1127: while (my $line = <$idf>) {
1128: chomp($line);
1129: if (&hostname($line) ne '') {
1130: $try_server = $line;
1131: last;
1132: }
1133: }
1134: close($idf);
1135: if (($try_server) &&
1136: (&has_user_session($try_server,$possudom,$possuname))) {
1137: my $lowest_load = 30000;
1138: ($otherserver,$lowest_load) =
1139: &compare_server_load($try_server,undef,$lowest_load);
1140: if ($otherserver ne '' && $lowest_load < 100) {
1141: $has_session = 1;
1142: } else {
1143: undef($otherserver);
1144: }
1145: }
1146: }
1147: }
1148: if ($has_session) {
1149: if ($update_mtime) {
1150: my $atime = my $mtime = time;
1151: utime($atime,$mtime,"$balancedir/$cookie.id");
1152: }
1153: } else {
1154: unlink("$balancedir/$cookie.id");
1155: }
1156: }
1157: }
1158: }
1159: return ($otherserver,$cookie);
1160: }
1161:
1162: sub updatebalcookie {
1163: my ($cookie,$balancer,$lastentry)=@_;
1164: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1165: my ($udom,$uname) = ($1,$2);
1166: my $uprimary_id = &domain($udom,'primary');
1167: my $uintdom = &internet_dom($uprimary_id);
1168: my $intdom = &internet_dom($balancer);
1169: my $serverhomedom = &host_domain($balancer);
1170: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1171: return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
1172: }
1173: }
1174: return;
1175: }
1176:
1177: sub delbalcookie {
1178: my ($cookie,$balancer) =@_;
1179: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1180: my ($udom,$uname) = ($1,$2);
1181: my $uprimary_id = &domain($udom,'primary');
1182: my $uintdom = &internet_dom($uprimary_id);
1183: my $intdom = &internet_dom($balancer);
1184: my $serverhomedom = &host_domain($balancer);
1185: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1186: return &reply('delbalcookie:'.&escape($cookie),$balancer);
1187: }
1188: }
1189: }
1190:
1191: # -------------------------------- ask if server already has a session for user
1192: sub has_user_session {
1193: my ($lonid,$udom,$uname) = @_;
1194: my $result = &reply(join(':','userhassession',
1195: map {&escape($_)} ($udom,$uname)),$lonid);
1196: return 1 if ($result eq 'ok');
1197:
1198: return 0;
1199: }
1200:
1201: # --------- determine least loaded server in a user's domain which allows login
1202:
1203: sub choose_server {
1204: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1205: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1206: my %servers = &get_servers($udom);
1207: my $lowest_load = 30000;
1208: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1209: if ($skiploadbal) {
1210: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1211: unless (defined($cached)) {
1212: my $cachetime = 60*60*24;
1213: my %domconfig =
1214: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1215: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1216: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1217: $cachetime);
1218: }
1219: }
1220: }
1221: foreach my $lonhost (keys(%servers)) {
1222: if ($skiploadbal) {
1223: if (ref($balancers) eq 'HASH') {
1224: next if (exists($balancers->{$lonhost}));
1225: }
1226: }
1227: my $loginvia;
1228: if ($checkloginvia) {
1229: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1230: if ($loginvia) {
1231: my ($server,$path) = split(/:/,$loginvia);
1232: ($login_host, $lowest_load) =
1233: &compare_server_load($server, $login_host, $lowest_load, $required);
1234: if ($login_host eq $server) {
1235: $portal_path = $path;
1236: $isredirect = 1;
1237: }
1238: } else {
1239: ($login_host, $lowest_load) =
1240: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1241: if ($login_host eq $lonhost) {
1242: $portal_path = '';
1243: $isredirect = '';
1244: }
1245: }
1246: } else {
1247: ($login_host, $lowest_load) =
1248: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1249: }
1250: }
1251: if ($login_host ne '') {
1252: $hostname = &hostname($login_host);
1253: }
1254: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1255: }
1256:
1257: sub get_course_sessions {
1258: my ($cnum,$cdom,$lastactivity) = @_;
1259: my %servers = &internet_dom_servers($cdom);
1260: my %returnhash;
1261: foreach my $server (sort(keys(%servers))) {
1262: my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
1263: my @pairs=split(/\&/,$rep);
1264: unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
1265: foreach my $item (@pairs) {
1266: my ($key,$value)=split(/=/,$item,2);
1267: $key = &unescape($key);
1268: next if ($key =~ /^error: 2 /);
1269: if (exists($returnhash{$key})) {
1270: next if ($value < $returnhash{$key});
1271: }
1272: $returnhash{$key}=$value;
1273: }
1274: }
1275: }
1276: return %returnhash;
1277: }
1278:
1279: # --------------------------------------------- Try to change a user's password
1280:
1281: sub changepass {
1282: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1283: $currentpass = &escape($currentpass);
1284: $newpass = &escape($newpass);
1285: my $lonhost = $perlvar{'lonHostID'};
1286: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1287: $server);
1288: if (! $answer) {
1289: &logthis("No reply on password change request to $server ".
1290: "by $uname in domain $udom.");
1291: } elsif ($answer =~ "^ok") {
1292: &logthis("$uname in $udom successfully changed their password ".
1293: "on $server.");
1294: } elsif ($answer =~ "^pwchange_failure") {
1295: &logthis("$uname in $udom was unable to change their password ".
1296: "on $server. The action was blocked by either lcpasswd ".
1297: "or pwchange");
1298: } elsif ($answer =~ "^non_authorized") {
1299: &logthis("$uname in $udom did not get their password correct when ".
1300: "attempting to change it on $server.");
1301: } elsif ($answer =~ "^auth_mode_error") {
1302: &logthis("$uname in $udom attempted to change their password despite ".
1303: "not being locally or internally authenticated on $server.");
1304: } elsif ($answer =~ "^unknown_user") {
1305: &logthis("$uname in $udom attempted to change their password ".
1306: "on $server but were unable to because $server is not ".
1307: "their home server.");
1308: } elsif ($answer =~ "^refused") {
1309: &logthis("$server refused to change $uname in $udom password because ".
1310: "it was sent an unencrypted request to change the password.");
1311: } elsif ($answer =~ "invalid_client") {
1312: &logthis("$server refused to change $uname in $udom password because ".
1313: "it was a reset by e-mail originating from an invalid server.");
1314: } elsif ($answer =~ "^prioruse") {
1315: &logthis("$server refused to change $uname in $udom password because ".
1316: "the password had been used before");
1317: }
1318: return $answer;
1319: }
1320:
1321: # ----------------------- Try to determine user's current authentication scheme
1322:
1323: sub queryauthenticate {
1324: my ($uname,$udom)=@_;
1325: my $uhome=&homeserver($uname,$udom);
1326: if (!$uhome) {
1327: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1328: return 'no_host';
1329: }
1330: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1331: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1332: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1333: }
1334: return $answer;
1335: }
1336:
1337: # --------- Try to authenticate user from domain's lib servers (first this one)
1338:
1339: sub authenticate {
1340: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1341: $upass=&escape($upass);
1342: $uname= &LONCAPA::clean_username($uname);
1343: my $uhome=&homeserver($uname,$udom,1);
1344: my $newhome;
1345: if ((!$uhome) || ($uhome eq 'no_host')) {
1346: # Maybe the machine was offline and only re-appeared again recently?
1347: &reconlonc();
1348: # One more
1349: $uhome=&homeserver($uname,$udom,1);
1350: if (($uhome eq 'no_host') && $checkdefauth) {
1351: if (defined(&domain($udom,'primary'))) {
1352: $newhome=&domain($udom,'primary');
1353: }
1354: if ($newhome ne '') {
1355: $uhome = $newhome;
1356: }
1357: }
1358: if ((!$uhome) || ($uhome eq 'no_host')) {
1359: &logthis("User $uname at $udom is unknown in authenticate");
1360: return 'no_host';
1361: }
1362: }
1363: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1364: if ($answer eq 'authorized') {
1365: if ($newhome) {
1366: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1367: return 'no_account_on_host';
1368: } else {
1369: &logthis("User $uname at $udom authorized by $uhome");
1370: return $uhome;
1371: }
1372: }
1373: if ($answer eq 'non_authorized') {
1374: &logthis("User $uname at $udom rejected by $uhome");
1375: return 'no_host';
1376: }
1377: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1378: return 'no_host';
1379: }
1380:
1381: sub can_host_session {
1382: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1383: my $canhost = 1;
1384: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1385: if (ref($remotesessions) eq 'HASH') {
1386: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1387: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1388: $canhost = 0;
1389: } else {
1390: $canhost = 1;
1391: }
1392: }
1393: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1394: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1395: $canhost = 1;
1396: } else {
1397: $canhost = 0;
1398: }
1399: }
1400: if ($canhost) {
1401: if ($remotesessions->{'version'} ne '') {
1402: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1403: if ($reqmajor ne '' && $reqminor ne '') {
1404: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1405: my $major = $1;
1406: my $minor = $2;
1407: if (($major < $reqmajor ) ||
1408: (($major == $reqmajor) && ($minor < $reqminor))) {
1409: $canhost = 0;
1410: }
1411: } else {
1412: $canhost = 0;
1413: }
1414: }
1415: }
1416: }
1417: }
1418: if ($canhost) {
1419: if (ref($hostedsessions) eq 'HASH') {
1420: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1421: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1422: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1423: if (($uint_dom ne '') &&
1424: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1425: $canhost = 0;
1426: } else {
1427: $canhost = 1;
1428: }
1429: }
1430: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1431: if (($uint_dom ne '') &&
1432: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1433: $canhost = 1;
1434: } else {
1435: $canhost = 0;
1436: }
1437: }
1438: }
1439: }
1440: return $canhost;
1441: }
1442:
1443: sub spare_can_host {
1444: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1445: my $canhost=1;
1446: my $try_server_hostname = &hostname($try_server);
1447: my $serverhomeID = &get_server_homeID($try_server_hostname);
1448: my $serverhomedom = &host_domain($serverhomeID);
1449: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1450: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1451: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1452: $canhost = 0;
1453: }
1454: }
1455: if ($canhost) {
1456: if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
1457: if ($defdomdefaults{'offloadoth'}{$try_server}) {
1458: unless (&shared_institution($udom,$try_server)) {
1459: $canhost = 0;
1460: }
1461: }
1462: }
1463: }
1464: if (($canhost) && ($uint_dom)) {
1465: my @intdoms;
1466: my $internet_names = &get_internet_names($try_server);
1467: if (ref($internet_names) eq 'ARRAY') {
1468: @intdoms = @{$internet_names};
1469: }
1470: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1471: my $remoterev = &get_server_loncaparev(undef,$try_server);
1472: $canhost = &can_host_session($udom,$try_server,$remoterev,
1473: $remotesessions,
1474: $defdomdefaults{'hostedsessions'});
1475: }
1476: }
1477: return $canhost;
1478: }
1479:
1480: sub this_host_spares {
1481: my ($dom) = @_;
1482: my ($dom_in_use,$lonhost_in_use,$result);
1483: my @hosts = ¤t_machine_ids();
1484: foreach my $lonhost (@hosts) {
1485: if (&host_domain($lonhost) eq $dom) {
1486: $dom_in_use = $dom;
1487: $lonhost_in_use = $lonhost;
1488: last;
1489: }
1490: }
1491: if ($dom_in_use ne '') {
1492: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1493: }
1494: if (ref($result) ne 'HASH') {
1495: $lonhost_in_use = $perlvar{'lonHostID'};
1496: $dom_in_use = &host_domain($lonhost_in_use);
1497: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1498: if (ref($result) ne 'HASH') {
1499: $result = \%spareid;
1500: }
1501: }
1502: return $result;
1503: }
1504:
1505: sub spares_for_offload {
1506: my ($dom_in_use,$lonhost_in_use) = @_;
1507: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1508: if (defined($cached)) {
1509: return $result;
1510: } else {
1511: my $cachetime = 60*60*24;
1512: my %domconfig =
1513: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1514: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1515: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1516: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1517: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1518: }
1519: }
1520: }
1521: }
1522: return;
1523: }
1524:
1525: sub get_lonbalancer_config {
1526: my ($servers) = @_;
1527: my ($currbalancer,$currtargets);
1528: if (ref($servers) eq 'HASH') {
1529: foreach my $server (keys(%{$servers})) {
1530: my %what = (
1531: spareid => 1,
1532: perlvar => 1,
1533: );
1534: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1535: if ($result eq 'ok') {
1536: if (ref($returnhash) eq 'HASH') {
1537: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1538: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1539: $currbalancer = $server;
1540: $currtargets = {};
1541: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1542: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1543: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1544: }
1545: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1546: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1547: }
1548: }
1549: last;
1550: }
1551: }
1552: }
1553: }
1554: }
1555: }
1556: return ($currbalancer,$currtargets);
1557: }
1558:
1559: sub check_loadbalancing {
1560: my ($uname,$udom,$caller) = @_;
1561: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1562: $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1563: my $lonhost = $perlvar{'lonHostID'};
1564: my @hosts = ¤t_machine_ids();
1565: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1566: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1567: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1568: my $serverhomedom = &host_domain($lonhost);
1569: my $domneedscache;
1570: my $cachetime = 60*60*24;
1571:
1572: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1573: $dom_in_use = $udom;
1574: $homeintdom = 1;
1575: } else {
1576: $dom_in_use = $serverhomedom;
1577: }
1578: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1579: unless (defined($cached)) {
1580: my %domconfig =
1581: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1582: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1583: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1584: } else {
1585: $domneedscache = $dom_in_use;
1586: }
1587: }
1588: if (ref($result) eq 'HASH') {
1589: ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1590: &check_balancer_result($result,@hosts);
1591: if ($is_balancer) {
1592: if (ref($currrules) eq 'HASH') {
1593: if ($homeintdom) {
1594: if ($uname ne '') {
1595: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1596: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1597: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1598: $rule_in_effect = $currrules->{'_LC_author'};
1599: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1600: $rule_in_effect = $currrules->{'_LC_adv'}
1601: }
1602: }
1603: if ($rule_in_effect eq '') {
1604: my %userenv = &userenvironment($udom,$uname,'inststatus');
1605: if ($userenv{'inststatus'} ne '') {
1606: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1607: my ($othertitle,$usertypes,$types) =
1608: &Apache::loncommon::sorted_inst_types($udom);
1609: if (ref($types) eq 'ARRAY') {
1610: foreach my $type (@{$types}) {
1611: if (grep(/^\Q$type\E$/,@statuses)) {
1612: if (exists($currrules->{$type})) {
1613: $rule_in_effect = $currrules->{$type};
1614: }
1615: }
1616: }
1617: }
1618: } else {
1619: if (exists($currrules->{'default'})) {
1620: $rule_in_effect = $currrules->{'default'};
1621: }
1622: }
1623: }
1624: } else {
1625: if (exists($currrules->{'default'})) {
1626: $rule_in_effect = $currrules->{'default'};
1627: }
1628: }
1629: } else {
1630: if ($currrules->{'_LC_external'} ne '') {
1631: $rule_in_effect = $currrules->{'_LC_external'};
1632: }
1633: }
1634: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1635: $uname,$udom);
1636: }
1637: }
1638: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1639: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1640: unless (defined($cached)) {
1641: my %domconfig =
1642: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1643: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1644: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1645: } else {
1646: $domneedscache = $serverhomedom;
1647: }
1648: }
1649: if (ref($result) eq 'HASH') {
1650: ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1651: &check_balancer_result($result,@hosts);
1652: if ($is_balancer) {
1653: if (ref($currrules) eq 'HASH') {
1654: if ($currrules->{'_LC_internetdom'} ne '') {
1655: $rule_in_effect = $currrules->{'_LC_internetdom'};
1656: }
1657: }
1658: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1659: $uname,$udom);
1660: }
1661: } else {
1662: if ($perlvar{'lonBalancer'} eq 'yes') {
1663: $is_balancer = 1;
1664: $offloadto = &this_host_spares($dom_in_use);
1665: }
1666: unless (defined($cached)) {
1667: $domneedscache = $serverhomedom;
1668: }
1669: }
1670: } else {
1671: if ($perlvar{'lonBalancer'} eq 'yes') {
1672: $is_balancer = 1;
1673: $offloadto = &this_host_spares($dom_in_use);
1674: }
1675: unless (defined($cached)) {
1676: $domneedscache = $serverhomedom;
1677: }
1678: }
1679: if ($domneedscache) {
1680: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1681: }
1682: if (($is_balancer) && ($caller ne 'switchserver')) {
1683: my $lowest_load = 30000;
1684: if (ref($offloadto) eq 'HASH') {
1685: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1686: foreach my $try_server (@{$offloadto->{'primary'}}) {
1687: ($otherserver,$lowest_load) =
1688: &compare_server_load($try_server,$otherserver,$lowest_load);
1689: }
1690: }
1691: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1692:
1693: if (!$found_server) {
1694: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1695: foreach my $try_server (@{$offloadto->{'default'}}) {
1696: ($otherserver,$lowest_load) =
1697: &compare_server_load($try_server,$otherserver,$lowest_load);
1698: }
1699: }
1700: }
1701: } elsif (ref($offloadto) eq 'ARRAY') {
1702: if (@{$offloadto} == 1) {
1703: $otherserver = $offloadto->[0];
1704: } elsif (@{$offloadto} > 1) {
1705: foreach my $try_server (@{$offloadto}) {
1706: ($otherserver,$lowest_load) =
1707: &compare_server_load($try_server,$otherserver,$lowest_load);
1708: }
1709: }
1710: }
1711: unless ($caller eq 'login') {
1712: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1713: $is_balancer = 0;
1714: if ($uname ne '' && $udom ne '') {
1715: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1716: &appenv({'user.loadbalexempt' => $lonhost,
1717: 'user.loadbalcheck.time' => time});
1718: }
1719: }
1720: }
1721: }
1722: }
1723: if (($is_balancer) && (!$homeintdom)) {
1724: undef($setcookie);
1725: }
1726: return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1727: }
1728:
1729: sub check_balancer_result {
1730: my ($result,@hosts) = @_;
1731: my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1732: if (ref($result) eq 'HASH') {
1733: if ($result->{'lonhost'} ne '') {
1734: my $currbalancer = $result->{'lonhost'};
1735: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1736: $is_balancer = 1;
1737: $currtargets = $result->{'targets'};
1738: $currrules = $result->{'rules'};
1739: }
1740: $dom_balancers = $currbalancer;
1741: } else {
1742: if (keys(%{$result})) {
1743: foreach my $key (keys(%{$result})) {
1744: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1745: (ref($result->{$key}) eq 'HASH')) {
1746: $is_balancer = 1;
1747: $currrules = $result->{$key}{'rules'};
1748: $currtargets = $result->{$key}{'targets'};
1749: $setcookie = $result->{$key}{'cookie'};
1750: last;
1751: }
1752: }
1753: $dom_balancers = join(',',sort(keys(%{$result})));
1754: }
1755: }
1756: }
1757: return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1758: }
1759:
1760: sub get_loadbalancer_targets {
1761: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1762: my $offloadto;
1763: if ($rule_in_effect eq 'none') {
1764: return [$perlvar{'lonHostID'}];
1765: } elsif ($rule_in_effect eq '') {
1766: $offloadto = $currtargets;
1767: } else {
1768: if ($rule_in_effect eq 'homeserver') {
1769: my $homeserver = &homeserver($uname,$udom);
1770: if ($homeserver ne 'no_host') {
1771: $offloadto = [$homeserver];
1772: }
1773: } elsif ($rule_in_effect eq 'externalbalancer') {
1774: my %domconfig =
1775: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1776: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1777: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1778: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1779: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1780: }
1781: }
1782: } else {
1783: my %servers = &internet_dom_servers($udom);
1784: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1785: if (&hostname($remotebalancer) ne '') {
1786: $offloadto = [$remotebalancer];
1787: }
1788: }
1789: } elsif (&hostname($rule_in_effect) ne '') {
1790: $offloadto = [$rule_in_effect];
1791: }
1792: }
1793: return $offloadto;
1794: }
1795:
1796: sub internet_dom_servers {
1797: my ($dom) = @_;
1798: my (%uniqservers,%servers);
1799: my $primaryserver = &hostname(&domain($dom,'primary'));
1800: my @machinedoms = &machine_domains($primaryserver);
1801: foreach my $mdom (@machinedoms) {
1802: my %currservers = %servers;
1803: my %server = &get_servers($mdom);
1804: %servers = (%currservers,%server);
1805: }
1806: my %by_hostname;
1807: foreach my $id (keys(%servers)) {
1808: push(@{$by_hostname{$servers{$id}}},$id);
1809: }
1810: foreach my $hostname (sort(keys(%by_hostname))) {
1811: if (@{$by_hostname{$hostname}} > 1) {
1812: my $match = 0;
1813: foreach my $id (@{$by_hostname{$hostname}}) {
1814: if (&host_domain($id) eq $dom) {
1815: $uniqservers{$id} = $hostname;
1816: $match = 1;
1817: }
1818: }
1819: unless ($match) {
1820: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1821: }
1822: } else {
1823: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1824: }
1825: }
1826: return %uniqservers;
1827: }
1828:
1829: sub trusted_domains {
1830: my ($cmdtype,$calldom) = @_;
1831: my ($trusted,$untrusted);
1832: if (&domain($calldom) eq '') {
1833: return ($trusted,$untrusted);
1834: }
1835: unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
1836: return ($trusted,$untrusted);
1837: }
1838: my $callprimary = &domain($calldom,'primary');
1839: my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
1840: if ($intcalldom eq '') {
1841: return ($trusted,$untrusted);
1842: }
1843:
1844: my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
1845: unless (defined($cached)) {
1846: my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
1847: &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
1848: $trustconfig = $domconfig{'trust'};
1849: }
1850: if (ref($trustconfig)) {
1851: my (%possexc,%possinc,@allexc,@allinc);
1852: if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
1853: if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
1854: map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}};
1855: }
1856: if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1857: $possinc{$intcalldom} = 1;
1858: map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
1859: }
1860: }
1861: if (keys(%possexc)) {
1862: if (keys(%possinc)) {
1863: foreach my $key (sort(keys(%possexc))) {
1864: next if ($key eq $intcalldom);
1865: unless ($possinc{$key}) {
1866: push(@allexc,$key);
1867: }
1868: }
1869: } else {
1870: @allexc = sort(keys(%possexc));
1871: }
1872: }
1873: if (keys(%possinc)) {
1874: $possinc{$intcalldom} = 1;
1875: @allinc = sort(keys(%possinc));
1876: }
1877: if ((@allexc > 0) || (@allinc > 0)) {
1878: my %doms_by_intdom;
1879: my %allintdoms = &all_host_intdom();
1880: my %alldoms = &all_host_domain();
1881: foreach my $key (%allintdoms) {
1882: if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
1883: unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
1884: push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
1885: }
1886: } else {
1887: $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}];
1888: }
1889: }
1890: foreach my $exc (@allexc) {
1891: if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1892: push(@{$untrusted},@{$doms_by_intdom{$exc}});
1893: }
1894: }
1895: foreach my $inc (@allinc) {
1896: if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1897: push(@{$trusted},@{$doms_by_intdom{$inc}});
1898: }
1899: }
1900: }
1901: }
1902: return ($trusted,$untrusted);
1903: }
1904:
1905: sub will_trust {
1906: my ($cmdtype,$domain,$possdom) = @_;
1907: return 1 if ($domain eq $possdom);
1908: my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
1909: my $willtrust;
1910: if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
1911: if (grep(/^\Q$domain\E$/,@{$trustedref})) {
1912: $willtrust = 1;
1913: }
1914: } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
1915: unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
1916: $willtrust = 1;
1917: }
1918: } else {
1919: $willtrust = 1;
1920: }
1921: return $willtrust;
1922: }
1923:
1924: # ---------------------- Find the homebase for a user from domain's lib servers
1925:
1926: my %homecache;
1927: sub homeserver {
1928: my ($uname,$udom,$ignoreBadCache)=@_;
1929: my $index="$uname:$udom";
1930:
1931: if (exists($homecache{$index})) { return $homecache{$index}; }
1932:
1933: my %servers = &get_servers($udom,'library');
1934: foreach my $tryserver (keys(%servers)) {
1935: next if ($ignoreBadCache ne 'true' &&
1936: exists($badServerCache{$tryserver}));
1937:
1938: my $answer=reply("home:$udom:$uname",$tryserver);
1939: if ($answer eq 'found') {
1940: delete($badServerCache{$tryserver});
1941: return $homecache{$index}=$tryserver;
1942: } elsif ($answer eq 'no_host') {
1943: $badServerCache{$tryserver}=1;
1944: }
1945: }
1946: return 'no_host';
1947: }
1948:
1949: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1950:
1951: sub idget {
1952: my ($udom,$idsref,$namespace)=@_;
1953: my %returnhash=();
1954: my @ids=();
1955: if (ref($idsref) eq 'ARRAY') {
1956: @ids = @{$idsref};
1957: } else {
1958: return %returnhash;
1959: }
1960: if ($namespace eq '') {
1961: $namespace = 'ids';
1962: }
1963:
1964: my %servers = &get_servers($udom,'library');
1965: foreach my $tryserver (keys(%servers)) {
1966: my $idlist=join('&', map { &escape($_); } @ids);
1967: if ($namespace eq 'ids') {
1968: $idlist=~tr/A-Z/a-z/;
1969: }
1970: my $reply;
1971: if ($namespace eq 'ids') {
1972: $reply=&reply("idget:$udom:".$idlist,$tryserver);
1973: } else {
1974: $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
1975: }
1976: my @answer=();
1977: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1978: @answer=split(/\&/,$reply);
1979: } ;
1980: my $i;
1981: for ($i=0;$i<=$#ids;$i++) {
1982: if ($answer[$i]) {
1983: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1984: }
1985: }
1986: }
1987: return %returnhash;
1988: }
1989:
1990: # ------------------------------------- Find the IDs behind a list of usernames
1991:
1992: sub idrget {
1993: my ($udom,@unames)=@_;
1994: my %returnhash=();
1995: foreach my $uname (@unames) {
1996: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1997: }
1998: return %returnhash;
1999: }
2000:
2001: # Store away a list of names and associated student/employee IDs or clicker IDs
2002:
2003: sub idput {
2004: my ($udom,$idsref,$uhom,$namespace)=@_;
2005: my %servers=();
2006: my %ids=();
2007: my %byid = ();
2008: if (ref($idsref) eq 'HASH') {
2009: %ids=%{$idsref};
2010: }
2011: if ($namespace eq '') {
2012: $namespace = 'ids';
2013: }
2014: foreach my $uname (keys(%ids)) {
2015: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
2016: if ($uhom eq '') {
2017: $uhom=&homeserver($uname,$udom);
2018: }
2019: if ($uhom ne 'no_host') {
2020: my $esc_unam=&escape($uname);
2021: if ($namespace eq 'ids') {
2022: my $id=&escape($ids{$uname});
2023: $id=~tr/A-Z/a-z/;
2024: my $esc_unam=&escape($uname);
2025: $servers{$uhom}.=$id.'='.$esc_unam.'&';
2026: } else {
2027: my @currids = split(/,/,$ids{$uname});
2028: foreach my $id (@currids) {
2029: $byid{$uhom}{$id} .= $uname.',';
2030: }
2031: }
2032: }
2033: }
2034: if ($namespace eq 'clickers') {
2035: foreach my $server (keys(%byid)) {
2036: if (ref($byid{$server}) eq 'HASH') {
2037: foreach my $id (keys(%{$byid{$server}})) {
2038: $byid{$server} =~ s/,$//;
2039: $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&';
2040: }
2041: }
2042: }
2043: }
2044: foreach my $server (keys(%servers)) {
2045: $servers{$server} =~ s/\&$//;
2046: if ($namespace eq 'ids') {
2047: &critical('idput:'.$udom.':'.$servers{$server},$server);
2048: } else {
2049: &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
2050: }
2051: }
2052: }
2053:
2054: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
2055:
2056: sub iddel {
2057: my ($udom,$idshashref,$uhome,$namespace)=@_;
2058: my %result=();
2059: my %ids=();
2060: my %byid = ();
2061: if (ref($idshashref) eq 'HASH') {
2062: %ids=%{$idshashref};
2063: } else {
2064: return %result;
2065: }
2066: if ($namespace eq '') {
2067: $namespace = 'ids';
2068: }
2069: my %servers=();
2070: while (my ($id,$unamestr) = each(%ids)) {
2071: if ($namespace eq 'ids') {
2072: my $uhom = $uhome;
2073: if ($uhom eq '') {
2074: $uhom=&homeserver($unamestr,$udom);
2075: }
2076: if ($uhom ne 'no_host') {
2077: $servers{$uhom}.='&'.&escape($id);
2078: }
2079: } else {
2080: my @curritems = split(/,/,$ids{$id});
2081: foreach my $uname (@curritems) {
2082: my $uhom = $uhome;
2083: if ($uhom eq '') {
2084: $uhom=&homeserver($uname,$udom);
2085: }
2086: if ($uhom ne 'no_host') {
2087: $byid{$uhom}{$id} .= $uname.',';
2088: }
2089: }
2090: }
2091: }
2092: if ($namespace eq 'clickers') {
2093: foreach my $server (keys(%byid)) {
2094: if (ref($byid{$server}) eq 'HASH') {
2095: foreach my $id (keys(%{$byid{$server}})) {
2096: $byid{$server}{$id} =~ s/,$//;
2097: $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
2098: }
2099: }
2100: }
2101: }
2102: foreach my $server (keys(%servers)) {
2103: $servers{$server} =~ s/\&$//;
2104: if ($namespace eq 'ids') {
2105: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
2106: } elsif ($namespace eq 'clickers') {
2107: $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
2108: }
2109: }
2110: return %result;
2111: }
2112:
2113: # ----- Update clicker ID-to-username look-ups in clickers.db on library server
2114:
2115: sub updateclickers {
2116: my ($udom,$action,$idshashref,$uhome,$critical) = @_;
2117: my %clickers;
2118: if (ref($idshashref) eq 'HASH') {
2119: %clickers=%{$idshashref};
2120: } else {
2121: return;
2122: }
2123: my $items='';
2124: foreach my $item (keys(%clickers)) {
2125: $items.=&escape($item).'='.&escape($clickers{$item}).'&';
2126: }
2127: $items=~s/\&$//;
2128: my $request = "updateclickers:$udom:$action:$items";
2129: if ($critical) {
2130: return &critical($request,$uhome);
2131: } else {
2132: return &reply($request,$uhome);
2133: }
2134: }
2135:
2136: # ------------------------------dump from db file owned by domainconfig user
2137: sub dump_dom {
2138: my ($namespace, $udom, $regexp) = @_;
2139:
2140: $udom ||= $env{'user.domain'};
2141:
2142: return () unless $udom;
2143:
2144: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
2145: }
2146:
2147: # ------------------------------------------ get items from domain db files
2148:
2149: sub get_dom {
2150: my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
2151: return if ($udom eq 'public');
2152: my $items='';
2153: foreach my $item (@$storearr) {
2154: $items.=&escape($item).'&';
2155: }
2156: $items=~s/\&$//;
2157: if (!$udom) {
2158: $udom=$env{'user.domain'};
2159: return if ($udom eq 'public');
2160: if (defined(&domain($udom,'primary'))) {
2161: $uhome=&domain($udom,'primary');
2162: } else {
2163: undef($uhome);
2164: }
2165: } else {
2166: if (!$uhome) {
2167: if (defined(&domain($udom,'primary'))) {
2168: $uhome=&domain($udom,'primary');
2169: }
2170: }
2171: }
2172: if ($udom && $uhome && ($uhome ne 'no_host')) {
2173: my $rep;
2174: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
2175: # domain information is hosted on this machine
2176: $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
2177: } else {
2178: if ($encrypt) {
2179: $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
2180: } else {
2181: $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
2182: }
2183: }
2184: my %returnhash;
2185: if ($rep eq '' || $rep =~ /^error: 2 /) {
2186: return %returnhash;
2187: }
2188: my @pairs=split(/\&/,$rep);
2189: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
2190: return @pairs;
2191: }
2192: my $i=0;
2193: foreach my $item (@$storearr) {
2194: $returnhash{$item}=&thaw_unescape($pairs[$i]);
2195: $i++;
2196: }
2197: return %returnhash;
2198: } else {
2199: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
2200: }
2201: }
2202:
2203: # -------------------------------------------- put items in domain db files
2204:
2205: sub put_dom {
2206: my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
2207: if (!$udom) {
2208: $udom=$env{'user.domain'};
2209: if (defined(&domain($udom,'primary'))) {
2210: $uhome=&domain($udom,'primary');
2211: } else {
2212: undef($uhome);
2213: }
2214: } else {
2215: if (!$uhome) {
2216: if (defined(&domain($udom,'primary'))) {
2217: $uhome=&domain($udom,'primary');
2218: }
2219: }
2220: }
2221: if ($udom && $uhome && ($uhome ne 'no_host')) {
2222: my $items='';
2223: foreach my $item (keys(%$storehash)) {
2224: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
2225: }
2226: $items=~s/\&$//;
2227: if ($encrypt) {
2228: return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
2229: } else {
2230: return &reply("putdom:$udom:$namespace:$items",$uhome);
2231: }
2232: } else {
2233: &logthis("put_dom failed - no homeserver and/or domain");
2234: }
2235: }
2236:
2237: # --------------------- newput for items in db file owned by domainconfig user
2238: sub newput_dom {
2239: my ($namespace,$storehash,$udom) = @_;
2240: my $result;
2241: if (!$udom) {
2242: $udom=$env{'user.domain'};
2243: }
2244: if ($udom) {
2245: my $uname = &get_domainconfiguser($udom);
2246: $result = &newput($namespace,$storehash,$udom,$uname);
2247: }
2248: return $result;
2249: }
2250:
2251: # --------------------- delete for items in db file owned by domainconfig user
2252: sub del_dom {
2253: my ($namespace,$storearr,$udom)=@_;
2254: if (ref($storearr) eq 'ARRAY') {
2255: if (!$udom) {
2256: $udom=$env{'user.domain'};
2257: }
2258: if ($udom) {
2259: my $uname = &get_domainconfiguser($udom);
2260: return &del($namespace,$storearr,$udom,$uname);
2261: }
2262: }
2263: }
2264:
2265: sub store_dom {
2266: my ($storehash,$id,$namespace,$dom,$home) = @_;
2267: $$storehash{'ip'}=&get_requestor_ip();
2268: $$storehash{'host'}=$perlvar{'lonHostID'};
2269: my $namevalue='';
2270: foreach my $key (keys(%{$storehash})) {
2271: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
2272: }
2273: $namevalue=~s/\&$//;
2274: if (grep { $_ eq $home } current_machine_ids()) {
2275: return LONCAPA::Lond::store_dom("storedom:$dom:$namespace:$id:$namevalue");
2276: } else {
2277: if ($namespace eq 'private') {
2278: return 'refused';
2279: } else {
2280: return reply("storedom:$dom:$namespace:$id:$namevalue","$home");
2281: }
2282: }
2283: }
2284:
2285: # ----------------------------------construct domainconfig user for a domain
2286: sub get_domainconfiguser {
2287: my ($udom) = @_;
2288: return $udom.'-domainconfig';
2289: }
2290:
2291: sub retrieve_inst_usertypes {
2292: my ($udom) = @_;
2293: my (%returnhash,@order);
2294: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
2295: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
2296: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
2297: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
2298: } else {
2299: if (defined(&domain($udom,'primary'))) {
2300: my $uhome=&domain($udom,'primary');
2301: my $rep=&reply("inst_usertypes:$udom",$uhome);
2302: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
2303: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
2304: return (\%returnhash,\@order);
2305: }
2306: my ($hashitems,$orderitems) = split(/:/,$rep);
2307: my @pairs=split(/\&/,$hashitems);
2308: foreach my $item (@pairs) {
2309: my ($key,$value)=split(/=/,$item,2);
2310: $key = &unescape($key);
2311: next if ($key =~ /^error: 2 /);
2312: $returnhash{$key}=&thaw_unescape($value);
2313: }
2314: my @esc_order = split(/\&/,$orderitems);
2315: foreach my $item (@esc_order) {
2316: push(@order,&unescape($item));
2317: }
2318: } else {
2319: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
2320: }
2321: return (\%returnhash,\@order);
2322: }
2323: }
2324:
2325: sub is_domainimage {
2326: my ($url) = @_;
2327: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
2328: if (&domain($1) ne '') {
2329: return '1';
2330: }
2331: }
2332: return;
2333: }
2334:
2335: sub inst_directory_query {
2336: my ($srch) = @_;
2337: my $udom = $srch->{'srchdomain'};
2338: my %results;
2339: my $homeserver = &domain($udom,'primary');
2340: my $outcome;
2341: if ($homeserver ne '') {
2342: unless ($homeserver eq $perlvar{'lonHostID'}) {
2343: if ($srch->{'srchby'} eq 'email') {
2344: my $lcrev = &get_server_loncaparev($udom,$homeserver);
2345: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2346: if (($major eq '' && $minor eq '') || ($major < 2) ||
2347: (($major == 2) && ($minor < 12))) {
2348: return;
2349: }
2350: }
2351: }
2352: my $queryid=&reply("querysend:instdirsearch:".
2353: &escape($srch->{'srchby'}).':'.
2354: &escape($srch->{'srchterm'}).':'.
2355: &escape($srch->{'srchtype'}),$homeserver);
2356: my $host=&hostname($homeserver);
2357: if ($queryid !~/^\Q$host\E\_/) {
2358: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
2359: return;
2360: }
2361: my $response = &get_query_reply($queryid);
2362: my $maxtries = 5;
2363: my $tries = 1;
2364: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2365: $response = &get_query_reply($queryid);
2366: $tries ++;
2367: }
2368:
2369: if (!&error($response) && $response ne 'refused') {
2370: if ($response eq 'unavailable') {
2371: $outcome = $response;
2372: } else {
2373: $outcome = 'ok';
2374: my @matches = split(/\n/,$response);
2375: foreach my $match (@matches) {
2376: my ($key,$value) = split(/=/,$match);
2377: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2378: }
2379: }
2380: }
2381: }
2382: return ($outcome,%results);
2383: }
2384:
2385: sub usersearch {
2386: my ($srch) = @_;
2387: my $dom = $srch->{'srchdomain'};
2388: my %results;
2389: my %libserv = &all_library();
2390: my $query = 'usersearch';
2391: foreach my $tryserver (keys(%libserv)) {
2392: if (&host_domain($tryserver) eq $dom) {
2393: unless ($tryserver eq $perlvar{'lonHostID'}) {
2394: if ($srch->{'srchby'} eq 'email') {
2395: my $lcrev = &get_server_loncaparev($dom,$tryserver);
2396: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2397: next if (($major eq '' && $minor eq '') || ($major < 2) ||
2398: (($major == 2) && ($minor < 12)));
2399: }
2400: }
2401: my $host=&hostname($tryserver);
2402: my $queryid=
2403: &reply("querysend:".&escape($query).':'.
2404: &escape($srch->{'srchby'}).':'.
2405: &escape($srch->{'srchtype'}).':'.
2406: &escape($srch->{'srchterm'}),$tryserver);
2407: if ($queryid !~/^\Q$host\E\_/) {
2408: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
2409: next;
2410: }
2411: my $reply = &get_query_reply($queryid);
2412: my $maxtries = 1;
2413: my $tries = 1;
2414: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2415: $reply = &get_query_reply($queryid);
2416: $tries ++;
2417: }
2418: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2419: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2420: } else {
2421: my @matches;
2422: if ($reply =~ /\n/) {
2423: @matches = split(/\n/,$reply);
2424: } else {
2425: @matches = split(/\&/,$reply);
2426: }
2427: foreach my $match (@matches) {
2428: my ($uname,$udom,%userhash);
2429: foreach my $entry (split(/:/,$match)) {
2430: my ($key,$value) =
2431: map {&unescape($_);} split(/=/,$entry);
2432: $userhash{$key} = $value;
2433: if ($key eq 'username') {
2434: $uname = $value;
2435: } elsif ($key eq 'domain') {
2436: $udom = $value;
2437: }
2438: }
2439: $results{$uname.':'.$udom} = \%userhash;
2440: }
2441: }
2442: }
2443: }
2444: return %results;
2445: }
2446:
2447: sub get_instuser {
2448: my ($udom,$uname,$id) = @_;
2449: my $homeserver = &domain($udom,'primary');
2450: my ($outcome,%results);
2451: if ($homeserver ne '') {
2452: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2453: &escape($id).':'.&escape($udom),$homeserver);
2454: my $host=&hostname($homeserver);
2455: if ($queryid !~/^\Q$host\E\_/) {
2456: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2457: return;
2458: }
2459: my $response = &get_query_reply($queryid);
2460: my $maxtries = 5;
2461: my $tries = 1;
2462: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2463: $response = &get_query_reply($queryid);
2464: $tries ++;
2465: }
2466: if (!&error($response) && $response ne 'refused') {
2467: if ($response eq 'unavailable') {
2468: $outcome = $response;
2469: } else {
2470: $outcome = 'ok';
2471: my @matches = split(/\n/,$response);
2472: foreach my $match (@matches) {
2473: my ($key,$value) = split(/=/,$match);
2474: $results{&unescape($key)} = &thaw_unescape($value);
2475: }
2476: }
2477: }
2478: }
2479: my %userinfo;
2480: if (ref($results{$uname}) eq 'HASH') {
2481: %userinfo = %{$results{$uname}};
2482: }
2483: return ($outcome,%userinfo);
2484: }
2485:
2486: sub get_multiple_instusers {
2487: my ($udom,$users,$caller) = @_;
2488: my ($outcome,$results);
2489: if (ref($users) eq 'HASH') {
2490: my $count = keys(%{$users});
2491: my $requested = &freeze_escape($users);
2492: my $homeserver = &domain($udom,'primary');
2493: if ($homeserver ne '') {
2494: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2495: my $host=&hostname($homeserver);
2496: if ($queryid !~/^\Q$host\E\_/) {
2497: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2498: ' for host: '.$homeserver.'in domain '.$udom);
2499: return ($outcome,$results);
2500: }
2501: my $response = &get_query_reply($queryid);
2502: my $maxtries = 5;
2503: if ($count > 100) {
2504: $maxtries = 1+int($count/20);
2505: }
2506: my $tries = 1;
2507: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2508: $response = &get_query_reply($queryid);
2509: $tries ++;
2510: }
2511: if ($response eq '') {
2512: $results = {};
2513: foreach my $key (keys(%{$users})) {
2514: my ($uname,$id);
2515: if ($caller eq 'id') {
2516: $id = $key;
2517: } else {
2518: $uname = $key;
2519: }
2520: my ($resp,%info) = &get_instuser($udom,$uname,$id);
2521: $outcome = $resp;
2522: if ($resp eq 'ok') {
2523: %{$results} = (%{$results}, %info);
2524: } else {
2525: last;
2526: }
2527: }
2528: } elsif(!&error($response) && ($response ne 'refused')) {
2529: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2530: $outcome = $response;
2531: } else {
2532: ($outcome,my $userdata) = split(/=/,$response,2);
2533: if ($outcome eq 'ok') {
2534: $results = &thaw_unescape($userdata);
2535: }
2536: }
2537: }
2538: }
2539: }
2540: return ($outcome,$results);
2541: }
2542:
2543: sub inst_rulecheck {
2544: my ($udom,$uname,$id,$item,$rules) = @_;
2545: my %returnhash;
2546: if ($udom ne '') {
2547: if (ref($rules) eq 'ARRAY') {
2548: @{$rules} = map {&escape($_);} (@{$rules});
2549: my $rulestr = join(':',@{$rules});
2550: my $homeserver=&domain($udom,'primary');
2551: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
2552: my $response;
2553: if ($item eq 'username') {
2554: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2555: ':'.&escape($uname).':'.$rulestr,
2556: $homeserver));
2557: } elsif ($item eq 'id') {
2558: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2559: ':'.&escape($id).':'.$rulestr,
2560: $homeserver));
2561: } elsif ($item eq 'selfcreate') {
2562: $response=&unescape(&reply('instselfcreatecheck:'.
2563: &escape($udom).':'.&escape($uname).
2564: ':'.$rulestr,$homeserver));
2565: }
2566: if ($response ne 'refused') {
2567: my @pairs=split(/\&/,$response);
2568: foreach my $item (@pairs) {
2569: my ($key,$value)=split(/=/,$item,2);
2570: $key = &unescape($key);
2571: next if ($key =~ /^error: 2 /);
2572: $returnhash{$key}=&thaw_unescape($value);
2573: }
2574: }
2575: }
2576: }
2577: }
2578: return %returnhash;
2579: }
2580:
2581: sub inst_userrules {
2582: my ($udom,$check) = @_;
2583: my (%ruleshash,@ruleorder);
2584: if ($udom ne '') {
2585: my $homeserver=&domain($udom,'primary');
2586: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
2587: my $response;
2588: if ($check eq 'id') {
2589: $response=&reply('instidrules:'.&escape($udom),
2590: $homeserver);
2591: } elsif ($check eq 'email') {
2592: $response=&reply('instemailrules:'.&escape($udom),
2593: $homeserver);
2594: } else {
2595: $response=&reply('instuserrules:'.&escape($udom),
2596: $homeserver);
2597: }
2598: if (($response ne 'refused') && ($response ne 'error') &&
2599: ($response ne 'unknown_cmd') &&
2600: ($response ne 'no_such_host')) {
2601: my ($hashitems,$orderitems) = split(/:/,$response);
2602: my @pairs=split(/\&/,$hashitems);
2603: foreach my $item (@pairs) {
2604: my ($key,$value)=split(/=/,$item,2);
2605: $key = &unescape($key);
2606: next if ($key =~ /^error: 2 /);
2607: $ruleshash{$key}=&thaw_unescape($value);
2608: }
2609: my @esc_order = split(/\&/,$orderitems);
2610: foreach my $item (@esc_order) {
2611: push(@ruleorder,&unescape($item));
2612: }
2613: }
2614: }
2615: }
2616: return (\%ruleshash,\@ruleorder);
2617: }
2618:
2619: # ------------- Get Authentication, Language and User Tools Defaults for Domain
2620:
2621: sub get_domain_defaults {
2622: my ($domain,$ignore_cache) = @_;
2623: return if (($domain eq '') || ($domain eq 'public'));
2624: my $cachetime = 60*60*24;
2625: unless ($ignore_cache) {
2626: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2627: if (defined($cached)) {
2628: if (ref($result) eq 'HASH') {
2629: return %{$result};
2630: }
2631: }
2632: }
2633: my %domdefaults;
2634: my %domconfig =
2635: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
2636: 'requestcourses','inststatus',
2637: 'coursedefaults','usersessions',
2638: 'requestauthor','selfenrollment',
2639: 'coursecategories','ssl','autoenroll',
2640: 'trust','helpsettings','wafproxy'],$domain);
2641: my @coursetypes = ('official','unofficial','community','textbook','placement');
2642: if (ref($domconfig{'defaults'}) eq 'HASH') {
2643: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2644: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2645: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
2646: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
2647: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
2648: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
2649: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2650: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2651: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
2652: } else {
2653: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2654: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2655: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2656: }
2657: if (ref($domconfig{'quotas'}) eq 'HASH') {
2658: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2659: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2660: } else {
2661: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
2662: }
2663: my @usertools = ('aboutme','blog','webdav','portfolio');
2664: foreach my $item (@usertools) {
2665: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2666: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2667: }
2668: }
2669: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2670: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2671: }
2672: }
2673: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
2674: foreach my $item ('official','unofficial','community','textbook','placement') {
2675: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2676: }
2677: }
2678: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2679: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2680: }
2681: if (ref($domconfig{'inststatus'}) eq 'HASH') {
2682: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
2683: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2684: }
2685: }
2686: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
2687: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
2688: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2689: $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
2690: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2691: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2692: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2693: }
2694: foreach my $type (@coursetypes) {
2695: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2696: unless ($type eq 'community') {
2697: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2698: }
2699: }
2700: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2701: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2702: }
2703: if ($domdefaults{'postsubmit'} eq 'on') {
2704: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2705: $domdefaults{$type.'postsubtimeout'} =
2706: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2707: }
2708: }
2709: }
2710: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2711: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2712: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2713: if (@clonecodes) {
2714: $domdefaults{'canclone'} = join('+',@clonecodes);
2715: }
2716: }
2717: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2718: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2719: }
2720: if ($domconfig{'coursedefaults'}{'texengine'}) {
2721: $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
2722: }
2723: if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
2724: $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
2725: }
2726: }
2727: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2728: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2729: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2730: }
2731: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2732: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2733: }
2734: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2735: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2736: }
2737: if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
2738: $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
2739: }
2740: }
2741: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2742: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2743: my @settings = ('types','registered','enroll_dates','access_dates','section',
2744: 'approval','limit');
2745: foreach my $type (@coursetypes) {
2746: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2747: my @mgrdc = ();
2748: foreach my $item (@settings) {
2749: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2750: push(@mgrdc,$item);
2751: }
2752: }
2753: if (@mgrdc) {
2754: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2755: }
2756: }
2757: }
2758: }
2759: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2760: foreach my $type (@coursetypes) {
2761: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2762: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2763: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2764: }
2765: }
2766: }
2767: }
2768: }
2769: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2770: $domdefaults{'catauth'} = 'std';
2771: $domdefaults{'catunauth'} = 'std';
2772: if ($domconfig{'coursecategories'}{'auth'}) {
2773: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2774: }
2775: if ($domconfig{'coursecategories'}{'unauth'}) {
2776: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2777: }
2778: }
2779: if (ref($domconfig{'ssl'}) eq 'HASH') {
2780: if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
2781: $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
2782: }
2783: if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
2784: $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
2785: }
2786: if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
2787: $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
2788: }
2789: }
2790: if (ref($domconfig{'trust'}) eq 'HASH') {
2791: my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
2792: foreach my $prefix (@prefixes) {
2793: if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
2794: $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
2795: }
2796: }
2797: }
2798: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2799: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2800: $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
2801: }
2802: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2803: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2804: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2805: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2806: }
2807: }
2808: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
2809: foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
2810: if ($domconfig{'wafproxy'}{$item}) {
2811: $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
2812: }
2813: }
2814: }
2815: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
2816: return %domdefaults;
2817: }
2818:
2819: sub get_dom_cats {
2820: my ($dom) = @_;
2821: return unless (&domain($dom));
2822: my ($cats,$cached)=&is_cached_new('cats',$dom);
2823: unless (defined($cached)) {
2824: my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
2825: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2826: if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
2827: %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
2828: } else {
2829: $cats = {};
2830: }
2831: } else {
2832: $cats = {};
2833: }
2834: &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
2835: }
2836: return $cats;
2837: }
2838:
2839: sub get_dom_instcats {
2840: my ($dom) = @_;
2841: return unless (&domain($dom));
2842: my ($instcats,$cached)=&is_cached_new('instcats',$dom);
2843: unless (defined($cached)) {
2844: my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
2845: my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
2846: if ($totcodes > 0) {
2847: my $caller = 'global';
2848: if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
2849: \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
2850: $instcats = {
2851: codes => \%codes,
2852: codetitles => \@codetitles,
2853: cat_titles => \%cat_titles,
2854: cat_order => \%cat_order,
2855: };
2856: &do_cache_new('instcats',$dom,$instcats,3600);
2857: }
2858: }
2859: }
2860: return $instcats;
2861: }
2862:
2863: sub retrieve_instcodes {
2864: my ($coursecodes,$dom) = @_;
2865: my $totcodes;
2866: my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
2867: foreach my $course (keys(%courses)) {
2868: if (ref($courses{$course}) eq 'HASH') {
2869: if ($courses{$course}{'inst_code'} ne '') {
2870: $$coursecodes{$course} = $courses{$course}{'inst_code'};
2871: $totcodes ++;
2872: }
2873: }
2874: }
2875: return $totcodes;
2876: }
2877:
2878: sub course_portal_url {
2879: my ($cnum,$cdom,$r) = @_;
2880: my $chome = &homeserver($cnum,$cdom);
2881: my $hostname = &hostname($chome);
2882: my $protocol = $protocol{$chome};
2883: $protocol = 'http' if ($protocol ne 'https');
2884: my %domdefaults = &get_domain_defaults($cdom);
2885: my $firsturl;
2886: if ($domdefaults{'portal_def'}) {
2887: $firsturl = $domdefaults{'portal_def'};
2888: } else {
2889: my $alias = &Apache::lonnet::use_proxy_alias($r,$chome);
2890: $hostname = $alias if ($alias ne '');
2891: $firsturl = $protocol.'://'.$hostname;
2892: }
2893: return $firsturl;
2894: }
2895:
2896: # --------------------------------------------- Get domain config for passwords
2897:
2898: sub get_passwdconf {
2899: my ($dom) = @_;
2900: my (%passwdconf,$gotconf,$lookup);
2901: my ($result,$cached)=&is_cached_new('passwdconf',$dom);
2902: if (defined($cached)) {
2903: if (ref($result) eq 'HASH') {
2904: %passwdconf = %{$result};
2905: $gotconf = 1;
2906: }
2907: }
2908: unless ($gotconf) {
2909: my %domconfig = &get_dom('configuration',['passwords'],$dom);
2910: if (ref($domconfig{'passwords'}) eq 'HASH') {
2911: %passwdconf = %{$domconfig{'passwords'}};
2912: }
2913: my $cachetime = 24*60*60;
2914: &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
2915: }
2916: return %passwdconf;
2917: }
2918:
2919: # --------------------------------------------------- Assign a key to a student
2920:
2921: sub assign_access_key {
2922: #
2923: # a valid key looks like uname:udom#comments
2924: # comments are being appended
2925: #
2926: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2927: $kdom=
2928: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
2929: $knum=
2930: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
2931: $cdom=
2932: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2933: $cnum=
2934: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2935: $udom=$env{'user.name'} unless (defined($udom));
2936: $uname=$env{'user.domain'} unless (defined($uname));
2937: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
2938: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
2939: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
2940: # assigned to this person
2941: # - this should not happen,
2942: # unless something went wrong
2943: # the first time around
2944: # ready to assign
2945: $logentry=$1.'; '.$logentry;
2946: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
2947: $kdom,$knum) eq 'ok') {
2948: # key now belongs to user
2949: my $envkey='key.'.$cdom.'_'.$cnum;
2950: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
2951: &appenv({'environment.'.$envkey => $ckey});
2952: return 'ok';
2953: } else {
2954: return
2955: 'error: Count not permanently assign key, will need to be re-entered later.';
2956: }
2957: } else {
2958: return 'error: Could not assign key, try again later.';
2959: }
2960: } elsif (!$existing{$ckey}) {
2961: # the key does not exist
2962: return 'error: The key does not exist';
2963: } else {
2964: # the key is somebody else's
2965: return 'error: The key is already in use';
2966: }
2967: }
2968:
2969: # ------------------------------------------ put an additional comment on a key
2970:
2971: sub comment_access_key {
2972: #
2973: # a valid key looks like uname:udom#comments
2974: # comments are being appended
2975: #
2976: my ($ckey,$cdom,$cnum,$logentry)=@_;
2977: $cdom=
2978: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2979: $cnum=
2980: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2981: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2982: if ($existing{$ckey}) {
2983: $existing{$ckey}.='; '.$logentry;
2984: # ready to assign
2985: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
2986: $cdom,$cnum) eq 'ok') {
2987: return 'ok';
2988: } else {
2989: return 'error: Count not store comment.';
2990: }
2991: } else {
2992: # the key does not exist
2993: return 'error: The key does not exist';
2994: }
2995: }
2996:
2997: # ------------------------------------------------------ Generate a set of keys
2998:
2999: sub generate_access_keys {
3000: my ($number,$cdom,$cnum,$logentry)=@_;
3001: $cdom=
3002: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
3003: $cnum=
3004: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
3005: unless (&allowed('mky',$cdom)) { return 0; }
3006: unless (($cdom) && ($cnum)) { return 0; }
3007: if ($number>10000) { return 0; }
3008: sleep(2); # make sure don't get same seed twice
3009: srand(time()^($$+($$<<15))); # from "Programming Perl"
3010: my $total=0;
3011: for (my $i=1;$i<=$number;$i++) {
3012: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
3013: sprintf("%lx",int(100000*rand)).'-'.
3014: sprintf("%lx",int(100000*rand));
3015: $newkey=~s/1/g/g; # folks mix up 1 and l
3016: $newkey=~s/0/h/g; # and also 0 and O
3017: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
3018: if ($existing{$newkey}) {
3019: $i--;
3020: } else {
3021: if (&put('accesskeys',
3022: { $newkey => '# generated '.localtime().
3023: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
3024: '; '.$logentry },
3025: $cdom,$cnum) eq 'ok') {
3026: $total++;
3027: }
3028: }
3029: }
3030: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
3031: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
3032: return $total;
3033: }
3034:
3035: # ------------------------------------------------------- Validate an accesskey
3036:
3037: sub validate_access_key {
3038: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
3039: $cdom=
3040: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
3041: $cnum=
3042: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
3043: $udom=$env{'user.domain'} unless (defined($udom));
3044: $uname=$env{'user.name'} unless (defined($uname));
3045: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
3046: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
3047: }
3048:
3049: # ------------------------------------- Find the section of student in a course
3050: sub devalidate_getsection_cache {
3051: my ($udom,$unam,$courseid)=@_;
3052: my $hashid="$udom:$unam:$courseid";
3053: &devalidate_cache_new('getsection',$hashid);
3054: }
3055:
3056: sub courseid_to_courseurl {
3057: my ($courseid) = @_;
3058: #already url style courseid
3059: return $courseid if ($courseid =~ m{^/});
3060:
3061: if (exists($env{'course.'.$courseid.'.num'})) {
3062: my $cnum = $env{'course.'.$courseid.'.num'};
3063: my $cdom = $env{'course.'.$courseid.'.domain'};
3064: return "/$cdom/$cnum";
3065: }
3066:
3067: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
3068: if (exists($courseinfo{'num'})) {
3069: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
3070: }
3071:
3072: return undef;
3073: }
3074:
3075: sub getsection {
3076: my ($udom,$unam,$courseid)=@_;
3077: my $cachetime=1800;
3078:
3079: my $hashid="$udom:$unam:$courseid";
3080: my ($result,$cached)=&is_cached_new('getsection',$hashid);
3081: if (defined($cached)) { return $result; }
3082:
3083: my %Pending;
3084: my %Expired;
3085: #
3086: # Each role can either have not started yet (pending), be active,
3087: # or have expired.
3088: #
3089: # If there is an active role, we are done.
3090: #
3091: # If there is more than one role which has not started yet,
3092: # choose the one which will start sooner
3093: # If there is one role which has not started yet, return it.
3094: #
3095: # If there is more than one expired role, choose the one which ended last.
3096: # If there is a role which has expired, return it.
3097: #
3098: $courseid = &courseid_to_courseurl($courseid);
3099: my %roleshash = &dump('roles',$udom,$unam,$courseid);
3100: foreach my $key (keys(%roleshash)) {
3101: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
3102: my $section=$1;
3103: if ($key eq $courseid.'_st') { $section=''; }
3104: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
3105: my $now=time;
3106: if (defined($end) && $end && ($now > $end)) {
3107: $Expired{$end}=$section;
3108: next;
3109: }
3110: if (defined($start) && $start && ($now < $start)) {
3111: $Pending{$start}=$section;
3112: next;
3113: }
3114: return &do_cache_new('getsection',$hashid,$section,$cachetime);
3115: }
3116: #
3117: # Presumedly there will be few matching roles from the above
3118: # loop and the sorting time will be negligible.
3119: if (scalar(keys(%Pending))) {
3120: my ($time) = sort {$a <=> $b} keys(%Pending);
3121: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
3122: }
3123: if (scalar(keys(%Expired))) {
3124: my @sorted = sort {$a <=> $b} keys(%Expired);
3125: my $time = pop(@sorted);
3126: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
3127: }
3128: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
3129: }
3130:
3131: sub save_cache {
3132: &purge_remembered();
3133: #&Apache::loncommon::validate_page();
3134: undef(%env);
3135: undef($env_loaded);
3136: }
3137:
3138: my $to_remember=-1;
3139: my %remembered;
3140: my %accessed;
3141: my $kicks=0;
3142: my $hits=0;
3143: sub make_key {
3144: my ($name,$id) = @_;
3145: if (length($id) > 65
3146: && length(&escape($id)) > 200) {
3147: $id=length($id).':'.&Digest::MD5::md5_hex($id);
3148: }
3149: return &escape($name.':'.$id);
3150: }
3151:
3152: sub devalidate_cache_new {
3153: my ($name,$id,$debug) = @_;
3154: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
3155: my $remembered_id=$name.':'.$id;
3156: $id=&make_key($name,$id);
3157: $memcache->delete($id);
3158: delete($remembered{$remembered_id});
3159: delete($accessed{$remembered_id});
3160: }
3161:
3162: sub is_cached_new {
3163: my ($name,$id,$debug) = @_;
3164: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
3165: if (exists($remembered{$remembered_id})) {
3166: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
3167: $accessed{$remembered_id}=[&gettimeofday()];
3168: $hits++;
3169: return ($remembered{$remembered_id},1);
3170: }
3171: $id=&make_key($name,$id);
3172: my $value = $memcache->get($id);
3173: if (!(defined($value))) {
3174: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
3175: return (undef,undef);
3176: }
3177: if ($value eq '__undef__') {
3178: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
3179: $value=undef;
3180: }
3181: &make_room($remembered_id,$value,$debug);
3182: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
3183: return ($value,1);
3184: }
3185:
3186: sub do_cache_new {
3187: my ($name,$id,$value,$time,$debug) = @_;
3188: my $remembered_id=$name.':'.$id;
3189: $id=&make_key($name,$id);
3190: my $setvalue=$value;
3191: if (!defined($setvalue)) {
3192: $setvalue='__undef__';
3193: }
3194: if (!defined($time) ) {
3195: $time=600;
3196: }
3197: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
3198: my $result = $memcache->set($id,$setvalue,$time);
3199: if (! $result) {
3200: &logthis("caching of id -> $id failed");
3201: $memcache->disconnect_all();
3202: }
3203: # need to make a copy of $value
3204: &make_room($remembered_id,$value,$debug);
3205: return $value;
3206: }
3207:
3208: sub make_room {
3209: my ($remembered_id,$value,$debug)=@_;
3210:
3211: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
3212: : $value;
3213: if ($to_remember<0) { return; }
3214: $accessed{$remembered_id}=[&gettimeofday()];
3215: if (scalar(keys(%remembered)) <= $to_remember) { return; }
3216: my $to_kick;
3217: my $max_time=0;
3218: foreach my $other (keys(%accessed)) {
3219: if (&tv_interval($accessed{$other}) > $max_time) {
3220: $to_kick=$other;
3221: $max_time=&tv_interval($accessed{$other});
3222: }
3223: }
3224: delete($remembered{$to_kick});
3225: delete($accessed{$to_kick});
3226: $kicks++;
3227: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
3228: return;
3229: }
3230:
3231: sub purge_remembered {
3232: #&logthis("Tossing ".scalar(keys(%remembered)));
3233: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
3234: undef(%remembered);
3235: undef(%accessed);
3236: }
3237: # ------------------------------------- Read an entry from a user's environment
3238:
3239: sub userenvironment {
3240: my ($udom,$unam,@what)=@_;
3241: my $items;
3242: foreach my $item (@what) {
3243: $items.=&escape($item).'&';
3244: }
3245: $items=~s/\&$//;
3246: my %returnhash=();
3247: my $uhome = &homeserver($unam,$udom);
3248: unless ($uhome eq 'no_host') {
3249: my @answer=split(/\&/,
3250: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
3251: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
3252: return %returnhash;
3253: }
3254: my $i;
3255: for ($i=0;$i<=$#what;$i++) {
3256: $returnhash{$what[$i]}=&unescape($answer[$i]);
3257: }
3258: }
3259: return %returnhash;
3260: }
3261:
3262: # ---------------------------------------------------------- Get a studentphoto
3263: sub studentphoto {
3264: my ($udom,$unam,$ext) = @_;
3265: my $home=&Apache::lonnet::homeserver($unam,$udom);
3266: if (defined($env{'request.course.id'})) {
3267: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
3268: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
3269: return(&retrievestudentphoto($udom,$unam,$ext));
3270: } else {
3271: my ($result,$perm_reqd)=
3272: &Apache::lonnet::auto_photo_permission($unam,$udom);
3273: if ($result eq 'ok') {
3274: if (!($perm_reqd eq 'yes')) {
3275: return(&retrievestudentphoto($udom,$unam,$ext));
3276: }
3277: }
3278: }
3279: }
3280: } else {
3281: my ($result,$perm_reqd) =
3282: &Apache::lonnet::auto_photo_permission($unam,$udom);
3283: if ($result eq 'ok') {
3284: if (!($perm_reqd eq 'yes')) {
3285: return(&retrievestudentphoto($udom,$unam,$ext));
3286: }
3287: }
3288: }
3289: return '/adm/lonKaputt/lonlogo_broken.gif';
3290: }
3291:
3292: sub retrievestudentphoto {
3293: my ($udom,$unam,$ext,$type) = @_;
3294: my $home=&Apache::lonnet::homeserver($unam,$udom);
3295: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
3296: if ($ret eq 'ok') {
3297: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
3298: if ($type eq 'thumbnail') {
3299: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
3300: }
3301: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
3302: return $tokenurl;
3303: } else {
3304: if ($type eq 'thumbnail') {
3305: return '/adm/lonKaputt/genericstudent_tn.gif';
3306: } else {
3307: return '/adm/lonKaputt/lonlogo_broken.gif';
3308: }
3309: }
3310: }
3311:
3312: # -------------------------------------------------------------------- New chat
3313:
3314: sub chatsend {
3315: my ($newentry,$anon,$group)=@_;
3316: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
3317: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3318: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
3319: &reply('chatsend:'.$cdom.':'.$cnum.':'.
3320: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
3321: &escape($newentry)).':'.$group,$chome);
3322: }
3323:
3324: # ------------------------------------------ Find current version of a resource
3325:
3326: sub getversion {
3327: my $fname=&clutter(shift);
3328: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
3329: return ¤tversion(&filelocation('',$fname));
3330: }
3331:
3332: sub currentversion {
3333: my $fname=shift;
3334: my $author=$fname;
3335: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3336: my ($udom,$uname)=split(/\//,$author);
3337: my $home=&homeserver($uname,$udom);
3338: if ($home eq 'no_host') {
3339: return -1;
3340: }
3341: my $answer=&reply("currentversion:$fname",$home);
3342: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3343: return -1;
3344: }
3345: return $answer;
3346: }
3347:
3348: #
3349: # Return special version number of resource if set by override, empty otherwise
3350: #
3351: sub usedversion {
3352: my $fname=shift;
3353: unless ($fname) { $fname=$env{'request.uri'}; }
3354: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
3355: if ($urlversion) { return $urlversion; }
3356: return '';
3357: }
3358:
3359: # ----------------------------- Subscribe to a resource, return URL if possible
3360:
3361: sub subscribe {
3362: my $fname=shift;
3363: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
3364: $fname=~s/[\n\r]//g;
3365: my $author=$fname;
3366: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3367: my ($udom,$uname)=split(/\//,$author);
3368: my $home=homeserver($uname,$udom);
3369: if ($home eq 'no_host') {
3370: return 'not_found';
3371: }
3372: my $answer=reply("sub:$fname",$home);
3373: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3374: $answer.=' by '.$home;
3375: }
3376: return $answer;
3377: }
3378:
3379: # -------------------------------------------------------------- Replicate file
3380:
3381: sub repcopy {
3382: my $filename=shift;
3383: $filename=~s/\/+/\//g;
3384: my $londocroot = $perlvar{'lonDocRoot'};
3385: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
3386: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
3387: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3388: $filename=~m{^/*(uploaded|editupload)/}) {
3389: return &repcopy_userfile($filename);
3390: }
3391: $filename=~s/[\n\r]//g;
3392: my $transname="$filename.in.transfer";
3393: # FIXME: this should flock
3394: if ((-e $filename) || (-e $transname)) { return 'ok'; }
3395: my $remoteurl=subscribe($filename);
3396: if ($remoteurl =~ /^con_lost by/) {
3397: &logthis("Subscribe returned $remoteurl: $filename");
3398: return 'unavailable';
3399: } elsif ($remoteurl eq 'not_found') {
3400: #&logthis("Subscribe returned not_found: $filename");
3401: return 'not_found';
3402: } elsif ($remoteurl =~ /^rejected by/) {
3403: &logthis("Subscribe returned $remoteurl: $filename");
3404: return 'forbidden';
3405: } elsif ($remoteurl eq 'directory') {
3406: return 'ok';
3407: } else {
3408: my $author=$filename;
3409: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3410: my ($udom,$uname)=split(/\//,$author);
3411: my $home=homeserver($uname,$udom);
3412: unless ($home eq $perlvar{'lonHostID'}) {
3413: my @parts=split(/\//,$filename);
3414: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
3415: if ($path ne "$londocroot/res") {
3416: &logthis("Malconfiguration for replication: $filename");
3417: return 'bad_request';
3418: }
3419: my $count;
3420: for ($count=5;$count<$#parts;$count++) {
3421: $path.="/$parts[$count]";
3422: if ((-e $path)!=1) {
3423: mkdir($path,0777);
3424: }
3425: }
3426: my $request=new HTTP::Request('GET',"$remoteurl");
3427: my $response;
3428: if ($remoteurl =~ m{/raw/}) {
3429: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
3430: } else {
3431: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
3432: }
3433: if ($response->is_error()) {
3434: unlink($transname);
3435: my $message=$response->status_line;
3436: &logthis("<font color=\"blue\">WARNING:"
3437: ." LWP get: $message: $filename</font>");
3438: return 'unavailable';
3439: } else {
3440: if ($remoteurl!~/\.meta$/) {
3441: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
3442: my $mresponse;
3443: if ($remoteurl =~ m{/raw/}) {
3444: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
3445: } else {
3446: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
3447: }
3448: if ($mresponse->is_error()) {
3449: unlink($filename.'.meta');
3450: &logthis(
3451: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
3452: }
3453: }
3454: rename($transname,$filename);
3455: return 'ok';
3456: }
3457: }
3458: }
3459: }
3460:
3461: # ------------------------------------------------- Unsubscribe from a resource
3462:
3463: sub unsubscribe {
3464: my ($fname) = @_;
3465: my $answer;
3466: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
3467: $fname=~s/[\n\r]//g;
3468: my $author=$fname;
3469: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3470: my ($udom,$uname)=split(/\//,$author);
3471: my $home=homeserver($uname,$udom);
3472: if ($home eq 'no_host') {
3473: $answer = 'no_host';
3474: } elsif (grep { $_ eq $home } ¤t_machine_ids()) {
3475: $answer = 'home';
3476: } else {
3477: my $defdom = $perlvar{'lonDefDomain'};
3478: if (&will_trust('content',$defdom,$udom)) {
3479: $answer = reply("unsub:$fname",$home);
3480: } else {
3481: $answer = 'untrusted';
3482: }
3483: }
3484: return $answer;
3485: }
3486:
3487: # ------------------------------------------------ Get server side include body
3488: sub ssi_body {
3489: my ($filelink,%form)=@_;
3490: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3491: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3492: }
3493: my $output='';
3494: my $response;
3495: if ($filelink=~/^https?\:/) {
3496: ($output,$response)=&externalssi($filelink);
3497: } else {
3498: $filelink .= $filelink=~/\?/ ? '&' : '?';
3499: $filelink .= 'inhibitmenu=yes';
3500: ($output,$response)=&ssi($filelink,%form);
3501: }
3502: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
3503: $output=~s/^.*?\<body[^\>]*\>//si;
3504: $output=~s/\<\/body\s*\>.*?$//si;
3505: if (wantarray) {
3506: return ($output, $response);
3507: } else {
3508: return $output;
3509: }
3510: }
3511:
3512: # --------------------------------------------------------- Server Side Include
3513:
3514: sub absolute_url {
3515: my ($host_name,$unalias,$keep_proto) = @_;
3516: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3517: if ($host_name eq '') {
3518: $host_name = $ENV{'SERVER_NAME'};
3519: }
3520: if ($unalias) {
3521: my $alias = &get_proxy_alias();
3522: if ($alias eq $host_name) {
3523: my $lonhost = $perlvar{'lonHostID'};
3524: my $hostname = &hostname($lonhost);
3525: my $lcproto;
3526: if (($keep_proto) || ($hostname eq '')) {
3527: $lcproto = $protocol;
3528: } else {
3529: $lcproto = $protocol{$lonhost};
3530: $lcproto = 'http' if ($lcproto ne 'https');
3531: $lcproto .= '://';
3532: }
3533: unless ($hostname eq '') {
3534: return $lcproto.$hostname;
3535: }
3536: }
3537: }
3538: return $protocol.$host_name;
3539: }
3540:
3541: #
3542: # Server side include.
3543: # Parameters:
3544: # fn Possibly encrypted resource name/id.
3545: # form Hash that describes how the rendering should be done
3546: # and other things.
3547: # Returns:
3548: # Scalar context: The content of the response.
3549: # Array context: 2 element list of the content and the full response object.
3550: #
3551: sub ssi {
3552:
3553: my ($fn,%form)=@_;
3554: my ($host,$request,$response);
3555: $host = &absolute_url('',1);
3556:
3557: $form{'no_update_last_known'}=1;
3558: &Apache::lonenc::check_encrypt(\$fn);
3559: if (%form) {
3560: $request=new HTTP::Request('POST',$host.$fn);
3561: $request->content(join('&',map {
3562: my $name = escape($_);
3563: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3564: ? join("&$name=", map {escape($_) } @{$form{$_}})
3565: : &escape($form{$_}) );
3566: } keys(%form)));
3567: } else {
3568: $request=new HTTP::Request('GET',$host.$fn);
3569: }
3570:
3571: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
3572: my $lonhost = $perlvar{'lonHostID'};
3573: my $islocal;
3574: if (($env{'request.course.id'}) &&
3575: ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
3576: ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
3577: ($form{'grade_symb'} ne '') &&
3578: (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
3579: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
3580: $islocal = 1;
3581: }
3582: $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
3583: '','','',$islocal);
3584:
3585: if (wantarray) {
3586: return ($response->content, $response);
3587: } else {
3588: return $response->content;
3589: }
3590: }
3591:
3592: sub externalssi {
3593: my ($url)=@_;
3594: my $request=new HTTP::Request('GET',$url);
3595: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
3596: if (wantarray) {
3597: return ($response->content, $response);
3598: } else {
3599: return $response->content;
3600: }
3601: }
3602:
3603:
3604: # If the local copy of a replicated resource is outdated, trigger a
3605: # connection from the homeserver to flush the delayed queue. If no update
3606: # happens, remove local copies of outdated resource (and corresponding
3607: # metadata file).
3608:
3609: sub remove_stale_resfile {
3610: my ($url) = @_;
3611: my $removed;
3612: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3613: my $audom = $1;
3614: my $auname = $2;
3615: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
3616: my $homeserver = &homeserver($auname,$audom);
3617: unless (($homeserver eq 'no_host') ||
3618: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3619: my $fname = &filelocation('',$url);
3620: if (-e $fname) {
3621: my $hostname = &hostname($homeserver);
3622: if ($hostname) {
3623: my $protocol = $protocol{$homeserver};
3624: $protocol = 'http' if ($protocol ne 'https');
3625: my $uri = &declutter($url);
3626: my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
3627: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
3628: if ($response->is_success()) {
3629: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3630: my $locmodtime = (stat($fname))[9];
3631: if ($locmodtime < $remmodtime) {
3632: my $stale;
3633: my $answer = &reply('pong',$homeserver);
3634: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3635: sleep(0.2);
3636: $locmodtime = (stat($fname))[9];
3637: if ($locmodtime < $remmodtime) {
3638: my $posstransfer = $fname.'.in.transfer';
3639: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3640: $removed = 1;
3641: } else {
3642: $stale = 1;
3643: }
3644: } else {
3645: $removed = 1;
3646: }
3647: } else {
3648: $stale = 1;
3649: }
3650: if ($stale) {
3651: if (unlink($fname)) {
3652: if ($uri!~/\.meta$/) {
3653: if (-e $fname.'.meta') {
3654: unlink($fname.'.meta');
3655: }
3656: }
3657: my $unsubresult = &unsubscribe($fname);
3658: unless ($unsubresult eq 'ok') {
3659: &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
3660: }
3661: $removed = 1;
3662: }
3663: }
3664: }
3665: }
3666: }
3667: }
3668: }
3669: }
3670: }
3671: return $removed;
3672: }
3673:
3674: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3675:
3676: sub allowuploaded {
3677: my ($srcurl,$url)=@_;
3678: $url=&clutter(&declutter($url));
3679: my $dir=$url;
3680: $dir=~s/\/[^\/]+$//;
3681: my %httpref=();
3682: my $httpurl=&hreflocation('',$url);
3683: $httpref{'httpref.'.$httpurl}=$srcurl;
3684: &Apache::lonnet::appenv(\%httpref);
3685: }
3686:
3687: #
3688: # Determine if the current user should be able to edit a particular resource,
3689: # when viewing in course context.
3690: # (a) When viewing resource used to determine if "Edit" item is included in
3691: # Functions.
3692: # (b) When displaying folder contents in course editor, used to determine if
3693: # "Edit" link will be displayed alongside resource.
3694: #
3695: # input: six args -- filename (decluttered), course number, course domain,
3696: # url, symb (if registered) and group (if this is a group
3697: # item -- e.g., bulletin board, group page etc.).
3698: # output: array of five scalars --
3699: # $cfile -- url for file editing if editable on current server
3700: # $home -- homeserver of resource (i.e., for author if published,
3701: # or course if uploaded.).
3702: # $switchserver -- 1 if server switch will be needed.
3703: # $forceedit -- 1 if icon/link should be to go to edit mode
3704: # $forceview -- 1 if icon/link should be to go to view mode
3705: #
3706:
3707: sub can_edit_resource {
3708: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3709: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3710: #
3711: # For aboutme pages user can only edit his/her own.
3712: #
3713: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
3714: my ($sdom,$sname) = ($1,$2);
3715: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3716: $home = $env{'user.home'};
3717: $cfile = $resurl;
3718: if ($env{'form.forceedit'}) {
3719: $forceview = 1;
3720: } else {
3721: $forceedit = 1;
3722: }
3723: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3724: } else {
3725: return;
3726: }
3727: }
3728:
3729: if ($env{'request.course.id'}) {
3730: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3731: if ($group ne '') {
3732: # if this is a group homepage or group bulletin board, check group privs
3733: my $allowed = 0;
3734: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3735: if ((&allowed('mdg',$env{'request.course.id'}.
3736: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3737: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3738: $allowed = 1;
3739: }
3740: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3741: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3742: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3743: $allowed = 1;
3744: }
3745: }
3746: if ($allowed) {
3747: $home=&homeserver($cnum,$cdom);
3748: if ($env{'form.forceedit'}) {
3749: $forceview = 1;
3750: } else {
3751: $forceedit = 1;
3752: }
3753: $cfile = $resurl;
3754: } else {
3755: return;
3756: }
3757: } else {
3758: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3759: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3760: return;
3761: }
3762: } elsif (!$crsedit) {
3763: #
3764: # No edit allowed where CC has switched to student role.
3765: #
3766: return;
3767: }
3768: }
3769: }
3770:
3771: if ($file ne '') {
3772: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
3773: if (&is_course_upload($file,$cnum,$cdom)) {
3774: $uploaded = 1;
3775: $incourse = 1;
3776: if ($file =~/\.(htm|html|css|js|txt)$/) {
3777: $cfile = &hreflocation('',$file);
3778: if ($env{'form.forceedit'}) {
3779: $forceview = 1;
3780: } else {
3781: $forceedit = 1;
3782: }
3783: }
3784: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3785: $incourse = 1;
3786: if ($env{'form.forceedit'}) {
3787: $forceview = 1;
3788: } else {
3789: $forceedit = 1;
3790: }
3791: $cfile = $resurl;
3792: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3793: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3794: $incourse = 1;
3795: if ($env{'form.forceedit'}) {
3796: $forceview = 1;
3797: } else {
3798: $forceedit = 1;
3799: }
3800: $cfile = $resurl;
3801: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
3802: $incourse = 1;
3803: $cfile = $resurl.'/smpedit';
3804: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
3805: $incourse = 1;
3806: if ($env{'form.forceedit'}) {
3807: $forceview = 1;
3808: } else {
3809: $forceedit = 1;
3810: }
3811: $cfile = $resurl;
3812: } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
3813: my ($map,$id,$res) = &decode_symb($symb);
3814: if ($map =~ /\.page$/) {
3815: $incourse = 1;
3816: if ($env{'form.forceedit'}) {
3817: $forceview = 1;
3818: $cfile = $map;
3819: } else {
3820: $forceedit = 1;
3821: $cfile = '/adm/wrapper'.$resurl;
3822: }
3823: }
3824: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
3825: $incourse = 1;
3826: if ($env{'form.forceedit'}) {
3827: $forceview = 1;
3828: } else {
3829: $forceedit = 1;
3830: }
3831: $cfile = $resurl;
3832: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3833: $incourse = 1;
3834: if ($env{'form.forceedit'}) {
3835: $forceview = 1;
3836: } else {
3837: $forceedit = 1;
3838: }
3839: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
3840: }
3841: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3842: my $template = '/res/lib/templates/simpleproblem.problem';
3843: if (&is_on_map($template)) {
3844: $incourse = 1;
3845: $forceview = 1;
3846: $cfile = $template;
3847: }
3848: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3849: $incourse = 1;
3850: if ($env{'form.forceedit'}) {
3851: $forceview = 1;
3852: } else {
3853: $forceedit = 1;
3854: }
3855: $cfile = $resurl;
3856: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3857: $incourse = 1;
3858: if ($env{'form.forceedit'}) {
3859: $forceview = 1;
3860: } else {
3861: $forceedit = 1;
3862: }
3863: $cfile = $resurl;
3864: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3865: $incourse = 1;
3866: $forceview = 1;
3867: if ($symb) {
3868: my ($map,$id,$res)=&decode_symb($symb);
3869: $env{'request.symb'} = $symb;
3870: $cfile = &clutter($res);
3871: } else {
3872: $cfile = $env{'form.suppurl'};
3873: my $escfile = &unescape($cfile);
3874: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
3875: $cfile = '/adm/wrapper'.$escfile;
3876: } else {
3877: $escfile =~ s{^http://}{};
3878: $cfile = &escape("/adm/wrapper/ext/$escfile");
3879: }
3880: }
3881: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3882: if ($env{'form.forceedit'}) {
3883: $forceview = 1;
3884: } else {
3885: $forceedit = 1;
3886: }
3887: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
3888: }
3889: }
3890: if ($uploaded || $incourse) {
3891: $home=&homeserver($cnum,$cdom);
3892: } elsif ($file !~ m{/$}) {
3893: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3894: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3895: # Check that the user has permission to edit this resource
3896: my $setpriv = 1;
3897: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3898: if (defined($cfudom)) {
3899: $home=&homeserver($cfuname,$cfudom);
3900: $cfile=$file;
3901: }
3902: }
3903: if (($cfile ne '') && (!$incourse || $uploaded) &&
3904: (($home ne '') && ($home ne 'no_host'))) {
3905: my @ids=¤t_machine_ids();
3906: unless (grep(/^\Q$home\E$/,@ids)) {
3907: $switchserver=1;
3908: }
3909: }
3910: }
3911: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3912: }
3913:
3914: sub is_course_upload {
3915: my ($file,$cnum,$cdom) = @_;
3916: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3917: $uploadpath =~ s{^\/}{};
3918: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3919: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3920: return 1;
3921: }
3922: return;
3923: }
3924:
3925: sub in_course {
3926: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3927: if ($hideprivileged) {
3928: my $skipuser;
3929: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3930: my @possdoms = ($cdom);
3931: if ($coursehash{'checkforpriv'}) {
3932: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3933: }
3934: if (&privileged($uname,$udom,\@possdoms)) {
3935: $skipuser = 1;
3936: if ($coursehash{'nothideprivileged'}) {
3937: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3938: my $user;
3939: if ($item =~ /:/) {
3940: $user = $item;
3941: } else {
3942: $user = join(':',split(/[\@]/,$item));
3943: }
3944: if ($user eq $uname.':'.$udom) {
3945: undef($skipuser);
3946: last;
3947: }
3948: }
3949: }
3950: if ($skipuser) {
3951: return 0;
3952: }
3953: }
3954: }
3955: $type ||= 'any';
3956: if (!defined($cdom) || !defined($cnum)) {
3957: my $cid = $env{'request.course.id'};
3958: $cdom = $env{'course.'.$cid.'.domain'};
3959: $cnum = $env{'course.'.$cid.'.num'};
3960: }
3961: my $typesref;
3962: if (($type eq 'any') || ($type eq 'all')) {
3963: $typesref = ['active','previous','future'];
3964: } elsif ($type eq 'previous' || $type eq 'future') {
3965: $typesref = [$type];
3966: }
3967: my %roles = &get_my_roles($uname,$udom,'userroles',
3968: $typesref,undef,[$cdom]);
3969: my ($tmp) = keys(%roles);
3970: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3971: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3972: if (@course_roles > 0) {
3973: return 1;
3974: }
3975: return 0;
3976: }
3977:
3978: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
3979: # input: action, courseID, current domain, intended
3980: # path to file, source of file, instruction to parse file for objects,
3981: # ref to hash for embedded objects,
3982: # ref to hash for codebase of java objects.
3983: # reference to scalar to accommodate mime type determined
3984: # from File::MMagic if $parser = parse.
3985: #
3986: # output: url to file (if action was uploaddoc),
3987: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
3988: #
3989: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3990: # course.
3991: #
3992: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3993: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3994: # course's home server.
3995: #
3996: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3997: # be copied from $source (current location) to
3998: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3999: # and will then be copied to
4000: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
4001: # course's home server.
4002: #
4003: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
4004: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
4005: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
4006: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
4007: # in course's home server.
4008: #
4009:
4010: sub process_coursefile {
4011: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
4012: $mimetype)=@_;
4013: my $fetchresult;
4014: my $home=&homeserver($docuname,$docudom);
4015: if ($action eq 'propagate') {
4016: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
4017: $home);
4018: } else {
4019: my $fpath = '';
4020: my $fname = $file;
4021: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
4022: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
4023: my $filepath = &build_filepath($fpath);
4024: if ($action eq 'copy') {
4025: if ($source eq '') {
4026: $fetchresult = 'no source file';
4027: return $fetchresult;
4028: } else {
4029: my $destination = $filepath.'/'.$fname;
4030: rename($source,$destination);
4031: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
4032: $home);
4033: }
4034: } elsif ($action eq 'uploaddoc') {
4035: open(my $fh,'>',$filepath.'/'.$fname);
4036: print $fh $env{'form.'.$source};
4037: close($fh);
4038: if ($parser eq 'parse') {
4039: my $mm = new File::MMagic;
4040: my $type = $mm->checktype_filename($filepath.'/'.$fname);
4041: if ($type eq 'text/html') {
4042: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
4043: unless ($parse_result eq 'ok') {
4044: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
4045: }
4046: }
4047: if (ref($mimetype)) {
4048: $$mimetype = $type;
4049: }
4050: }
4051: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
4052: $home);
4053: if ($fetchresult eq 'ok') {
4054: return '/uploaded/'.$fpath.'/'.$fname;
4055: } else {
4056: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
4057: ' to host '.$home.': '.$fetchresult);
4058: return '/adm/notfound.html';
4059: }
4060: }
4061: }
4062: unless ( $fetchresult eq 'ok') {
4063: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
4064: ' to host '.$home.': '.$fetchresult);
4065: }
4066: return $fetchresult;
4067: }
4068:
4069: sub build_filepath {
4070: my ($fpath) = @_;
4071: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
4072: unless ($fpath eq '') {
4073: my @parts=split('/',$fpath);
4074: foreach my $part (@parts) {
4075: $filepath.= '/'.$part;
4076: if ((-e $filepath)!=1) {
4077: mkdir($filepath,0777);
4078: }
4079: }
4080: }
4081: return $filepath;
4082: }
4083:
4084: sub store_edited_file {
4085: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
4086: my $file = $primary_url;
4087: $file =~ s#^/uploaded/$docudom/$docuname/##;
4088: my $fpath = '';
4089: my $fname = $file;
4090: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
4091: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
4092: my $filepath = &build_filepath($fpath);
4093: open(my $fh,'>',$filepath.'/'.$fname);
4094: print $fh $content;
4095: close($fh);
4096: my $home=&homeserver($docuname,$docudom);
4097: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
4098: $home);
4099: if ($$fetchresult eq 'ok') {
4100: return '/uploaded/'.$fpath.'/'.$fname;
4101: } else {
4102: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
4103: ' to host '.$home.': '.$$fetchresult);
4104: return '/adm/notfound.html';
4105: }
4106: }
4107:
4108: sub clean_filename {
4109: my ($fname,$args)=@_;
4110: # Replace Windows backslashes by forward slashes
4111: $fname=~s/\\/\//g;
4112: if (!$args->{'keep_path'}) {
4113: # Get rid of everything but the actual filename
4114: $fname=~s/^.*\/([^\/]+)$/$1/;
4115: }
4116: # Replace spaces by underscores
4117: $fname=~s/\s+/\_/g;
4118: # Transliterate non-ascii text to ascii
4119: my $lang = &Apache::lonlocal::current_language();
4120: $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
4121: # Replace all other weird characters by nothing
4122: $fname=~s{[^/\w\.\-]}{}g;
4123: # Replace all .\d. sequences with _\d. so they no longer look like version
4124: # numbers
4125: $fname=~s/\.(\d+)(?=\.)/_$1/g;
4126: # Replace three or more adjacent underscores with one for consistency
4127: # with loncfile::filename_check() so complete url can be extracted by
4128: # lonnet::decode_symb()
4129: $fname=~s/_{3,}/_/g;
4130: return $fname;
4131: }
4132:
4133: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
4134: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
4135: # image with the same aspect ratio as the original, but with dimensions which do
4136: # not exceed $resizewidth and $resizeheight.
4137:
4138: sub resizeImage {
4139: my ($img_path,$resizewidth,$resizeheight) = @_;
4140: my $ima = Image::Magick->new;
4141: my $resized;
4142: if (-e $img_path) {
4143: $ima->Read($img_path);
4144: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
4145: my $width = $ima->Get('width');
4146: my $height = $ima->Get('height');
4147: if ($width > $resizewidth) {
4148: my $factor = $width/$resizewidth;
4149: my $newheight = $height/$factor;
4150: $ima->Scale(width=>$resizewidth,height=>$newheight);
4151: $resized = 1;
4152: }
4153: }
4154: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
4155: my $width = $ima->Get('width');
4156: my $height = $ima->Get('height');
4157: if ($height > $resizeheight) {
4158: my $factor = $height/$resizeheight;
4159: my $newwidth = $width/$factor;
4160: $ima->Scale(width=>$newwidth,height=>$resizeheight);
4161: $resized = 1;
4162: }
4163: }
4164: if ($resized) {
4165: $ima->Write($img_path);
4166: }
4167: }
4168: return;
4169: }
4170:
4171: # --------------- Take an uploaded file and put it into the userfiles directory
4172: # input: $formname - the contents of the file are in $env{"form.$formname"}
4173: # the desired filename is in $env{"form.$formname.filename"}
4174: # $context - possible values: coursedoc, existingfile, overwrite,
4175: # canceloverwrite, scantron or ''.
4176: # if 'coursedoc': upload to the current course
4177: # if 'existingfile': write file to tmp/overwrites directory
4178: # if 'canceloverwrite': delete file written to tmp/overwrites directory
4179: # $context is passed as argument to &finishuserfileupload
4180: # $subdir - directory in userfile to store the file into
4181: # $parser - instruction to parse file for objects ($parser = parse) or
4182: # if context is 'scantron', $parser is hashref of csv column mapping
4183: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
4184: # Section => 4, CODE => 5, FirstQuestion => 9 }).
4185: # $allfiles - reference to hash for embedded objects
4186: # $codebase - reference to hash for codebase of java objects
4187: # $desuname - username for permanent storage of uploaded file
4188: # $dsetudom - domain for permanaent storage of uploaded file
4189: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
4190: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
4191: # $resizewidth - width (pixels) to which to resize uploaded image
4192: # $resizeheight - height (pixels) to which to resize uploaded image
4193: # $mimetype - reference to scalar to accommodate mime type determined
4194: # from File::MMagic.
4195: #
4196: # output: url of file in userspace, or error: <message>
4197: # or /adm/notfound.html if failure to upload occurse
4198:
4199: sub userfileupload {
4200: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
4201: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
4202: if (!defined($subdir)) { $subdir='unknown'; }
4203: my $fname=$env{'form.'.$formname.'.filename'};
4204: $fname=&clean_filename($fname);
4205: # See if there is anything left
4206: unless ($fname) { return 'error: no uploaded file'; }
4207: # If filename now begins with a . prepend unix timestamp _ milliseconds
4208: if ($fname =~ /^\./) {
4209: my ($s,$usec) = &gettimeofday();
4210: while (length($usec) < 6) {
4211: $usec = '0'.$usec;
4212: }
4213: $fname = $s.'_'.substr($usec,0,3).$fname;
4214: }
4215: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
4216: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
4217: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
4218: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
4219: my $now = time;
4220: my $filepath;
4221: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
4222: $filepath = 'tmp/helprequests/'.$now;
4223: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
4224: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
4225: '_'.$env{'user.domain'}.'/pending';
4226: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
4227: my ($docuname,$docudom);
4228: if ($destudom =~ /^$match_domain$/) {
4229: $docudom = $destudom;
4230: } else {
4231: $docudom = $env{'user.domain'};
4232: }
4233: if ($destuname =~ /^$match_username$/) {
4234: $docuname = $destuname;
4235: } else {
4236: $docuname = $env{'user.name'};
4237: }
4238: if (exists($env{'form.group'})) {
4239: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4240: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4241: }
4242: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
4243: if ($context eq 'canceloverwrite') {
4244: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
4245: if (-e $tempfile) {
4246: my @info = stat($tempfile);
4247: if ($info[9] eq $env{'form.timestamp'}) {
4248: unlink($tempfile);
4249: }
4250: }
4251: return;
4252: }
4253: }
4254: # Create the directory if not present
4255: my @parts=split(/\//,$filepath);
4256: my $fullpath = $perlvar{'lonDaemons'};
4257: for (my $i=0;$i<@parts;$i++) {
4258: $fullpath .= '/'.$parts[$i];
4259: if ((-e $fullpath)!=1) {
4260: mkdir($fullpath,0777);
4261: }
4262: }
4263: open(my $fh,'>',$fullpath.'/'.$fname);
4264: print $fh $env{'form.'.$formname};
4265: close($fh);
4266: if ($context eq 'existingfile') {
4267: my @info = stat($fullpath.'/'.$fname);
4268: return ($fullpath.'/'.$fname,$info[9]);
4269: } else {
4270: return $fullpath.'/'.$fname;
4271: }
4272: }
4273: if ($subdir eq 'scantron') {
4274: $fname = 'scantron_orig_'.$fname;
4275: } else {
4276: $fname="$subdir/$fname";
4277: }
4278: if ($context eq 'coursedoc') {
4279: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4280: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4281: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
4282: return &finishuserfileupload($docuname,$docudom,
4283: $formname,$fname,$parser,$allfiles,
4284: $codebase,$thumbwidth,$thumbheight,
4285: $resizewidth,$resizeheight,$context,$mimetype);
4286: } else {
4287: if ($env{'form.folder'}) {
4288: $fname=$env{'form.folder'}.'/'.$fname;
4289: }
4290: return &process_coursefile('uploaddoc',$docuname,$docudom,
4291: $fname,$formname,$parser,
4292: $allfiles,$codebase,$mimetype);
4293: }
4294: } elsif (defined($destuname)) {
4295: my $docuname=$destuname;
4296: my $docudom=$destudom;
4297: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4298: $parser,$allfiles,$codebase,
4299: $thumbwidth,$thumbheight,
4300: $resizewidth,$resizeheight,$context,$mimetype);
4301: } else {
4302: my $docuname=$env{'user.name'};
4303: my $docudom=$env{'user.domain'};
4304: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
4305: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4306: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4307: }
4308: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4309: $parser,$allfiles,$codebase,
4310: $thumbwidth,$thumbheight,
4311: $resizewidth,$resizeheight,$context,$mimetype);
4312: }
4313: }
4314:
4315: sub finishuserfileupload {
4316: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
4317: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
4318: my $path=$docudom.'/'.$docuname.'/';
4319: my $filepath=$perlvar{'lonDocRoot'};
4320:
4321: my ($fnamepath,$file,$fetchthumb);
4322: $file=$fname;
4323: if ($fname=~m|/|) {
4324: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
4325: $path.=$fnamepath.'/';
4326: }
4327: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
4328: my $count;
4329: for ($count=4;$count<=$#parts;$count++) {
4330: $filepath.="/$parts[$count]";
4331: if ((-e $filepath)!=1) {
4332: mkdir($filepath,0777);
4333: }
4334: }
4335:
4336: # Save the file
4337: {
4338: if (!open(FH,'>',$filepath.'/'.$file)) {
4339: &logthis('Failed to create '.$filepath.'/'.$file);
4340: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
4341: return '/adm/notfound.html';
4342: }
4343: if ($context eq 'overwrite') {
4344: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
4345: my $target = $filepath.'/'.$file;
4346: if (-e $source) {
4347: my @info = stat($source);
4348: if ($info[9] eq $env{'form.timestamp'}) {
4349: unless (&File::Copy::move($source,$target)) {
4350: &logthis('Failed to overwrite '.$filepath.'/'.$file);
4351: return "Moving from $source failed";
4352: }
4353: } else {
4354: return "Temporary file: $source had unexpected date/time for last modification";
4355: }
4356: } else {
4357: return "Temporary file: $source missing";
4358: }
4359: } elsif (!print FH ($env{'form.'.$formname})) {
4360: &logthis('Failed to write to '.$filepath.'/'.$file);
4361: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
4362: return '/adm/notfound.html';
4363: }
4364: close(FH);
4365: if ($resizewidth && $resizeheight) {
4366: my $mm = new File::MMagic;
4367: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
4368: if ($mime_type =~ m{^image/}) {
4369: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
4370: }
4371: }
4372: }
4373: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
4374: if (ref($mimetype)) {
4375: if ($$mimetype eq '') {
4376: my $mm = new File::MMagic;
4377: my $type = $mm->checktype_filename($filepath.'/'.$file);
4378: $$mimetype = $type;
4379: }
4380: }
4381: }
4382: if (($context ne 'scantron') && ($parser eq 'parse')) {
4383: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
4384: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
4385: $allfiles,$codebase);
4386: unless ($parse_result eq 'ok') {
4387: &logthis('Failed to parse '.$filepath.$file.
4388: ' for embedded media: '.$parse_result);
4389: }
4390: }
4391: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
4392: my $format = $env{'form.scantron_format'};
4393: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
4394: }
4395: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
4396: my $input = $filepath.'/'.$file;
4397: my $output = $filepath.'/'.'tn-'.$file;
4398: my $thumbsize = $thumbwidth.'x'.$thumbheight;
4399: my @args = ('convert','-sample',$thumbsize,$input,$output);
4400: system({$args[0]} @args);
4401: if (-e $filepath.'/'.'tn-'.$file) {
4402: $fetchthumb = 1;
4403: }
4404: }
4405:
4406: # Notify homeserver to grep it
4407: #
4408: my $docuhome=&homeserver($docuname,$docudom);
4409: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
4410: if ($fetchresult eq 'ok') {
4411: if ($fetchthumb) {
4412: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
4413: if ($thumbresult ne 'ok') {
4414: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
4415: $docuhome.': '.$thumbresult);
4416: }
4417: }
4418: #
4419: # Return the URL to it
4420: return '/uploaded/'.$path.$file;
4421: } else {
4422: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
4423: ': '.$fetchresult);
4424: return '/adm/notfound.html';
4425: }
4426: }
4427:
4428: sub extract_embedded_items {
4429: my ($fullpath,$allfiles,$codebase,$content) = @_;
4430: my @state = ();
4431: my (%lastids,%related,%shockwave,%flashvars);
4432: my %javafiles = (
4433: codebase => '',
4434: code => '',
4435: archive => ''
4436: );
4437: my %mediafiles = (
4438: src => '',
4439: movie => '',
4440: );
4441: my $p;
4442: if ($content) {
4443: $p = HTML::LCParser->new($content);
4444: } else {
4445: $p = HTML::LCParser->new($fullpath);
4446: }
4447: while (my $t=$p->get_token()) {
4448: if ($t->[0] eq 'S') {
4449: my ($tagname, $attr) = ($t->[1],$t->[2]);
4450: push(@state, $tagname);
4451: if (lc($tagname) eq 'allow') {
4452: &add_filetype($allfiles,$attr->{'src'},'src');
4453: }
4454: if (lc($tagname) eq 'img') {
4455: &add_filetype($allfiles,$attr->{'src'},'src');
4456: }
4457: if (lc($tagname) eq 'a') {
4458: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
4459: &add_filetype($allfiles,$attr->{'href'},'href');
4460: }
4461: }
4462: if (lc($tagname) eq 'script') {
4463: my $src;
4464: if ($attr->{'archive'} =~ /\.jar$/i) {
4465: &add_filetype($allfiles,$attr->{'archive'},'archive');
4466: } else {
4467: if ($attr->{'src'} ne '') {
4468: $src = $attr->{'src'};
4469: &add_filetype($allfiles,$src,'src');
4470: }
4471: }
4472: my $text = $p->get_trimmed_text();
4473: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4474: my @swfargs = split(/,/,$1);
4475: foreach my $item (@swfargs) {
4476: $item =~ s/["']//g;
4477: $item =~ s/^\s+//;
4478: $item =~ s/\s+$//;
4479: }
4480: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4481: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4482: push(@{$related{$swfargs[0]}},$swfargs[2]);
4483: } else {
4484: $related{$swfargs[0]} = [$swfargs[2]];
4485: }
4486: }
4487: }
4488: }
4489: if (lc($tagname) eq 'link') {
4490: if (lc($attr->{'rel'}) eq 'stylesheet') {
4491: &add_filetype($allfiles,$attr->{'href'},'href');
4492: }
4493: }
4494: if (lc($tagname) eq 'object' ||
4495: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4496: foreach my $item (keys(%javafiles)) {
4497: $javafiles{$item} = '';
4498: }
4499: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4500: $lastids{lc($tagname)} = $attr->{'id'};
4501: }
4502: }
4503: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4504: my $name = lc($attr->{'name'});
4505: foreach my $item (keys(%javafiles)) {
4506: if ($name eq $item) {
4507: $javafiles{$item} = $attr->{'value'};
4508: last;
4509: }
4510: }
4511: my $pathfrom;
4512: foreach my $item (keys(%mediafiles)) {
4513: if ($name eq $item) {
4514: $pathfrom = $attr->{'value'};
4515: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4516: &add_filetype($allfiles,$pathfrom,$name);
4517: last;
4518: }
4519: }
4520: if ($name eq 'flashvars') {
4521: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4522: }
4523: if ($pathfrom ne '') {
4524: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4525: $pathfrom);
4526: }
4527: }
4528: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4529: foreach my $item (keys(%javafiles)) {
4530: if ($attr->{$item}) {
4531: $javafiles{$item} = $attr->{$item};
4532: last;
4533: }
4534: }
4535: foreach my $item (keys(%mediafiles)) {
4536: if ($attr->{$item}) {
4537: &add_filetype($allfiles,$attr->{$item},$item);
4538: last;
4539: }
4540: }
4541: if (lc($tagname) eq 'embed') {
4542: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4543: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4544: $attr->{'src'});
4545: }
4546: }
4547: }
4548: if (lc($tagname) eq 'iframe') {
4549: my $src = $attr->{'src'} ;
4550: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4551: &add_filetype($allfiles,$src,'src');
4552: } elsif ($src =~ m{^/}) {
4553: if ($env{'request.course.id'}) {
4554: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4555: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4556: my $url = &hreflocation('',$fullpath);
4557: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4558: my $relpath = $1;
4559: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4560: &add_filetype($allfiles,$1,'src');
4561: }
4562: }
4563: }
4564: }
4565: }
4566: if ($t->[4] =~ m{/>$}) {
4567: pop(@state);
4568: }
4569: } elsif ($t->[0] eq 'E') {
4570: my ($tagname) = ($t->[1]);
4571: if ($javafiles{'codebase'} ne '') {
4572: $javafiles{'codebase'} .= '/';
4573: }
4574: if (lc($tagname) eq 'applet' ||
4575: lc($tagname) eq 'object' ||
4576: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4577: ) {
4578: foreach my $item (keys(%javafiles)) {
4579: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4580: my $file=$javafiles{'codebase'}.$javafiles{$item};
4581: &add_filetype($allfiles,$file,$item);
4582: }
4583: }
4584: }
4585: pop @state;
4586: }
4587: }
4588: foreach my $id (sort(keys(%flashvars))) {
4589: if ($shockwave{$id} ne '') {
4590: my @pairs = split(/\&/,$flashvars{$id});
4591: foreach my $pair (@pairs) {
4592: my ($key,$value) = split(/\=/,$pair);
4593: if ($key eq 'thumb') {
4594: &add_filetype($allfiles,$value,$key);
4595: } elsif ($key eq 'content') {
4596: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4597: my ($ext) = ($value =~ /\.([^.]+)$/);
4598: if ($ext ne '') {
4599: &add_filetype($allfiles,$path.$value,$ext);
4600: }
4601: }
4602: }
4603: }
4604: }
4605: return 'ok';
4606: }
4607:
4608: sub add_filetype {
4609: my ($allfiles,$file,$type)=@_;
4610: if (exists($allfiles->{$file})) {
4611: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4612: push(@{$allfiles->{$file}}, &escape($type));
4613: }
4614: } else {
4615: @{$allfiles->{$file}} = (&escape($type));
4616: }
4617: }
4618:
4619: sub embedded_dependency {
4620: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4621: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4622: if (($identifier ne '') &&
4623: (ref($related->{$identifier}) eq 'ARRAY') &&
4624: ($pathfrom ne '')) {
4625: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4626: foreach my $dep (@{$related->{$identifier}}) {
4627: &add_filetype($allfiles,$path.$dep,'object');
4628: }
4629: }
4630: }
4631: return;
4632: }
4633:
4634: sub bubblesheet_converter {
4635: my ($cdom,$fullpath,$config,$format) = @_;
4636: if ((&domain($cdom) ne '') &&
4637: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
4638: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
4639: my (%csvcols,%csvoptions);
4640: if (ref($config->{'fields'}) eq 'HASH') {
4641: %csvcols = %{$config->{'fields'}};
4642: }
4643: if (ref($config->{'options'}) eq 'HASH') {
4644: %csvoptions = %{$config->{'options'}};
4645: }
4646: my %csvbynum = reverse(%csvcols);
4647: my %scantronconf = &get_scantron_config($format,$cdom);
4648: if (keys(%scantronconf)) {
4649: my %bynum = (
4650: $scantronconf{CODEstart} => 'CODEstart',
4651: $scantronconf{IDstart} => 'IDstart',
4652: $scantronconf{PaperID} => 'PaperID',
4653: $scantronconf{FirstName} => 'FirstName',
4654: $scantronconf{LastName} => 'LastName',
4655: $scantronconf{Qstart} => 'Qstart',
4656: );
4657: my @ordered;
4658: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
4659: push(@ordered,$bynum{$item});
4660: }
4661: my %mapstart = (
4662: CODEstart => 'CODE',
4663: IDstart => 'ID',
4664: PaperID => 'PaperID',
4665: FirstName => 'FirstName',
4666: LastName => 'LastName',
4667: Qstart => 'FirstQuestion',
4668: );
4669: my %maplength = (
4670: CODEstart => 'CODElength',
4671: IDstart => 'IDlength',
4672: PaperID => 'PaperIDlength',
4673: FirstName => 'FirstNamelength',
4674: LastName => 'LastNamelength',
4675: );
4676: if (open(my $fh,'<',$fullpath)) {
4677: my $output;
4678: my %lettdig = &letter_to_digits();
4679: my %diglett = reverse(%lettdig);
4680: my $numletts = scalar(keys(%lettdig));
4681: my $num = 0;
4682: while (my $line=<$fh>) {
4683: $num ++;
4684: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
4685: $line =~ s{[\r\n]+$}{};
4686: my %found;
4687: my @values = split(/,/,$line,-1);
4688: my ($qstart,$record);
4689: for (my $i=0; $i<@values; $i++) {
4690: if ((($qstart ne '') && ($i > $qstart)) ||
4691: ($csvbynum{$i} eq 'FirstQuestion')) {
4692: if ($values[$i] eq '') {
4693: $values[$i] = $scantronconf{'Qoff'};
4694: } elsif ($scantronconf{'Qon'} eq 'number') {
4695: if ($values[$i] =~ /^[A-Ja-j]$/) {
4696: $values[$i] = $lettdig{uc($values[$i])};
4697: }
4698: } elsif ($scantronconf{'Qon'} eq 'letter') {
4699: if ($values[$i] =~ /^[0-9]$/) {
4700: $values[$i] = $diglett{$values[$i]};
4701: }
4702: } else {
4703: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4704: my $digit;
4705: if ($values[$i] =~ /^[A-Ja-j]$/) {
4706: $digit = $lettdig{uc($values[$i])}-1;
4707: if ($values[$i] eq 'J') {
4708: $digit += $numletts;
4709: }
4710: } elsif ($values[$i] =~ /^[0-9]$/) {
4711: $digit = $values[$i]-1;
4712: if ($values[$i] eq '0') {
4713: $digit += $numletts;
4714: }
4715: }
4716: my $qval='';
4717: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
4718: if ($j == $digit) {
4719: $qval .= $scantronconf{'Qon'};
4720: } else {
4721: $qval .= $scantronconf{'Qoff'};
4722: }
4723: }
4724: $values[$i] = $qval;
4725: }
4726: }
4727: if (length($values[$i]) > $scantronconf{'Qlength'}) {
4728: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
4729: }
4730: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
4731: if ($numblank > 0) {
4732: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
4733: }
4734: if ($csvbynum{$i} eq 'FirstQuestion') {
4735: $qstart = $i;
4736: $found{$csvbynum{$i}} = $values[$i];
4737: } else {
4738: $found{'FirstQuestion'} .= $values[$i];
4739: }
4740: } elsif (exists($csvbynum{$i})) {
4741: if ($csvoptions{'rem'}) {
4742: $values[$i] =~ s/^\s+//;
4743: }
4744: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
4745: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
4746: $values[$i] = '0'.$values[$i];
4747: }
4748: }
4749: $found{$csvbynum{$i}} = $values[$i];
4750: }
4751: }
4752: foreach my $item (@ordered) {
4753: my $currlength = 1+length($record);
4754: my $numspaces = $scantronconf{$item} - $currlength;
4755: if ($numspaces > 0) {
4756: $record .= (' ' x $numspaces);
4757: }
4758: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
4759: unless ($item eq 'Qstart') {
4760: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
4761: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
4762: }
4763: }
4764: $record .= $found{$mapstart{$item}};
4765: }
4766: }
4767: $output .= "$record\n";
4768: }
4769: close($fh);
4770: if ($output) {
4771: if (open(my $fh,'>',$fullpath)) {
4772: print $fh $output;
4773: close($fh);
4774: }
4775: }
4776: }
4777: }
4778: return;
4779: }
4780: }
4781:
4782: sub letter_to_digits {
4783: my %lettdig = (
4784: A => 1,
4785: B => 2,
4786: C => 3,
4787: D => 4,
4788: E => 5,
4789: F => 6,
4790: G => 7,
4791: H => 8,
4792: I => 9,
4793: J => 0,
4794: );
4795: return %lettdig;
4796: }
4797:
4798: sub get_scantron_config {
4799: my ($which,$cdom) = @_;
4800: my @lines = &get_scantronformat_file($cdom);
4801: my %config;
4802: #FIXME probably should move to XML it has already gotten a bit much now
4803: foreach my $line (@lines) {
4804: my ($name,$descrip)=split(/:/,$line);
4805: if ($name ne $which ) { next; }
4806: chomp($line);
4807: my @config=split(/:/,$line);
4808: $config{'name'}=$config[0];
4809: $config{'description'}=$config[1];
4810: $config{'CODElocation'}=$config[2];
4811: $config{'CODEstart'}=$config[3];
4812: $config{'CODElength'}=$config[4];
4813: $config{'IDstart'}=$config[5];
4814: $config{'IDlength'}=$config[6];
4815: $config{'Qstart'}=$config[7];
4816: $config{'Qlength'}=$config[8];
4817: $config{'Qoff'}=$config[9];
4818: $config{'Qon'}=$config[10];
4819: $config{'PaperID'}=$config[11];
4820: $config{'PaperIDlength'}=$config[12];
4821: $config{'FirstName'}=$config[13];
4822: $config{'FirstNamelength'}=$config[14];
4823: $config{'LastName'}=$config[15];
4824: $config{'LastNamelength'}=$config[16];
4825: $config{'BubblesPerRow'}=$config[17];
4826: last;
4827: }
4828: return %config;
4829: }
4830:
4831: sub get_scantronformat_file {
4832: my ($cdom) = @_;
4833: if ($cdom eq '') {
4834: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4835: }
4836: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4837: my $gottab = 0;
4838: my @lines;
4839: if (ref($domconfig{'scantron'}) eq 'HASH') {
4840: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4841: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4842: if ($formatfile ne '-1') {
4843: @lines = split("\n",$formatfile,-1);
4844: $gottab = 1;
4845: }
4846: }
4847: }
4848: if (!$gottab) {
4849: my $confname = $cdom.'-domainconfig';
4850: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4851: my $formatfile = &getfile($default);
4852: if ($formatfile ne '-1') {
4853: @lines = split("\n",$formatfile,-1);
4854: $gottab = 1;
4855: }
4856: }
4857: if (!$gottab) {
4858: my @domains = ¤t_machine_domains();
4859: if (grep(/^\Q$cdom\E$/,@domains)) {
4860: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
4861: @lines = <$fh>;
4862: close($fh);
4863: }
4864: } else {
4865: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
4866: @lines = <$fh>;
4867: close($fh);
4868: }
4869: }
4870: }
4871: return @lines;
4872: }
4873:
4874: sub removeuploadedurl {
4875: my ($url)=@_;
4876: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
4877: return &removeuserfile($uname,$udom,$fname);
4878: }
4879:
4880: sub removeuserfile {
4881: my ($docuname,$docudom,$fname)=@_;
4882: my $home=&homeserver($docuname,$docudom);
4883: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
4884: if ($result eq 'ok') {
4885: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4886: my $metafile = $fname.'.meta';
4887: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
4888: my $url = "/uploaded/$docudom/$docuname/$fname";
4889: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
4890: my $sqlresult =
4891: &update_portfolio_table($docuname,$docudom,$file,
4892: 'portfolio_metadata',$group,
4893: 'delete');
4894: }
4895: }
4896: return $result;
4897: }
4898:
4899: sub mkdiruserfile {
4900: my ($docuname,$docudom,$dir)=@_;
4901: my $home=&homeserver($docuname,$docudom);
4902: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4903: }
4904:
4905: sub renameuserfile {
4906: my ($docuname,$docudom,$old,$new)=@_;
4907: my $home=&homeserver($docuname,$docudom);
4908: my $result = &reply("renameuserfile:$docudom:$docuname:".
4909: &escape("$old").':'.&escape("$new"),$home);
4910: if ($result eq 'ok') {
4911: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4912: my $oldmeta = $old.'.meta';
4913: my $newmeta = $new.'.meta';
4914: my $metaresult =
4915: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
4916: my $url = "/uploaded/$docudom/$docuname/$old";
4917: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
4918: my $sqlresult =
4919: &update_portfolio_table($docuname,$docudom,$file,
4920: 'portfolio_metadata',$group,
4921: 'delete');
4922: }
4923: }
4924: return $result;
4925: }
4926:
4927: # ------------------------------------------------------------------------- Log
4928:
4929: sub log {
4930: my ($dom,$nam,$hom,$what)=@_;
4931: return critical("log:$dom:$nam:$what",$hom);
4932: }
4933:
4934: # ------------------------------------------------------------------ Course Log
4935: #
4936: # This routine flushes several buffers of non-mission-critical nature
4937: #
4938:
4939: sub flushcourselogs {
4940: &logthis('Flushing log buffers');
4941: #
4942: # course logs
4943: # This is a log of all transactions in a course, which can be used
4944: # for data mining purposes
4945: #
4946: # It also collects the courseid database, which lists last transaction
4947: # times and course titles for all courseids
4948: #
4949: my %courseidbuffer=();
4950: foreach my $crsid (keys(%courselogs)) {
4951: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
4952: &escape($courselogs{$crsid}),
4953: $coursehombuf{$crsid}) eq 'ok') {
4954: delete $courselogs{$crsid};
4955: } else {
4956: &logthis('Failed to flush log buffer for '.$crsid);
4957: if (length($courselogs{$crsid})>40000) {
4958: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
4959: " exceeded maximum size, deleting.</font>");
4960: delete $courselogs{$crsid};
4961: }
4962: }
4963: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
4964: 'description' => $coursedescrbuf{$crsid},
4965: 'inst_code' => $courseinstcodebuf{$crsid},
4966: 'type' => $coursetypebuf{$crsid},
4967: 'owner' => $courseownerbuf{$crsid},
4968: };
4969: }
4970: #
4971: # Write course id database (reverse lookup) to homeserver of courses
4972: # Is used in pickcourse
4973: #
4974: foreach my $crs_home (keys(%courseidbuffer)) {
4975: my $response = &courseidput(&host_domain($crs_home),
4976: $courseidbuffer{$crs_home},
4977: $crs_home,'timeonly');
4978: }
4979: #
4980: # File accesses
4981: # Writes to the dynamic metadata of resources to get hit counts, etc.
4982: #
4983: foreach my $entry (keys(%accesshash)) {
4984: if ($entry =~ /___count$/) {
4985: my ($dom,$name);
4986: ($dom,$name,undef)=
4987: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
4988: if (! defined($dom) || $dom eq '' ||
4989: ! defined($name) || $name eq '') {
4990: my $cid = $env{'request.course.id'};
4991: #
4992: # FIXME 11/29/2021
4993: # Typo in rev. 1.458 (2003/12/09)??
4994: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
4995: #
4996: # While these ramain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
4997: # $dom and $name will always be null, so the &inc() call will default to storing this data
4998: # in a nohist_accesscount.db file for the user rather than the course.
4999: #
5000: # That said there is a lot of noise in the data being stored.
5001: # So counts for prtspool/ and adm/ etc. are recorded.
5002: #
5003: # A review of which items ending '___count' are written to %accesshash should likely be
5004: # made before deciding whether to set these to 'course.' instead of 'request.'
5005: #
5006: # Under the current scheme each user receives a nohist_accesscount.db file listing
5007: # accesses for things which are not published resources, regardless of course, and
5008: # there is not a nohist_accesscount.db file in a course, which might log accesses from
5009: # anyone in the course for things which are not published resources.
5010: #
5011: # For an author, nohist_accesscount.db ends up having records for other items
5012: # mixed up with the legitimate access counts for the author's published resources.
5013: #
5014: $dom = $env{'request.'.$cid.'.domain'};
5015: $name = $env{'request.'.$cid.'.num'};
5016: }
5017: my $value = $accesshash{$entry};
5018: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
5019: my %temphash=($url => $value);
5020: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
5021: if ($result eq 'ok') {
5022: delete $accesshash{$entry};
5023: }
5024: } else {
5025: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
5026: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
5027: my %temphash=($entry => $accesshash{$entry});
5028: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
5029: delete $accesshash{$entry};
5030: }
5031: }
5032: }
5033: #
5034: # Roles
5035: # Reverse lookup of user roles for course faculty/staff and co-authorship
5036: #
5037: foreach my $entry (keys(%userrolehash)) {
5038: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
5039: split(/\:/,$entry);
5040: if (&Apache::lonnet::put('nohist_userroles',
5041: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
5042: $rudom,$runame) eq 'ok') {
5043: delete $userrolehash{$entry};
5044: }
5045: }
5046: #
5047: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
5048: #
5049: my %domrolebuffer = ();
5050: foreach my $entry (keys(%domainrolehash)) {
5051: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
5052: if ($domrolebuffer{$rudom}) {
5053: $domrolebuffer{$rudom}.='&'.&escape($entry).
5054: '='.&escape($domainrolehash{$entry});
5055: } else {
5056: $domrolebuffer{$rudom}.=&escape($entry).
5057: '='.&escape($domainrolehash{$entry});
5058: }
5059: delete $domainrolehash{$entry};
5060: }
5061: foreach my $dom (keys(%domrolebuffer)) {
5062: my %servers;
5063: if (defined(&domain($dom,'primary'))) {
5064: my $primary=&domain($dom,'primary');
5065: my $hostname=&hostname($primary);
5066: $servers{$primary} = $hostname;
5067: } else {
5068: %servers = &get_servers($dom,'library');
5069: }
5070: foreach my $tryserver (keys(%servers)) {
5071: if (&reply('domroleput:'.$dom.':'.
5072: $domrolebuffer{$dom},$tryserver) eq 'ok') {
5073: last;
5074: } else {
5075: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
5076: }
5077: }
5078: }
5079: $dumpcount++;
5080: }
5081:
5082: sub courselog {
5083: my $what=shift;
5084: $what=time.':'.$what;
5085: unless ($env{'request.course.id'}) { return ''; }
5086: $coursedombuf{$env{'request.course.id'}}=
5087: $env{'course.'.$env{'request.course.id'}.'.domain'};
5088: $coursenumbuf{$env{'request.course.id'}}=
5089: $env{'course.'.$env{'request.course.id'}.'.num'};
5090: $coursehombuf{$env{'request.course.id'}}=
5091: $env{'course.'.$env{'request.course.id'}.'.home'};
5092: $coursedescrbuf{$env{'request.course.id'}}=
5093: $env{'course.'.$env{'request.course.id'}.'.description'};
5094: $courseinstcodebuf{$env{'request.course.id'}}=
5095: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
5096: $courseownerbuf{$env{'request.course.id'}}=
5097: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
5098: $coursetypebuf{$env{'request.course.id'}}=
5099: $env{'course.'.$env{'request.course.id'}.'.type'};
5100: if (defined $courselogs{$env{'request.course.id'}}) {
5101: $courselogs{$env{'request.course.id'}}.='&'.$what;
5102: } else {
5103: $courselogs{$env{'request.course.id'}}.=$what;
5104: }
5105: if (length($courselogs{$env{'request.course.id'}})>4048) {
5106: &flushcourselogs();
5107: }
5108: }
5109:
5110: sub courseacclog {
5111: my $fnsymb=shift;
5112: unless ($env{'request.course.id'}) { return ''; }
5113: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
5114: if ($fnsymb=~/$LONCAPA::assess_re/) {
5115: $what.=':POST';
5116: # FIXME: Probably ought to escape things....
5117: foreach my $key (keys(%env)) {
5118: if ($key=~/^form\.(.*)/) {
5119: my $formitem = $1;
5120: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
5121: $what.=':'.$formitem.'='.$env{$key};
5122: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
5123: if ($formitem eq 'proctorpassword') {
5124: $what.=':'.$formitem.'=' . '*' x length($env{$key});
5125: } else {
5126: $what.=':'.$formitem.'='.$env{$key};
5127: }
5128: }
5129: }
5130: }
5131: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
5132: # FIXME: We should not be depending on a form parameter that someone
5133: # editing lonsearchcat.pm might change in the future.
5134: if ($env{'form.phase'} eq 'course_search') {
5135: $what.= ':POST';
5136: # FIXME: Probably ought to escape things....
5137: foreach my $element ('courseexp','crsfulltext','crsrelated',
5138: 'crsdiscuss') {
5139: $what.=':'.$element.'='.$env{'form.'.$element};
5140: }
5141: }
5142: }
5143: &courselog($what);
5144: }
5145:
5146: sub countacc {
5147: my $url=&declutter(shift);
5148: return if (! defined($url) || $url eq '');
5149: unless ($env{'request.course.id'}) { return ''; }
5150: #
5151: # Mark that this url was used in this course
5152: #
5153: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
5154: #
5155: # Increase the access count for this resource in this child process
5156: #
5157: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
5158: $accesshash{$key}++;
5159: }
5160:
5161: sub linklog {
5162: my ($from,$to)=@_;
5163: $from=&declutter($from);
5164: $to=&declutter($to);
5165: $accesshash{$from.'___'.$to.'___comefrom'}=1;
5166: $accesshash{$to.'___'.$from.'___goto'}=1;
5167: }
5168:
5169: sub statslog {
5170: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
5171: if ($users<2) { return; }
5172: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
5173: 'course' => $env{'request.course.id'},
5174: 'sections' => '"all"',
5175: 'num_students' => $users,
5176: 'part' => $part,
5177: 'symb' => $symb,
5178: 'mean_tries' => $av_attempts,
5179: 'deg_of_diff' => $degdiff});
5180: foreach my $key (keys(%dynstore)) {
5181: $accesshash{$key}=$dynstore{$key};
5182: }
5183: }
5184:
5185: sub userrolelog {
5186: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
5187: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
5188: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5189: $userrolehash
5190: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
5191: =$tend.':'.$tstart;
5192: }
5193: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
5194: $userrolehash
5195: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
5196: =$tend.':'.$tstart;
5197: }
5198: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
5199: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5200: $domainrolehash
5201: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
5202: = $tend.':'.$tstart;
5203: }
5204: }
5205:
5206: sub courserolelog {
5207: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
5208: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
5209: my $cdom = $1;
5210: my $cnum = $2;
5211: my $sec = $3;
5212: my $namespace = 'rolelog';
5213: my %storehash = (
5214: role => $trole,
5215: start => $tstart,
5216: end => $tend,
5217: selfenroll => $selfenroll,
5218: context => $context,
5219: );
5220: if ($trole eq 'gr') {
5221: $namespace = 'groupslog';
5222: $storehash{'group'} = $sec;
5223: } else {
5224: $storehash{'section'} = $sec;
5225: }
5226: &write_log('course',$namespace,\%storehash,$delflag,$username,
5227: $domain,$cnum,$cdom);
5228: if (($trole ne 'st') || ($sec ne '')) {
5229: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
5230: }
5231: }
5232: return;
5233: }
5234:
5235: sub domainrolelog {
5236: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5237: if ($area =~ m{^/($match_domain)/$}) {
5238: my $cdom = $1;
5239: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
5240: my $namespace = 'rolelog';
5241: my %storehash = (
5242: role => $trole,
5243: start => $tstart,
5244: end => $tend,
5245: context => $context,
5246: );
5247: &write_log('domain',$namespace,\%storehash,$delflag,$username,
5248: $domain,$domconfiguser,$cdom);
5249: }
5250: return;
5251:
5252: }
5253:
5254: sub coauthorrolelog {
5255: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5256: if ($area =~ m{^/($match_domain)/($match_username)$}) {
5257: my $audom = $1;
5258: my $auname = $2;
5259: my $namespace = 'rolelog';
5260: my %storehash = (
5261: role => $trole,
5262: start => $tstart,
5263: end => $tend,
5264: context => $context,
5265: );
5266: &write_log('author',$namespace,\%storehash,$delflag,$username,
5267: $domain,$auname,$audom);
5268: }
5269: return;
5270: }
5271:
5272: sub get_course_adv_roles {
5273: my ($cid,$codes) = @_;
5274: $cid=$env{'request.course.id'} unless (defined($cid));
5275: my %coursehash=&coursedescription($cid);
5276: my $crstype = &Apache::loncommon::course_type($cid);
5277: my %nothide=();
5278: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
5279: if ($user !~ /:/) {
5280: $nothide{join(':',split(/[\@]/,$user))}=1;
5281: } else {
5282: $nothide{$user}=1;
5283: }
5284: }
5285: my @possdoms = ($coursehash{'domain'});
5286: if ($coursehash{'checkforpriv'}) {
5287: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
5288: }
5289: my %returnhash=();
5290: my %dumphash=
5291: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
5292: my $now=time;
5293: my %privileged;
5294: foreach my $entry (keys(%dumphash)) {
5295: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
5296: if (($tstart) && ($tstart<0)) { next; }
5297: if (($tend) && ($tend<$now)) { next; }
5298: if (($tstart) && ($now<$tstart)) { next; }
5299: my ($role,$username,$domain,$section)=split(/\:/,$entry);
5300: if ($username eq '' || $domain eq '') { next; }
5301: if ((&privileged($username,$domain,\@possdoms)) &&
5302: (!$nothide{$username.':'.$domain})) { next; }
5303: if ($role eq 'cr') { next; }
5304: if ($codes) {
5305: if ($section) { $role .= ':'.$section; }
5306: if ($returnhash{$role}) {
5307: $returnhash{$role}.=','.$username.':'.$domain;
5308: } else {
5309: $returnhash{$role}=$username.':'.$domain;
5310: }
5311: } else {
5312: my $key=&plaintext($role,$crstype);
5313: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
5314: if ($returnhash{$key}) {
5315: $returnhash{$key}.=','.$username.':'.$domain;
5316: } else {
5317: $returnhash{$key}=$username.':'.$domain;
5318: }
5319: }
5320: }
5321: return %returnhash;
5322: }
5323:
5324: sub get_my_roles {
5325: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
5326: unless (defined($uname)) { $uname=$env{'user.name'}; }
5327: unless (defined($udom)) { $udom=$env{'user.domain'}; }
5328: my (%dumphash,%nothide);
5329: if ($context eq 'userroles') {
5330: %dumphash = &dump('roles',$udom,$uname);
5331: } else {
5332: %dumphash = &dump('nohist_userroles',$udom,$uname);
5333: if ($hidepriv) {
5334: my %coursehash=&coursedescription($udom.'_'.$uname);
5335: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
5336: if ($user !~ /:/) {
5337: $nothide{join(':',split(/[\@]/,$user))} = 1;
5338: } else {
5339: $nothide{$user} = 1;
5340: }
5341: }
5342: }
5343: }
5344: my %returnhash=();
5345: my $now=time;
5346: my %privileged;
5347: foreach my $entry (keys(%dumphash)) {
5348: my ($role,$tend,$tstart);
5349: if ($context eq 'userroles') {
5350: next if ($entry =~ /^rolesdef/);
5351: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
5352: } else {
5353: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
5354: }
5355: if (($tstart) && ($tstart<0)) { next; }
5356: my $status = 'active';
5357: if (($tend) && ($tend<=$now)) {
5358: $status = 'previous';
5359: }
5360: if (($tstart) && ($now<$tstart)) {
5361: $status = 'future';
5362: }
5363: if (ref($types) eq 'ARRAY') {
5364: if (!grep(/^\Q$status\E$/,@{$types})) {
5365: next;
5366: }
5367: } else {
5368: if ($status ne 'active') {
5369: next;
5370: }
5371: }
5372: my ($rolecode,$username,$domain,$section,$area);
5373: if ($context eq 'userroles') {
5374: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
5375: (undef,$domain,$username,$section) = split(/\//,$area);
5376: } else {
5377: ($role,$username,$domain,$section) = split(/\:/,$entry);
5378: }
5379: if (ref($roledoms) eq 'ARRAY') {
5380: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
5381: next;
5382: }
5383: }
5384: if (ref($roles) eq 'ARRAY') {
5385: if (!grep(/^\Q$role\E$/,@{$roles})) {
5386: if ($role =~ /^cr\//) {
5387: if (!grep(/^cr$/,@{$roles})) {
5388: next;
5389: }
5390: } elsif ($role =~ /^gr\//) {
5391: if (!grep(/^gr$/,@{$roles})) {
5392: next;
5393: }
5394: } else {
5395: next;
5396: }
5397: }
5398: }
5399: if ($hidepriv) {
5400: my @privroles = ('dc','su');
5401: if ($context eq 'userroles') {
5402: next if (grep(/^\Q$role\E$/,@privroles));
5403: } else {
5404: my $possdoms = [$domain];
5405: if (ref($roledoms) eq 'ARRAY') {
5406: push(@{$possdoms},@{$roledoms});
5407: }
5408: if (&privileged($username,$domain,$possdoms,\@privroles)) {
5409: if (!$nothide{$username.':'.$domain}) {
5410: next;
5411: }
5412: }
5413: }
5414: }
5415: if ($withsec) {
5416: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
5417: $tstart.':'.$tend;
5418: } else {
5419: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
5420: }
5421: }
5422: return %returnhash;
5423: }
5424:
5425: sub get_all_adhocroles {
5426: my ($dom) = @_;
5427: my @roles_by_num = ();
5428: my %domdefaults = &get_domain_defaults($dom);
5429: my (%description,%access_in_dom,%access_info);
5430: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
5431: my $count = 0;
5432: my %domcurrent = %{$domdefaults{'adhocroles'}};
5433: my %ordered;
5434: foreach my $role (sort(keys(%domcurrent))) {
5435: my ($order,$desc,$access_in_dom);
5436: if (ref($domcurrent{$role}) eq 'HASH') {
5437: $order = $domcurrent{$role}{'order'};
5438: $desc = $domcurrent{$role}{'desc'};
5439: $access_in_dom{$role} = $domcurrent{$role}{'access'};
5440: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
5441: }
5442: if ($order eq '') {
5443: $order = $count;
5444: }
5445: $ordered{$order} = $role;
5446: if ($desc ne '') {
5447: $description{$role} = $desc;
5448: } else {
5449: $description{$role}= $role;
5450: }
5451: $count++;
5452: }
5453: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
5454: push(@roles_by_num,$ordered{$item});
5455: }
5456: }
5457: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
5458: }
5459:
5460: sub get_my_adhocroles {
5461: my ($cid,$checkreg) = @_;
5462: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
5463: if ($env{'request.course.id'} eq $cid) {
5464: $cdom = $env{'course.'.$cid.'.domain'};
5465: $cnum = $env{'course.'.$cid.'.num'};
5466: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
5467: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
5468: $cdom = $1;
5469: $cnum = $2;
5470: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
5471: $cdom,$cnum);
5472: }
5473: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
5474: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5475: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
5476: if ($rosterhash{$user} ne '') {
5477: my $type = (split(/:/,$rosterhash{$user}))[5];
5478: return ([],{}) if ($type eq 'auto');
5479: }
5480: }
5481: if (($cdom ne '') && ($cnum ne '')) {
5482: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
5483: my $then=$env{'user.login.time'};
5484: my $update=$env{'user.update.time'};
5485: if (!$update) {
5486: $update = $then;
5487: }
5488: my @liveroles;
5489: foreach my $role ('dh','da') {
5490: if ($env{"user.role.$role./$cdom/"}) {
5491: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
5492: my $limit = $update;
5493: if ($env{'request.role'} eq "$role./$cdom/") {
5494: $limit = $then;
5495: }
5496: my $activerole = 1;
5497: if ($tstart && $tstart>$limit) { $activerole = 0; }
5498: if ($tend && $tend <$limit) { $activerole = 0; }
5499: if ($activerole) {
5500: push(@liveroles,$role);
5501: }
5502: }
5503: }
5504: if (@liveroles) {
5505: if (&homeserver($cnum,$cdom) ne 'no_host') {
5506: my ($accessref,$accessinfo,%access_in_dom);
5507: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5508: if (ref($roles_by_num) eq 'ARRAY') {
5509: if (@{$roles_by_num}) {
5510: my %settings;
5511: if ($env{'request.course.id'} eq $cid) {
5512: foreach my $envkey (keys(%env)) {
5513: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5514: $settings{$1} = $env{$envkey};
5515: }
5516: }
5517: } else {
5518: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5519: }
5520: my %setincrs;
5521: if ($settings{'internal.adhocaccess'}) {
5522: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5523: }
5524: my @statuses;
5525: if ($env{'environment.inststatus'}) {
5526: @statuses = split(/,/,$env{'environment.inststatus'});
5527: }
5528: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5529: if (ref($accessref) eq 'HASH') {
5530: %access_in_dom = %{$accessref};
5531: }
5532: foreach my $role (@{$roles_by_num}) {
5533: my ($curraccess,@okstatus,@personnel);
5534: if ($setincrs{$role}) {
5535: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5536: if ($curraccess eq 'status') {
5537: @okstatus = split(/\&/,$rest);
5538: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5539: @personnel = split(/\&/,$rest);
5540: }
5541: } else {
5542: $curraccess = $access_in_dom{$role};
5543: if (ref($accessinfo) eq 'HASH') {
5544: if ($curraccess eq 'status') {
5545: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5546: @okstatus = @{$accessinfo->{$role}};
5547: }
5548: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5549: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5550: @personnel = @{$accessinfo->{$role}};
5551: }
5552: }
5553: }
5554: }
5555: if ($curraccess eq 'none') {
5556: next;
5557: } elsif ($curraccess eq 'all') {
5558: push(@possroles,$role);
5559: } elsif ($curraccess eq 'dh') {
5560: if (grep(/^dh$/,@liveroles)) {
5561: push(@possroles,$role);
5562: } else {
5563: next;
5564: }
5565: } elsif ($curraccess eq 'da') {
5566: if (grep(/^da$/,@liveroles)) {
5567: push(@possroles,$role);
5568: } else {
5569: next;
5570: }
5571: } elsif ($curraccess eq 'status') {
5572: if (@okstatus) {
5573: if (!@statuses) {
5574: if (grep(/^default$/,@okstatus)) {
5575: push(@possroles,$role);
5576: }
5577: } else {
5578: foreach my $status (@okstatus) {
5579: if (grep(/^\Q$status\E$/,@statuses)) {
5580: push(@possroles,$role);
5581: last;
5582: }
5583: }
5584: }
5585: }
5586: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5587: if (grep(/^\Q$user\E$/,@personnel)) {
5588: if ($curraccess eq 'exc') {
5589: push(@possroles,$role);
5590: }
5591: } elsif ($curraccess eq 'inc') {
5592: push(@possroles,$role);
5593: }
5594: }
5595: }
5596: }
5597: }
5598: }
5599: }
5600: }
5601: }
5602: unless (ref($description) eq 'HASH') {
5603: if (ref($roles_by_num) eq 'ARRAY') {
5604: my %desc;
5605: map { $desc{$_} = $_; } (@{$roles_by_num});
5606: $description = \%desc;
5607: } else {
5608: $description = {};
5609: }
5610: }
5611: return (\@possroles,$description);
5612: }
5613:
5614: # ----------------------------------------------------- Frontpage Announcements
5615: #
5616: #
5617:
5618: sub postannounce {
5619: my ($server,$text)=@_;
5620: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
5621: unless ($text=~/\w/) { $text=''; }
5622: return &reply('setannounce:'.&escape($text),$server);
5623: }
5624:
5625: sub getannounce {
5626:
5627: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
5628: my $announcement='';
5629: while (my $line = <$fh>) { $announcement .= $line; }
5630: close($fh);
5631: if ($announcement=~/\w/) {
5632: return
5633: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
5634: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
5635: } else {
5636: return '';
5637: }
5638: } else {
5639: return '';
5640: }
5641: }
5642:
5643: # ---------------------------------------------------------- Course ID routines
5644: # Deal with domain's nohist_courseid.db files
5645: #
5646:
5647: sub courseidput {
5648: my ($domain,$storehash,$coursehome,$caller) = @_;
5649: return unless (ref($storehash) eq 'HASH');
5650: my $outcome;
5651: if ($caller eq 'timeonly') {
5652: my $cids = '';
5653: foreach my $item (keys(%$storehash)) {
5654: $cids.=&escape($item).'&';
5655: }
5656: $cids=~s/\&$//;
5657: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5658: $coursehome);
5659: } else {
5660: my $items = '';
5661: foreach my $item (keys(%$storehash)) {
5662: $items.= &escape($item).'='.
5663: &freeze_escape($$storehash{$item}).'&';
5664: }
5665: $items=~s/\&$//;
5666: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5667: $coursehome);
5668: }
5669: if ($outcome eq 'unknown_cmd') {
5670: my $what;
5671: foreach my $cid (keys(%$storehash)) {
5672: $what .= &escape($cid).'=';
5673: foreach my $item ('description','inst_code','owner','type') {
5674: $what .= &escape($storehash->{$cid}{$item}).':';
5675: }
5676: $what =~ s/\:$/&/;
5677: }
5678: $what =~ s/\&$//;
5679: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5680: } else {
5681: return $outcome;
5682: }
5683: }
5684:
5685: sub courseiddump {
5686: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
5687: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
5688: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
5689: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
5690: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
5691: my $as_hash = 1;
5692: my %returnhash;
5693: if (!$domfilter) { $domfilter=''; }
5694: my %libserv = &all_library();
5695: foreach my $tryserver (keys(%libserv)) {
5696: if ( ( $hostidflag == 1
5697: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5698: || (!defined($hostidflag)) ) {
5699:
5700: if (($domfilter eq '') ||
5701: (&host_domain($tryserver) eq $domfilter)) {
5702: my $rep;
5703: if (grep { $_ eq $tryserver } current_machine_ids()) {
5704: $rep = LONCAPA::Lond::dump_course_id_handler(
5705: join(":", (&host_domain($tryserver), $sincefilter,
5706: &escape($descfilter), &escape($instcodefilter),
5707: &escape($ownerfilter), &escape($coursefilter),
5708: &escape($typefilter), &escape($regexp_ok),
5709: $as_hash, &escape($selfenrollonly),
5710: &escape($catfilter), $showhidden, $caller,
5711: &escape($cloner), &escape($cc_clone), $cloneonly,
5712: &escape($createdbefore), &escape($createdafter),
5713: &escape($creationcontext),$domcloner,$hasuniquecode,
5714: $reqcrsdom,&escape($reqinstcode))));
5715: } else {
5716: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5717: $sincefilter.':'.&escape($descfilter).':'.
5718: &escape($instcodefilter).':'.&escape($ownerfilter).
5719: ':'.&escape($coursefilter).':'.&escape($typefilter).
5720: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5721: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5722: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5723: &escape($cc_clone).':'.$cloneonly.':'.
5724: &escape($createdbefore).':'.&escape($createdafter).':'.
5725: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5726: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
5727: }
5728:
5729: my @pairs=split(/\&/,$rep);
5730: foreach my $item (@pairs) {
5731: my ($key,$value)=split(/\=/,$item,2);
5732: $key = &unescape($key);
5733: next if ($key =~ /^error: 2 /);
5734: my $result = &thaw_unescape($value);
5735: if (ref($result) eq 'HASH') {
5736: $returnhash{$key}=$result;
5737: } else {
5738: my @responses = split(/:/,$value);
5739: my @items = ('description','inst_code','owner','type');
5740: for (my $i=0; $i<@responses; $i++) {
5741: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
5742: }
5743: }
5744: }
5745: }
5746: }
5747: }
5748: return %returnhash;
5749: }
5750:
5751: sub courselastaccess {
5752: my ($cdom,$cnum,$hostidref) = @_;
5753: my %returnhash;
5754: if ($cdom && $cnum) {
5755: my $chome = &homeserver($cnum,$cdom);
5756: if ($chome ne 'no_host') {
5757: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5758: &extract_lastaccess(\%returnhash,$rep);
5759: }
5760: } else {
5761: if (!$cdom) { $cdom=''; }
5762: my %libserv = &all_library();
5763: foreach my $tryserver (keys(%libserv)) {
5764: if (ref($hostidref) eq 'ARRAY') {
5765: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5766: }
5767: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5768: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5769: &extract_lastaccess(\%returnhash,$rep);
5770: }
5771: }
5772: }
5773: return %returnhash;
5774: }
5775:
5776: sub extract_lastaccess {
5777: my ($returnhash,$rep) = @_;
5778: if (ref($returnhash) eq 'HASH') {
5779: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5780: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5781: $rep eq '') {
5782: my @pairs=split(/\&/,$rep);
5783: foreach my $item (@pairs) {
5784: my ($key,$value)=split(/\=/,$item,2);
5785: $key = &unescape($key);
5786: next if ($key =~ /^error: 2 /);
5787: $returnhash->{$key} = &thaw_unescape($value);
5788: }
5789: }
5790: }
5791: return;
5792: }
5793:
5794: # ---------------------------------------------------------- DC e-mail
5795:
5796: sub dcmailput {
5797: my ($domain,$msgid,$message,$server)=@_;
5798: my $status = &Apache::lonnet::critical(
5799: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5800: &escape($message),$server);
5801: return $status;
5802: }
5803:
5804: sub dcmaildump {
5805: my ($dom,$startdate,$enddate,$senders) = @_;
5806: my %returnhash=();
5807:
5808: if (defined(&domain($dom,'primary'))) {
5809: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5810: &escape($enddate).':';
5811: my @esc_senders=map { &escape($_)} @$senders;
5812: $cmd.=&escape(join('&',@esc_senders));
5813: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
5814: my ($key,$value) = split(/\=/,$line,2);
5815: if (($key) && ($value)) {
5816: $returnhash{&unescape($key)} = &unescape($value);
5817: }
5818: }
5819: }
5820: return %returnhash;
5821: }
5822: # ---------------------------------------------------------- Domain roles
5823:
5824: sub get_domain_roles {
5825: my ($dom,$roles,$startdate,$enddate)=@_;
5826: if ((!defined($startdate)) || ($startdate eq '')) {
5827: $startdate = '.';
5828: }
5829: if ((!defined($enddate)) || ($enddate eq '')) {
5830: $enddate = '.';
5831: }
5832: my $rolelist;
5833: if (ref($roles) eq 'ARRAY') {
5834: $rolelist = join('&',@{$roles});
5835: }
5836: my %personnel = ();
5837:
5838: my %servers = &get_servers($dom,'library');
5839: foreach my $tryserver (keys(%servers)) {
5840: %{$personnel{$tryserver}}=();
5841: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5842: &escape($startdate).':'.
5843: &escape($enddate).':'.
5844: &escape($rolelist), $tryserver))) {
5845: my ($key,$value) = split(/\=/,$line,2);
5846: if (($key) && ($value)) {
5847: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5848: }
5849: }
5850: }
5851: return %personnel;
5852: }
5853:
5854: sub get_active_domroles {
5855: my ($dom,$roles) = @_;
5856: return () unless (ref($roles) eq 'ARRAY');
5857: my $now = time;
5858: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5859: my %domroles;
5860: foreach my $server (keys(%dompersonnel)) {
5861: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5862: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5863: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5864: }
5865: }
5866: return %domroles;
5867: }
5868:
5869: # ----------------------------------------------------------- Interval timing
5870:
5871: {
5872: # Caches needed for speedup of navmaps
5873: # We don't want to cache this for very long at all (5 seconds at most)
5874: #
5875: # The user for whom we cache
5876: my $cachedkey='';
5877: # The cached times for this user
5878: my %cachedtimes=();
5879: # When this was last done
5880: my $cachedtime='';
5881:
5882: sub load_all_first_access {
5883: my ($uname,$udom,$ignorecache)=@_;
5884: if (($cachedkey eq $uname.':'.$udom) &&
5885: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
5886: (!$ignorecache)) {
5887: return;
5888: }
5889: $cachedtime=time;
5890: $cachedkey=$uname.':'.$udom;
5891: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
5892: }
5893:
5894: sub get_first_access {
5895: my ($type,$argsymb,$argmap,$ignorecache)=@_;
5896: my ($symb,$courseid,$udom,$uname)=&whichuser();
5897: if ($argsymb) { $symb=$argsymb; }
5898: my ($map,$id,$res)=&decode_symb($symb);
5899: if ($argmap) { $map = $argmap; }
5900: if ($type eq 'course') {
5901: $res='course';
5902: } elsif ($type eq 'map') {
5903: $res=&symbread($map);
5904: } else {
5905: $res=$symb;
5906: }
5907: &load_all_first_access($uname,$udom,$ignorecache);
5908: return $cachedtimes{"$courseid\0$res"};
5909: }
5910:
5911: sub set_first_access {
5912: my ($type,$interval)=@_;
5913: my ($symb,$courseid,$udom,$uname)=&whichuser();
5914: my ($map,$id,$res)=&decode_symb($symb);
5915: if ($type eq 'course') {
5916: $res='course';
5917: } elsif ($type eq 'map') {
5918: $res=&symbread($map);
5919: } else {
5920: $res=$symb;
5921: }
5922: $cachedkey='';
5923: my $firstaccess=&get_first_access($type,$symb,$map);
5924: if ($firstaccess) {
5925: &logthis("First access time already set ($firstaccess) when attempting ".
5926: "to set new value (type: $type, extent: $res) for $uname:$udom ".
5927: "in $courseid");
5928: return 'already_set';
5929: } else {
5930: my $start = time;
5931: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5932: $udom,$uname);
5933: if ($putres eq 'ok') {
5934: &put('timerinterval',{"$courseid\0$res"=>$interval},
5935: $udom,$uname);
5936: &appenv(
5937: {
5938: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5939: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5940: }
5941: );
5942: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
5943: $cachedtimes{"$courseid\0$res"} = $start;
5944: }
5945: } elsif ($putres ne 'refused') {
5946: &logthis("Result: $putres when attempting to set first access time ".
5947: "(type: $type, extent: $res) for $uname:$udom in $courseid");
5948: }
5949: return $putres;
5950: }
5951: return 'already_set';
5952: }
5953: }
5954:
5955: # --------------------------------------------- Set Expire Date for Spreadsheet
5956:
5957: sub expirespread {
5958: my ($uname,$udom,$stype,$usymb)=@_;
5959: my $cid=$env{'request.course.id'};
5960: if ($cid) {
5961: my $now=time;
5962: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
5963: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5964: $env{'course.'.$cid.'.num'}.
5965: ':nohist_expirationdates:'.
5966: &escape($key).'='.$now,
5967: $env{'course.'.$cid.'.home'})
5968: }
5969: return 'ok';
5970: }
5971:
5972: # ----------------------------------------------------- Devalidate Spreadsheets
5973:
5974: sub devalidate {
5975: my ($symb,$uname,$udom)=@_;
5976: my $cid=$env{'request.course.id'};
5977: if ($cid) {
5978: # delete the stored spreadsheets for
5979: # - the student level sheet of this user in course's homespace
5980: # - the assessment level sheet for this resource
5981: # for this user in user's homespace
5982: # - current conditional state info
5983: my $key=$uname.':'.$udom.':';
5984: my $status=
5985: &del('nohist_calculatedsheets',
5986: [$key.'studentcalc:'],
5987: $env{'course.'.$cid.'.domain'},
5988: $env{'course.'.$cid.'.num'})
5989: .' '.
5990: &del('nohist_calculatedsheets_'.$cid,
5991: [$key.'assesscalc:'.$symb],$udom,$uname);
5992: unless ($status eq 'ok ok') {
5993: &logthis('Could not devalidate spreadsheet '.
5994: $uname.' at '.$udom.' for '.
5995: $symb.': '.$status);
5996: }
5997: &delenv('user.state.'.$cid);
5998: }
5999: }
6000:
6001: sub get_scalar {
6002: my ($string,$end) = @_;
6003: my $value;
6004: if ($$string =~ s/^([^&]*?)($end)/$2/) {
6005: $value = $1;
6006: } elsif ($$string =~ s/^([^&]*?)&//) {
6007: $value = $1;
6008: }
6009: return &unescape($value);
6010: }
6011:
6012: sub array2str {
6013: my (@array) = @_;
6014: my $result=&arrayref2str(\@array);
6015: $result=~s/^__ARRAY_REF__//;
6016: $result=~s/__END_ARRAY_REF__$//;
6017: return $result;
6018: }
6019:
6020: sub arrayref2str {
6021: my ($arrayref) = @_;
6022: my $result='__ARRAY_REF__';
6023: foreach my $elem (@$arrayref) {
6024: if(ref($elem) eq 'ARRAY') {
6025: $result.=&arrayref2str($elem).'&';
6026: } elsif(ref($elem) eq 'HASH') {
6027: $result.=&hashref2str($elem).'&';
6028: } elsif(ref($elem)) {
6029: #print("Got a ref of ".(ref($elem))." skipping.");
6030: } else {
6031: $result.=&escape($elem).'&';
6032: }
6033: }
6034: $result=~s/\&$//;
6035: $result .= '__END_ARRAY_REF__';
6036: return $result;
6037: }
6038:
6039: sub hash2str {
6040: my (%hash) = @_;
6041: my $result=&hashref2str(\%hash);
6042: $result=~s/^__HASH_REF__//;
6043: $result=~s/__END_HASH_REF__$//;
6044: return $result;
6045: }
6046:
6047: sub hashref2str {
6048: my ($hashref)=@_;
6049: my $result='__HASH_REF__';
6050: foreach my $key (sort(keys(%$hashref))) {
6051: if (ref($key) eq 'ARRAY') {
6052: $result.=&arrayref2str($key).'=';
6053: } elsif (ref($key) eq 'HASH') {
6054: $result.=&hashref2str($key).'=';
6055: } elsif (ref($key)) {
6056: $result.='=';
6057: #print("Got a ref of ".(ref($key))." skipping.");
6058: } else {
6059: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
6060: }
6061:
6062: if(ref($hashref->{$key}) eq 'ARRAY') {
6063: $result.=&arrayref2str($hashref->{$key}).'&';
6064: } elsif(ref($hashref->{$key}) eq 'HASH') {
6065: $result.=&hashref2str($hashref->{$key}).'&';
6066: } elsif(ref($hashref->{$key})) {
6067: $result.='&';
6068: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
6069: } else {
6070: $result.=&escape($hashref->{$key}).'&';
6071: }
6072: }
6073: $result=~s/\&$//;
6074: $result .= '__END_HASH_REF__';
6075: return $result;
6076: }
6077:
6078: sub str2hash {
6079: my ($string)=@_;
6080: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
6081: return %$hash;
6082: }
6083:
6084: sub str2hashref {
6085: my ($string) = @_;
6086:
6087: my %hash;
6088:
6089: if($string !~ /^__HASH_REF__/) {
6090: if (! ($string eq '' || !defined($string))) {
6091: $hash{'error'}='Not hash reference';
6092: }
6093: return (\%hash, $string);
6094: }
6095:
6096: $string =~ s/^__HASH_REF__//;
6097:
6098: while($string !~ /^__END_HASH_REF__/) {
6099: #key
6100: my $key='';
6101: if($string =~ /^__HASH_REF__/) {
6102: ($key, $string)=&str2hashref($string);
6103: if(defined($key->{'error'})) {
6104: $hash{'error'}='Bad data';
6105: return (\%hash, $string);
6106: }
6107: } elsif($string =~ /^__ARRAY_REF__/) {
6108: ($key, $string)=&str2arrayref($string);
6109: if($key->[0] eq 'Array reference error') {
6110: $hash{'error'}='Bad data';
6111: return (\%hash, $string);
6112: }
6113: } else {
6114: $string =~ s/^(.*?)=//;
6115: $key=&unescape($1);
6116: }
6117: $string =~ s/^=//;
6118:
6119: #value
6120: my $value='';
6121: if($string =~ /^__HASH_REF__/) {
6122: ($value, $string)=&str2hashref($string);
6123: if(defined($value->{'error'})) {
6124: $hash{'error'}='Bad data';
6125: return (\%hash, $string);
6126: }
6127: } elsif($string =~ /^__ARRAY_REF__/) {
6128: ($value, $string)=&str2arrayref($string);
6129: if($value->[0] eq 'Array reference error') {
6130: $hash{'error'}='Bad data';
6131: return (\%hash, $string);
6132: }
6133: } else {
6134: $value=&get_scalar(\$string,'__END_HASH_REF__');
6135: }
6136: $string =~ s/^&//;
6137:
6138: $hash{$key}=$value;
6139: }
6140:
6141: $string =~ s/^__END_HASH_REF__//;
6142:
6143: return (\%hash, $string);
6144: }
6145:
6146: sub str2array {
6147: my ($string)=@_;
6148: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
6149: return @$array;
6150: }
6151:
6152: sub str2arrayref {
6153: my ($string) = @_;
6154: my @array;
6155:
6156: if($string !~ /^__ARRAY_REF__/) {
6157: if (! ($string eq '' || !defined($string))) {
6158: $array[0]='Array reference error';
6159: }
6160: return (\@array, $string);
6161: }
6162:
6163: $string =~ s/^__ARRAY_REF__//;
6164:
6165: while($string !~ /^__END_ARRAY_REF__/) {
6166: my $value='';
6167: if($string =~ /^__HASH_REF__/) {
6168: ($value, $string)=&str2hashref($string);
6169: if(defined($value->{'error'})) {
6170: $array[0] ='Array reference error';
6171: return (\@array, $string);
6172: }
6173: } elsif($string =~ /^__ARRAY_REF__/) {
6174: ($value, $string)=&str2arrayref($string);
6175: if($value->[0] eq 'Array reference error') {
6176: $array[0] ='Array reference error';
6177: return (\@array, $string);
6178: }
6179: } else {
6180: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
6181: }
6182: $string =~ s/^&//;
6183:
6184: push(@array, $value);
6185: }
6186:
6187: $string =~ s/^__END_ARRAY_REF__//;
6188:
6189: return (\@array, $string);
6190: }
6191:
6192: # -------------------------------------------------------------------Temp Store
6193:
6194: sub tmpreset {
6195: my ($symb,$namespace,$domain,$stuname) = @_;
6196: if (!$symb) {
6197: $symb=&symbread();
6198: if (!$symb) { $symb= $env{'request.url'}; }
6199: }
6200: $symb=escape($symb);
6201:
6202: if (!$namespace) { $namespace=$env{'request.state'}; }
6203: $namespace=~s/\//\_/g;
6204: $namespace=~s/\W//g;
6205:
6206: if (!$domain) { $domain=$env{'user.domain'}; }
6207: if (!$stuname) { $stuname=$env{'user.name'}; }
6208: if ($domain eq 'public' && $stuname eq 'public') {
6209: $stuname=&get_requestor_ip();
6210: }
6211: my $path=LONCAPA::tempdir();
6212: my %hash;
6213: if (tie(%hash,'GDBM_File',
6214: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
6215: &GDBM_WRCREAT(),0640)) {
6216: foreach my $key (keys(%hash)) {
6217: if ($key=~ /:$symb/) {
6218: delete($hash{$key});
6219: }
6220: }
6221: }
6222: }
6223:
6224: sub tmpstore {
6225: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
6226:
6227: if (!$symb) {
6228: $symb=&symbread();
6229: if (!$symb) { $symb= $env{'request.url'}; }
6230: }
6231: $symb=escape($symb);
6232:
6233: if (!$namespace) {
6234: # I don't think we would ever want to store this for a course.
6235: # it seems this will only be used if we don't have a course.
6236: #$namespace=$env{'request.course.id'};
6237: #if (!$namespace) {
6238: $namespace=$env{'request.state'};
6239: #}
6240: }
6241: $namespace=~s/\//\_/g;
6242: $namespace=~s/\W//g;
6243: if (!$domain) { $domain=$env{'user.domain'}; }
6244: if (!$stuname) { $stuname=$env{'user.name'}; }
6245: if ($domain eq 'public' && $stuname eq 'public') {
6246: $stuname=&get_requestor_ip();
6247: }
6248: my $now=time;
6249: my %hash;
6250: my $path=LONCAPA::tempdir();
6251: if (tie(%hash,'GDBM_File',
6252: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
6253: &GDBM_WRCREAT(),0640)) {
6254: $hash{"version:$symb"}++;
6255: my $version=$hash{"version:$symb"};
6256: my $allkeys='';
6257: foreach my $key (keys(%$storehash)) {
6258: $allkeys.=$key.':';
6259: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
6260: }
6261: $hash{"$version:$symb:timestamp"}=$now;
6262: $allkeys.='timestamp';
6263: $hash{"$version:keys:$symb"}=$allkeys;
6264: if (untie(%hash)) {
6265: return 'ok';
6266: } else {
6267: return "error:$!";
6268: }
6269: } else {
6270: return "error:$!";
6271: }
6272: }
6273:
6274: # -----------------------------------------------------------------Temp Restore
6275:
6276: sub tmprestore {
6277: my ($symb,$namespace,$domain,$stuname) = @_;
6278:
6279: if (!$symb) {
6280: $symb=&symbread();
6281: if (!$symb) { $symb= $env{'request.url'}; }
6282: }
6283: $symb=escape($symb);
6284:
6285: if (!$namespace) { $namespace=$env{'request.state'}; }
6286:
6287: if (!$domain) { $domain=$env{'user.domain'}; }
6288: if (!$stuname) { $stuname=$env{'user.name'}; }
6289: if ($domain eq 'public' && $stuname eq 'public') {
6290: $stuname=&get_requestor_ip();
6291: }
6292: my %returnhash;
6293: $namespace=~s/\//\_/g;
6294: $namespace=~s/\W//g;
6295: my %hash;
6296: my $path=LONCAPA::tempdir();
6297: if (tie(%hash,'GDBM_File',
6298: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
6299: &GDBM_READER(),0640)) {
6300: my $version=$hash{"version:$symb"};
6301: $returnhash{'version'}=$version;
6302: my $scope;
6303: for ($scope=1;$scope<=$version;$scope++) {
6304: my $vkeys=$hash{"$scope:keys:$symb"};
6305: my @keys=split(/:/,$vkeys);
6306: my $key;
6307: $returnhash{"$scope:keys"}=$vkeys;
6308: foreach $key (@keys) {
6309: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
6310: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
6311: }
6312: }
6313: if (!(untie(%hash))) {
6314: return "error:$!";
6315: }
6316: } else {
6317: return "error:$!";
6318: }
6319: return %returnhash;
6320: }
6321:
6322: # ----------------------------------------------------------------------- Store
6323:
6324: sub store {
6325: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
6326: my $home='';
6327:
6328: if ($stuname) { $home=&homeserver($stuname,$domain); }
6329:
6330: $symb=&symbclean($symb);
6331: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
6332:
6333: if (!$domain) { $domain=$env{'user.domain'}; }
6334: if (!$stuname) { $stuname=$env{'user.name'}; }
6335:
6336: &devalidate($symb,$stuname,$domain);
6337:
6338: $symb=escape($symb);
6339: if (!$namespace) {
6340: unless ($namespace=$env{'request.course.id'}) {
6341: return '';
6342: }
6343: }
6344: if (!$home) { $home=$env{'user.home'}; }
6345:
6346: $$storehash{'ip'}=&get_requestor_ip();
6347: $$storehash{'host'}=$perlvar{'lonHostID'};
6348:
6349: my $namevalue='';
6350: foreach my $key (keys(%$storehash)) {
6351: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6352: }
6353: $namevalue=~s/\&$//;
6354: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
6355: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
6356: }
6357:
6358: # -------------------------------------------------------------- Critical Store
6359:
6360: sub cstore {
6361: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
6362: my $home='';
6363:
6364: if ($stuname) { $home=&homeserver($stuname,$domain); }
6365:
6366: $symb=&symbclean($symb);
6367: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
6368:
6369: if (!$domain) { $domain=$env{'user.domain'}; }
6370: if (!$stuname) { $stuname=$env{'user.name'}; }
6371:
6372: &devalidate($symb,$stuname,$domain);
6373:
6374: $symb=escape($symb);
6375: if (!$namespace) {
6376: unless ($namespace=$env{'request.course.id'}) {
6377: return '';
6378: }
6379: }
6380: if (!$home) { $home=$env{'user.home'}; }
6381:
6382: $$storehash{'ip'}=&get_requestor_ip();
6383: $$storehash{'host'}=$perlvar{'lonHostID'};
6384:
6385: my $namevalue='';
6386: foreach my $key (keys(%$storehash)) {
6387: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6388: }
6389: $namevalue=~s/\&$//;
6390: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
6391: return critical
6392: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
6393: }
6394:
6395: # --------------------------------------------------------------------- Restore
6396:
6397: sub restore {
6398: my ($symb,$namespace,$domain,$stuname) = @_;
6399: my $home='';
6400:
6401: if ($stuname) { $home=&homeserver($stuname,$domain); }
6402:
6403: if (!$symb) {
6404: return if ($namespace eq 'courserequests');
6405: unless ($symb=escape(&symbread())) { return ''; }
6406: } else {
6407: unless ($namespace eq 'courserequests') {
6408: $symb=&escape(&symbclean($symb));
6409: }
6410: }
6411: if (!$namespace) {
6412: unless ($namespace=$env{'request.course.id'}) {
6413: return '';
6414: }
6415: }
6416: if (!$domain) { $domain=$env{'user.domain'}; }
6417: if (!$stuname) { $stuname=$env{'user.name'}; }
6418: if (!$home) { $home=$env{'user.home'}; }
6419: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6420:
6421: my %returnhash=();
6422: foreach my $line (split(/\&/,$answer)) {
6423: my ($name,$value)=split(/\=/,$line);
6424: $returnhash{&unescape($name)}=&thaw_unescape($value);
6425: }
6426: my $version;
6427: for ($version=1;$version<=$returnhash{'version'};$version++) {
6428: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6429: $returnhash{$item}=$returnhash{$version.':'.$item};
6430: }
6431: }
6432: return %returnhash;
6433: }
6434:
6435: # ---------------------------------------------------------- Course Description
6436: #
6437: #
6438:
6439: sub coursedescription {
6440: my ($courseid,$args)=@_;
6441: $courseid=~s/^\///;
6442: $courseid=~s/\_/\//g;
6443: my ($cdomain,$cnum)=split(/\//,$courseid);
6444: my $chome=&homeserver($cnum,$cdomain);
6445: my $normalid=$cdomain.'_'.$cnum;
6446: # need to always cache even if we get errors otherwise we keep
6447: # trying and trying and trying to get the course description.
6448: my %envhash=();
6449: my %returnhash=();
6450:
6451: my $expiretime=600;
6452: if ($env{'request.course.id'} eq $normalid) {
6453: $expiretime=120;
6454: }
6455:
6456: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6457: if (!$args->{'freshen_cache'}
6458: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6459: foreach my $key (keys(%env)) {
6460: next if ($key !~ /^\Q$prefix\E(.*)/);
6461: my ($setting) = $1;
6462: $returnhash{$setting} = $env{$key};
6463: }
6464: return %returnhash;
6465: }
6466:
6467: # get the data again
6468:
6469: if (!$args->{'one_time'}) {
6470: $envhash{'course.'.$normalid.'.last_cache'}=time;
6471: }
6472:
6473: if ($chome ne 'no_host') {
6474: %returnhash=&dump('environment',$cdomain,$cnum);
6475: if (!exists($returnhash{'con_lost'})) {
6476: my $username = $env{'user.name'}; # Defult username
6477: if(defined $args->{'user'}) {
6478: $username = $args->{'user'};
6479: }
6480: $returnhash{'home'}= $chome;
6481: $returnhash{'domain'} = $cdomain;
6482: $returnhash{'num'} = $cnum;
6483: if (!defined($returnhash{'type'})) {
6484: $returnhash{'type'} = 'Course';
6485: }
6486: while (my ($name,$value) = each %returnhash) {
6487: $envhash{'course.'.$normalid.'.'.$name}=$value;
6488: }
6489: $returnhash{'url'}=&clutter($returnhash{'url'});
6490: $returnhash{'fn'}=LONCAPA::tempdir() .
6491: $username.'_'.$cdomain.'_'.$cnum;
6492: $envhash{'course.'.$normalid.'.home'}=$chome;
6493: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6494: $envhash{'course.'.$normalid.'.num'}=$cnum;
6495: }
6496: }
6497: if (!$args->{'one_time'}) {
6498: &appenv(\%envhash);
6499: }
6500: return %returnhash;
6501: }
6502:
6503: sub update_released_required {
6504: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6505: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6506: $cid = $env{'request.course.id'};
6507: $cdom = $env{'course.'.$cid.'.domain'};
6508: $cnum = $env{'course.'.$cid.'.num'};
6509: $chome = $env{'course.'.$cid.'.home'};
6510: }
6511: if ($needsrelease) {
6512: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6513: my $needsupdate;
6514: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6515: $needsupdate = 1;
6516: } else {
6517: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6518: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6519: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6520: $needsupdate = 1;
6521: }
6522: }
6523: if ($needsupdate) {
6524: my %needshash = (
6525: 'internal.releaserequired' => $needsrelease,
6526: );
6527: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6528: if ($putresult eq 'ok') {
6529: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6530: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6531: if (ref($crsinfo{$cid}) eq 'HASH') {
6532: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6533: &courseidput($cdom,\%crsinfo,$chome,'notime');
6534: }
6535: }
6536: }
6537: }
6538: return;
6539: }
6540:
6541: # -------------------------------------------------See if a user is privileged
6542:
6543: sub privileged {
6544: my ($username,$domain,$possdomains,$possroles)=@_;
6545: my $now = time;
6546: my $roles;
6547: if (ref($possroles) eq 'ARRAY') {
6548: $roles = $possroles;
6549: } else {
6550: $roles = ['dc','su'];
6551: }
6552: if (ref($possdomains) eq 'ARRAY') {
6553: my %privileged = &privileged_by_domain($possdomains,$roles);
6554: foreach my $dom (@{$possdomains}) {
6555: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6556: (ref($privileged{$dom}) eq 'HASH')) {
6557: foreach my $role (@{$roles}) {
6558: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6559: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6560: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6561: return 1 unless (($end && $end < $now) ||
6562: ($start && $start > $now));
6563: }
6564: }
6565: }
6566: }
6567: }
6568: } else {
6569: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6570: my $now = time;
6571:
6572: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
6573: my ($trole, $tend, $tstart) = split(/_/, $role);
6574: if (grep(/^\Q$trole\E$/,@{$roles})) {
6575: return 1 unless ($tend && $tend < $now)
6576: or ($tstart && $tstart > $now);
6577: }
6578: }
6579: }
6580: return 0;
6581: }
6582:
6583: sub privileged_by_domain {
6584: my ($domains,$roles) = @_;
6585: my %privileged = ();
6586: my $cachetime = 60*60*24;
6587: my $now = time;
6588: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6589: return %privileged;
6590: }
6591: foreach my $dom (@{$domains}) {
6592: next if (ref($privileged{$dom}) eq 'HASH');
6593: my $needroles;
6594: foreach my $role (@{$roles}) {
6595: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6596: if (defined($cached)) {
6597: if (ref($result) eq 'HASH') {
6598: $privileged{$dom}{$role} = $result;
6599: }
6600: } else {
6601: $needroles = 1;
6602: }
6603: }
6604: if ($needroles) {
6605: my %dompersonnel = &get_domain_roles($dom,$roles);
6606: $privileged{$dom} = {};
6607: foreach my $server (keys(%dompersonnel)) {
6608: if (ref($dompersonnel{$server}) eq 'HASH') {
6609: foreach my $item (keys(%{$dompersonnel{$server}})) {
6610: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6611: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6612: next if ($end && $end < $now);
6613: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6614: $dompersonnel{$server}{$item};
6615: }
6616: }
6617: }
6618: if (ref($privileged{$dom}) eq 'HASH') {
6619: foreach my $role (@{$roles}) {
6620: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6621: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6622: } else {
6623: my %hash = ();
6624: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6625: }
6626: }
6627: }
6628: }
6629: }
6630: return %privileged;
6631: }
6632:
6633: # -------------------------------------------------------- Get user privileges
6634:
6635: sub rolesinit {
6636: my ($domain, $username) = @_;
6637: my %userroles = ('user.login.time' => time);
6638: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6639:
6640: # firstaccess and timerinterval are related to timed maps/resources.
6641: # also, blocking can be triggered by an activating timer
6642: # it's saved in the user's %env.
6643: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6644: my %timerinterval = &dump('timerinterval', $domain, $username);
6645: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
6646: %timerintchk, %timerintenv);
6647:
6648: foreach my $key (keys(%firstaccess)) {
6649: my ($cid, $rest) = split(/\0/, $key);
6650: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6651: }
6652:
6653: foreach my $key (keys(%timerinterval)) {
6654: my ($cid,$rest) = split(/\0/,$key);
6655: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6656: }
6657:
6658: my %allroles=();
6659: my %allgroups=();
6660:
6661: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
6662: my $role = $rolesdump{$area};
6663: $area =~ s/\_\w\w$//;
6664:
6665: my ($trole, $tend, $tstart, $group_privs);
6666:
6667: if ($role =~ /^cr/) {
6668: # Custom role, defined by a user
6669: # e.g., user.role.cr/msu/smith/mynewrole
6670: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6671: $trole = $1;
6672: ($tend, $tstart) = split('_', $2);
6673: } else {
6674: $trole = $role;
6675: }
6676: } elsif ($role =~ m|^gr/|) {
6677: # Role of member in a group, defined within a course/community
6678: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6679: ($trole, $tend, $tstart) = split(/_/, $role);
6680: next if $tstart eq '-1';
6681: ($trole, $group_privs) = split(/\//, $trole);
6682: $group_privs = &unescape($group_privs);
6683: } else {
6684: # Just a normal role, defined in roles.tab
6685: ($trole, $tend, $tstart) = split(/_/,$role);
6686: }
6687:
6688: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6689: $username);
6690: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6691:
6692: # role expired or not available yet?
6693: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6694: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6695:
6696: next if $area eq '' or $trole eq '';
6697:
6698: my $spec = "$trole.$area";
6699: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6700:
6701: if ($trole =~ /^cr\//) {
6702: # Custom role, defined by a user
6703: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6704: } elsif ($trole eq 'gr') {
6705: # Role of a member in a group, defined within a course/community
6706: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6707: next;
6708: } else {
6709: # Normal role, defined in roles.tab
6710: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6711: }
6712:
6713: my $cid = $tdomain.'_'.$trest;
6714: unless ($firstaccchk{$cid}) {
6715: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6716: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6717: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6718: $coursetimerstarts{$cid}{$item};
6719: }
6720: }
6721: $firstaccchk{$cid} = 1;
6722: }
6723: unless ($timerintchk{$cid}) {
6724: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6725: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6726: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6727: $coursetimerintervals{$cid}{$item};
6728: }
6729: }
6730: $timerintchk{$cid} = 1;
6731: }
6732: }
6733:
6734: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6735: \%allroles, \%allgroups);
6736: $env{'user.adv'} = $userroles{'user.adv'};
6737: $env{'user.rar'} = $userroles{'user.rar'};
6738:
6739: return (\%userroles,\%firstaccenv,\%timerintenv);
6740: }
6741:
6742: sub set_arearole {
6743: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6744: unless ($nolog) {
6745: # log the associated role with the area
6746: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6747: }
6748: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
6749: }
6750:
6751: sub custom_roleprivs {
6752: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6753: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
6754: my $homsvr = &homeserver($rauthor,$rdomain);
6755: if (&hostname($homsvr) ne '') {
6756: my ($rdummy,$roledef)=
6757: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6758: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6759: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6760: if (defined($syspriv)) {
6761: if ($trest =~ /^$match_community$/) {
6762: $syspriv =~ s/bre\&S//;
6763: }
6764: $$allroles{'cm./'}.=':'.$syspriv;
6765: $$allroles{$spec.'./'}.=':'.$syspriv;
6766: }
6767: if ($tdomain ne '') {
6768: if (defined($dompriv)) {
6769: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6770: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6771: }
6772: if (($trest ne '') && (defined($coursepriv))) {
6773: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6774: my $rolename = $1;
6775: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6776: }
6777: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6778: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6779: }
6780: }
6781: }
6782: }
6783: }
6784:
6785: sub course_adhocrole_privs {
6786: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6787: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6788: if ($overrides{"internal.adhocpriv.$rolename"}) {
6789: my (%currprivs,%storeprivs);
6790: foreach my $item (split(/:/,$coursepriv)) {
6791: my ($priv,$restrict) = split(/\&/,$item);
6792: $currprivs{$priv} = $restrict;
6793: }
6794: my (%possadd,%possremove,%full);
6795: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6796: my ($priv,$restrict)=split(/\&/,$item);
6797: $full{$priv} = $restrict;
6798: }
6799: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6800: next if ($item eq '');
6801: my ($rule,$rest) = split(/=/,$item);
6802: next unless (($rule eq 'off') || ($rule eq 'on'));
6803: foreach my $priv (split(/:/,$rest)) {
6804: if ($priv ne '') {
6805: if ($rule eq 'off') {
6806: $possremove{$priv} = 1;
6807: } else {
6808: $possadd{$priv} = 1;
6809: }
6810: }
6811: }
6812: }
6813: foreach my $priv (sort(keys(%full))) {
6814: if (exists($currprivs{$priv})) {
6815: unless (exists($possremove{$priv})) {
6816: $storeprivs{$priv} = $currprivs{$priv};
6817: }
6818: } elsif (exists($possadd{$priv})) {
6819: $storeprivs{$priv} = $full{$priv};
6820: }
6821: }
6822: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6823: }
6824: return $coursepriv;
6825: }
6826:
6827: sub group_roleprivs {
6828: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6829: my $access = 1;
6830: my $now = time;
6831: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6832: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6833: if ($access) {
6834: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
6835: $$allgroups{$course}{$group} .=':'.$group_privs;
6836: }
6837: }
6838:
6839: sub standard_roleprivs {
6840: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6841: if (defined($pr{$trole.':s'})) {
6842: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6843: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6844: }
6845: if ($tdomain ne '') {
6846: if (defined($pr{$trole.':d'})) {
6847: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6848: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6849: }
6850: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6851: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6852: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6853: }
6854: }
6855: }
6856:
6857: sub set_userprivs {
6858: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
6859: my $author=0;
6860: my $adv=0;
6861: my $rar=0;
6862: my %grouproles = ();
6863: if (keys(%{$allgroups}) > 0) {
6864: my @groupkeys;
6865: foreach my $role (keys(%{$allroles})) {
6866: push(@groupkeys,$role);
6867: }
6868: if (ref($groups_roles) eq 'HASH') {
6869: foreach my $key (keys(%{$groups_roles})) {
6870: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6871: push(@groupkeys,$key);
6872: }
6873: }
6874: }
6875: if (@groupkeys > 0) {
6876: foreach my $role (@groupkeys) {
6877: my ($trole,$area,$sec,$extendedarea);
6878: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6879: $trole = $1;
6880: $area = $2;
6881: $sec = $3;
6882: $extendedarea = $area.$sec;
6883: if (exists($$allgroups{$area})) {
6884: foreach my $group (keys(%{$$allgroups{$area}})) {
6885: my $spec = $trole.'.'.$extendedarea;
6886: $grouproles{$spec.'.'.$area.'/'.$group} =
6887: $$allgroups{$area}{$group};
6888: }
6889: }
6890: }
6891: }
6892: }
6893: }
6894: foreach my $group (keys(%grouproles)) {
6895: $$allroles{$group} = $grouproles{$group};
6896: }
6897: foreach my $role (keys(%{$allroles})) {
6898: my %thesepriv;
6899: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
6900: foreach my $item (split(/:/,$$allroles{$role})) {
6901: if ($item ne '') {
6902: my ($privilege,$restrictions)=split(/&/,$item);
6903: if ($restrictions eq '') {
6904: $thesepriv{$privilege}='F';
6905: } elsif ($thesepriv{$privilege} ne 'F') {
6906: $thesepriv{$privilege}.=$restrictions;
6907: }
6908: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
6909: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
6910: }
6911: }
6912: my $thesestr='';
6913: foreach my $priv (sort(keys(%thesepriv))) {
6914: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6915: }
6916: $userroles->{'user.priv.'.$role} = $thesestr;
6917: }
6918: return ($author,$adv,$rar);
6919: }
6920:
6921: sub role_status {
6922: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
6923: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
6924: my ($one,$two) = split(m{\./},$rolekey,2);
6925: (undef,undef,$$role) = split(/\./,$one,3);
6926: unless (!defined($$role) || $$role eq '') {
6927: $$where = '/'.$two;
6928: $$trolecode=$$role.'.'.$$where;
6929: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6930: $$tstatus='is';
6931: if ($$tstart && $$tstart>$update) {
6932: $$tstatus='future';
6933: if ($$tstart<$now) {
6934: if ($$tstart && $$tstart>$refresh) {
6935: if (($$where ne '') && ($$role ne '')) {
6936: my (%allroles,%allgroups,$group_privs,
6937: %groups_roles,@rolecodes);
6938: my %userroles = (
6939: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6940: );
6941: @rolecodes = ('cm');
6942: my $spec=$$role.'.'.$$where;
6943: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6944: if ($$role =~ /^cr\//) {
6945: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
6946: push(@rolecodes,'cr');
6947: } elsif ($$role eq 'gr') {
6948: push(@rolecodes,$$role);
6949: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6950: $env{'user.name'});
6951: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
6952: (undef,my $group_privs) = split(/\//,$trole);
6953: $group_privs = &unescape($group_privs);
6954: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
6955: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
6956: &get_groups_roles($tdomain,$trest,
6957: \%course_roles,\@rolecodes,
6958: \%groups_roles);
6959: } else {
6960: push(@rolecodes,$$role);
6961: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6962: }
6963: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6964: \%groups_roles);
6965: &appenv(\%userroles,\@rolecodes);
6966: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
6967: }
6968: }
6969: $$tstatus = 'is';
6970: }
6971: }
6972: if ($$tend) {
6973: if ($$tend<$update) {
6974: $$tstatus='expired';
6975: } elsif ($$tend<$now) {
6976: $$tstatus='will_not';
6977: }
6978: }
6979: }
6980: }
6981: }
6982:
6983: sub get_groups_roles {
6984: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6985: return unless((ref($cdom_courseroles) eq 'HASH') &&
6986: (ref($rolecodes) eq 'ARRAY') &&
6987: (ref($groups_roles) eq 'HASH'));
6988: if (keys(%{$cdom_courseroles}) > 0) {
6989: my ($cnum) = ($rest =~ /^($match_courseid)/);
6990: if ($cdom ne '' && $cnum ne '') {
6991: foreach my $key (keys(%{$cdom_courseroles})) {
6992: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6993: my $crsrole = $1;
6994: my $crssec = $2;
6995: if ($crsrole =~ /^cr/) {
6996: unless (grep(/^cr$/,@{$rolecodes})) {
6997: push(@{$rolecodes},'cr');
6998: }
6999: } else {
7000: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
7001: push(@{$rolecodes},$crsrole);
7002: }
7003: }
7004: my $rolekey = "$crsrole./$cdom/$cnum";
7005: if ($crssec ne '') {
7006: $rolekey .= "/$crssec";
7007: }
7008: $rolekey .= './';
7009: $groups_roles->{$rolekey} = $rolecodes;
7010: }
7011: }
7012: }
7013: }
7014: return;
7015: }
7016:
7017: sub delete_env_groupprivs {
7018: my ($where,$courseroles,$possroles) = @_;
7019: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
7020: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
7021: unless (ref($courseroles->{$udom}) eq 'HASH') {
7022: %{$courseroles->{$udom}} =
7023: &get_my_roles('','','userroles',['active'],
7024: $possroles,[$udom],1);
7025: }
7026: if (ref($courseroles->{$udom}) eq 'HASH') {
7027: foreach my $item (keys(%{$courseroles->{$udom}})) {
7028: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
7029: my $area = '/'.$cdom.'/'.$cnum;
7030: my $privkey = "user.priv.$crsrole.$area";
7031: if ($crssec ne '') {
7032: $privkey .= '/'.$crssec;
7033: }
7034: $privkey .= ".$area/$group";
7035: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
7036: }
7037: }
7038: return;
7039: }
7040:
7041: sub check_adhoc_privs {
7042: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
7043: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
7044: if ($sec) {
7045: $cckey .= '/'.$sec;
7046: }
7047: my $setprivs;
7048: if ($env{$cckey}) {
7049: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
7050: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
7051: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
7052: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
7053: $setprivs = 1;
7054: }
7055: } else {
7056: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
7057: $setprivs = 1;
7058: }
7059: return $setprivs;
7060: }
7061:
7062: sub set_adhoc_privileges {
7063: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
7064: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
7065: my $area = '/'.$dcdom.'/'.$pickedcourse;
7066: if ($sec ne '') {
7067: $area .= '/'.$sec;
7068: }
7069: my $spec = $role.'.'.$area;
7070: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
7071: $env{'user.name'},1);
7072: my %rolehash = ();
7073: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
7074: my $rolename = $1;
7075: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
7076: my %domdef = &get_domain_defaults($dcdom);
7077: if (ref($domdef{'adhocroles'}) eq 'HASH') {
7078: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
7079: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
7080: }
7081: }
7082: } else {
7083: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
7084: }
7085: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
7086: &appenv(\%userroles,[$role,'cm']);
7087: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
7088: unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
7089: ($caller eq 'tiny')) {
7090: &appenv( {'request.role' => $spec,
7091: 'request.role.domain' => $dcdom,
7092: 'request.course.sec' => $sec,
7093: }
7094: );
7095: my $tadv=0;
7096: if (&allowed('adv') eq 'F') { $tadv=1; }
7097: &appenv({'request.role.adv' => $tadv});
7098: }
7099: }
7100:
7101: # --------------------------------------------------------------- get interface
7102:
7103: sub get {
7104: my ($namespace,$storearr,$udomain,$uname)=@_;
7105: my $items='';
7106: foreach my $item (@$storearr) {
7107: $items.=&escape($item).'&';
7108: }
7109: $items=~s/\&$//;
7110: if (!$udomain) { $udomain=$env{'user.domain'}; }
7111: if (!$uname) { $uname=$env{'user.name'}; }
7112: my $uhome=&homeserver($uname,$udomain);
7113:
7114: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
7115: my @pairs=split(/\&/,$rep);
7116: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
7117: return @pairs;
7118: }
7119: my %returnhash=();
7120: my $i=0;
7121: foreach my $item (@$storearr) {
7122: $returnhash{$item}=&thaw_unescape($pairs[$i]);
7123: $i++;
7124: }
7125: return %returnhash;
7126: }
7127:
7128: # --------------------------------------------------------------- del interface
7129:
7130: sub del {
7131: my ($namespace,$storearr,$udomain,$uname)=@_;
7132: my $items='';
7133: foreach my $item (@$storearr) {
7134: $items.=&escape($item).'&';
7135: }
7136:
7137: $items=~s/\&$//;
7138: if (!$udomain) { $udomain=$env{'user.domain'}; }
7139: if (!$uname) { $uname=$env{'user.name'}; }
7140: my $uhome=&homeserver($uname,$udomain);
7141: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
7142: }
7143:
7144: # -------------------------------------------------------------- dump interface
7145:
7146: sub unserialize {
7147: my ($rep, $escapedkeys) = @_;
7148:
7149: return {} if $rep =~ /^error/;
7150:
7151: my %returnhash=();
7152: foreach my $item (split(/\&/,$rep)) {
7153: my ($key, $value) = split(/=/, $item, 2);
7154: $key = unescape($key) unless $escapedkeys;
7155: next if $key =~ /^error: 2 /;
7156: $returnhash{$key} = &thaw_unescape($value);
7157: }
7158: #return %returnhash;
7159: return \%returnhash;
7160: }
7161:
7162: # see Lond::dump_with_regexp
7163: # if $escapedkeys hash keys won't get unescaped.
7164: sub dump {
7165: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
7166: if (!$udomain) { $udomain=$env{'user.domain'}; }
7167: if (!$uname) { $uname=$env{'user.name'}; }
7168: my $uhome=&homeserver($uname,$udomain);
7169:
7170: if ($regexp) {
7171: $regexp=&escape($regexp);
7172: } else {
7173: $regexp='.';
7174: }
7175: if (grep { $_ eq $uhome } current_machine_ids()) {
7176: # user is hosted on this machine
7177: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
7178: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
7179: return %{unserialize($reply, $escapedkeys)};
7180: }
7181: my $rep;
7182: if ($encrypt) {
7183: $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
7184: } else {
7185: $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
7186: }
7187: my @pairs=split(/\&/,$rep);
7188: my %returnhash=();
7189: if (!($rep =~ /^error/ )) {
7190: foreach my $item (@pairs) {
7191: my ($key,$value)=split(/=/,$item,2);
7192: $key = unescape($key) unless $escapedkeys;
7193: #$key = &unescape($key);
7194: next if ($key =~ /^error: 2 /);
7195: $returnhash{$key}=&thaw_unescape($value);
7196: }
7197: }
7198: return %returnhash;
7199: }
7200:
7201:
7202: # --------------------------------------------------------- dumpstore interface
7203:
7204: sub dumpstore {
7205: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
7206: # same as dump but keys must be escaped. They may contain colon separated
7207: # lists of values that may themself contain colons (e.g. symbs).
7208: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
7209: }
7210:
7211: # -------------------------------------------------------------- keys interface
7212:
7213: sub getkeys {
7214: my ($namespace,$udomain,$uname)=@_;
7215: if (!$udomain) { $udomain=$env{'user.domain'}; }
7216: if (!$uname) { $uname=$env{'user.name'}; }
7217: my $uhome=&homeserver($uname,$udomain);
7218: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
7219: my @keyarray=();
7220: foreach my $key (split(/\&/,$rep)) {
7221: next if ($key =~ /^error: 2 /);
7222: push(@keyarray,&unescape($key));
7223: }
7224: return @keyarray;
7225: }
7226:
7227: # --------------------------------------------------------------- currentdump
7228: sub currentdump {
7229: my ($courseid,$sdom,$sname)=@_;
7230: $courseid = $env{'request.course.id'} if (! defined($courseid));
7231: $sdom = $env{'user.domain'} if (! defined($sdom));
7232: $sname = $env{'user.name'} if (! defined($sname));
7233: my $uhome = &homeserver($sname,$sdom);
7234: my $rep;
7235:
7236: if (grep { $_ eq $uhome } current_machine_ids()) {
7237: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
7238: $courseid)));
7239: } else {
7240: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
7241: }
7242:
7243: return if ($rep =~ /^(error:|no_such_host)/);
7244: #
7245: my %returnhash=();
7246: #
7247: if ($rep eq 'unknown_cmd') {
7248: # an old lond will not know currentdump
7249: # Do a dump and make it look like a currentdump
7250: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
7251: return if ($tmp[0] =~ /^(error:|no_such_host)/);
7252: my %hash = @tmp;
7253: @tmp=();
7254: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
7255: } else {
7256: my @pairs=split(/\&/,$rep);
7257: foreach my $pair (@pairs) {
7258: my ($key,$value)=split(/=/,$pair,2);
7259: my ($symb,$param) = split(/:/,$key);
7260: $returnhash{&unescape($symb)}->{&unescape($param)} =
7261: &thaw_unescape($value);
7262: }
7263: }
7264: return %returnhash;
7265: }
7266:
7267: sub convert_dump_to_currentdump{
7268: my %hash = %{shift()};
7269: my %returnhash;
7270: # Code ripped from lond, essentially. The only difference
7271: # here is the unescaping done by lonnet::dump(). Conceivably
7272: # we might run in to problems with parameter names =~ /^v\./
7273: while (my ($key,$value) = each(%hash)) {
7274: my ($v,$symb,$param) = split(/:/,$key);
7275: $symb = &unescape($symb);
7276: $param = &unescape($param);
7277: next if ($v eq 'version' || $symb eq 'keys');
7278: next if (exists($returnhash{$symb}) &&
7279: exists($returnhash{$symb}->{$param}) &&
7280: $returnhash{$symb}->{'v.'.$param} > $v);
7281: $returnhash{$symb}->{$param}=$value;
7282: $returnhash{$symb}->{'v.'.$param}=$v;
7283: }
7284: #
7285: # Remove all of the keys in the hashes which keep track of
7286: # the version of the parameter.
7287: while (my ($symb,$param_hash) = each(%returnhash)) {
7288: # use a foreach because we are going to delete from the hash.
7289: foreach my $key (keys(%$param_hash)) {
7290: delete($param_hash->{$key}) if ($key =~ /^v\./);
7291: }
7292: }
7293: return \%returnhash;
7294: }
7295:
7296: # ------------------------------------------------------ critical inc interface
7297:
7298: sub cinc {
7299: return &inc(@_,'critical');
7300: }
7301:
7302: # --------------------------------------------------------------- inc interface
7303:
7304: sub inc {
7305: my ($namespace,$store,$udomain,$uname,$critical) = @_;
7306: if (!$udomain) { $udomain=$env{'user.domain'}; }
7307: if (!$uname) { $uname=$env{'user.name'}; }
7308: my $uhome=&homeserver($uname,$udomain);
7309: my $items='';
7310: if (! ref($store)) {
7311: # got a single value, so use that instead
7312: $items = &escape($store).'=&';
7313: } elsif (ref($store) eq 'SCALAR') {
7314: $items = &escape($$store).'=&';
7315: } elsif (ref($store) eq 'ARRAY') {
7316: $items = join('=&',map {&escape($_);} @{$store});
7317: } elsif (ref($store) eq 'HASH') {
7318: while (my($key,$value) = each(%{$store})) {
7319: $items.= &escape($key).'='.&escape($value).'&';
7320: }
7321: }
7322: $items=~s/\&$//;
7323: if ($critical) {
7324: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
7325: } else {
7326: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
7327: }
7328: }
7329:
7330: # --------------------------------------------------------------- put interface
7331:
7332: sub put {
7333: my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
7334: if (!$udomain) { $udomain=$env{'user.domain'}; }
7335: if (!$uname) { $uname=$env{'user.name'}; }
7336: my $uhome=&homeserver($uname,$udomain);
7337: my $items='';
7338: foreach my $item (keys(%$storehash)) {
7339: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
7340: }
7341: $items=~s/\&$//;
7342: if ($encrypt) {
7343: return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
7344: } else {
7345: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
7346: }
7347: }
7348:
7349: # ------------------------------------------------------------ newput interface
7350:
7351: sub newput {
7352: my ($namespace,$storehash,$udomain,$uname)=@_;
7353: if (!$udomain) { $udomain=$env{'user.domain'}; }
7354: if (!$uname) { $uname=$env{'user.name'}; }
7355: my $uhome=&homeserver($uname,$udomain);
7356: my $items='';
7357: foreach my $key (keys(%$storehash)) {
7358: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7359: }
7360: $items=~s/\&$//;
7361: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
7362: }
7363:
7364: # --------------------------------------------------------- putstore interface
7365:
7366: sub putstore {
7367: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
7368: if (!$udomain) { $udomain=$env{'user.domain'}; }
7369: if (!$uname) { $uname=$env{'user.name'}; }
7370: my $uhome=&homeserver($uname,$udomain);
7371: my $items='';
7372: foreach my $key (keys(%$storehash)) {
7373: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7374: }
7375: $items=~s/\&$//;
7376: my $esc_symb=&escape($symb);
7377: my $esc_v=&escape($version);
7378: my $reply =
7379: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
7380: $uhome);
7381: if (($tolog) && ($reply eq 'ok')) {
7382: my $namevalue='';
7383: foreach my $key (keys(%{$storehash})) {
7384: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7385: }
7386: my $ip = &get_requestor_ip();
7387: $namevalue .= 'ip='.&escape($ip).
7388: '&host='.&escape($perlvar{'lonHostID'}).
7389: '&version='.$esc_v.
7390: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
7391: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
7392: }
7393: if ($reply eq 'unknown_cmd') {
7394: # gfall back to way things use to be done
7395: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7396: $uname);
7397: }
7398: return $reply;
7399: }
7400:
7401: sub old_putstore {
7402: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
7403: if (!$udomain) { $udomain=$env{'user.domain'}; }
7404: if (!$uname) { $uname=$env{'user.name'}; }
7405: my $uhome=&homeserver($uname,$udomain);
7406: my %newstorehash;
7407: foreach my $item (keys(%$storehash)) {
7408: my $key = $version.':'.&escape($symb).':'.$item;
7409: $newstorehash{$key} = $storehash->{$item};
7410: }
7411: my $items='';
7412: my %allitems = ();
7413: foreach my $item (keys(%newstorehash)) {
7414: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
7415: my $key = $1.':keys:'.$2;
7416: $allitems{$key} .= $3.':';
7417: }
7418: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
7419: }
7420: foreach my $item (keys(%allitems)) {
7421: $allitems{$item} =~ s/\:$//;
7422: $items.= $item.'='.$allitems{$item}.'&';
7423: }
7424: $items=~s/\&$//;
7425: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
7426: }
7427:
7428: # ------------------------------------------------------ critical put interface
7429:
7430: sub cput {
7431: my ($namespace,$storehash,$udomain,$uname)=@_;
7432: if (!$udomain) { $udomain=$env{'user.domain'}; }
7433: if (!$uname) { $uname=$env{'user.name'}; }
7434: my $uhome=&homeserver($uname,$udomain);
7435: my $items='';
7436: foreach my $item (keys(%$storehash)) {
7437: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
7438: }
7439: $items=~s/\&$//;
7440: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
7441: }
7442:
7443: # -------------------------------------------------------------- eget interface
7444:
7445: sub eget {
7446: my ($namespace,$storearr,$udomain,$uname)=@_;
7447: my $items='';
7448: foreach my $item (@$storearr) {
7449: $items.=&escape($item).'&';
7450: }
7451: $items=~s/\&$//;
7452: if (!$udomain) { $udomain=$env{'user.domain'}; }
7453: if (!$uname) { $uname=$env{'user.name'}; }
7454: my $uhome=&homeserver($uname,$udomain);
7455: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
7456: my @pairs=split(/\&/,$rep);
7457: my %returnhash=();
7458: my $i=0;
7459: foreach my $item (@$storearr) {
7460: $returnhash{$item}=&thaw_unescape($pairs[$i]);
7461: $i++;
7462: }
7463: return %returnhash;
7464: }
7465:
7466: # ------------------------------------------------------------ tmpput interface
7467: sub tmpput {
7468: my ($storehash,$server,$context)=@_;
7469: my $items='';
7470: foreach my $item (keys(%$storehash)) {
7471: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
7472: }
7473: $items=~s/\&$//;
7474: if (defined($context)) {
7475: $items .= ':'.&escape($context);
7476: }
7477: return &reply("tmpput:$items",$server);
7478: }
7479:
7480: # ------------------------------------------------------------ tmpget interface
7481: sub tmpget {
7482: my ($token,$server)=@_;
7483: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7484: my $rep=&reply("tmpget:$token",$server);
7485: my %returnhash;
7486: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7487: return %returnhash;
7488: }
7489: foreach my $item (split(/\&/,$rep)) {
7490: my ($key,$value)=split(/=/,$item);
7491: $returnhash{&unescape($key)}=&thaw_unescape($value);
7492: }
7493: return %returnhash;
7494: }
7495:
7496: # ------------------------------------------------------------ tmpdel interface
7497: sub tmpdel {
7498: my ($token,$server)=@_;
7499: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7500: return &reply("tmpdel:$token",$server);
7501: }
7502:
7503: # ------------------------------------------------------------ get_timebased_id
7504:
7505: sub get_timebased_id {
7506: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7507: $maxtries) = @_;
7508: my ($newid,$error,$dellock);
7509: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7510: return ('','ok','invalid call to get suffix');
7511: }
7512:
7513: # set defaults for any optional args for which values were not supplied
7514: if ($who eq '') {
7515: $who = $env{'user.name'}.':'.$env{'user.domain'};
7516: }
7517: if (!$locktries) {
7518: $locktries = 3;
7519: }
7520: if (!$maxtries) {
7521: $maxtries = 10;
7522: }
7523:
7524: if (($cdom eq '') || ($cnum eq '')) {
7525: if ($env{'request.course.id'}) {
7526: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7527: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7528: }
7529: if (($cdom eq '') || ($cnum eq '')) {
7530: return ('','ok','call to get suffix not in course context');
7531: }
7532: }
7533:
7534: # construct locking item
7535: my $lockhash = {
7536: $prefix."\0".'locked_'.$keyid => $who,
7537: };
7538: my $tries = 0;
7539:
7540: # attempt to get lock on nohist_$namespace file
7541: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7542: while (($gotlock ne 'ok') && $tries <$locktries) {
7543: $tries ++;
7544: sleep 1;
7545: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7546: }
7547:
7548: # attempt to get unique identifier, based on current timestamp
7549: if ($gotlock eq 'ok') {
7550: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
7551: my $id = time;
7552: $newid = $id;
7553: if ($idtype eq 'addcode') {
7554: $newid .= &sixnum_code();
7555: }
7556: my $idtries = 0;
7557: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7558: if ($idtype eq 'concat') {
7559: $newid = $id.$idtries;
7560: } elsif ($idtype eq 'addcode') {
7561: $newid = $newid.&sixnum_code();
7562: } else {
7563: $newid ++;
7564: }
7565: $idtries ++;
7566: }
7567: if (!exists($inuse{$prefix."\0".$newid})) {
7568: my %new_item = (
7569: $prefix."\0".$newid => $who,
7570: );
7571: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
7572: $cdom,$cnum);
7573: if ($putresult ne 'ok') {
7574: undef($newid);
7575: $error = 'error saving new item: '.$putresult;
7576: }
7577: } else {
7578: undef($newid);
7579: $error = ('error: no unique suffix available for the new item ');
7580: }
7581: # remove lock
7582: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7583: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7584: } else {
7585: $error = "error: could not obtain lockfile\n";
7586: $dellock = 'ok';
7587: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7588: $dellock = 'nolock';
7589: }
7590: }
7591: return ($newid,$dellock,$error);
7592: }
7593:
7594: sub sixnum_code {
7595: my $code;
7596: for (0..6) {
7597: $code .= int( rand(9) );
7598: }
7599: return $code;
7600: }
7601:
7602: # -------------------------------------------------- portfolio access checking
7603:
7604: sub portfolio_access {
7605: my ($requrl,$clientip) = @_;
7606: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
7607: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
7608: if ($result) {
7609: my %setters;
7610: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7611: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
7612: &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
7613: if (($startblock && $endblock) || ($by_ip)) {
7614: return 'B';
7615: }
7616: } else {
7617: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
7618: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
7619: if (($startblock && $endblock) || ($by_ip)) {
7620: return 'B';
7621: }
7622: }
7623: }
7624: if ($result eq 'ok') {
7625: return 'F';
7626: } elsif ($result =~ /^[^:]+:guest_/) {
7627: return 'A';
7628: }
7629: return '';
7630: }
7631:
7632: sub get_portfolio_access {
7633: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
7634:
7635: if (!ref($access_hash)) {
7636: my $current_perms = &get_portfile_permissions($udom,$unum);
7637: my %access_controls = &get_access_controls($current_perms,$group,
7638: $file_name);
7639: $access_hash = $access_controls{$file_name};
7640: }
7641:
7642: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
7643: my $now = time;
7644: if (ref($access_hash) eq 'HASH') {
7645: foreach my $key (keys(%{$access_hash})) {
7646: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7647: if ($start > $now) {
7648: next;
7649: }
7650: if ($end && $end<$now) {
7651: next;
7652: }
7653: if ($scope eq 'public') {
7654: $public = $key;
7655: last;
7656: } elsif ($scope eq 'guest') {
7657: $guest = $key;
7658: } elsif ($scope eq 'domains') {
7659: push(@domains,$key);
7660: } elsif ($scope eq 'users') {
7661: push(@users,$key);
7662: } elsif ($scope eq 'course') {
7663: push(@courses,$key);
7664: } elsif ($scope eq 'group') {
7665: push(@groups,$key);
7666: } elsif ($scope eq 'ip') {
7667: push(@ips,$key);
7668: }
7669: }
7670: if ($public) {
7671: return 'ok';
7672: } elsif (@ips > 0) {
7673: my $allowed;
7674: foreach my $ipkey (@ips) {
7675: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7676: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7677: $allowed = 1;
7678: last;
7679: }
7680: }
7681: }
7682: if ($allowed) {
7683: return 'ok';
7684: }
7685: }
7686: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7687: if ($guest) {
7688: return $guest;
7689: }
7690: } else {
7691: if (@domains > 0) {
7692: foreach my $domkey (@domains) {
7693: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7694: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7695: return 'ok';
7696: }
7697: }
7698: }
7699: }
7700: if (@users > 0) {
7701: foreach my $userkey (@users) {
7702: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7703: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7704: if (ref($item) eq 'HASH') {
7705: if (($item->{'uname'} eq $env{'user.name'}) &&
7706: ($item->{'udom'} eq $env{'user.domain'})) {
7707: return 'ok';
7708: }
7709: }
7710: }
7711: }
7712: }
7713: }
7714: my %roleshash;
7715: my @courses_and_groups = @courses;
7716: push(@courses_and_groups,@groups);
7717: if (@courses_and_groups > 0) {
7718: my (%allgroups,%allroles);
7719: my ($start,$end,$role,$sec,$group);
7720: foreach my $envkey (%env) {
7721: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
7722: my $cid = $2.'_'.$3;
7723: if ($1 eq 'gr') {
7724: $group = $4;
7725: $allgroups{$cid}{$group} = $env{$envkey};
7726: } else {
7727: if ($4 eq '') {
7728: $sec = 'none';
7729: } else {
7730: $sec = $4;
7731: }
7732: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7733: }
7734: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
7735: my $cid = $2.'_'.$3;
7736: if ($4 eq '') {
7737: $sec = 'none';
7738: } else {
7739: $sec = $4;
7740: }
7741: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7742: }
7743: }
7744: if (keys(%allroles) == 0) {
7745: return;
7746: }
7747: foreach my $key (@courses_and_groups) {
7748: my %content = %{$$access_hash{$key}};
7749: my $cnum = $content{'number'};
7750: my $cdom = $content{'domain'};
7751: my $cid = $cdom.'_'.$cnum;
7752: if (!exists($allroles{$cid})) {
7753: next;
7754: }
7755: foreach my $role_id (keys(%{$content{'roles'}})) {
7756: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7757: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7758: my @status = @{$content{'roles'}{$role_id}{'access'}};
7759: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7760: foreach my $role (keys(%{$allroles{$cid}})) {
7761: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7762: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7763: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7764: if (grep/^all$/,@sections) {
7765: return 'ok';
7766: } else {
7767: if (grep/^$sec$/,@sections) {
7768: return 'ok';
7769: }
7770: }
7771: }
7772: }
7773: if (keys(%{$allgroups{$cid}}) == 0) {
7774: if (grep/^none$/,@groups) {
7775: return 'ok';
7776: }
7777: } else {
7778: if (grep/^all$/,@groups) {
7779: return 'ok';
7780: }
7781: foreach my $group (keys(%{$allgroups{$cid}})) {
7782: if (grep/^$group$/,@groups) {
7783: return 'ok';
7784: }
7785: }
7786: }
7787: }
7788: }
7789: }
7790: }
7791: }
7792: if ($guest) {
7793: return $guest;
7794: }
7795: }
7796: }
7797: return;
7798: }
7799:
7800: sub course_group_datechecker {
7801: my ($dates,$now,$status) = @_;
7802: my ($start,$end) = split(/\./,$dates);
7803: if (!$start && !$end) {
7804: return 'ok';
7805: }
7806: if (grep/^active$/,@{$status}) {
7807: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7808: return 'ok';
7809: }
7810: }
7811: if (grep/^previous$/,@{$status}) {
7812: if ($end > $now ) {
7813: return 'ok';
7814: }
7815: }
7816: if (grep/^future$/,@{$status}) {
7817: if ($start > $now) {
7818: return 'ok';
7819: }
7820: }
7821: return;
7822: }
7823:
7824: sub parse_portfolio_url {
7825: my ($url) = @_;
7826:
7827: my ($type,$udom,$unum,$group,$file_name);
7828:
7829: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
7830: $type = 1;
7831: $udom = $1;
7832: $unum = $2;
7833: $file_name = $3;
7834: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
7835: $type = 2;
7836: $udom = $1;
7837: $unum = $2;
7838: $group = $3;
7839: $file_name = $3.'/'.$4;
7840: }
7841: if (wantarray) {
7842: return ($type,$udom,$unum,$file_name,$group);
7843: }
7844: return $type;
7845: }
7846:
7847: sub is_portfolio_url {
7848: my ($url) = @_;
7849: return scalar(&parse_portfolio_url($url));
7850: }
7851:
7852: sub is_portfolio_file {
7853: my ($file) = @_;
7854: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
7855: return 1;
7856: }
7857: return;
7858: }
7859:
7860: sub usertools_access {
7861: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
7862: my ($access,%tools);
7863: if ($context eq '') {
7864: $context = 'tools';
7865: }
7866: if ($context eq 'requestcourses') {
7867: %tools = (
7868: official => 1,
7869: unofficial => 1,
7870: community => 1,
7871: textbook => 1,
7872: placement => 1,
7873: lti => 1,
7874: );
7875: } elsif ($context eq 'requestauthor') {
7876: %tools = (
7877: requestauthor => 1,
7878: );
7879: } else {
7880: %tools = (
7881: aboutme => 1,
7882: blog => 1,
7883: webdav => 1,
7884: portfolio => 1,
7885: );
7886: }
7887: return if (!defined($tools{$tool}));
7888:
7889: if (($udom eq '') || ($uname eq '')) {
7890: $udom = $env{'user.domain'};
7891: $uname = $env{'user.name'};
7892: }
7893:
7894: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7895: if ($action ne 'reload') {
7896: if ($context eq 'requestcourses') {
7897: return $env{'environment.canrequest.'.$tool};
7898: } elsif ($context eq 'requestauthor') {
7899: return $env{'environment.canrequest.author'};
7900: } else {
7901: return $env{'environment.availabletools.'.$tool};
7902: }
7903: }
7904: }
7905:
7906: my ($toolstatus,$inststatus,$envkey);
7907: if ($context eq 'requestauthor') {
7908: $envkey = $context;
7909: } else {
7910: $envkey = $context.'.'.$tool;
7911: }
7912:
7913: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7914: ($action ne 'reload')) {
7915: $toolstatus = $env{'environment.'.$envkey};
7916: $inststatus = $env{'environment.inststatus'};
7917: } else {
7918: if (ref($userenvref) eq 'HASH') {
7919: $toolstatus = $userenvref->{$envkey};
7920: $inststatus = $userenvref->{'inststatus'};
7921: } else {
7922: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7923: $toolstatus = $userenv{$envkey};
7924: $inststatus = $userenv{'inststatus'};
7925: }
7926: }
7927:
7928: if ($toolstatus ne '') {
7929: if ($toolstatus) {
7930: $access = 1;
7931: } else {
7932: $access = 0;
7933: }
7934: return $access;
7935: }
7936:
7937: my ($is_adv,%domdef);
7938: if (ref($is_advref) eq 'HASH') {
7939: $is_adv = $is_advref->{'is_adv'};
7940: } else {
7941: $is_adv = &is_advanced_user($udom,$uname);
7942: }
7943: if (ref($domdefref) eq 'HASH') {
7944: %domdef = %{$domdefref};
7945: } else {
7946: %domdef = &get_domain_defaults($udom);
7947: }
7948: if (ref($domdef{$tool}) eq 'HASH') {
7949: if ($is_adv) {
7950: if ($domdef{$tool}{'_LC_adv'} ne '') {
7951: if ($domdef{$tool}{'_LC_adv'}) {
7952: $access = 1;
7953: } else {
7954: $access = 0;
7955: }
7956: return $access;
7957: }
7958: }
7959: if ($inststatus ne '') {
7960: my ($hasaccess,$hasnoaccess);
7961: foreach my $affiliation (split(/:/,$inststatus)) {
7962: if ($domdef{$tool}{$affiliation} ne '') {
7963: if ($domdef{$tool}{$affiliation}) {
7964: $hasaccess = 1;
7965: } else {
7966: $hasnoaccess = 1;
7967: }
7968: }
7969: }
7970: if ($hasaccess || $hasnoaccess) {
7971: if ($hasaccess) {
7972: $access = 1;
7973: } elsif ($hasnoaccess) {
7974: $access = 0;
7975: }
7976: return $access;
7977: }
7978: } else {
7979: if ($domdef{$tool}{'default'} ne '') {
7980: if ($domdef{$tool}{'default'}) {
7981: $access = 1;
7982: } elsif ($domdef{$tool}{'default'} == 0) {
7983: $access = 0;
7984: }
7985: return $access;
7986: }
7987: }
7988: } else {
7989: if (($context eq 'tools') && ($tool ne 'webdav')) {
7990: $access = 1;
7991: } else {
7992: $access = 0;
7993: }
7994: return $access;
7995: }
7996: }
7997:
7998: sub is_course_owner {
7999: my ($cdom,$cnum,$udom,$uname) = @_;
8000: if (($udom eq '') || ($uname eq '')) {
8001: $udom = $env{'user.domain'};
8002: $uname = $env{'user.name'};
8003: }
8004: unless (($udom eq '') || ($uname eq '')) {
8005: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
8006: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
8007: return 1;
8008: } else {
8009: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
8010: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
8011: return 1;
8012: }
8013: }
8014: }
8015: }
8016: return;
8017: }
8018:
8019: sub is_advanced_user {
8020: my ($udom,$uname) = @_;
8021: if ($udom ne '' && $uname ne '') {
8022: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
8023: if (wantarray) {
8024: return ($env{'user.adv'},$env{'user.author'});
8025: } else {
8026: return $env{'user.adv'};
8027: }
8028: }
8029: }
8030: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
8031: my %allroles;
8032: my ($is_adv,$is_author);
8033: foreach my $role (keys(%roleshash)) {
8034: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
8035: my $area = '/'.$tdomain.'/'.$trest;
8036: if ($sec ne '') {
8037: $area .= '/'.$sec;
8038: }
8039: if (($area ne '') && ($trole ne '')) {
8040: my $spec=$trole.'.'.$area;
8041: if ($trole =~ /^cr\//) {
8042: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
8043: } elsif ($trole ne 'gr') {
8044: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
8045: }
8046: if ($trole eq 'au') {
8047: $is_author = 1;
8048: }
8049: }
8050: }
8051: foreach my $role (keys(%allroles)) {
8052: last if ($is_adv);
8053: foreach my $item (split(/:/,$allroles{$role})) {
8054: if ($item ne '') {
8055: my ($privilege,$restrictions)=split(/&/,$item);
8056: if ($privilege eq 'adv') {
8057: $is_adv = 1;
8058: last;
8059: }
8060: }
8061: }
8062: }
8063: if (wantarray) {
8064: return ($is_adv,$is_author);
8065: }
8066: return $is_adv;
8067: }
8068:
8069: sub check_can_request {
8070: my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
8071: my $canreq = 0;
8072: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8073: $uname = $env{'user.name'};
8074: $udom = $env{'user.domain'};
8075: }
8076: my ($types,$typename) = &Apache::loncommon::course_types();
8077: my @options = ('approval','validate','autolimit');
8078: my $optregex = join('|',@options);
8079: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
8080: foreach my $type (@{$types}) {
8081: if (&usertools_access($uname,$udom,$type,undef,
8082: 'requestcourses')) {
8083: $canreq ++;
8084: if (ref($request_domains) eq 'HASH') {
8085: push(@{$request_domains->{$type}},$udom);
8086: }
8087: if ($dom eq $udom) {
8088: $can_request->{$type} = 1;
8089: }
8090: }
8091: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
8092: ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
8093: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
8094: if (@curr > 0) {
8095: foreach my $item (@curr) {
8096: if (ref($request_domains) eq 'HASH') {
8097: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
8098: if ($otherdom ne '') {
8099: if (ref($request_domains->{$type}) eq 'ARRAY') {
8100: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
8101: push(@{$request_domains->{$type}},$otherdom);
8102: }
8103: } else {
8104: push(@{$request_domains->{$type}},$otherdom);
8105: }
8106: }
8107: }
8108: }
8109: unless ($dom eq $env{'user.domain'}) {
8110: $canreq ++;
8111: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
8112: $can_request->{$type} = 1;
8113: }
8114: }
8115: }
8116: }
8117: }
8118: }
8119: return $canreq;
8120: }
8121:
8122: # ---------------------------------------------- Custom access rule evaluation
8123:
8124: sub customaccess {
8125: my ($priv,$uri)=@_;
8126: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
8127: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
8128: $udom = &LONCAPA::clean_domain($udom);
8129: $ucrs = &LONCAPA::clean_username($ucrs);
8130: my $access=0;
8131: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
8132: my ($effect,$realm,$role,$type)=split(/\:/,$right);
8133: if ($type eq 'user') {
8134: foreach my $scope (split(/\s*\,\s*/,$realm)) {
8135: my ($tdom,$tuname)=split(m{/},$scope);
8136: if ($tdom) {
8137: if ($tdom ne $env{'user.domain'}) { next; }
8138: }
8139: if ($tuname) {
8140: if ($tuname ne $env{'user.name'}) { next; }
8141: }
8142: $access=($effect eq 'allow');
8143: last;
8144: }
8145: } else {
8146: if ($role) {
8147: if ($role ne $urole) { next; }
8148: }
8149: foreach my $scope (split(/\s*\,\s*/,$realm)) {
8150: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
8151: if ($tdom) {
8152: if ($tdom ne $udom) { next; }
8153: }
8154: if ($tcrs) {
8155: if ($tcrs ne $ucrs) { next; }
8156: }
8157: if ($tsec) {
8158: if ($tsec ne $usec) { next; }
8159: }
8160: $access=($effect eq 'allow');
8161: last;
8162: }
8163: if ($realm eq '' && $role eq '') {
8164: $access=($effect eq 'allow');
8165: }
8166: }
8167: }
8168: return $access;
8169: }
8170:
8171: # ------------------------------------------------- Check for a user privilege
8172:
8173: sub allowed {
8174: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
8175: my $ver_orguri=$uri;
8176: $uri=&deversion($uri);
8177: my $orguri=$uri;
8178: $uri=&declutter($uri);
8179:
8180: if ($priv eq 'evb') {
8181: # Evade communication block restrictions for specified role in a course or domain
8182: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
8183: return $1;
8184: } else {
8185: return;
8186: }
8187: }
8188:
8189: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
8190: # Free bre access to adm and meta resources
8191: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$}))
8192: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
8193: && ($priv eq 'bre')) {
8194: return 'F';
8195: }
8196:
8197: # Free bre access to user's own portfolio contents
8198: my ($space,$domain,$name,@dir)=split('/',$uri);
8199: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
8200: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
8201: my %setters;
8202: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
8203: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
8204: if (($startblock && $endblock) || ($by_ip)) {
8205: return 'B';
8206: } else {
8207: return 'F';
8208: }
8209: }
8210:
8211: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
8212: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
8213: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
8214: if (exists($env{'request.course.id'})) {
8215: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8216: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8217: if (($domain eq $cdom) && ($name eq $cnum)) {
8218: my $courseprivid=$env{'request.course.id'};
8219: $courseprivid=~s/\_/\//;
8220: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
8221: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
8222: return $1;
8223: } else {
8224: if ($env{'request.course.sec'}) {
8225: $courseprivid.='/'.$env{'request.course.sec'};
8226: }
8227: if ($env{'user.priv.'.$env{'request.role'}.'./'.
8228: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
8229: return $2;
8230: }
8231: }
8232: }
8233: }
8234: }
8235:
8236: # Free bre to public access
8237:
8238: if ($priv eq 'bre') {
8239: my $copyright;
8240: unless ($uri =~ /ext\.tool/) {
8241: $copyright=&metadata($uri,'copyright');
8242: }
8243: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
8244: return 'F';
8245: }
8246: if ($copyright eq 'priv') {
8247: $uri=~/([^\/]+)\/([^\/]+)\//;
8248: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
8249: return '';
8250: }
8251: }
8252: if ($copyright eq 'domain') {
8253: $uri=~/([^\/]+)\/([^\/]+)\//;
8254: unless (($env{'user.domain'} eq $1) ||
8255: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
8256: return '';
8257: }
8258: }
8259: if ($env{'request.role'}=~ /li\.\//) {
8260: # Library role, so allow browsing of resources in this domain.
8261: return 'F';
8262: }
8263: if ($copyright eq 'custom') {
8264: unless (&customaccess($priv,$uri)) { return ''; }
8265: }
8266: }
8267: # Domain coordinator is trying to create a course
8268: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
8269: # uri is the requested domain in this case.
8270: # comparison to 'request.role.domain' shows if the user has selected
8271: # a role of dc for the domain in question.
8272: return 'F' if ($uri eq $env{'request.role.domain'});
8273: }
8274:
8275: my $thisallowed='';
8276: my $statecond=0;
8277: my $courseprivid='';
8278:
8279: my $ownaccess;
8280: # Community Coordinator or Assistant Co-author browsing resource space.
8281: if (($priv eq 'bro') && ($env{'user.author'})) {
8282: if ($uri eq '') {
8283: $ownaccess = 1;
8284: } else {
8285: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
8286: my $udom = $env{'user.domain'};
8287: my $uname = $env{'user.name'};
8288: if ($uri =~ m{^\Q$udom\E/?$}) {
8289: $ownaccess = 1;
8290: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
8291: unless ($uri =~ m{\.\./}) {
8292: $ownaccess = 1;
8293: }
8294: } elsif (($udom ne 'public') && ($uname ne 'public')) {
8295: my $now = time;
8296: if ($uri =~ m{^([^/]+)/?$}) {
8297: my $adom = $1;
8298: foreach my $key (keys(%env)) {
8299: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
8300: my ($start,$end) = split(/\./,$env{$key});
8301: if (($now >= $start) && (!$end || $end > $now)) {
8302: $ownaccess = 1;
8303: last;
8304: }
8305: }
8306: }
8307: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
8308: my $adom = $1;
8309: my $aname = $2;
8310: foreach my $role ('ca','aa') {
8311: if ($env{"user.role.$role./$adom/$aname"}) {
8312: my ($start,$end) =
8313: split(/\./,$env{"user.role.$role./$adom/$aname"});
8314: if (($now >= $start) && (!$end || $end > $now)) {
8315: $ownaccess = 1;
8316: last;
8317: }
8318: }
8319: }
8320: }
8321: }
8322: }
8323: }
8324: }
8325:
8326: # Course
8327:
8328: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
8329: unless (($priv eq 'bro') && (!$ownaccess)) {
8330: $thisallowed.=$1;
8331: }
8332: }
8333:
8334: # Domain
8335:
8336: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
8337: =~/\Q$priv\E\&([^\:]*)/) {
8338: unless (($priv eq 'bro') && (!$ownaccess)) {
8339: $thisallowed.=$1;
8340: }
8341: }
8342:
8343: # User who is not author or co-author might still be able to edit
8344: # resource of an author in the domain (e.g., if Domain Coordinator).
8345: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
8346: (&allowed('mdc',$env{'request.course.id'}))) {
8347: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
8348: $thisallowed.=$1;
8349: }
8350: }
8351:
8352: # Course: uri itself is a course
8353: my $courseuri=$uri;
8354: $courseuri=~s/\_(\d)/\/$1/;
8355: $courseuri=~s/^([^\/])/\/$1/;
8356:
8357: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
8358: =~/\Q$priv\E\&([^\:]*)/) {
8359: if ($priv eq 'mip') {
8360: my $rem = $1;
8361: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
8362: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
8363: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8364: if ($cdom ne '') {
8365: my %passwdconf = &get_passwdconf($cdom);
8366: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
8367: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
8368: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
8369: my @inststatuses = split(':',$env{'environment.inststatus'});
8370: unless (@inststatuses) {
8371: @inststatuses = ('default');
8372: }
8373: foreach my $status (@inststatuses) {
8374: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
8375: $thisallowed.=$rem;
8376: }
8377: }
8378: }
8379: }
8380: }
8381: }
8382: }
8383: } else {
8384: unless (($priv eq 'bro') && (!$ownaccess)) {
8385: $thisallowed.=$1;
8386: }
8387: }
8388: }
8389:
8390: # URI is an uploaded document for this course, default permissions don't matter
8391: # not allowing 'edit' access (editupload) to uploaded course docs
8392: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
8393: $thisallowed='';
8394: my ($match)=&is_on_map($uri);
8395: if ($match) {
8396: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8397: =~/\Q$priv\E\&([^\:]*)/) {
8398: my $value = $1;
8399: my $deeplinkblock;
8400: unless ($nodeeplinkcheck) {
8401: $deeplinkblock = &deeplink_check($priv,$symb,$uri);
8402: }
8403: if ($deeplinkblock) {
8404: $thisallowed='D';
8405: } elsif ($noblockcheck) {
8406: $thisallowed.=$value;
8407: } else {
8408: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
8409: if (@blockers > 0) {
8410: $thisallowed = 'B';
8411: } else {
8412: $thisallowed.=$value;
8413: }
8414: }
8415: }
8416: } else {
8417: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
8418: if ($refuri) {
8419: if ($refuri =~ m|^/adm/|) {
8420: $thisallowed='F';
8421: } else {
8422: $refuri=&declutter($refuri);
8423: my ($match) = &is_on_map($refuri);
8424: if ($match) {
8425: my $deeplinkblock;
8426: unless ($nodeeplinkcheck) {
8427: $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8428: }
8429: if ($deeplinkblock) {
8430: $thisallowed='D';
8431: } elsif ($noblockcheck) {
8432: $thisallowed='F';
8433: } else {
8434: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
8435: if (@blockers > 0) {
8436: $thisallowed = 'B';
8437: } else {
8438: $thisallowed='F';
8439: }
8440: }
8441: }
8442: }
8443: }
8444: }
8445: }
8446:
8447: if ($priv eq 'bre'
8448: && $thisallowed ne 'F'
8449: && $thisallowed ne '2'
8450: && &is_portfolio_url($uri)) {
8451: $thisallowed = &portfolio_access($uri,$clientip);
8452: }
8453:
8454: # Full access at system, domain or course-wide level? Exit.
8455: if ($thisallowed=~/F/) {
8456: return 'F';
8457: }
8458:
8459: # If this is generating or modifying users, exit with special codes
8460:
8461: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
8462: if (($priv eq 'cca') || ($priv eq 'caa')) {
8463: my ($audom,$auname)=split('/',$uri);
8464: # no author name given, so this just checks on the general right to make a co-author in this domain
8465: unless ($auname) { return $thisallowed; }
8466: # an author name is given, so we are about to actually make a co-author for a certain account
8467: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8468: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8469: ($audom ne $env{'request.role.domain'}))) { return ''; }
8470: }
8471: return $thisallowed;
8472: }
8473: #
8474: # Gathered so far: system, domain and course wide privileges
8475: #
8476: # Course: See if uri or referer is an individual resource that is part of
8477: # the course
8478:
8479: if ($env{'request.course.id'}) {
8480:
8481: # If this is modifying password (internal auth) domains must match for user and user's role.
8482:
8483: if ($priv eq 'mip') {
8484: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
8485: return $thisallowed;
8486: } else {
8487: return '';
8488: }
8489: }
8490:
8491: $courseprivid=$env{'request.course.id'};
8492: if ($env{'request.course.sec'}) {
8493: $courseprivid.='/'.$env{'request.course.sec'};
8494: }
8495: $courseprivid=~s/\_/\//;
8496: my $checkreferer=1;
8497: my ($match,$cond)=&is_on_map($uri);
8498: if ($match) {
8499: $statecond=$cond;
8500: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
8501: =~/\Q$priv\E\&([^\:]*)/) {
8502: my $value = $1;
8503: if ($priv eq 'bre') {
8504: my $deeplinkblock;
8505: unless ($nodeeplinkcheck) {
8506: $deeplinkblock = &deeplink_check($priv,$symb,$uri);
8507: }
8508: if ($deeplinkblock) {
8509: $thisallowed = 'D';
8510: } elsif ($noblockcheck) {
8511: $thisallowed.=$value;
8512: } else {
8513: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
8514: if (@blockers > 0) {
8515: $thisallowed = 'B';
8516: } else {
8517: $thisallowed.=$value;
8518: }
8519: }
8520: } else {
8521: $thisallowed.=$value;
8522: }
8523: $checkreferer=0;
8524: }
8525: }
8526:
8527: if ($checkreferer) {
8528: my $refuri=$env{'httpref.'.$orguri};
8529: unless ($refuri) {
8530: foreach my $key (keys(%env)) {
8531: if ($key=~/^httpref\..*\*/) {
8532: my $pattern=$key;
8533: $pattern=~s/^httpref\.\/res\///;
8534: $pattern=~s/\*/\[\^\/\]\+/g;
8535: $pattern=~s/\//\\\//g;
8536: if ($orguri=~/$pattern/) {
8537: $refuri=$env{$key};
8538: }
8539: }
8540: }
8541: }
8542:
8543: if ($refuri) {
8544: $refuri=&declutter($refuri);
8545: my ($match,$cond)=&is_on_map($refuri);
8546: if ($match) {
8547: my $refstatecond=$cond;
8548: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
8549: =~/\Q$priv\E\&([^\:]*)/) {
8550: my $value = $1;
8551: if ($priv eq 'bre') {
8552: my $deeplinkblock;
8553: unless ($nodeeplinkcheck) {
8554: $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8555: }
8556: if ($deeplinkblock) {
8557: $thisallowed = 'D';
8558: } elsif ($noblockcheck) {
8559: $thisallowed.=$value;
8560: } else {
8561: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
8562: if (@blockers > 0) {
8563: $thisallowed = 'B';
8564: } else {
8565: $thisallowed.=$value;
8566: }
8567: }
8568: } else {
8569: $thisallowed.=$value;
8570: }
8571: $uri=$refuri;
8572: $statecond=$refstatecond;
8573: }
8574: }
8575: }
8576: }
8577: }
8578:
8579: #
8580: # Gathered now: all privileges that could apply, and condition number
8581: #
8582: #
8583: # Full or no access?
8584: #
8585:
8586: if ($thisallowed=~/F/) {
8587: return 'F';
8588: }
8589:
8590: unless ($thisallowed) {
8591: return '';
8592: }
8593:
8594: # Restrictions exist, deal with them
8595: #
8596: # C:according to course preferences
8597: # R:according to resource settings
8598: # L:unless locked
8599: # X:according to user session state
8600: #
8601:
8602: # Possibly locked functionality, check all courses
8603: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
8604: # Locks might take effect only after 10 minutes cache expiration for other
8605: # courses, and 2 minutes for current course, in which user has st or ta role
8606: # which is neither expired nor a future role (unless current course).
8607:
8608: my ($needlockcheck,$now,$crsonly);
8609: if ($thisallowed=~/L/) {
8610: $now = time;
8611: if ($priv eq 'bre') {
8612: if ($uri ne '') {
8613: if ($orguri =~ m{^/+res/}) {
8614: if ($uri =~ m{^lib/templates/}) {
8615: if ($env{'request.course.id'}) {
8616: $crsonly = 1;
8617: $needlockcheck = 1;
8618: }
8619: } else {
8620: $needlockcheck = 1;
8621: }
8622: } elsif ($env{'request.course.id'}) {
8623: my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
8624: if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
8625: ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
8626: $crsonly = 1;
8627: }
8628: $needlockcheck = 1;
8629: }
8630: }
8631: } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
8632: $needlockcheck = 1;
8633: }
8634: }
8635: if ($needlockcheck) {
8636: foreach my $envkey (keys(%env)) {
8637: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8638: my $courseid=$2;
8639: my $roleid=$1.'.'.$2;
8640: $courseid=~s/^\///;
8641: unless ($env{'request.role'} eq $roleid) {
8642: my ($start,$end) = split(/\./,$env{$envkey});
8643: next unless (($now >= $start) && (!$end || $end > $now));
8644: }
8645: my $expiretime=600;
8646: if ($env{'request.role'} eq $roleid) {
8647: $expiretime=120;
8648: }
8649: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8650: my $prefix='course.'.$cdom.'_'.$cnum.'.';
8651: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
8652: &coursedescription($courseid,{'freshen_cache' => 1});
8653: }
8654: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8655: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8656: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8657: &log($env{'user.domain'},$env{'user.name'},
8658: $env{'user.home'},
8659: 'Locked by res: '.$priv.' for '.$uri.' due to '.
8660: $cdom.'/'.$cnum.'/'.$csec.' expire '.
8661: $env{$prefix.'priv.'.$priv.'.lock.expire'});
8662: return '';
8663: }
8664: }
8665: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8666: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
8667: if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
8668: &log($env{'user.domain'},$env{'user.name'},
8669: $env{'user.home'},
8670: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
8671: $cdom.'/'.$cnum.'/'.$csec.' expire '.
8672: $env{$prefix.'priv.'.$priv.'.lock.expire'});
8673: return '';
8674: }
8675: }
8676: }
8677: }
8678: }
8679:
8680: #
8681: # Rest of the restrictions depend on selected course
8682: #
8683:
8684: unless ($env{'request.course.id'}) {
8685: if ($thisallowed eq 'A') {
8686: return 'A';
8687: } elsif ($thisallowed eq 'B') {
8688: return 'B';
8689: } else {
8690: return '1';
8691: }
8692: }
8693:
8694: #
8695: # Now user is definitely in a course
8696: #
8697:
8698:
8699: # Course preferences
8700:
8701: if ($thisallowed=~/C/) {
8702: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8703: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8704: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
8705: =~/\Q$rolecode\E/) {
8706: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
8707: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8708: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8709: $env{'request.course.id'});
8710: }
8711: return '';
8712: }
8713:
8714: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
8715: =~/\Q$unamedom\E/) {
8716: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
8717: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8718: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8719: $env{'request.course.id'});
8720: }
8721: return '';
8722: }
8723: }
8724:
8725: # Resource preferences
8726:
8727: if ($thisallowed=~/R/) {
8728: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8729: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
8730: if (($priv ne 'pch') && ($priv ne 'plc')) {
8731: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8732: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8733: }
8734: return '';
8735: }
8736: }
8737:
8738: # Restricted for deeplinked session?
8739:
8740: if ($env{'request.deeplink.login'}) {
8741: if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
8742: if (!$symb) { $symb=&symbread($uri,1); }
8743: if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
8744: return '';
8745: }
8746: }
8747: }
8748:
8749: # Restricted by state or randomout?
8750:
8751: if ($thisallowed=~/X/) {
8752: if ($env{'acc.randomout'}) {
8753: if (!$symb) { $symb=&symbread($uri,1); }
8754: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
8755: return '';
8756: }
8757: }
8758: if (&condval($statecond)) {
8759: return '2';
8760: } else {
8761: return '';
8762: }
8763: }
8764:
8765: if ($thisallowed eq 'A') {
8766: return 'A';
8767: } elsif ($thisallowed eq 'B') {
8768: return 'B';
8769: } elsif ($thisallowed eq 'D') {
8770: return 'D';
8771: }
8772: return 'F';
8773: }
8774:
8775: # ------------------------------------------- Check construction space access
8776:
8777: sub constructaccess {
8778: my ($url,$setpriv)=@_;
8779:
8780: # We do not allow editing of previous versions of files
8781: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8782:
8783: # Get username and domain from URL
8784: my ($ownername,$ownerdomain,$ownerhome);
8785:
8786: ($ownerdomain,$ownername) =
8787: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
8788:
8789: # The URL does not really point to any authorspace, forget it
8790: unless (($ownername) && ($ownerdomain)) { return ''; }
8791:
8792: # Now we need to see if the user has access to the authorspace of
8793: # $ownername at $ownerdomain
8794:
8795: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8796: # Real author for this?
8797: $ownerhome = $env{'user.home'};
8798: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8799: return ($ownername,$ownerdomain,$ownerhome);
8800: }
8801: } else {
8802: # Co-author for this?
8803: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
8804: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
8805: $ownerhome = &homeserver($ownername,$ownerdomain);
8806: return ($ownername,$ownerdomain,$ownerhome);
8807: }
8808: if ($env{'request.course.id'}) {
8809: if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
8810: ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
8811: if (&allowed('mdc',$env{'request.course.id'})) {
8812: $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
8813: return ($ownername,$ownerdomain,$ownerhome);
8814: }
8815: }
8816: }
8817: }
8818:
8819: # We don't have any access right now. If we are not possibly going to do anything about this,
8820: # we might as well leave
8821: unless ($setpriv) { return ''; }
8822:
8823: # Backdoor access?
8824: my $allowed=&allowed('eco',$ownerdomain);
8825: # Nope
8826: unless ($allowed) { return ''; }
8827: # Looks like we may have access, but could be locked by the owner of the construction space
8828: if ($allowed eq 'U') {
8829: my %blocked=&get('environment',['domcoord.author'],
8830: $ownerdomain,$ownername);
8831: # Is blocked by owner
8832: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
8833: }
8834: if (($allowed eq 'F') || ($allowed eq 'U')) {
8835: # Grant temporary access
8836: my $then=$env{'user.login.time'};
8837: my $update=$env{'user.update.time'};
8838: if (!$update) { $update = $then; }
8839: my $refresh=$env{'user.refresh.time'};
8840: if (!$refresh) { $refresh = $update; }
8841: my $now = time;
8842: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
8843: $now,'ca','constructaccess');
8844: $ownerhome = &homeserver($ownername,$ownerdomain);
8845: return($ownername,$ownerdomain,$ownerhome);
8846: }
8847: # No business here
8848: return '';
8849: }
8850:
8851: # ----------------------------------------------------------- Content Blocking
8852:
8853: {
8854: # Caches for faster Course Contents display where content blocking
8855: # is in operation (i.e., interval param set) for timed quiz.
8856: #
8857: # User for whom data are being temporarily cached.
8858: my $cacheduser='';
8859: # Course for which data are being temporarily cached.
8860: my $cachedcid='';
8861: # Cached blockers for this user (a hash of blocking items).
8862: my %cachedblockers=();
8863: # When the data were last cached.
8864: my $cachedlast='';
8865:
8866: sub load_all_blockers {
8867: my ($uname,$udom)=@_;
8868: if (($uname ne '') && ($udom ne '')) {
8869: if (($cacheduser eq $uname.':'.$udom) &&
8870: ($cachedcid eq $env{'request.course.id'}) &&
8871: (abs($cachedlast-time)<5)) {
8872: return;
8873: }
8874: }
8875: $cachedlast=time;
8876: $cacheduser=$uname.':'.$udom;
8877: $cachedcid=$env{'request.course.id'};
8878: %cachedblockers = &get_commblock_resources();
8879: return;
8880: }
8881:
8882: sub get_comm_blocks {
8883: my ($cdom,$cnum) = @_;
8884: if ($cdom eq '' || $cnum eq '') {
8885: return unless ($env{'request.course.id'});
8886: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8887: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8888: }
8889: my %commblocks;
8890: my $hashid=$cdom.'_'.$cnum;
8891: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8892: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8893: %commblocks = %{$blocksref};
8894: } else {
8895: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8896: my $cachetime = 600;
8897: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8898: }
8899: return %commblocks;
8900: }
8901:
8902: sub get_commblock_resources {
8903: my ($blocks) = @_;
8904: my %blockers = ();
8905: return %blockers unless ($env{'request.course.id'});
8906: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
8907: if ($env{'request.course.sec'}) {
8908: $courseurl .= '/'.$env{'request.course.sec'};
8909: }
8910: return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
8911: my %commblocks;
8912: if (ref($blocks) eq 'HASH') {
8913: %commblocks = %{$blocks};
8914: } else {
8915: %commblocks = &get_comm_blocks();
8916: }
8917: return %blockers unless (keys(%commblocks) > 0);
8918: my $navmap = Apache::lonnavmaps::navmap->new();
8919: return %blockers unless (ref($navmap));
8920: my $now = time;
8921: foreach my $block (keys(%commblocks)) {
8922: if ($block =~ /^(\d+)____(\d+)$/) {
8923: my ($start,$end) = ($1,$2);
8924: if ($start <= $now && $end >= $now) {
8925: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8926: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8927: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8928: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8929: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8930: }
8931: }
8932: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8933: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8934: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
8935: }
8936: }
8937: }
8938: }
8939: }
8940: } elsif ($block =~ /^firstaccess____(.+)$/) {
8941: my $item = $1;
8942: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8943: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8944: my (@interval,$mapname);
8945: my $type = 'map';
8946: if ($item eq 'course') {
8947: $type = 'course';
8948: @interval=&EXT("resource.0.interval");
8949: } else {
8950: if ($item =~ /___\d+___/) {
8951: $type = 'resource';
8952: @interval=&EXT("resource.0.interval",$item);
8953: } else {
8954: $mapname = &deversion($item);
8955: if (ref($navmap)) {
8956: my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
8957: @interval = ($timelimit,'map');
8958: }
8959: }
8960: }
8961: if ($interval[0] =~ /^(\d+)/) {
8962: my $timelimit = $1;
8963: my $first_access;
8964: if ($type eq 'resource') {
8965: $first_access=&get_first_access($interval[1],$item);
8966: } elsif ($type eq 'map') {
8967: $first_access=&get_first_access($interval[1],undef,$item);
8968: } else {
8969: $first_access=&get_first_access($interval[1]);
8970: }
8971: if ($first_access) {
8972: my $timesup = $first_access+$timelimit;
8973: if ($timesup > $now) {
8974: my $activeblock;
8975: if ($type eq 'resource') {
8976: if (ref($navmap)) {
8977: my $res = $navmap->getBySymb($item);
8978: if ($res->answerable()) {
8979: $activeblock = 1;
8980: }
8981: }
8982: } elsif ($type eq 'map') {
8983: my $mapsymb = &symbread($mapname,1);
8984: if (($mapsymb) && (ref($navmap))) {
8985: my $mapres = $navmap->getBySymb($mapsymb);
8986: if (ref($mapres)) {
8987: my $first = $mapres->map_start();
8988: my $finish = $mapres->map_finish();
8989: my $it = $navmap->getIterator($first,$finish,undef,0,0);
8990: if (ref($it)) {
8991: my $res;
8992: while ($res = $it->next(undef,1)) {
8993: next unless (ref($res));
8994: my $symb = $res->symb();
8995: next if (($symb eq $mapsymb) || ($symb eq ''));
8996: @interval=&EXT("resource.0.interval",$symb);
8997: if ($interval[1] eq 'map') {
8998: if ($res->answerable()) {
8999: $activeblock = 1;
9000: last;
9001: }
9002: }
9003: }
9004: }
9005: }
9006: }
9007: }
9008: if ($activeblock) {
9009: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
9010: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
9011: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
9012: }
9013: }
9014: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
9015: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
9016: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
9017: }
9018: }
9019: }
9020: }
9021: }
9022: }
9023: }
9024: }
9025: }
9026: }
9027: return %blockers;
9028: }
9029:
9030: sub has_comm_blocking {
9031: my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
9032: my @blockers;
9033: return unless ($env{'request.course.id'});
9034: return unless ($priv eq 'bre');
9035: return if ($env{'request.state'} eq 'construct');
9036: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
9037: if ($env{'request.course.sec'}) {
9038: $courseurl .= '/'.$env{'request.course.sec'};
9039: }
9040: return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
9041: my %blockinfo;
9042: if (ref($blocks) eq 'HASH') {
9043: %blockinfo = &get_commblock_resources($blocks);
9044: } else {
9045: &load_all_blockers($env{'user.name'},$env{'user.domain'});
9046: %blockinfo = %cachedblockers;
9047: }
9048: return unless (keys(%blockinfo) > 0);
9049: my (%possibles,@symbs);
9050: if (!$symb) {
9051: $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
9052: }
9053: if ($symb) {
9054: @symbs = ($symb);
9055: } elsif (keys(%possibles)) {
9056: @symbs = keys(%possibles);
9057: }
9058: my $noblock;
9059: foreach my $symb (@symbs) {
9060: last if ($noblock);
9061: my ($map,$resid,$resurl)=&decode_symb($symb);
9062: foreach my $block (keys(%blockinfo)) {
9063: if ($block =~ /^firstaccess____(.+)$/) {
9064: my $item = $1;
9065: unless ($blocked) {
9066: if (($item eq $map) || ($item eq $symb)) {
9067: $noblock = 1;
9068: last;
9069: }
9070: }
9071: }
9072: if (ref($blockinfo{$block}) eq 'HASH') {
9073: if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
9074: if ($blockinfo{$block}{'resources'}{$symb}) {
9075: unless (grep(/^\Q$block\E$/,@blockers)) {
9076: push(@blockers,$block);
9077: }
9078: }
9079: }
9080: if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
9081: if ($blockinfo{$block}{'maps'}{$map}) {
9082: unless (grep(/^\Q$block\E$/,@blockers)) {
9083: push(@blockers,$block);
9084: }
9085: }
9086: }
9087: }
9088: }
9089: }
9090: unless ($noblock) {
9091: return @blockers;
9092: }
9093: return;
9094: }
9095: }
9096:
9097: sub deeplink_check {
9098: my ($priv,$symb,$uri) = @_;
9099: return unless ($env{'request.course.id'});
9100: return unless ($priv eq 'bre');
9101: return if ($env{'request.state'} eq 'construct');
9102: return if ($env{'request.role.adv'});
9103: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9104: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9105: my (%possibles,@symbs);
9106: if (!$symb) {
9107: $symb = &symbread($uri,1,1,1,\%possibles);
9108: }
9109: if ($symb) {
9110: @symbs = ($symb);
9111: } elsif (keys(%possibles)) {
9112: @symbs = keys(%possibles);
9113: }
9114:
9115: my ($deeplink_symb,$allow);
9116: if ($env{'request.deeplink.login'}) {
9117: $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
9118: }
9119: foreach my $symb (@symbs) {
9120: last if ($allow);
9121: my $deeplink = &EXT("resource.0.deeplink",$symb);
9122: if ($deeplink eq '') {
9123: $allow = 1;
9124: } else {
9125: my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
9126: if ($state ne 'only') {
9127: $allow = 1;
9128: } else {
9129: my $check_deeplink_entry;
9130: if ($protect ne 'none') {
9131: my ($acctype,$item) = split(/:/,$protect);
9132: if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
9133: if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
9134: $check_deeplink_entry = 1
9135: }
9136: } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
9137: if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
9138: $check_deeplink_entry = 1;
9139: }
9140: } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
9141: if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
9142: $check_deeplink_entry = 1;
9143: }
9144: }
9145: }
9146: if (($protect eq 'none') || ($check_deeplink_entry)) {
9147: if ($scope eq 'res') {
9148: if ($symb eq $deeplink_symb) {
9149: $allow = 1;
9150: }
9151: } elsif (($scope eq 'map') || ($scope eq 'rec')) {
9152: my ($map_from_symb,$map_from_login);
9153: $map_from_symb = &deversion((&decode_symb($symb))[0]);
9154: if ($deeplink_symb =~ /\.(page|sequence)$/) {
9155: $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
9156: } else {
9157: $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
9158: }
9159: if (($map_from_symb) && ($map_from_login)) {
9160: if ($map_from_symb eq $map_from_login) {
9161: $allow = 1;
9162: } elsif ($scope eq 'rec') {
9163: my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
9164: if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
9165: $allow = 1;
9166: }
9167: }
9168: }
9169: }
9170: }
9171: }
9172: }
9173: }
9174: return if ($allow);
9175: return 1;
9176: }
9177:
9178: # -------------------------------- Deversion and split uri into path an filename
9179:
9180: #
9181: # Removes the version from a URI and
9182: # splits it in to its filename and path to the filename.
9183: # Seems like File::Basename could have done this more clearly.
9184: # Parameters:
9185: # $uri - input URI
9186: # Returns:
9187: # Two element list consisting of
9188: # $pathname - the URI up to and excluding the trailing /
9189: # $filename - The part of the URI following the last /
9190: # NOTE:
9191: # Another realization of this is simply:
9192: # use File::Basename;
9193: # ...
9194: # $uri = shift;
9195: # $filename = basename($uri);
9196: # $path = dirname($uri);
9197: # return ($filename, $path);
9198: #
9199: # The implementation below is probably faster however.
9200: #
9201: sub split_uri_for_cond {
9202: my $uri=&deversion(&declutter(shift));
9203: my @uriparts=split(/\//,$uri);
9204: my $filename=pop(@uriparts);
9205: my $pathname=join('/',@uriparts);
9206: return ($pathname,$filename);
9207: }
9208: # --------------------------------------------------- Is a resource on the map?
9209:
9210: sub is_on_map {
9211: my ($pathname,$filename) = &split_uri_for_cond(shift);
9212: #Trying to find the conditional for the file
9213: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
9214: /\&\Q$filename\E\:([\d\|]+)\&/);
9215: if ($match) {
9216: return (1,$1);
9217: } else {
9218: return (0,0);
9219: }
9220: }
9221:
9222: # --------------------------------------------------------- Get symb from alias
9223:
9224: sub get_symb_from_alias {
9225: my $symb=shift;
9226: my ($map,$resid,$url)=&decode_symb($symb);
9227: # Already is a symb
9228: if ($url) { return $symb; }
9229: # Must be an alias
9230: my $aliassymb='';
9231: my %bighash;
9232: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9233: &GDBM_READER(),0640)) {
9234: my $rid=$bighash{'mapalias_'.$symb};
9235: if ($rid) {
9236: my ($mapid,$resid)=split(/\./,$rid);
9237: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
9238: $resid,$bighash{'src_'.$rid});
9239: }
9240: untie %bighash;
9241: }
9242: return $aliassymb;
9243: }
9244:
9245: # ----------------------------------------------------------------- Define Role
9246:
9247: sub definerole {
9248: if (allowed('mcr','/')) {
9249: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
9250: foreach my $role (split(':',$sysrole)) {
9251: my ($crole,$cqual)=split(/\&/,$role);
9252: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
9253: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
9254: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
9255: return "refused:s:$crole&$cqual";
9256: }
9257: }
9258: }
9259: foreach my $role (split(':',$domrole)) {
9260: my ($crole,$cqual)=split(/\&/,$role);
9261: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
9262: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
9263: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
9264: return "refused:d:$crole&$cqual";
9265: }
9266: }
9267: }
9268: foreach my $role (split(':',$courole)) {
9269: my ($crole,$cqual)=split(/\&/,$role);
9270: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
9271: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
9272: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
9273: return "refused:c:$crole&$cqual";
9274: }
9275: }
9276: }
9277: my $uhome;
9278: if (($uname ne '') && ($udom ne '')) {
9279: $uhome = &homeserver($uname,$udom);
9280: return $uhome if ($uhome eq 'no_host');
9281: } else {
9282: $uname = $env{'user.name'};
9283: $udom = $env{'user.domain'};
9284: $uhome = $env{'user.home'};
9285: }
9286: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
9287: "$udom:$uname:rolesdef_$rolename=".
9288: escape($sysrole.'_'.$domrole.'_'.$courole);
9289: return reply($command,$uhome);
9290: } else {
9291: return 'refused';
9292: }
9293: }
9294:
9295: # ---------------- Make a metadata query against the network of library servers
9296:
9297: sub metadata_query {
9298: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
9299: my %rhash;
9300: my %libserv = &all_library();
9301: my @server_list = (defined($server_array) ? @$server_array
9302: : keys(%libserv) );
9303: for my $server (@server_list) {
9304: my $domains = '';
9305: if (ref($domains_hash) eq 'HASH') {
9306: $domains = $domains_hash->{$server};
9307: }
9308: unless ($custom or $customshow) {
9309: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
9310: $rhash{$server}=$reply;
9311: }
9312: else {
9313: my $reply=&reply("querysend:".&escape($query).':'.
9314: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
9315: $server);
9316: $rhash{$server}=$reply;
9317: }
9318: }
9319: return \%rhash;
9320: }
9321:
9322: # ----------------------------------------- Send log queries and wait for reply
9323:
9324: sub log_query {
9325: my ($uname,$udom,$query,%filters)=@_;
9326: my $uhome=&homeserver($uname,$udom);
9327: if ($uhome eq 'no_host') { return 'error: no_host'; }
9328: my $uhost=&hostname($uhome);
9329: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
9330: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
9331: $uhome);
9332: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
9333: return get_query_reply($queryid);
9334: }
9335:
9336: # -------------------------- Update MySQL table for portfolio file
9337:
9338: sub update_portfolio_table {
9339: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
9340: if ($group ne '') {
9341: $file_name =~s /^\Q$group\E//;
9342: }
9343: my $homeserver = &homeserver($uname,$udom);
9344: my $queryid=
9345: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
9346: ':'.&escape($file_name).':'.$action,$homeserver);
9347: my $reply = &get_query_reply($queryid);
9348: return $reply;
9349: }
9350:
9351: # -------------------------- Update MySQL allusers table
9352:
9353: sub update_allusers_table {
9354: my ($uname,$udom,$names) = @_;
9355: my $homeserver = &homeserver($uname,$udom);
9356: my $queryid=
9357: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
9358: 'lastname='.&escape($names->{'lastname'}).'%%'.
9359: 'firstname='.&escape($names->{'firstname'}).'%%'.
9360: 'middlename='.&escape($names->{'middlename'}).'%%'.
9361: 'generation='.&escape($names->{'generation'}).'%%'.
9362: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
9363: 'id='.&escape($names->{'id'}),$homeserver);
9364: return;
9365: }
9366:
9367: # ------- Request retrieval of institutional classlists for course(s)
9368:
9369: sub fetch_enrollment_query {
9370: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
9371: my ($homeserver,$sleep,$loopmax);
9372: my $maxtries = 1;
9373: if ($context eq 'automated') {
9374: $homeserver = $perlvar{'lonHostID'};
9375: $sleep = 2;
9376: $loopmax = 100;
9377: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
9378: } else {
9379: $homeserver = &homeserver($cnum,$dom);
9380: }
9381: my $host=&hostname($homeserver);
9382: my $cmd = '';
9383: foreach my $affiliate (keys(%{$affiliatesref})) {
9384: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
9385: }
9386: $cmd =~ s/%%$//;
9387: $cmd = &escape($cmd);
9388: my $query = 'fetchenrollment';
9389: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
9390: unless ($queryid=~/^\Q$host\E\_/) {
9391: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
9392: return 'error: '.$queryid;
9393: }
9394: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
9395: my $tries = 1;
9396: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9397: $reply = &get_query_reply($queryid,$sleep,$loopmax);
9398: $tries ++;
9399: }
9400: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9401: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9402: } else {
9403: my @responses = split(/:/,$reply);
9404: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
9405: foreach my $line (@responses) {
9406: my ($key,$value) = split(/=/,$line,2);
9407: $$replyref{$key} = $value;
9408: }
9409: } else {
9410: my $pathname = LONCAPA::tempdir();
9411: foreach my $line (@responses) {
9412: my ($key,$value) = split(/=/,$line);
9413: $$replyref{$key} = $value;
9414: if ($value > 0) {
9415: foreach my $item (@{$$affiliatesref{$key}}) {
9416: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
9417: my $destname = $pathname.'/'.$filename;
9418: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
9419: if ($xml_classlist =~ /^error/) {
9420: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
9421: } else {
9422: if ( open(FILE,">",$destname) ) {
9423: print FILE &unescape($xml_classlist);
9424: close(FILE);
9425: } else {
9426: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
9427: }
9428: }
9429: }
9430: }
9431: }
9432: }
9433: return 'ok';
9434: }
9435: return 'error';
9436: }
9437:
9438: sub get_query_reply {
9439: my ($queryid,$sleep,$loopmax) = @_;
9440: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
9441: $sleep = 0.2;
9442: }
9443: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
9444: $loopmax = 100;
9445: }
9446: my $replyfile=LONCAPA::tempdir().$queryid;
9447: my $reply='';
9448: for (1..$loopmax) {
9449: sleep($sleep);
9450: if (-e $replyfile.'.end') {
9451: if (open(my $fh,"<",$replyfile)) {
9452: $reply = join('',<$fh>);
9453: close($fh);
9454: } else { return 'error: reply_file_error'; }
9455: return &unescape($reply);
9456: }
9457: }
9458: return 'timeout:'.$queryid;
9459: }
9460:
9461: sub courselog_query {
9462: #
9463: # possible filters:
9464: # url: url or symb
9465: # username
9466: # domain
9467: # action: view, submit, grade
9468: # start: timestamp
9469: # end: timestamp
9470: #
9471: my (%filters)=@_;
9472: unless ($env{'request.course.id'}) { return 'no_course'; }
9473: if ($filters{'url'}) {
9474: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
9475: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
9476: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
9477: }
9478: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
9479: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
9480: return &log_query($cname,$cdom,'courselog',%filters);
9481: }
9482:
9483: sub userlog_query {
9484: #
9485: # possible filters:
9486: # action: log check role
9487: # start: timestamp
9488: # end: timestamp
9489: #
9490: my ($uname,$udom,%filters)=@_;
9491: return &log_query($uname,$udom,'userlog',%filters);
9492: }
9493:
9494: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
9495:
9496: sub auto_run {
9497: my ($cnum,$cdom) = @_;
9498: my $response = 0;
9499: my $settings;
9500: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
9501: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
9502: $settings = $domconfig{'autoenroll'};
9503: if ($settings->{'run'} eq '1') {
9504: $response = 1;
9505: }
9506: } else {
9507: my $homeserver;
9508: if (&is_course($cdom,$cnum)) {
9509: $homeserver = &homeserver($cnum,$cdom);
9510: } else {
9511: $homeserver = &domain($cdom,'primary');
9512: }
9513: if ($homeserver ne 'no_host') {
9514: $response = &reply('autorun:'.$cdom,$homeserver);
9515: }
9516: }
9517: return $response;
9518: }
9519:
9520: sub auto_get_sections {
9521: my ($cnum,$cdom,$inst_coursecode) = @_;
9522: my $homeserver;
9523: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9524: $homeserver = &homeserver($cnum,$cdom);
9525: }
9526: if (!defined($homeserver)) {
9527: if ($cdom =~ /^$match_domain$/) {
9528: $homeserver = &domain($cdom,'primary');
9529: }
9530: }
9531: my @secs;
9532: if (defined($homeserver)) {
9533: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
9534: unless ($response eq 'refused') {
9535: @secs = split(/:/,$response);
9536: }
9537: }
9538: return @secs;
9539: }
9540:
9541: sub auto_new_course {
9542: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
9543: my $homeserver = &homeserver($cnum,$cdom);
9544: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
9545: return $response;
9546: }
9547:
9548: sub auto_validate_courseID {
9549: my ($cnum,$cdom,$inst_course_id) = @_;
9550: my $homeserver = &homeserver($cnum,$cdom);
9551: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
9552: return $response;
9553: }
9554:
9555: sub auto_validate_instcode {
9556: my ($cnum,$cdom,$instcode,$owner) = @_;
9557: my ($homeserver,$response);
9558: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9559: $homeserver = &homeserver($cnum,$cdom);
9560: }
9561: if (!defined($homeserver)) {
9562: if ($cdom =~ /^$match_domain$/) {
9563: $homeserver = &domain($cdom,'primary');
9564: }
9565: }
9566: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
9567: &escape($instcode).':'.&escape($owner),$homeserver));
9568: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
9569: return ($outcome,$description,$defaultcredits);
9570: }
9571:
9572: sub auto_validate_inst_crosslist {
9573: my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
9574: my ($homeserver,$response);
9575: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9576: $homeserver = &homeserver($cnum,$cdom);
9577: }
9578: if (!defined($homeserver)) {
9579: if ($cdom =~ /^$match_domain$/) {
9580: $homeserver = &domain($cdom,'primary');
9581: }
9582: }
9583: unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
9584: $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
9585: &escape($instcode).':'.&escape($inst_xlist).':'.
9586: &escape($coowner),$homeserver);
9587: }
9588: return $response;
9589: }
9590:
9591: sub auto_create_password {
9592: my ($cnum,$cdom,$authparam,$udom) = @_;
9593: my ($homeserver,$response);
9594: my $create_passwd = 0;
9595: my $authchk = '';
9596: if ($udom =~ /^$match_domain$/) {
9597: $homeserver = &domain($udom,'primary');
9598: }
9599: if ($homeserver eq '') {
9600: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9601: $homeserver = &homeserver($cnum,$cdom);
9602: }
9603: }
9604: if ($homeserver eq '') {
9605: $authchk = 'nodomain';
9606: } else {
9607: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
9608: if ($response eq 'refused') {
9609: $authchk = 'refused';
9610: } else {
9611: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
9612: }
9613: }
9614: return ($authparam,$create_passwd,$authchk);
9615: }
9616:
9617: sub auto_photo_permission {
9618: my ($cnum,$cdom,$students) = @_;
9619: my $homeserver = &homeserver($cnum,$cdom);
9620: my ($outcome,$perm_reqd,$conditions) =
9621: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
9622: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9623: return (undef,undef);
9624: }
9625: return ($outcome,$perm_reqd,$conditions);
9626: }
9627:
9628: sub auto_checkphotos {
9629: my ($uname,$udom,$pid) = @_;
9630: my $homeserver = &homeserver($uname,$udom);
9631: my ($result,$resulttype);
9632: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
9633: &escape($uname).':'.&escape($pid),
9634: $homeserver));
9635: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9636: return (undef,undef);
9637: }
9638: if ($outcome) {
9639: ($result,$resulttype) = split(/:/,$outcome);
9640: }
9641: return ($result,$resulttype);
9642: }
9643:
9644: sub auto_photochoice {
9645: my ($cnum,$cdom) = @_;
9646: my $homeserver = &homeserver($cnum,$cdom);
9647: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
9648: &escape($cdom),
9649: $homeserver)));
9650: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9651: return (undef,undef);
9652: }
9653: return ($update,$comment);
9654: }
9655:
9656: sub auto_photoupdate {
9657: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9658: my $homeserver = &homeserver($cnum,$dom);
9659: my $host=&hostname($homeserver);
9660: my $cmd = '';
9661: my $maxtries = 1;
9662: foreach my $affiliate (keys(%{$affiliatesref})) {
9663: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
9664: }
9665: $cmd =~ s/%%$//;
9666: $cmd = &escape($cmd);
9667: my $query = 'institutionalphotos';
9668: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9669: unless ($queryid=~/^\Q$host\E\_/) {
9670: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9671: return 'error: '.$queryid;
9672: }
9673: my $reply = &get_query_reply($queryid);
9674: my $tries = 1;
9675: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9676: $reply = &get_query_reply($queryid);
9677: $tries ++;
9678: }
9679: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9680: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9681: } else {
9682: my @responses = split(/:/,$reply);
9683: my $outcome = shift(@responses);
9684: foreach my $item (@responses) {
9685: my ($key,$value) = split(/=/,$item);
9686: $$photo{$key} = $value;
9687: }
9688: return $outcome;
9689: }
9690: return 'error';
9691: }
9692:
9693: sub auto_instcode_format {
9694: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9695: $cat_order) = @_;
9696: my $courses = '';
9697: my @homeservers;
9698: if ($caller eq 'global') {
9699: my %servers = &get_servers($codedom,'library');
9700: foreach my $tryserver (keys(%servers)) {
9701: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9702: push(@homeservers,$tryserver);
9703: }
9704: }
9705: } elsif ($caller eq 'requests') {
9706: if ($codedom =~ /^$match_domain$/) {
9707: my $chome = &domain($codedom,'primary');
9708: unless ($chome eq 'no_host') {
9709: push(@homeservers,$chome);
9710: }
9711: }
9712: } else {
9713: push(@homeservers,&homeserver($caller,$codedom));
9714: }
9715: foreach my $code (keys(%{$instcodes})) {
9716: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
9717: }
9718: chop($courses);
9719: my $ok_response = 0;
9720: my $response;
9721: while (@homeservers > 0 && $ok_response == 0) {
9722: my $server = shift(@homeservers);
9723: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9724: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9725: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
9726: split(/:/,$response);
9727: %{$codes} = (%{$codes},&str2hash($codes_str));
9728: push(@{$codetitles},&str2array($codetitles_str));
9729: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9730: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9731: $ok_response = 1;
9732: }
9733: }
9734: if ($ok_response) {
9735: return 'ok';
9736: } else {
9737: return $response;
9738: }
9739: }
9740:
9741: sub auto_instcode_defaults {
9742: my ($domain,$returnhash,$code_order) = @_;
9743: my @homeservers;
9744:
9745: my %servers = &get_servers($domain,'library');
9746: foreach my $tryserver (keys(%servers)) {
9747: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9748: push(@homeservers,$tryserver);
9749: }
9750: }
9751:
9752: my $response;
9753: foreach my $server (@homeservers) {
9754: $response=&reply('autoinstcodedefaults:'.$domain,$server);
9755: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9756:
9757: foreach my $pair (split(/\&/,$response)) {
9758: my ($name,$value)=split(/\=/,$pair);
9759: if ($name eq 'code_order') {
9760: @{$code_order} = split(/\&/,&unescape($value));
9761: } else {
9762: $returnhash->{&unescape($name)}=&unescape($value);
9763: }
9764: }
9765: return 'ok';
9766: }
9767:
9768: return $response;
9769: }
9770:
9771: sub auto_possible_instcodes {
9772: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9773: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9774: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9775: return;
9776: }
9777: my (@homeservers,$uhome);
9778: if (defined(&domain($domain,'primary'))) {
9779: $uhome=&domain($domain,'primary');
9780: push(@homeservers,&domain($domain,'primary'));
9781: } else {
9782: my %servers = &get_servers($domain,'library');
9783: foreach my $tryserver (keys(%servers)) {
9784: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9785: push(@homeservers,$tryserver);
9786: }
9787: }
9788: }
9789: my $response;
9790: foreach my $server (@homeservers) {
9791: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9792: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9793: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9794: split(':',$response);
9795: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9796: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
9797: foreach my $item (split('&',$cat_title)) {
9798: my ($name,$value)=split('=',$item);
9799: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
9800: }
9801: foreach my $item (split('&',$cat_order)) {
9802: my ($name,$value)=split('=',$item);
9803: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
9804: }
9805: return 'ok';
9806: }
9807: return $response;
9808: }
9809:
9810: sub auto_courserequest_checks {
9811: my ($dom) = @_;
9812: my ($homeserver,%validations);
9813: if ($dom =~ /^$match_domain$/) {
9814: $homeserver = &domain($dom,'primary');
9815: }
9816: unless ($homeserver eq 'no_host') {
9817: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9818: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9819: my @items = split(/&/,$response);
9820: foreach my $item (@items) {
9821: my ($key,$value) = split('=',$item);
9822: $validations{&unescape($key)} = &thaw_unescape($value);
9823: }
9824: }
9825: }
9826: return %validations;
9827: }
9828:
9829: sub auto_courserequest_validation {
9830: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
9831: my ($homeserver,$response);
9832: if ($dom =~ /^$match_domain$/) {
9833: $homeserver = &domain($dom,'primary');
9834: }
9835: unless ($homeserver eq 'no_host') {
9836: my $customdata;
9837: if (ref($custominfo) eq 'HASH') {
9838: $customdata = &freeze_escape($custominfo);
9839: }
9840: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
9841: ':'.&escape($crstype).':'.&escape($inststatuslist).
9842: ':'.&escape($instcode).':'.&escape($instseclist).':'.
9843: $customdata,$homeserver));
9844: }
9845: return $response;
9846: }
9847:
9848: sub auto_validate_class_sec {
9849: my ($cdom,$cnum,$owners,$inst_class) = @_;
9850: my $homeserver = &homeserver($cnum,$cdom);
9851: my $ownerlist;
9852: if (ref($owners) eq 'ARRAY') {
9853: $ownerlist = join(',',@{$owners});
9854: } else {
9855: $ownerlist = $owners;
9856: }
9857: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
9858: &escape($ownerlist).':'.$cdom,$homeserver);
9859: return $response;
9860: }
9861:
9862: sub auto_instsec_reformat {
9863: my ($cdom,$action,$instsecref) = @_;
9864: return unless(($action eq 'clutter') || ($action eq 'declutter'));
9865: my @homeservers;
9866: if (defined(&domain($cdom,'primary'))) {
9867: push(@homeservers,&domain($cdom,'primary'));
9868: } else {
9869: my %servers = &get_servers($cdom,'library');
9870: foreach my $tryserver (keys(%servers)) {
9871: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9872: push(@homeservers,$tryserver);
9873: }
9874: }
9875: }
9876: my $response;
9877: my %reformatted = %{$instsecref};
9878: foreach my $server (@homeservers) {
9879: if (ref($instsecref) eq 'HASH') {
9880: my $info = &freeze_escape($instsecref);
9881: my $response=&reply('autoinstsecreformat:'.$cdom.':'.
9882: $action.':'.$info,$server);
9883: next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
9884: my @items = split(/&/,$response);
9885: foreach my $item (@items) {
9886: my ($key,$value) = split(/=/,$item);
9887: $reformatted{&unescape($key)} = &thaw_unescape($value);
9888: }
9889: }
9890: }
9891: return %reformatted;
9892: }
9893:
9894: sub auto_validate_instclasses {
9895: my ($cdom,$cnum,$owners,$classesref) = @_;
9896: my ($homeserver,%validations);
9897: $homeserver = &homeserver($cnum,$cdom);
9898: unless ($homeserver eq 'no_host') {
9899: my $ownerlist;
9900: if (ref($owners) eq 'ARRAY') {
9901: $ownerlist = join(',',@{$owners});
9902: } else {
9903: $ownerlist = $owners;
9904: }
9905: if (ref($classesref) eq 'HASH') {
9906: my $classes = &freeze_escape($classesref);
9907: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
9908: ':'.$cdom.':'.$classes,$homeserver);
9909: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9910: my @items = split(/&/,$response);
9911: foreach my $item (@items) {
9912: my ($key,$value) = split('=',$item);
9913: $validations{&unescape($key)} = &thaw_unescape($value);
9914: }
9915: }
9916: }
9917: }
9918: return %validations;
9919: }
9920:
9921: sub auto_crsreq_update {
9922: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
9923: $code,$accessstart,$accessend,$inbound) = @_;
9924: my ($homeserver,%crsreqresponse);
9925: if ($cdom =~ /^$match_domain$/) {
9926: $homeserver = &domain($cdom,'primary');
9927: }
9928: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9929: my $info;
9930: if (ref($inbound) eq 'HASH') {
9931: $info = &freeze_escape($inbound);
9932: }
9933: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
9934: ':'.&escape($action).':'.&escape($ownername).':'.
9935: &escape($ownerdomain).':'.&escape($fullname).':'.
9936: &escape($title).':'.&escape($code).':'.
9937: &escape($accessstart).':'.&escape($accessend).':'.$info,
9938: $homeserver);
9939: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9940: my @items = split(/&/,$response);
9941: foreach my $item (@items) {
9942: my ($key,$value) = split('=',$item);
9943: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
9944: }
9945: }
9946: }
9947: return \%crsreqresponse;
9948: }
9949:
9950: sub auto_export_grades {
9951: my ($cdom,$cnum,$inforef,$gradesref) = @_;
9952: my ($homeserver,%exportresponse);
9953: if ($cdom =~ /^$match_domain$/) {
9954: $homeserver = &domain($cdom,'primary');
9955: }
9956: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9957: my $info;
9958: if (ref($inforef) eq 'HASH') {
9959: $info = &freeze_escape($inforef);
9960: }
9961: if (ref($gradesref) eq 'HASH') {
9962: my $grades = &freeze_escape($gradesref);
9963: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
9964: $info.':'.$grades,$homeserver);
9965: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
9966: my @items = split(/&/,$response);
9967: foreach my $item (@items) {
9968: my ($key,$value) = split('=',$item);
9969: $exportresponse{&unescape($key)} = &thaw_unescape($value);
9970: }
9971: }
9972: }
9973: }
9974: return \%exportresponse;
9975: }
9976:
9977: sub check_instcode_cloning {
9978: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
9979: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9980: return;
9981: }
9982: my $canclone;
9983: if (@{$code_order} > 0) {
9984: my $instcoderegexp ='^';
9985: my @clonecodes = split(/\&/,$cloner);
9986: foreach my $item (@{$code_order}) {
9987: if (grep(/^\Q$item\E=/,@clonecodes)) {
9988: foreach my $pair (@clonecodes) {
9989: my ($key,$val) = split(/\=/,$pair,2);
9990: $val = &unescape($val);
9991: if ($key eq $item) {
9992: $instcoderegexp .= '('.$val.')';
9993: last;
9994: }
9995: }
9996: } else {
9997: $instcoderegexp .= $codedefaults->{$item};
9998: }
9999: }
10000: $instcoderegexp .= '$';
10001: my (@from,@to);
10002: eval {
10003: (@from) = ($clonefromcode =~ /$instcoderegexp/);
10004: (@to) = ($clonetocode =~ /$instcoderegexp/);
10005: };
10006: if ((@from > 0) && (@to > 0)) {
10007: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10008: if (!@diffs) {
10009: $canclone = 1;
10010: }
10011: }
10012: }
10013: return $canclone;
10014: }
10015:
10016: sub default_instcode_cloning {
10017: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
10018: my (%codedefaults,@code_order,$canclone);
10019: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
10020: %codedefaults = %{$codedefaultsref};
10021: @code_order = @{$codeorderref};
10022: } elsif ($clonedom) {
10023: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
10024: }
10025: if (($domdefclone) && (@code_order)) {
10026: my @clonecodes = split(/\+/,$domdefclone);
10027: my $instcoderegexp ='^';
10028: foreach my $item (@code_order) {
10029: if (grep(/^\Q$item\E$/,@clonecodes)) {
10030: $instcoderegexp .= '('.$codedefaults{$item}.')';
10031: } else {
10032: $instcoderegexp .= $codedefaults{$item};
10033: }
10034: }
10035: $instcoderegexp .= '$';
10036: my (@from,@to);
10037: eval {
10038: (@from) = ($clonefromcode =~ /$instcoderegexp/);
10039: (@to) = ($clonetocode =~ /$instcoderegexp/);
10040: };
10041: if ((@from > 0) && (@to > 0)) {
10042: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10043: if (!@diffs) {
10044: $canclone = 1;
10045: }
10046: }
10047: }
10048: return $canclone;
10049: }
10050:
10051: # ------------------------------------------------------- Course Group routines
10052:
10053: sub get_coursegroups {
10054: my ($cdom,$cnum,$group,$namespace) = @_;
10055: return(&dump($namespace,$cdom,$cnum,$group));
10056: }
10057:
10058: sub modify_coursegroup {
10059: my ($cdom,$cnum,$groupsettings) = @_;
10060: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
10061: }
10062:
10063: sub toggle_coursegroup_status {
10064: my ($cdom,$cnum,$group,$action) = @_;
10065: my ($from_namespace,$to_namespace);
10066: if ($action eq 'delete') {
10067: $from_namespace = 'coursegroups';
10068: $to_namespace = 'deleted_groups';
10069: } else {
10070: $from_namespace = 'deleted_groups';
10071: $to_namespace = 'coursegroups';
10072: }
10073: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
10074: if (my $tmp = &error(%curr_group)) {
10075: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
10076: return ('read error',$tmp);
10077: } else {
10078: my %savedsettings = %curr_group;
10079: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
10080: my $deloutcome;
10081: if ($result eq 'ok') {
10082: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
10083: } else {
10084: return ('write error',$result);
10085: }
10086: if ($deloutcome eq 'ok') {
10087: return 'ok';
10088: } else {
10089: return ('delete error',$deloutcome);
10090: }
10091: }
10092: }
10093:
10094: sub modify_group_roles {
10095: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
10096: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
10097: my $role = 'gr/'.&escape($userprivs);
10098: my ($uname,$udom) = split(/:/,$user);
10099: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
10100: if ($result eq 'ok') {
10101: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
10102: }
10103: return $result;
10104: }
10105:
10106: sub modify_coursegroup_membership {
10107: my ($cdom,$cnum,$membership) = @_;
10108: my $result = &put('groupmembership',$membership,$cdom,$cnum);
10109: return $result;
10110: }
10111:
10112: sub get_active_groups {
10113: my ($udom,$uname,$cdom,$cnum) = @_;
10114: my $now = time;
10115: my %groups = ();
10116: foreach my $key (keys(%env)) {
10117: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
10118: my ($start,$end) = split(/\./,$env{$key});
10119: if (($end!=0) && ($end<$now)) { next; }
10120: if (($start!=0) && ($start>$now)) { next; }
10121: if ($1 eq $cdom && $2 eq $cnum) {
10122: $groups{$3} = $env{$key} ;
10123: }
10124: }
10125: }
10126: return %groups;
10127: }
10128:
10129: sub get_group_membership {
10130: my ($cdom,$cnum,$group) = @_;
10131: return(&dump('groupmembership',$cdom,$cnum,$group));
10132: }
10133:
10134: sub get_users_groups {
10135: my ($udom,$uname,$courseid) = @_;
10136: my @usersgroups;
10137: my $cachetime=1800;
10138:
10139: my $hashid="$udom:$uname:$courseid";
10140: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
10141: if (defined($cached)) {
10142: @usersgroups = split(/:/,$grouplist);
10143: } else {
10144: $grouplist = '';
10145: my $courseurl = &courseid_to_courseurl($courseid);
10146: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
10147: my $access_end = $env{'course.'.$courseid.
10148: '.default_enrollment_end_date'};
10149: my $now = time;
10150: foreach my $key (keys(%roleshash)) {
10151: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10152: my $group = $1;
10153: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10154: my $start = $2;
10155: my $end = $1;
10156: if ($start == -1) { next; } # deleted from group
10157: if (($start!=0) && ($start>$now)) { next; }
10158: if (($end!=0) && ($end<$now)) {
10159: if ($access_end && $access_end < $now) {
10160: if ($access_end - $end < 86400) {
10161: push(@usersgroups,$group);
10162: }
10163: }
10164: next;
10165: }
10166: push(@usersgroups,$group);
10167: }
10168: }
10169: }
10170: @usersgroups = &sort_course_groups($courseid,@usersgroups);
10171: $grouplist = join(':',@usersgroups);
10172: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
10173: }
10174: return @usersgroups;
10175: }
10176:
10177: sub devalidate_getgroups_cache {
10178: my ($udom,$uname,$cdom,$cnum)=@_;
10179: my $courseid = $cdom.'_'.$cnum;
10180:
10181: my $hashid="$udom:$uname:$courseid";
10182: &devalidate_cache_new('getgroups',$hashid);
10183: }
10184:
10185: # ------------------------------------------------------------------ Plain Text
10186:
10187: sub plaintext {
10188: my ($short,$type,$cid,$forcedefault) = @_;
10189: if ($short =~ m{^cr/}) {
10190: return (split('/',$short))[-1];
10191: }
10192: if (!defined($cid)) {
10193: $cid = $env{'request.course.id'};
10194: }
10195: my %rolenames = (
10196: Course => 'std',
10197: Community => 'alt1',
10198: Placement => 'std',
10199: );
10200: if ($cid ne '') {
10201: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10202: unless ($forcedefault) {
10203: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
10204: &Apache::lonlocal::mt_escape(\$roletext);
10205: return &Apache::lonlocal::mt($roletext);
10206: }
10207: }
10208: }
10209: if ((defined($type)) && (defined($rolenames{$type})) &&
10210: (defined($rolenames{$type})) &&
10211: (defined($prp{$short}{$rolenames{$type}}))) {
10212: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
10213: } elsif ($cid ne '') {
10214: my $crstype = $env{'course.'.$cid.'.type'};
10215: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10216: (defined($prp{$short}{$rolenames{$crstype}}))) {
10217: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10218: }
10219: }
10220: return &Apache::lonlocal::mt($prp{$short}{'std'});
10221: }
10222:
10223: # ----------------------------------------------------------------- Assign Role
10224:
10225: sub assignrole {
10226: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10227: $context)=@_;
10228: my $mrole;
10229: if ($role =~ /^cr\//) {
10230: my $cwosec=$url;
10231: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10232: unless (&allowed('ccr',$cwosec)) {
10233: my $refused = 1;
10234: if ($context eq 'requestcourses') {
10235: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10236: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10237: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10238: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10239: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10240: if ($crsenv{'internal.courseowner'} eq
10241: $env{'user.name'}.':'.$env{'user.domain'}) {
10242: $refused = '';
10243: }
10244: }
10245: }
10246: }
10247: }
10248: if ($refused) {
10249: &logthis('Refused custom assignrole: '.
10250: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10251: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10252: return 'refused';
10253: }
10254: }
10255: $mrole='cr';
10256: } elsif ($role =~ /^gr\//) {
10257: my $cwogrp=$url;
10258: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
10259: unless (&allowed('mdg',$cwogrp)) {
10260: &logthis('Refused group assignrole: '.
10261: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10262: $env{'user.name'}.' at '.$env{'user.domain'});
10263: return 'refused';
10264: }
10265: $mrole='gr';
10266: } else {
10267: my $cwosec=$url;
10268: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10269: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10270: my $refused;
10271: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
10272: if (!(&allowed('c'.$role,$url))) {
10273: $refused = 1;
10274: }
10275: } else {
10276: $refused = 1;
10277: }
10278: if ($refused) {
10279: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10280: if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
10281: my %crsenv;
10282: if ($role eq 'cc' || $role eq 'co') {
10283: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10284: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10285: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10286: if ($crsenv{'internal.courseowner'} eq
10287: $env{'user.name'}.':'.$env{'user.domain'}) {
10288: $refused = '';
10289: }
10290: }
10291: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
10292: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10293: if ($crsenv{'internal.courseowner'} eq
10294: $env{'user.name'}.':'.$env{'user.domain'}) {
10295: $refused = '';
10296: }
10297: }
10298: }
10299: }
10300: } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10301: if ($role eq 'st') {
10302: $refused = '';
10303: } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10304: $refused = '';
10305: }
10306: } elsif ($context eq 'requestcourses') {
10307: my @possroles = ('st','ta','ep','in','cc','co');
10308: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
10309: my $wrongcc;
10310: if ($cnum =~ /^$match_community$/) {
10311: $wrongcc = 1 if ($role eq 'cc');
10312: } else {
10313: $wrongcc = 1 if ($role eq 'co');
10314: }
10315: unless ($wrongcc) {
10316: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10317: if ($crsenv{'internal.courseowner'} eq
10318: $env{'user.name'}.':'.$env{'user.domain'}) {
10319: $refused = '';
10320: }
10321: }
10322: }
10323: } elsif ($context eq 'requestauthor') {
10324: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
10325: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10326: if ($env{'environment.requestauthor'} eq 'automatic') {
10327: $refused = '';
10328: } else {
10329: my %domdefaults = &get_domain_defaults($udom);
10330: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10331: my $checkbystatus;
10332: if ($env{'user.adv'}) {
10333: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10334: if ($disposition eq 'automatic') {
10335: $refused = '';
10336: } elsif ($disposition eq '') {
10337: $checkbystatus = 1;
10338: }
10339: } else {
10340: $checkbystatus = 1;
10341: }
10342: if ($checkbystatus) {
10343: if ($env{'environment.inststatus'}) {
10344: my @inststatuses = split(/,/,$env{'environment.inststatus'});
10345: foreach my $type (@inststatuses) {
10346: if (($type ne '') &&
10347: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10348: $refused = '';
10349: }
10350: }
10351: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10352: $refused = '';
10353: }
10354: }
10355: }
10356: }
10357: }
10358: }
10359: if ($refused) {
10360: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10361: ' '.$role.' '.$end.' '.$start.' by '.
10362: $env{'user.name'}.' at '.$env{'user.domain'});
10363: return 'refused';
10364: }
10365: }
10366: } elsif ($role eq 'au') {
10367: if ($url ne '/'.$udom.'/') {
10368: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10369: ' to assign author role for '.$uname.':'.$udom.
10370: ' in domain: '.$url.' refused (wrong domain).');
10371: return 'refused';
10372: }
10373: }
10374: $mrole=$role;
10375: }
10376: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
10377: "$udom:$uname:$url".'_'."$mrole=$role";
10378: if ($end) { $command.='_'.$end; }
10379: if ($start) {
10380: if ($end) {
10381: $command.='_'.$start;
10382: } else {
10383: $command.='_0_'.$start;
10384: }
10385: }
10386: my $origstart = $start;
10387: my $origend = $end;
10388: my $delflag;
10389: # actually delete
10390: if ($deleteflag) {
10391: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
10392: # modify command to delete the role
10393: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
10394: "$udom:$uname:$url".'_'."$mrole";
10395: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
10396: # set start and finish to negative values for userrolelog
10397: $start=-1;
10398: $end=-1;
10399: $delflag = 1;
10400: }
10401: }
10402: # send command
10403: my $answer=&reply($command,&homeserver($uname,$udom));
10404: # log new user role if status is ok
10405: if ($answer eq 'ok') {
10406: &userrolelog($role,$uname,$udom,$url,$start,$end);
10407: if (($role eq 'cc') || ($role eq 'in') ||
10408: ($role eq 'ep') || ($role eq 'ad') ||
10409: ($role eq 'ta') || ($role eq 'st') ||
10410: ($role=~/^cr/) || ($role eq 'gr') ||
10411: ($role eq 'co')) {
10412: # for course roles, perform group memberships changes triggered by role change.
10413: unless ($role =~ /^gr/) {
10414: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10415: $origstart,$selfenroll,$context);
10416: }
10417: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10418: $selfenroll,$context);
10419: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10420: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10421: ($role eq 'da')) {
10422: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10423: $context);
10424: } elsif (($role eq 'ca') || ($role eq 'aa')) {
10425: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10426: $context);
10427: }
10428: if ($role eq 'cc') {
10429: &autoupdate_coowners($url,$end,$start,$uname,$udom);
10430: }
10431: }
10432: return $answer;
10433: }
10434:
10435: sub autoupdate_coowners {
10436: my ($url,$end,$start,$uname,$udom) = @_;
10437: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10438: if (($cdom ne '') && ($cnum ne '')) {
10439: my $now = time;
10440: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10441: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10442: my %coursehash = &coursedescription($cdom.'_'.$cnum);
10443: my $instcode = $coursehash{'internal.coursecode'};
10444: my $xlists = $coursehash{'internal.crosslistings'};
10445: if ($instcode ne '') {
10446: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10447: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10448: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10449: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10450: unless ($result eq 'valid') {
10451: if ($xlists ne '') {
10452: foreach my $xlist (split(',',$xlists)) {
10453: my ($inst_crosslist,$lcsec) = split(':',$xlist);
10454: $result =
10455: &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10456: $inst_crosslist,$uname.':'.$udom);
10457: last if ($result eq 'valid');
10458: }
10459: }
10460: }
10461: if ($result eq 'valid') {
10462: if ($coursehash{'internal.co-owners'}) {
10463: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10464: push(@newcoowners,$coowner);
10465: }
10466: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10467: push(@newcoowners,$uname.':'.$udom);
10468: }
10469: @newcoowners = sort(@newcoowners);
10470: } else {
10471: push(@newcoowners,$uname.':'.$udom);
10472: }
10473: } elsif ($coursehash{'internal.co-owners'}) {
10474: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10475: unless ($coowner eq $uname.':'.$udom) {
10476: push(@newcoowners,$coowner);
10477: }
10478: }
10479: unless (@newcoowners > 0) {
10480: $delcoowners = 1;
10481: $coowners = '';
10482: }
10483: }
10484: if (@newcoowners || $delcoowners) {
10485: &store_coowners($cdom,$cnum,$coursehash{'home'},
10486: $delcoowners,@newcoowners);
10487: }
10488: }
10489: }
10490: }
10491: }
10492: }
10493: }
10494:
10495: sub store_coowners {
10496: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10497: my $cid = $cdom.'_'.$cnum;
10498: my ($coowners,$delresult,$putresult);
10499: if (@newcoowners) {
10500: $coowners = join(',',@newcoowners);
10501: my %coownershash = (
10502: 'internal.co-owners' => $coowners,
10503: );
10504: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10505: if ($putresult eq 'ok') {
10506: if ($env{'course.'.$cid.'.num'} eq $cnum) {
10507: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10508: }
10509: }
10510: }
10511: if ($delcoowners) {
10512: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10513: if ($delresult eq 'ok') {
10514: if ($env{'course.'.$cid.'.internal.co-owners'}) {
10515: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10516: }
10517: }
10518: }
10519: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10520: my %crsinfo =
10521: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10522: if (ref($crsinfo{$cid}) eq 'HASH') {
10523: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10524: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10525: }
10526: }
10527: }
10528:
10529: # -------------------------------------------------- Modify user authentication
10530: # Overrides without validation
10531:
10532: sub modifyuserauth {
10533: my ($udom,$uname,$umode,$upass)=@_;
10534: my $uhome=&homeserver($uname,$udom);
10535: my $allowed;
10536: if (&allowed('mau',$udom)) {
10537: $allowed = 1;
10538: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10539: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10540: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10541: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10542: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10543: if (($cdom ne '') && ($cnum ne '')) {
10544: my $is_owner = &is_course_owner($cdom,$cnum);
10545: if ($is_owner) {
10546: $allowed = 1;
10547: }
10548: }
10549: }
10550: unless ($allowed) { return 'refused'; }
10551: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
10552: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10553: ' in domain '.$env{'request.role.domain'});
10554: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10555: &escape($upass),$uhome);
10556: my $ip = &get_requestor_ip();
10557: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
10558: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10559: '(Remote '.$ip.'): '.$reply);
10560: &log($udom,,$uname,$uhome,
10561: 'Authentication changed by '.$env{'user.domain'}.', '.
10562: $env{'user.name'}.', '.$umode.
10563: '(Remote '.$ip.'): '.$reply);
10564: unless ($reply eq 'ok') {
10565: &logthis('Authentication mode error: '.$reply);
10566: return 'error: '.$reply;
10567: }
10568: return 'ok';
10569: }
10570:
10571: # --------------------------------------------------------------- Modify a user
10572:
10573: sub modifyuser {
10574: my ($udom, $uname, $uid,
10575: $umode, $upass, $first,
10576: $middle, $last, $gene,
10577: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10578: $udom= &LONCAPA::clean_domain($udom);
10579: $uname=&LONCAPA::clean_username($uname);
10580: my $showcandelete = 'none';
10581: if (ref($candelete) eq 'ARRAY') {
10582: if (@{$candelete} > 0) {
10583: $showcandelete = join(', ',@{$candelete});
10584: }
10585: }
10586: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10587: $umode.', '.$first.', '.$middle.', '.
10588: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10589: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10590: ' desiredhome not specified').
10591: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10592: ' in domain '.$env{'request.role.domain'});
10593: my $uhome=&homeserver($uname,$udom,'true');
10594: my $newuser;
10595: if ($uhome eq 'no_host') {
10596: $newuser = 1;
10597: unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10598: ($umode eq 'lti')) {
10599: return 'error: more information needed to create new user';
10600: }
10601: }
10602: # ----------------------------------------------------------------- Create User
10603: if (($uhome eq 'no_host') &&
10604: (($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
10605: my $unhome='';
10606: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
10607: $unhome = $desiredhome;
10608: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10609: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10610: } else { # load balancing routine for determining $unhome
10611: my $loadm=10000000;
10612: my %servers = &get_servers($udom,'library');
10613: foreach my $tryserver (keys(%servers)) {
10614: my $answer=reply('load',$tryserver);
10615: if (($answer=~/\d+/) && ($answer<$loadm)) {
10616: $loadm=$answer;
10617: $unhome=$tryserver;
10618: }
10619: }
10620: }
10621: if (($unhome eq '') || ($unhome eq 'no_host')) {
10622: return 'error: unable to find a home server for '.$uname.
10623: ' in domain '.$udom;
10624: }
10625: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10626: &escape($upass),$unhome);
10627: unless ($reply eq 'ok') {
10628: return 'error: '.$reply;
10629: }
10630: $uhome=&homeserver($uname,$udom,'true');
10631: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10632: return 'error: unable verify users home machine.';
10633: }
10634: } # End of creation of new user
10635: # ---------------------------------------------------------------------- Add ID
10636: if ($uid) {
10637: $uid=~tr/A-Z/a-z/;
10638: my %uidhash=&idrget($udom,$uname);
10639: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
10640: && (!$forceid)) {
10641: unless ($uid eq $uidhash{$uname}) {
10642: return 'error: user id "'.$uid.'" does not match '.
10643: 'current user id "'.$uidhash{$uname}.'".';
10644: }
10645: } else {
10646: &idput($udom,{$uname => $uid},$uhome,'ids');
10647: }
10648: }
10649: # -------------------------------------------------------------- Add names, etc
10650: my @tmp=&get('environment',
10651: ['firstname','middlename','lastname','generation','id',
10652: 'permanentemail','inststatus'],
10653: $udom,$uname);
10654: my (%names,%oldnames);
10655: if ($tmp[0] =~ m/^error:.*/) {
10656: %names=();
10657: } else {
10658: %names = @tmp;
10659: %oldnames = %names;
10660: }
10661: #
10662: # If name, email and/or uid are blank (e.g., because an uploaded file
10663: # of users did not contain them), do not overwrite existing values
10664: # unless field is in $candelete array ref.
10665: #
10666:
10667: my @fields = ('firstname','middlename','lastname','generation',
10668: 'permanentemail','id');
10669: my %newvalues;
10670: if (ref($candelete) eq 'ARRAY') {
10671: foreach my $field (@fields) {
10672: if (grep(/^\Q$field\E$/,@{$candelete})) {
10673: if ($field eq 'firstname') {
10674: $names{$field} = $first;
10675: } elsif ($field eq 'middlename') {
10676: $names{$field} = $middle;
10677: } elsif ($field eq 'lastname') {
10678: $names{$field} = $last;
10679: } elsif ($field eq 'generation') {
10680: $names{$field} = $gene;
10681: } elsif ($field eq 'permanentemail') {
10682: $names{$field} = $email;
10683: } elsif ($field eq 'id') {
10684: $names{$field} = $uid;
10685: }
10686: }
10687: }
10688: }
10689: if ($first) { $names{'firstname'} = $first; }
10690: if (defined($middle)) { $names{'middlename'} = $middle; }
10691: if ($last) { $names{'lastname'} = $last; }
10692: if (defined($gene)) { $names{'generation'} = $gene; }
10693: if ($email) {
10694: $email=~s/[^\w\@\.\-\,]//gs;
10695: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10696: }
10697: if ($uid) { $names{'id'} = $uid; }
10698: if (defined($inststatus)) {
10699: $names{'inststatus'} = '';
10700: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10701: if (ref($usertypes) eq 'HASH') {
10702: my @okstatuses;
10703: foreach my $item (split(/:/,$inststatus)) {
10704: if (defined($usertypes->{$item})) {
10705: push(@okstatuses,$item);
10706: }
10707: }
10708: if (@okstatuses) {
10709: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10710: }
10711: }
10712: }
10713: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10714: $umode.', '.$first.', '.$middle.', '.
10715: $last.', '.$gene.', '.$email.', '.$inststatus;
10716: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10717: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10718: } else {
10719: $logmsg .= ' during self creation';
10720: }
10721: my $changed;
10722: if ($newuser) {
10723: $changed = 1;
10724: } else {
10725: foreach my $field (@fields) {
10726: if ($names{$field} ne $oldnames{$field}) {
10727: $changed = 1;
10728: last;
10729: }
10730: }
10731: }
10732: unless ($changed) {
10733: $logmsg = 'No changes in user information needed for: '.$logmsg;
10734: &logthis($logmsg);
10735: return 'ok';
10736: }
10737: my $reply = &put('environment', \%names, $udom,$uname);
10738: if ($reply ne 'ok') {
10739: return 'error: '.$reply;
10740: }
10741: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10742: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10743: }
10744: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10745: &devalidate_cache_new('namescache',$uname.':'.$udom);
10746: $logmsg = 'Success modifying user '.$logmsg;
10747: &logthis($logmsg);
10748: return 'ok';
10749: }
10750:
10751: # -------------------------------------------------------------- Modify student
10752:
10753: sub modifystudent {
10754: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10755: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10756: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10757: if (!$cid) {
10758: unless ($cid=$env{'request.course.id'}) {
10759: return 'not_in_class';
10760: }
10761: }
10762: # --------------------------------------------------------------- Make the user
10763: my $reply=&modifyuser
10764: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10765: $desiredhome,$email,$inststatus);
10766: unless ($reply eq 'ok') { return $reply; }
10767: # This will cause &modify_student_enrollment to get the uid from the
10768: # student's environment
10769: $uid = undef if (!$forceid);
10770: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10771: $gene,$usec,$end,$start,$type,$locktype,
10772: $cid,$selfenroll,$context,$credits,$instsec);
10773: return $reply;
10774: }
10775:
10776: sub modify_student_enrollment {
10777: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10778: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10779: my ($cdom,$cnum,$chome);
10780: if (!$cid) {
10781: unless ($cid=$env{'request.course.id'}) {
10782: return 'not_in_class';
10783: }
10784: $cdom=$env{'course.'.$cid.'.domain'};
10785: $cnum=$env{'course.'.$cid.'.num'};
10786: } else {
10787: ($cdom,$cnum)=split(/_/,$cid);
10788: }
10789: $chome=$env{'course.'.$cid.'.home'};
10790: if (!$chome) {
10791: $chome=&homeserver($cnum,$cdom);
10792: }
10793: if (!$chome) { return 'unknown_course'; }
10794: # Make sure the user exists
10795: my $uhome=&homeserver($uname,$udom);
10796: if (($uhome eq '') || ($uhome eq 'no_host')) {
10797: return 'error: no such user';
10798: }
10799: # Get student data if we were not given enough information
10800: if (!defined($first) || $first eq '' ||
10801: !defined($last) || $last eq '' ||
10802: !defined($uid) || $uid eq '' ||
10803: !defined($middle) || $middle eq '' ||
10804: !defined($gene) || $gene eq '') {
10805: # They did not supply us with enough data to enroll the student, so
10806: # we need to pick up more information.
10807: my %tmp = &get('environment',
10808: ['firstname','middlename','lastname', 'generation','id']
10809: ,$udom,$uname);
10810:
10811: #foreach my $key (keys(%tmp)) {
10812: # &logthis("key $key = ".$tmp{$key});
10813: #}
10814: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10815: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10816: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
10817: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
10818: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10819: }
10820: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10821: my $user = "$uname:$udom";
10822: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10823: my $reply=cput('classlist',
10824: {$user =>
10825: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10826: $cdom,$cnum);
10827: if (($reply eq 'ok') || ($reply eq 'delayed')) {
10828: &devalidate_getsection_cache($udom,$uname,$cid);
10829: } else {
10830: return 'error: '.$reply;
10831: }
10832: # Add student role to user
10833: my $uurl='/'.$cid;
10834: $uurl=~s/\_/\//g;
10835: if ($usec) {
10836: $uurl.='/'.$usec;
10837: }
10838: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10839: $selfenroll,$context);
10840: if ($result ne 'ok') {
10841: if ($old_entry{$user} ne '') {
10842: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10843: } else {
10844: $reply = &del('classlist',[$user],$cdom,$cnum);
10845: }
10846: }
10847: return $result;
10848: }
10849:
10850: sub format_name {
10851: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10852: my $name;
10853: if ($first ne 'lastname') {
10854: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10855: } else {
10856: if ($lastname=~/\S/) {
10857: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10858: $name=~s/\s+,/,/;
10859: } else {
10860: $name.= $firstname.' '.$middlename.' '.$generation;
10861: }
10862: }
10863: $name=~s/^\s+//;
10864: $name=~s/\s+$//;
10865: $name=~s/\s+/ /g;
10866: return $name;
10867: }
10868:
10869: # ------------------------------------------------- Write to course preferences
10870:
10871: sub writecoursepref {
10872: my ($courseid,%prefs)=@_;
10873: $courseid=~s/^\///;
10874: $courseid=~s/\_/\//g;
10875: my ($cdomain,$cnum)=split(/\//,$courseid);
10876: my $chome=homeserver($cnum,$cdomain);
10877: if (($chome eq '') || ($chome eq 'no_host')) {
10878: return 'error: no such course';
10879: }
10880: my $cstring='';
10881: foreach my $pref (keys(%prefs)) {
10882: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10883: }
10884: $cstring=~s/\&$//;
10885: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10886: }
10887:
10888: # ---------------------------------------------------------- Make/modify course
10889:
10890: sub createcourse {
10891: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10892: $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
10893: $url=&declutter($url);
10894: my $cid='';
10895: if ($context eq 'requestcourses') {
10896: my $can_create = 0;
10897: my ($ownername,$ownerdom) = split(':',$course_owner);
10898: if ($udom eq $ownerdom) {
10899: my $reload;
10900: if (($callercontext eq 'auto') &&
10901: ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
10902: $reload = 'reload';
10903: }
10904: if (&usertools_access($ownername,$ownerdom,$category,$reload,
10905: $context)) {
10906: $can_create = 1;
10907: }
10908: } else {
10909: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10910: $category);
10911: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10912: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10913: if (@curr > 0) {
10914: my @options = qw(approval validate autolimit);
10915: my $optregex = join('|',@options);
10916: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10917: $can_create = 1;
10918: }
10919: }
10920: }
10921: }
10922: if ($can_create) {
10923: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10924: unless (&allowed('ccc',$udom)) {
10925: return 'refused';
10926: }
10927: }
10928: } else {
10929: return 'refused';
10930: }
10931: } elsif (!&allowed('ccc',$udom)) {
10932: return 'refused';
10933: }
10934: # --------------------------------------------------------------- Get Unique ID
10935: my $uname;
10936: if ($cnum =~ /^$match_courseid$/) {
10937: my $chome=&homeserver($cnum,$udom,'true');
10938: if (($chome eq '') || ($chome eq 'no_host')) {
10939: $uname = $cnum;
10940: } else {
10941: $uname = &generate_coursenum($udom,$crstype);
10942: }
10943: } else {
10944: $uname = &generate_coursenum($udom,$crstype);
10945: }
10946: return $uname if ($uname =~ /^error/);
10947: # -------------------------------------------------- Check supplied server name
10948: if (!defined($course_server)) {
10949: if (defined(&domain($udom,'primary'))) {
10950: $course_server = &domain($udom,'primary');
10951: } else {
10952: $course_server = $env{'user.home'};
10953: }
10954: }
10955: my %host_servers =
10956: &Apache::lonnet::get_servers($udom,'library');
10957: unless ($host_servers{$course_server}) {
10958: return 'error: invalid home server for course: '.$course_server;
10959: }
10960: # ------------------------------------------------------------- Make the course
10961: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10962: $course_server);
10963: unless ($reply eq 'ok') { return 'error: '.$reply; }
10964: my $uhome=&homeserver($uname,$udom,'true');
10965: if (($uhome eq '') || ($uhome eq 'no_host')) {
10966: return 'error: no such course';
10967: }
10968: # ----------------------------------------------------------------- Course made
10969: # log existence
10970: my $now = time;
10971: my $newcourse = {
10972: $udom.'_'.$uname => {
10973: description => $description,
10974: inst_code => $inst_code,
10975: owner => $course_owner,
10976: type => $crstype,
10977: creator => $env{'user.name'}.':'.
10978: $env{'user.domain'},
10979: created => $now,
10980: context => $context,
10981: },
10982: };
10983: &courseidput($udom,$newcourse,$uhome,'notime');
10984: # set toplevel url
10985: my $topurl=$url;
10986: unless ($nonstandard) {
10987: # ------------------------------------------ For standard courses, make top url
10988: my $mapurl=&clutter($url);
10989: if ($mapurl eq '/res/') { $mapurl=''; }
10990: $env{'form.initmap'}=(<<ENDINITMAP);
10991: <map>
10992: <resource id="1" type="start"></resource>
10993: <resource id="2" src="$mapurl"></resource>
10994: <resource id="3" type="finish"></resource>
10995: <link index="1" from="1" to="2"></link>
10996: <link index="2" from="2" to="3"></link>
10997: </map>
10998: ENDINITMAP
10999: $topurl=&declutter(
11000: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
11001: );
11002: }
11003: # ----------------------------------------------------------- Write preferences
11004: &writecoursepref($udom.'_'.$uname,
11005: ('description' => $description,
11006: 'url' => $topurl,
11007: 'internal.creator' => $env{'user.name'}.':'.
11008: $env{'user.domain'},
11009: 'internal.created' => $now,
11010: 'internal.creationcontext' => $context)
11011: );
11012: return '/'.$udom.'/'.$uname;
11013: }
11014:
11015: # ------------------------------------------------------------------- Create ID
11016: sub generate_coursenum {
11017: my ($udom,$crstype) = @_;
11018: my $domdesc = &domain($udom);
11019: return 'error: invalid domain' if ($domdesc eq '');
11020: my $first;
11021: if ($crstype eq 'Community') {
11022: $first = '0';
11023: } else {
11024: $first = int(1+rand(9));
11025: }
11026: my $uname=$first.
11027: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11028: substr($$.time,0,5).unpack("H8",pack("I32",time)).
11029: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11030: # ----------------------------------------------- Make sure that does not exist
11031: my $uhome=&homeserver($uname,$udom,'true');
11032: unless (($uhome eq '') || ($uhome eq 'no_host')) {
11033: if ($crstype eq 'Community') {
11034: $first = '0';
11035: } else {
11036: $first = int(1+rand(9));
11037: }
11038: $uname=$first.
11039: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11040: substr($$.time,0,5).unpack("H8",pack("I32",time)).
11041: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11042: $uhome=&homeserver($uname,$udom,'true');
11043: unless (($uhome eq '') || ($uhome eq 'no_host')) {
11044: return 'error: unable to generate unique course-ID';
11045: }
11046: }
11047: return $uname;
11048: }
11049:
11050: sub is_course {
11051: my ($cdom, $cnum) = scalar(@_) == 1 ?
11052: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
11053:
11054: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
11055: my $uhome=&homeserver($cnum,$cdom);
11056: my $iscourse;
11057: if (grep { $_ eq $uhome } current_machine_ids()) {
11058: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
11059: } else {
11060: my $hashid = $cdom.':'.$cnum;
11061: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
11062: unless (defined($cached)) {
11063: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
11064: $cnum,undef,undef,'.');
11065: $iscourse = 0;
11066: if (exists($courses{$cdom.'_'.$cnum})) {
11067: $iscourse = 1;
11068: }
11069: &do_cache_new('iscourse',$hashid,$iscourse,3600);
11070: }
11071: }
11072: return unless ($iscourse);
11073: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
11074: }
11075:
11076: sub store_userdata {
11077: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
11078: my $result;
11079: if ($datakey ne '') {
11080: if (ref($storehash) eq 'HASH') {
11081: if ($udom eq '' || $uname eq '') {
11082: $udom = $env{'user.domain'};
11083: $uname = $env{'user.name'};
11084: }
11085: my $uhome=&homeserver($uname,$udom);
11086: if (($uhome eq '') || ($uhome eq 'no_host')) {
11087: $result = 'error: no_host';
11088: } else {
11089: $storehash->{'ip'} = &get_requestor_ip();
11090: $storehash->{'host'} = $perlvar{'lonHostID'};
11091:
11092: my $namevalue='';
11093: foreach my $key (keys(%{$storehash})) {
11094: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
11095: }
11096: $namevalue=~s/\&$//;
11097: unless ($namespace eq 'courserequests') {
11098: $datakey = &escape($datakey);
11099: }
11100: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
11101: $namevalue,$uhome);
11102: }
11103: } else {
11104: $result = 'error: data to store was not a hash reference';
11105: }
11106: } else {
11107: $result= 'error: invalid requestkey';
11108: }
11109: return $result;
11110: }
11111:
11112: # ---------------------------------------------------------- Assign Custom Role
11113:
11114: sub assigncustomrole {
11115: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
11116: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
11117: $end,$start,$deleteflag,$selfenroll,$context);
11118: }
11119:
11120: # ----------------------------------------------------------------- Revoke Role
11121:
11122: sub revokerole {
11123: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
11124: my $now=time;
11125: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
11126: }
11127:
11128: # ---------------------------------------------------------- Revoke Custom Role
11129:
11130: sub revokecustomrole {
11131: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
11132: my $now=time;
11133: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
11134: $deleteflag,$selfenroll,$context);
11135: }
11136:
11137: # ------------------------------------------------------------ Disk usage
11138: sub diskusage {
11139: my ($udom,$uname,$directorypath,$getpropath)=@_;
11140: $directorypath =~ s/\/$//;
11141: my $listing=&reply('du2:'.&escape($directorypath).':'
11142: .&escape($getpropath).':'.&escape($uname).':'
11143: .&escape($udom),homeserver($uname,$udom));
11144: if ($listing eq 'unknown_cmd') {
11145: if ($getpropath) {
11146: $directorypath = &propath($udom,$uname).'/'.$directorypath;
11147: }
11148: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11149: }
11150: return $listing;
11151: }
11152:
11153: sub is_locked {
11154: my ($file_name, $domain, $user, $which) = @_;
11155: my @check;
11156: my $is_locked;
11157: push (@check,$file_name);
11158: my %locked = &get('file_permissions',\@check,
11159: $env{'user.domain'},$env{'user.name'});
11160: my ($tmp)=keys(%locked);
11161: if ($tmp=~/^error:/) { undef(%locked); }
11162:
11163: if (ref($locked{$file_name}) eq 'ARRAY') {
11164: $is_locked = 'false';
11165: foreach my $entry (@{$locked{$file_name}}) {
11166: if (ref($entry) eq 'ARRAY') {
11167: $is_locked = 'true';
11168: if (ref($which) eq 'ARRAY') {
11169: push(@{$which},$entry);
11170: } else {
11171: last;
11172: }
11173: }
11174: }
11175: } else {
11176: $is_locked = 'false';
11177: }
11178: return $is_locked;
11179: }
11180:
11181: sub declutter_portfile {
11182: my ($file) = @_;
11183: $file =~ s{^(/portfolio/|portfolio/)}{/};
11184: return $file;
11185: }
11186:
11187: # ------------------------------------------------------------- Mark as Read Only
11188:
11189: sub mark_as_readonly {
11190: my ($domain,$user,$files,$what) = @_;
11191: my %current_permissions = &dump('file_permissions',$domain,$user);
11192: my ($tmp)=keys(%current_permissions);
11193: if ($tmp=~/^error:/) { undef(%current_permissions); }
11194: foreach my $file (@{$files}) {
11195: $file = &declutter_portfile($file);
11196: push(@{$current_permissions{$file}},$what);
11197: }
11198: &put('file_permissions',\%current_permissions,$domain,$user);
11199: return;
11200: }
11201:
11202: # ------------------------------------------------------------Save Selected Files
11203:
11204: sub save_selected_files {
11205: my ($user, $path, @files) = @_;
11206: my $filename = $user."savedfiles";
11207: my @other_files = &files_not_in_path($user, $path);
11208: open (OUT,'>',LONCAPA::tempdir().$filename);
11209: foreach my $file (@files) {
11210: print (OUT $env{'form.currentpath'}.$file."\n");
11211: }
11212: foreach my $file (@other_files) {
11213: print (OUT $file."\n");
11214: }
11215: close (OUT);
11216: return 'ok';
11217: }
11218:
11219: sub clear_selected_files {
11220: my ($user) = @_;
11221: my $filename = $user."savedfiles";
11222: open (OUT,'>',LONCAPA::tempdir().$filename);
11223: print (OUT undef);
11224: close (OUT);
11225: return ("ok");
11226: }
11227:
11228: sub files_in_path {
11229: my ($user, $path) = @_;
11230: my $filename = $user."savedfiles";
11231: my %return_files;
11232: open (IN,'<',LONCAPA::tempdir().$filename);
11233: while (my $line_in = <IN>) {
11234: chomp ($line_in);
11235: my @paths_and_file = split (m!/!, $line_in);
11236: my $file_part = pop (@paths_and_file);
11237: my $path_part = join ('/', @paths_and_file);
11238: $path_part.='/';
11239: my $path_and_file = $path_part.$file_part;
11240: if ($path_part eq $path) {
11241: $return_files{$file_part}= 'selected';
11242: }
11243: }
11244: close (IN);
11245: return (\%return_files);
11246: }
11247:
11248: # called in portfolio select mode, to show files selected NOT in current directory
11249: sub files_not_in_path {
11250: my ($user, $path) = @_;
11251: my $filename = $user."savedfiles";
11252: my @return_files;
11253: my $path_part;
11254: open(IN, '<',LONCAPA::tempdir().$filename);
11255: while (my $line = <IN>) {
11256: #ok, I know it's clunky, but I want it to work
11257: my @paths_and_file = split(m|/|, $line);
11258: my $file_part = pop(@paths_and_file);
11259: chomp($file_part);
11260: my $path_part = join('/', @paths_and_file);
11261: $path_part .= '/';
11262: my $path_and_file = $path_part.$file_part;
11263: if ($path_part ne $path) {
11264: push(@return_files, ($path_and_file));
11265: }
11266: }
11267: close(OUT);
11268: return (@return_files);
11269: }
11270:
11271: #------------------------------Submitted/Handedback Portfolio Files Versioning
11272:
11273: sub portfiles_versioning {
11274: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11275: my $portfolio_root = '/userfiles/portfolio';
11276: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11277: foreach my $file (@{$portfiles}) {
11278: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11279: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11280: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11281: my $getpropath = 1;
11282: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11283: $stu_name,$getpropath);
11284: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11285: my $new_answer =
11286: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11287: if ($new_answer ne 'problem getting file') {
11288: push(@{$versioned_portfiles}, $directory.$new_answer);
11289: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11290: [$symb,$env{'request.course.id'},'graded']);
11291: }
11292: }
11293: }
11294:
11295: sub get_next_version {
11296: my ($answer_name, $answer_ext, $dir_list) = @_;
11297: my $version;
11298: if (ref($dir_list) eq 'ARRAY') {
11299: foreach my $row (@{$dir_list}) {
11300: my ($file) = split(/\&/,$row,2);
11301: my ($file_name,$file_version,$file_ext) =
11302: &file_name_version_ext($file);
11303: if (($file_name eq $answer_name) &&
11304: ($file_ext eq $answer_ext)) {
11305: # gets here if filename and extension match,
11306: # regardless of version
11307: if ($file_version ne '') {
11308: # a versioned file is found so save it for later
11309: if ($file_version > $version) {
11310: $version = $file_version;
11311: }
11312: }
11313: }
11314: }
11315: }
11316: $version ++;
11317: return($version);
11318: }
11319:
11320: sub version_selected_portfile {
11321: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11322: my ($answer_name,$answer_ver,$answer_ext) =
11323: &file_name_version_ext($file_name);
11324: my $new_answer;
11325: $env{'form.copy'} =
11326: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11327: if($env{'form.copy'} eq '-1') {
11328: $new_answer = 'problem getting file';
11329: } else {
11330: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11331: my $copy_result =
11332: &finishuserfileupload($stu_name,$domain,'copy',
11333: '/portfolio'.$directory.$new_answer);
11334: }
11335: undef($env{'form.copy'});
11336: return ($new_answer);
11337: }
11338:
11339: sub file_name_version_ext {
11340: my ($file)=@_;
11341: my @file_parts = split(/\./, $file);
11342: my ($name,$version,$ext);
11343: if (@file_parts > 1) {
11344: $ext=pop(@file_parts);
11345: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11346: $version=pop(@file_parts);
11347: }
11348: $name=join('.',@file_parts);
11349: } else {
11350: $name=join('.',@file_parts);
11351: }
11352: return($name,$version,$ext);
11353: }
11354:
11355: #----------------------------------------------Get portfolio file permissions
11356:
11357: sub get_portfile_permissions {
11358: my ($domain,$user) = @_;
11359: my %current_permissions = &dump('file_permissions',$domain,$user);
11360: my ($tmp)=keys(%current_permissions);
11361: if ($tmp=~/^error:/) { undef(%current_permissions); }
11362: return \%current_permissions;
11363: }
11364:
11365: #---------------------------------------------Get portfolio file access controls
11366:
11367: sub get_access_controls {
11368: my ($current_permissions,$group,$file) = @_;
11369: my %access;
11370: my $real_file = $file;
11371: $file =~ s/\.meta$//;
11372: if (defined($file)) {
11373: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11374: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
11375: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
11376: }
11377: }
11378: } else {
11379: foreach my $key (keys(%{$current_permissions})) {
11380: if ($key =~ /\0accesscontrol$/) {
11381: if (defined($group)) {
11382: if ($key !~ m-^\Q$group\E/-) {
11383: next;
11384: }
11385: }
11386: my ($fullpath) = split(/\0/,$key);
11387: if (ref($$current_permissions{$key}) eq 'HASH') {
11388: foreach my $control (keys(%{$$current_permissions{$key}})) {
11389: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11390: }
11391: }
11392: }
11393: }
11394: }
11395: return %access;
11396: }
11397:
11398: sub modify_access_controls {
11399: my ($file_name,$changes,$domain,$user)=@_;
11400: my ($outcome,$deloutcome);
11401: my %store_permissions;
11402: my %new_values;
11403: my %new_control;
11404: my %translation;
11405: my @deletions = ();
11406: my $now = time;
11407: if (exists($$changes{'activate'})) {
11408: if (ref($$changes{'activate'}) eq 'HASH') {
11409: my @newitems = sort(keys(%{$$changes{'activate'}}));
11410: my $numnew = scalar(@newitems);
11411: for (my $i=0; $i<$numnew; $i++) {
11412: my $newkey = $newitems[$i];
11413: my $newid = &Apache::loncommon::get_cgi_id();
11414: if ($newkey =~ /^\d+:/) {
11415: $newkey =~ s/^(\d+)/$newid/;
11416: $translation{$1} = $newid;
11417: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11418: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11419: $translation{$1} = $newid;
11420: }
11421: $new_values{$file_name."\0".$newkey} =
11422: $$changes{'activate'}{$newitems[$i]};
11423: $new_control{$newkey} = $now;
11424: }
11425: }
11426: }
11427: my %todelete;
11428: my %changed_items;
11429: foreach my $action ('delete','update') {
11430: if (exists($$changes{$action})) {
11431: if (ref($$changes{$action}) eq 'HASH') {
11432: foreach my $key (keys(%{$$changes{$action}})) {
11433: my ($itemnum) = ($key =~ /^([^:]+):/);
11434: if ($action eq 'delete') {
11435: $todelete{$itemnum} = 1;
11436: } else {
11437: $changed_items{$itemnum} = $key;
11438: }
11439: }
11440: }
11441: }
11442: }
11443: # get lock on access controls for file.
11444: my $lockhash = {
11445: $file_name."\0".'locked_access_records' => $env{'user.name'}.
11446: ':'.$env{'user.domain'},
11447: };
11448: my $tries = 0;
11449: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11450:
11451: while (($gotlock ne 'ok') && $tries < 10) {
11452: $tries ++;
11453: sleep(0.1);
11454: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11455: }
11456: if ($gotlock eq 'ok') {
11457: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11458: my ($tmp)=keys(%curr_permissions);
11459: if ($tmp=~/^error:/) { undef(%curr_permissions); }
11460: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11461: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11462: if (ref($curr_controls) eq 'HASH') {
11463: foreach my $control_item (keys(%{$curr_controls})) {
11464: my ($itemnum) = ($control_item =~ /^([^:]+):/);
11465: if (defined($todelete{$itemnum})) {
11466: push(@deletions,$file_name."\0".$control_item);
11467: } else {
11468: if (defined($changed_items{$itemnum})) {
11469: $new_control{$changed_items{$itemnum}} = $now;
11470: push(@deletions,$file_name."\0".$control_item);
11471: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11472: } else {
11473: $new_control{$control_item} = $$curr_controls{$control_item};
11474: }
11475: }
11476: }
11477: }
11478: }
11479: my ($group);
11480: if (&is_course($domain,$user)) {
11481: ($group,my $file) = split(/\//,$file_name,2);
11482: }
11483: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11484: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11485: $outcome = &put('file_permissions',\%new_values,$domain,$user);
11486: # remove lock
11487: my @del_lock = ($file_name."\0".'locked_access_records');
11488: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
11489: my $sqlresult =
11490: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
11491: $group);
11492: } else {
11493: $outcome = "error: could not obtain lockfile\n";
11494: }
11495: return ($outcome,$deloutcome,\%new_values,\%translation);
11496: }
11497:
11498: sub make_public_indefinitely {
11499: my (@requrl) = @_;
11500: return &automated_portfile_access('public',\@requrl);
11501: }
11502:
11503: sub automated_portfile_access {
11504: my ($accesstype,$addsref,$delsref,$info) = @_;
11505: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11506: return 'invalid';
11507: }
11508: my %urls;
11509: if (ref($addsref) eq 'ARRAY') {
11510: foreach my $requrl (@{$addsref}) {
11511: if (&is_portfolio_url($requrl)) {
11512: unless (exists($urls{$requrl})) {
11513: $urls{$requrl} = 'add';
11514: }
11515: }
11516: }
11517: }
11518: if (ref($delsref) eq 'ARRAY') {
11519: foreach my $requrl (@{$delsref}) {
11520: if (&is_portfolio_url($requrl)) {
11521: unless (exists($urls{$requrl})) {
11522: $urls{$requrl} = 'delete';
11523: }
11524: }
11525: }
11526: }
11527: unless (keys(%urls)) {
11528: return 'invalid';
11529: }
11530: my $ip;
11531: if ($accesstype eq 'ip') {
11532: if (ref($info) eq 'HASH') {
11533: if ($info->{'ip'} ne '') {
11534: $ip = $info->{'ip'};
11535: }
11536: }
11537: if ($ip eq '') {
11538: return 'invalid';
11539: }
11540: }
11541: my $errors;
11542: my $now = time;
11543: my %current_perms;
11544: foreach my $requrl (sort(keys(%urls))) {
11545: my $action;
11546: if ($urls{$requrl} eq 'add') {
11547: $action = 'activate';
11548: } else {
11549: $action = 'none';
11550: }
11551: my $aclnum = 0;
11552: my (undef,$udom,$unum,$file_name,$group) =
11553: &parse_portfolio_url($requrl);
11554: unless (exists($current_perms{$unum.':'.$udom})) {
11555: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11556: }
11557: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
11558: $group,$file_name);
11559: foreach my $key (keys(%{$access_controls{$file_name}})) {
11560: my ($num,$scope,$end,$start) =
11561: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11562: if ($scope eq $accesstype) {
11563: if (($start <= $now) && ($end == 0)) {
11564: if ($accesstype eq 'ip') {
11565: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11566: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11567: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11568: if ($urls{$requrl} eq 'add') {
11569: $action = 'none';
11570: last;
11571: } else {
11572: $action = 'delete';
11573: $aclnum = $num;
11574: last;
11575: }
11576: }
11577: }
11578: }
11579: } elsif ($accesstype eq 'public') {
11580: if ($urls{$requrl} eq 'add') {
11581: $action = 'none';
11582: last;
11583: } else {
11584: $action = 'delete';
11585: $aclnum = $num;
11586: last;
11587: }
11588: }
11589: } elsif ($accesstype eq 'public') {
11590: $action = 'update';
11591: $aclnum = $num;
11592: last;
11593: }
11594: }
11595: }
11596: if ($action eq 'none') {
11597: next;
11598: } else {
11599: my %changes;
11600: my $newend = 0;
11601: my $newstart = $now;
11602: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
11603: $changes{$action}{$newkey} = {
11604: type => $accesstype,
11605: time => {
11606: start => $newstart,
11607: end => $newend,
11608: },
11609: };
11610: if ($accesstype eq 'ip') {
11611: $changes{$action}{$newkey}{'ip'} = [$ip];
11612: }
11613: my ($outcome,$deloutcome,$new_values,$translation) =
11614: &modify_access_controls($file_name,\%changes,$udom,$unum);
11615: unless ($outcome eq 'ok') {
11616: $errors .= $outcome.' ';
11617: }
11618: }
11619: }
11620: if ($errors) {
11621: $errors =~ s/\s$//;
11622: return $errors;
11623: } else {
11624: return 'ok';
11625: }
11626: }
11627:
11628: #------------------------------------------------------Get Marked as Read Only
11629:
11630: sub get_marked_as_readonly {
11631: my ($domain,$user,$what,$group) = @_;
11632: my $current_permissions = &get_portfile_permissions($domain,$user);
11633: my @readonly_files;
11634: my $cmp1=$what;
11635: if (ref($what)) { $cmp1=join('',@{$what}) };
11636: while (my ($file_name,$value) = each(%{$current_permissions})) {
11637: if (defined($group)) {
11638: if ($file_name !~ m-^\Q$group\E/-) {
11639: next;
11640: }
11641: }
11642: if (ref($value) eq "ARRAY"){
11643: foreach my $stored_what (@{$value}) {
11644: my $cmp2=$stored_what;
11645: if (ref($stored_what) eq 'ARRAY') {
11646: $cmp2=join('',@{$stored_what});
11647: }
11648: if ($cmp1 eq $cmp2) {
11649: push(@readonly_files, $file_name);
11650: last;
11651: } elsif (!defined($what)) {
11652: push(@readonly_files, $file_name);
11653: last;
11654: }
11655: }
11656: }
11657: }
11658: return @readonly_files;
11659: }
11660: #-----------------------------------------------------------Get Marked as Read Only Hash
11661:
11662: sub get_marked_as_readonly_hash {
11663: my ($current_permissions,$group,$what) = @_;
11664: my %readonly_files;
11665: while (my ($file_name,$value) = each(%{$current_permissions})) {
11666: if (defined($group)) {
11667: if ($file_name !~ m-^\Q$group\E/-) {
11668: next;
11669: }
11670: }
11671: if (ref($value) eq "ARRAY"){
11672: foreach my $stored_what (@{$value}) {
11673: if (ref($stored_what) eq 'ARRAY') {
11674: foreach my $lock_descriptor(@{$stored_what}) {
11675: if ($lock_descriptor eq 'graded') {
11676: $readonly_files{$file_name} = 'graded';
11677: } elsif ($lock_descriptor eq 'handback') {
11678: $readonly_files{$file_name} = 'handback';
11679: } else {
11680: if (!exists($readonly_files{$file_name})) {
11681: $readonly_files{$file_name} = 'locked';
11682: }
11683: }
11684: }
11685: }
11686: }
11687: }
11688: }
11689: return %readonly_files;
11690: }
11691: # ------------------------------------------------------------ Unmark as Read Only
11692:
11693: sub unmark_as_readonly {
11694: # unmarks $file_name (if $file_name is defined), or all files locked by $what
11695: # for portfolio submissions, $what contains [$symb,$crsid]
11696: my ($domain,$user,$what,$file_name,$group) = @_;
11697: $file_name = &declutter_portfile($file_name);
11698: my $symb_crs = $what;
11699: if (ref($what)) { $symb_crs=join('',@$what); }
11700: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
11701: my ($tmp)=keys(%current_permissions);
11702: if ($tmp=~/^error:/) { undef(%current_permissions); }
11703: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
11704: foreach my $file (@readonly_files) {
11705: my $clean_file = &declutter_portfile($file);
11706: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
11707: my $current_locks = $current_permissions{$file};
11708: my @new_locks;
11709: my @del_keys;
11710: if (ref($current_locks) eq "ARRAY"){
11711: foreach my $locker (@{$current_locks}) {
11712: my $compare=$locker;
11713: if (ref($locker) eq 'ARRAY') {
11714: $compare=join('',@{$locker});
11715: if ($compare ne $symb_crs) {
11716: push(@new_locks, $locker);
11717: }
11718: }
11719: }
11720: if (scalar(@new_locks) > 0) {
11721: $current_permissions{$file} = \@new_locks;
11722: } else {
11723: push(@del_keys, $file);
11724: &del('file_permissions',\@del_keys, $domain, $user);
11725: delete($current_permissions{$file});
11726: }
11727: }
11728: }
11729: &put('file_permissions',\%current_permissions,$domain,$user);
11730: return;
11731: }
11732:
11733: # ------------------------------------------------------------ Directory lister
11734:
11735: sub dirlist {
11736: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
11737: $uri=~s/^\///;
11738: $uri=~s/\/$//;
11739: my ($udom, $uname);
11740: if ($getuserdir) {
11741: $udom = $userdomain;
11742: $uname = $username;
11743: } else {
11744: (undef,$udom,$uname)=split(/\//,$uri);
11745: if(defined($userdomain)) {
11746: $udom = $userdomain;
11747: }
11748: if(defined($username)) {
11749: $uname = $username;
11750: }
11751: }
11752: my ($dirRoot,$listing,@listing_results);
11753:
11754: $dirRoot = $perlvar{'lonDocRoot'};
11755: if (defined($getpropath)) {
11756: $dirRoot = &propath($udom,$uname);
11757: $dirRoot =~ s/\/$//;
11758: } elsif (defined($getuserdir)) {
11759: my $subdir=$uname.'__';
11760: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11761: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11762: ."/$udom/$subdir/$uname";
11763: } elsif (defined($alternateRoot)) {
11764: $dirRoot = $alternateRoot;
11765: }
11766:
11767: if($udom) {
11768: if($uname) {
11769: my $uhome = &homeserver($uname,$udom);
11770: if ($uhome eq 'no_host') {
11771: return ([],'no_host');
11772: }
11773: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11774: .$getuserdir.':'.&escape($dirRoot)
11775: .':'.&escape($uname).':'.&escape($udom),$uhome);
11776: if ($listing eq 'unknown_cmd') {
11777: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11778: } else {
11779: @listing_results = map { &unescape($_); } split(/:/,$listing);
11780: }
11781: if ($listing eq 'unknown_cmd') {
11782: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11783: @listing_results = split(/:/,$listing);
11784: } else {
11785: @listing_results = map { &unescape($_); } split(/:/,$listing);
11786: }
11787: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11788: ($listing eq 'rejected') || ($listing eq 'refused') ||
11789: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11790: return ([],$listing);
11791: } else {
11792: return (\@listing_results);
11793: }
11794: } elsif(!$alternateRoot) {
11795: my (%allusers,%listerror);
11796: my %servers = &get_servers($udom,'library');
11797: foreach my $tryserver (keys(%servers)) {
11798: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11799: &escape($udom),$tryserver);
11800: if ($listing eq 'unknown_cmd') {
11801: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11802: $udom, $tryserver);
11803: } else {
11804: @listing_results = map { &unescape($_); } split(/:/,$listing);
11805: }
11806: if ($listing eq 'unknown_cmd') {
11807: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11808: $udom, $tryserver);
11809: @listing_results = split(/:/,$listing);
11810: } else {
11811: @listing_results =
11812: map { &unescape($_); } split(/:/,$listing);
11813: }
11814: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11815: ($listing eq 'rejected') || ($listing eq 'refused') ||
11816: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11817: $listerror{$tryserver} = $listing;
11818: } else {
11819: foreach my $line (@listing_results) {
11820: my ($entry) = split(/&/,$line,2);
11821: $allusers{$entry} = 1;
11822: }
11823: }
11824: }
11825: my @alluserslist=();
11826: foreach my $user (sort(keys(%allusers))) {
11827: push(@alluserslist,$user.'&user');
11828: }
11829:
11830: if (!%listerror) {
11831: # no errors
11832: return (\@alluserslist);
11833: } elsif (scalar(keys(%servers)) == 1) {
11834: # one library server, one error
11835: my ($key) = keys(%listerror);
11836: return (\@alluserslist, $listerror{$key});
11837: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11838: # con_lost indicates that we might miss data from at least one
11839: # library server
11840: return (\@alluserslist, 'con_lost');
11841: } else {
11842: # multiple library servers and no con_lost -> data should be
11843: # complete.
11844: return (\@alluserslist);
11845: }
11846:
11847: } else {
11848: return ([],'missing username');
11849: }
11850: } elsif(!defined($getpropath)) {
11851: my $path = $perlvar{'lonDocRoot'}.'/res/';
11852: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11853: return (\@all_domains);
11854: } else {
11855: return ([],'missing domain');
11856: }
11857: }
11858:
11859: # --------------------------------------------- GetFileTimestamp
11860: # This function utilizes dirlist and returns the date stamp for
11861: # when it was last modified. It will also return an error of -1
11862: # if an error occurs
11863:
11864: sub GetFileTimestamp {
11865: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11866: $studentDomain = &LONCAPA::clean_domain($studentDomain);
11867: $studentName = &LONCAPA::clean_username($studentName);
11868: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11869: undef,$getuserdir);
11870: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11871: return -1;
11872: }
11873: if (ref($fileref) eq 'ARRAY') {
11874: my @stats = split('&',$fileref->[0]);
11875: # @stats contains first the filename, then the stat output
11876: return $stats[10]; # so this is 10 instead of 9.
11877: } else {
11878: return -1;
11879: }
11880: }
11881:
11882: sub stat_file {
11883: my ($uri) = @_;
11884: $uri = &clutter_with_no_wrapper($uri);
11885:
11886: my ($udom,$uname,$file);
11887: if ($uri =~ m-^/(uploaded|editupload)/-) {
11888: ($udom,$uname,$file) =
11889: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11890: $file = 'userfiles/'.$file;
11891: }
11892: if ($uri =~ m-^/res/-) {
11893: ($udom,$uname) =
11894: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11895: $file = $uri;
11896: }
11897:
11898: if (!$udom || !$uname || !$file) {
11899: # unable to handle the uri
11900: return ();
11901: }
11902: my $getpropath;
11903: if ($file =~ /^userfiles\//) {
11904: $getpropath = 1;
11905: }
11906: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11907: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11908: return ();
11909: } else {
11910: if (ref($listref) eq 'ARRAY') {
11911: my @stats = split('&',$listref->[0]);
11912: shift(@stats); #filename is first
11913: return @stats;
11914: }
11915: }
11916: return ();
11917: }
11918:
11919: # --------------------------------------------------------- recursedirs
11920: # Recursive function to traverse either a specific user's Authoring Space
11921: # or corresponding Published Resource Space, and populate the hash ref:
11922: # $dirhashref with URLs of all directories, and if $filehashref hash
11923: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11924: # or .rights files in resource space, and .meta, .save, .log, and .bak
11925: # files in Authoring Space.
11926: #
11927: # Inputs:
11928: #
11929: # $is_home - true if current server is home server for user's space
11930: # $context - either: priv, or res respectively for Authoring or Resource Space.
11931: # $docroot - Document root (i.e., /home/httpd/html
11932: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11933: # $relpath - Current path (relative to top level).
11934: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11935: # $filehashref - reference to hash to populate with URLs of files (Optional)
11936: #
11937: # Returns: nothing
11938: #
11939: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11940: #
11941: # Currently used by interface/londocs.pm to create linked select boxes for
11942: # directory and filename to import a Course "Author" resource into a course, and
11943: # also to create linked select boxes for Authoring Space and Directory to choose
11944: # save location for creation of a new "standard" problem from the Course Editor.
11945: #
11946:
11947: sub recursedirs {
11948: my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11949: return unless (ref($dirhashref) eq 'HASH');
11950: my $currpath = $docroot.$toppath;
11951: if ($relpath) {
11952: $currpath .= "/$relpath";
11953: }
11954: my $savefile;
11955: if (ref($filehashref)) {
11956: $savefile = 1;
11957: }
11958: if ($is_home) {
11959: if (opendir(my $dirh,$currpath)) {
11960: foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11961: next if ($item eq '');
11962: if (-d "$currpath/$item") {
11963: my $newpath;
11964: if ($relpath) {
11965: $newpath = "$relpath/$item";
11966: } else {
11967: $newpath = $item;
11968: }
11969: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11970: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11971: } elsif ($savefile) {
11972: if ($context eq 'priv') {
11973: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11974: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11975: }
11976: } else {
11977: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11978: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11979: }
11980: }
11981: }
11982: }
11983: closedir($dirh);
11984: }
11985: } else {
11986: my ($dirlistref,$listerror) =
11987: &dirlist($toppath.$relpath);
11988: my @dir_lines;
11989: my $dirptr=16384;
11990: if (ref($dirlistref) eq 'ARRAY') {
11991: foreach my $dir_line (sort
11992: {
11993: my ($afile)=split('&',$a,2);
11994: my ($bfile)=split('&',$b,2);
11995: return (lc($afile) cmp lc($bfile));
11996: } (@{$dirlistref})) {
11997: my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11998: split(/\&/,$dir_line,16);
11999: $item =~ s/\s+$//;
12000: next if (($item =~ /^\.\.?$/) || ($obs));
12001: if ($dirptr&$testdir) {
12002: my $newpath;
12003: if ($relpath) {
12004: $newpath = "$relpath/$item";
12005: } else {
12006: $relpath = '/';
12007: $newpath = $item;
12008: }
12009: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12010: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
12011: } elsif ($savefile) {
12012: if ($context eq 'priv') {
12013: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
12014: $filehashref->{$relpath}{$item} = 1;
12015: }
12016: } else {
12017: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
12018: $filehashref->{$relpath}{$item} = 1;
12019: }
12020: }
12021: }
12022: }
12023: }
12024: }
12025: return;
12026: }
12027:
12028: # -------------------------------------------------------- Value of a Condition
12029:
12030: # gets the value of a specific preevaluated condition
12031: # stored in the string $env{user.state.<cid>}
12032: # or looks up a condition reference in the bighash and if if hasn't
12033: # already been evaluated recurses into docondval to get the value of
12034: # the condition, then memoizing it to
12035: # $env{user.state.<cid>.<condition>}
12036: sub directcondval {
12037: my $number=shift;
12038: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
12039: &Apache::lonuserstate::evalstate();
12040: }
12041: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
12042: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
12043: } elsif ($number =~ /^_/) {
12044: my $sub_condition;
12045: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12046: &GDBM_READER(),0640)) {
12047: $sub_condition=$bighash{'conditions'.$number};
12048: untie(%bighash);
12049: }
12050: my $value = &docondval($sub_condition);
12051: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
12052: return $value;
12053: }
12054: if ($env{'user.state.'.$env{'request.course.id'}}) {
12055: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
12056: } else {
12057: return 2;
12058: }
12059: }
12060:
12061: # get the collection of conditions for this resource
12062: sub condval {
12063: my $condidx=shift;
12064: my $allpathcond='';
12065: foreach my $cond (split(/\|/,$condidx)) {
12066: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
12067: $allpathcond.=
12068: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
12069: }
12070: }
12071: $allpathcond=~s/\|$//;
12072: return &docondval($allpathcond);
12073: }
12074:
12075: #evaluates an expression of conditions
12076: sub docondval {
12077: my ($allpathcond) = @_;
12078: my $result=0;
12079: if ($env{'request.course.id'}
12080: && defined($allpathcond)) {
12081: my $operand='|';
12082: my @stack;
12083: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
12084: if ($chunk eq '(') {
12085: push @stack,($operand,$result);
12086: } elsif ($chunk eq ')') {
12087: my $before=pop @stack;
12088: if (pop @stack eq '&') {
12089: $result=$result>$before?$before:$result;
12090: } else {
12091: $result=$result>$before?$result:$before;
12092: }
12093: } elsif (($chunk eq '&') || ($chunk eq '|')) {
12094: $operand=$chunk;
12095: } else {
12096: my $new=directcondval($chunk);
12097: if ($operand eq '&') {
12098: $result=$result>$new?$new:$result;
12099: } else {
12100: $result=$result>$new?$result:$new;
12101: }
12102: }
12103: }
12104: }
12105: return $result;
12106: }
12107:
12108: # ---------------------------------------------------- Devalidate courseresdata
12109:
12110: sub devalidatecourseresdata {
12111: my ($coursenum,$coursedomain)=@_;
12112: my $hashid=$coursenum.':'.$coursedomain;
12113: &devalidate_cache_new('courseres',$hashid);
12114: }
12115:
12116:
12117: # --------------------------------------------------- Course Resourcedata Query
12118: #
12119: # Parameters:
12120: # $coursenum - Number of the course.
12121: # $coursedomain - Domain at which the course was created.
12122: # Returns:
12123: # A hash of the course parameters along (I think) with timestamps
12124: # and version info.
12125:
12126: sub get_courseresdata {
12127: my ($coursenum,$coursedomain)=@_;
12128: my $coursehom=&homeserver($coursenum,$coursedomain);
12129: my $hashid=$coursenum.':'.$coursedomain;
12130: my ($result,$cached)=&is_cached_new('courseres',$hashid);
12131: my %dumpreply;
12132: unless (defined($cached)) {
12133: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
12134: $result=\%dumpreply;
12135: my ($tmp) = keys(%dumpreply);
12136: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12137: &do_cache_new('courseres',$hashid,$result,600);
12138: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
12139: return $tmp;
12140: } elsif ($tmp =~ /^(error)/) {
12141: $result=undef;
12142: &do_cache_new('courseres',$hashid,$result,600);
12143: }
12144: }
12145: return $result;
12146: }
12147:
12148: sub devalidateuserresdata {
12149: my ($uname,$udom)=@_;
12150: my $hashid="$udom:$uname";
12151: &devalidate_cache_new('userres',$hashid);
12152: }
12153:
12154: sub get_userresdata {
12155: my ($uname,$udom)=@_;
12156: #most student don\'t have any data set, check if there is some data
12157: if (&EXT_cache_status($udom,$uname)) { return undef; }
12158:
12159: my $hashid="$udom:$uname";
12160: my ($result,$cached)=&is_cached_new('userres',$hashid);
12161: if (!defined($cached)) {
12162: my %resourcedata=&dump('resourcedata',$udom,$uname);
12163: $result=\%resourcedata;
12164: &do_cache_new('userres',$hashid,$result,600);
12165: }
12166: my ($tmp)=keys(%$result);
12167: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12168: return $result;
12169: }
12170: #error 2 occurs when the .db doesn't exist
12171: if ($tmp!~/error: 2 /) {
12172: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12173: &logthis("<font color=\"blue\">WARNING:".
12174: " Trying to get resource data for ".
12175: $uname." at ".$udom.": ".
12176: $tmp."</font>");
12177: }
12178: } elsif ($tmp=~/error: 2 /) {
12179: #&EXT_cache_set($udom,$uname);
12180: &do_cache_new('userres',$hashid,undef,600);
12181: undef($tmp); # not really an error so don't send it back
12182: }
12183: return $tmp;
12184: }
12185: #----------------------------------------------- resdata - return resource data
12186: # Purpose:
12187: # Return resource data for either users or for a course.
12188: # Parameters:
12189: # $name - Course/user name.
12190: # $domain - Name of the domain the user/course is registered on.
12191: # $type - Type of thing $name is (must be 'course' or 'user')
12192: # $mapp - decluttered URL of enclosing map
12193: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
12194: # $recurseup - Ref to array of map URLs, starting with map containing
12195: # $mapp up through hierarchy of nested maps to top level map.
12196: # $courseid - CourseID (first part of param identifier).
12197: # $modifier - Middle part of param identifier.
12198: # $what - Last part of param identifier.
12199: # @which - Array of names of resources desired.
12200: # Returns:
12201: # The value of the first reasource in @which that is found in the
12202: # resource hash.
12203: # Exceptional Conditions:
12204: # If the $type passed in is not valid (not the string 'course' or
12205: # 'user', an undefined reference is returned.
12206: # If none of the resources are found, an undef is returned
12207: sub resdata {
12208: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12209: $modifier,$what,@which)=@_;
12210: my $result;
12211: if ($type eq 'course') {
12212: $result=&get_courseresdata($name,$domain);
12213: } elsif ($type eq 'user') {
12214: $result=&get_userresdata($name,$domain);
12215: }
12216: if (!ref($result)) { return $result; }
12217: foreach my $item (@which) {
12218: if ($item->[1] eq 'course') {
12219: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12220: unless ($$recursed) {
12221: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
12222: $$recursed = 1;
12223: }
12224: foreach my $item (@${recurseup}) {
12225: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12226: last if (defined($result->{$norecursechk}));
12227: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12228: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12229: }
12230: }
12231: }
12232: if (defined($result->{$item->[0]})) {
12233: return [$result->{$item->[0]},$item->[1]];
12234: }
12235: }
12236: return undef;
12237: }
12238:
12239: sub get_domain_lti {
12240: my ($cdom,$context) = @_;
12241: my ($name,%lti);
12242: if ($context eq 'consumer') {
12243: $name = 'ltitools';
12244: } elsif ($context eq 'provider') {
12245: $name = 'lti';
12246: } else {
12247: return %lti;
12248: }
12249: my ($result,$cached)=&is_cached_new($name,$cdom);
12250: if (defined($cached)) {
12251: if (ref($result) eq 'HASH') {
12252: %lti = %{$result};
12253: }
12254: } else {
12255: my %domconfig = &get_dom('configuration',[$name],$cdom);
12256: if (ref($domconfig{$name}) eq 'HASH') {
12257: %lti = %{$domconfig{$name}};
12258: my %encdomconfig = &get_dom('encconfig',[$name],$cdom,undef,1);
12259: if (ref($encdomconfig{$name}) eq 'HASH') {
12260: foreach my $id (keys(%lti)) {
12261: if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
12262: foreach my $item ('key','secret') {
12263: $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
12264: }
12265: }
12266: }
12267: }
12268: }
12269: my $cachetime = 24*60*60;
12270: &do_cache_new($name,$cdom,\%lti,$cachetime);
12271: }
12272: return %lti;
12273: }
12274:
12275: sub get_course_lti {
12276: my ($cnum,$cdom) = @_;
12277: my $hashid=$cdom.'_'.$cnum;
12278: my %courselti;
12279: my ($result,$cached)=&is_cached_new('courselti',$hashid);
12280: if (defined($cached)) {
12281: if (ref($result) eq 'HASH') {
12282: %courselti = %{$result};
12283: }
12284: } else {
12285: %courselti = &dump('lti',$cdom,$cnum,undef,undef,undef,1);
12286: my $cachetime = 24*60*60;
12287: &do_cache_new('courselti',$hashid,\%courselti,$cachetime);
12288: }
12289: return %courselti;
12290: }
12291:
12292: sub courselti_itemid {
12293: my ($cnum,$cdom,$url,$method,$params,$context) = @_;
12294: my ($chome,$itemid);
12295: $chome = &homeserver($cnum,$cdom);
12296: return if ($chome eq 'no_host');
12297: if (ref($params) eq 'HASH') {
12298: my $items = &freeze_escape($params);
12299: my $rep;
12300: if (grep { $_ eq $chome } current_machine_ids()) {
12301: $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
12302: } else {
12303: my $escurl = &escape($url);
12304: my $escmethod = &escape($method);
12305: my $items = &freeze_escape($params);
12306: $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
12307: }
12308: unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12309: ($rep eq 'unknown_cmd')) {
12310: $itemid = $rep;
12311: }
12312: }
12313: return $itemid;
12314: }
12315:
12316: sub domainlti_itemid {
12317: my ($cdom,$url,$method,$params,$context) = @_;
12318: my ($primary_id,$itemid);
12319: $primary_id = &domain($cdom,'primary');
12320: return if ($primary_id eq '');
12321: if (ref($params) eq 'HASH') {
12322: my $items = &freeze_escape($params);
12323: my $rep;
12324: if (grep { $_ eq $primary_id } current_machine_ids()) {
12325: $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
12326: } else {
12327: my $cnum = '';
12328: my $escurl = &escape($url);
12329: my $escmethod = &escape($method);
12330: my $items = &freeze_escape($params);
12331: $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
12332: }
12333: unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12334: ($rep eq 'unknown_cmd')) {
12335: $itemid = $rep;
12336: }
12337: }
12338: return $itemid;
12339: }
12340:
12341: sub get_numsuppfiles {
12342: my ($cnum,$cdom,$ignorecache)=@_;
12343: my $hashid=$cnum.':'.$cdom;
12344: my ($suppcount,$cached);
12345: unless ($ignorecache) {
12346: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
12347: }
12348: unless (defined($cached)) {
12349: my $chome=&homeserver($cnum,$cdom);
12350: unless ($chome eq 'no_host') {
12351: ($suppcount,my $supptools,my $errors) = (0,0,0);
12352: my $suppmap = 'supplemental.sequence';
12353: ($suppcount,$supptools,$errors) =
12354: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
12355: $supptools,$errors);
12356: }
12357: &do_cache_new('suppcount',$hashid,$suppcount,600);
12358: }
12359: return $suppcount;
12360: }
12361:
12362: #
12363: # EXT resource caching routines
12364: #
12365:
12366: {
12367: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12368: #
12369: # The course for which we cache
12370: my $cachedmapkey='';
12371: # The cached recursive maps for this course
12372: my %cachedmaps=();
12373: # When this was last done
12374: my $cachedmaptime='';
12375:
12376: sub clear_EXT_cache_status {
12377: &delenv('cache.EXT.');
12378: }
12379:
12380: sub EXT_cache_status {
12381: my ($target_domain,$target_user) = @_;
12382: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12383: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
12384: # We know already the user has no data
12385: return 1;
12386: } else {
12387: return 0;
12388: }
12389: }
12390:
12391: sub EXT_cache_set {
12392: my ($target_domain,$target_user) = @_;
12393: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12394: #&appenv({$cachename => time});
12395: }
12396:
12397: # --------------------------------------------------------- Value of a Variable
12398: sub EXT {
12399:
12400: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
12401: unless ($varname) { return ''; }
12402: #get real user name/domain, courseid and symb
12403: my $courseid;
12404: my $publicuser;
12405: if ($symbparm) {
12406: $symbparm=&get_symb_from_alias($symbparm);
12407: }
12408: if (!($uname && $udom)) {
12409: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
12410: if (!$symbparm) { $symbparm=$cursymb; }
12411: } else {
12412: $courseid=$env{'request.course.id'};
12413: }
12414: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12415: my $rest;
12416: if (defined($therest[0])) {
12417: $rest=join('.',@therest);
12418: } else {
12419: $rest='';
12420: }
12421:
12422: my $qualifierrest=$qualifier;
12423: if ($rest) { $qualifierrest.='.'.$rest; }
12424: my $spacequalifierrest=$space;
12425: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
12426: if ($realm eq 'user') {
12427: # --------------------------------------------------------------- user.resource
12428: if ($space eq 'resource') {
12429: if ( (defined($Apache::lonhomework::parsing_a_problem)
12430: || defined($Apache::lonhomework::parsing_a_task))
12431: &&
12432: ($symbparm eq &symbread()) ) {
12433: # if we are in the middle of processing the resource the
12434: # get the value we are planning on committing
12435: if (defined($Apache::lonhomework::results{$qualifierrest})) {
12436: return $Apache::lonhomework::results{$qualifierrest};
12437: } else {
12438: return $Apache::lonhomework::history{$qualifierrest};
12439: }
12440: } else {
12441: my %restored;
12442: if ($publicuser || $env{'request.state'} eq 'construct') {
12443: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12444: } else {
12445: %restored=&restore($symbparm,$courseid,$udom,$uname);
12446: }
12447: return $restored{$qualifierrest};
12448: }
12449: # ----------------------------------------------------------------- user.access
12450: } elsif ($space eq 'access') {
12451: # FIXME - not supporting calls for a specific user
12452: return &allowed($qualifier,$rest);
12453: # ------------------------------------------ user.preferences, user.environment
12454: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
12455: if (($uname eq $env{'user.name'}) &&
12456: ($udom eq $env{'user.domain'})) {
12457: return $env{join('.',('environment',$qualifierrest))};
12458: } else {
12459: my %returnhash;
12460: if (!$publicuser) {
12461: %returnhash=&userenvironment($udom,$uname,
12462: $qualifierrest);
12463: }
12464: return $returnhash{$qualifierrest};
12465: }
12466: # ----------------------------------------------------------------- user.course
12467: } elsif ($space eq 'course') {
12468: # FIXME - not supporting calls for a specific user
12469: return $env{join('.',('request.course',$qualifier))};
12470: # ------------------------------------------------------------------- user.role
12471: } elsif ($space eq 'role') {
12472: # FIXME - not supporting calls for a specific user
12473: my ($role,$where)=split(/\./,$env{'request.role'});
12474: if ($qualifier eq 'value') {
12475: return $role;
12476: } elsif ($qualifier eq 'extent') {
12477: return $where;
12478: }
12479: # ----------------------------------------------------------------- user.domain
12480: } elsif ($space eq 'domain') {
12481: return $udom;
12482: # ------------------------------------------------------------------- user.name
12483: } elsif ($space eq 'name') {
12484: return $uname;
12485: # ---------------------------------------------------- Any other user namespace
12486: } else {
12487: my %reply;
12488: if (!$publicuser) {
12489: %reply=&get($space,[$qualifierrest],$udom,$uname);
12490: }
12491: return $reply{$qualifierrest};
12492: }
12493: } elsif ($realm eq 'query') {
12494: # ---------------------------------------------- pull stuff out of query string
12495: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12496: [$spacequalifierrest]);
12497: return $env{'form.'.$spacequalifierrest};
12498: } elsif ($realm eq 'request') {
12499: # ------------------------------------------------------------- request.browser
12500: if ($space eq 'browser') {
12501: return $env{'browser.'.$qualifier};
12502: # ------------------------------------------------------------ request.filename
12503: } else {
12504: return $env{'request.'.$spacequalifierrest};
12505: }
12506: } elsif ($realm eq 'course') {
12507: # ---------------------------------------------------------- course.description
12508: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
12509: } elsif ($realm eq 'resource') {
12510:
12511: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
12512: if (!$symbparm) { $symbparm=&symbread(); }
12513: }
12514:
12515: if ($qualifier eq '') {
12516: if ($space eq 'title') {
12517: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12518: return &gettitle($symbparm);
12519: }
12520:
12521: if ($space eq 'map') {
12522: my ($map) = &decode_symb($symbparm);
12523: return &symbread($map);
12524: }
12525: if ($space eq 'maptitle') {
12526: my ($map) = &decode_symb($symbparm);
12527: return &gettitle($map);
12528: }
12529: if ($space eq 'filename') {
12530: if ($symbparm) {
12531: return &clutter((&decode_symb($symbparm))[2]);
12532: }
12533: return &hreflocation('',$env{'request.filename'});
12534: }
12535:
12536: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12537: if ($space eq 'visibleparts') {
12538: my $navmap = Apache::lonnavmaps::navmap->new();
12539: my $item;
12540: if (ref($navmap)) {
12541: my $res = $navmap->getBySymb($symbparm);
12542: my $parts = $res->parts();
12543: if (ref($parts) eq 'ARRAY') {
12544: $item = join(',',@{$parts});
12545: }
12546: undef($navmap);
12547: }
12548: return $item;
12549: }
12550: }
12551: }
12552:
12553: my ($section, $group, @groups, @recurseup, $recursed);
12554: if (ref($recurseupref) eq 'ARRAY') {
12555: @recurseup = @{$recurseupref};
12556: $recursed = 1;
12557: }
12558: my ($courselevelm,$courseleveli,$courselevel,$mapp);
12559: if (($courseid eq '') && ($cid)) {
12560: $courseid = $cid;
12561: }
12562: if (($symbparm && $courseid) &&
12563: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
12564:
12565: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
12566:
12567: # ----------------------------------------------------- Cascading lookup scheme
12568: my $symbp=$symbparm;
12569: $mapp=&deversion((&decode_symb($symbp))[0]);
12570: my $symbparm=$symbp.'.'.$spacequalifierrest;
12571: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
12572: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
12573: if (($env{'user.name'} eq $uname) &&
12574: ($env{'user.domain'} eq $udom)) {
12575: $section=$env{'request.course.sec'};
12576: @groups = split(/:/,$env{'request.course.groups'});
12577: @groups=&sort_course_groups($courseid,@groups);
12578: } else {
12579: if (! defined($usection)) {
12580: $section=&getsection($udom,$uname,$courseid);
12581: } else {
12582: $section = $usection;
12583: }
12584: @groups = &get_users_groups($udom,$uname,$courseid);
12585: }
12586:
12587: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12588: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
12589: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
12590: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12591:
12592: $courselevel=$courseid.'.'.$spacequalifierrest;
12593: my $courselevelr=$courseid.'.'.$symbparm;
12594: $courseleveli=$courseid.'.'.$recurseparm;
12595: $courselevelm=$courseid.'.'.$mapparm;
12596:
12597: # ----------------------------------------------------------- first, check user
12598:
12599: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12600: \@recurseup,$courseid,'.',$spacequalifierrest,
12601: ([$courselevelr,'resource'],
12602: [$courselevelm,'map' ],
12603: [$courseleveli,'map' ],
12604: [$courselevel, 'course' ]));
12605: if (defined($userreply)) { return &get_reply($userreply); }
12606:
12607: # ------------------------------------------------ second, check some of course
12608: my $coursereply;
12609: if (@groups > 0) {
12610: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
12611: $recurseparm,$mapparm,$spacequalifierrest,
12612: $mapp,\$recursed,\@recurseup);
12613: if (defined($coursereply)) { return &get_reply($coursereply); }
12614: }
12615:
12616: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12617: $env{'course.'.$courseid.'.domain'},
12618: 'course',$mapp,\$recursed,\@recurseup,
12619: $courseid,'.['.$section.'].',$spacequalifierrest,
12620: ([$seclevelr, 'resource'],
12621: [$seclevelm, 'map' ],
12622: [$secleveli, 'map' ],
12623: [$seclevel, 'course' ],
12624: [$courselevelr,'resource']));
12625: if (defined($coursereply)) { return &get_reply($coursereply); }
12626:
12627: # ------------------------------------------------------ third, check map parms
12628: my %parmhash=();
12629: my $thisparm='';
12630: if (tie(%parmhash,'GDBM_File',
12631: $env{'request.course.fn'}.'_parms.db',
12632: &GDBM_READER(),0640)) {
12633: $thisparm=$parmhash{$symbparm};
12634: untie(%parmhash);
12635: }
12636: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
12637: }
12638: # ------------------------------------------ fourth, look in resource metadata
12639:
12640: my $what = $spacequalifierrest;
12641: $what=~s/\./\_/;
12642: my $filename;
12643: if (!$symbparm) { $symbparm=&symbread(); }
12644: if ($symbparm) {
12645: $filename=(&decode_symb($symbparm))[2];
12646: } else {
12647: $filename=$env{'request.filename'};
12648: }
12649: my $toolsymb;
12650: if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12651: $toolsymb = $symbparm;
12652: }
12653: my $metadata=&metadata($filename,$what,$toolsymb);
12654: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12655: $metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
12656: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12657:
12658: # ----------------------------------------------- fifth, look in rest of course
12659: if ($symbparm && defined($courseid) &&
12660: $courseid eq $env{'request.course.id'}) {
12661: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12662: $env{'course.'.$courseid.'.domain'},
12663: 'course',$mapp,\$recursed,\@recurseup,
12664: $courseid,'.',$spacequalifierrest,
12665: ([$courselevelm,'map' ],
12666: [$courseleveli,'map' ],
12667: [$courselevel, 'course']));
12668: if (defined($coursereply)) { return &get_reply($coursereply); }
12669: }
12670: # ------------------------------------------------------------------ Cascade up
12671: unless ($space eq '0') {
12672: my @parts=split(/_/,$space);
12673: my $id=pop(@parts);
12674: my $part=join('_',@parts);
12675: if ($part eq '') { $part='0'; }
12676: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
12677: $symbparm,$udom,$uname,$section,1);
12678: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
12679: }
12680: if ($recurse) { return undef; }
12681: my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
12682: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
12683: # ---------------------------------------------------- Any other user namespace
12684: } elsif ($realm eq 'environment') {
12685: # ----------------------------------------------------------------- environment
12686: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12687: return $env{'environment.'.$spacequalifierrest};
12688: } else {
12689: if ($uname eq 'anonymous' && $udom eq '') {
12690: return '';
12691: }
12692: my %returnhash=&userenvironment($udom,$uname,
12693: $spacequalifierrest);
12694: return $returnhash{$spacequalifierrest};
12695: }
12696: } elsif ($realm eq 'system') {
12697: # ----------------------------------------------------------------- system.time
12698: if ($space eq 'time') {
12699: return time;
12700: }
12701: } elsif ($realm eq 'server') {
12702: # ----------------------------------------------------------------- system.time
12703: if ($space eq 'name') {
12704: return $ENV{'SERVER_NAME'};
12705: }
12706: } elsif ($realm eq 'client') {
12707: if ($space eq 'remote_addr') {
12708: return &get_requestor_ip();
12709: }
12710: }
12711: return '';
12712: }
12713:
12714: sub get_reply {
12715: my ($reply_value) = @_;
12716: if (ref($reply_value) eq 'ARRAY') {
12717: if (wantarray) {
12718: return @$reply_value;
12719: }
12720: return $reply_value->[0];
12721: } else {
12722: return $reply_value;
12723: }
12724: }
12725:
12726: sub check_group_parms {
12727: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12728: $recursed,$recurseupref) = @_;
12729: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12730: [$what,'course']);
12731: my $coursereply;
12732: foreach my $group (@{$groups}) {
12733: my @groupitems = ();
12734: foreach my $level (@levels) {
12735: my $item = $courseid.'.['.$group.'].'.$level->[0];
12736: push(@groupitems,[$item,$level->[1]]);
12737: }
12738: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12739: $env{'course.'.$courseid.'.domain'},
12740: 'course',$mapp,$recursed,$recurseupref,
12741: $courseid,'.['.$group.'].',$what,
12742: @groupitems);
12743: last if (defined($coursereply));
12744: }
12745: return $coursereply;
12746: }
12747:
12748: sub get_map_hierarchy {
12749: my ($mapname,$courseid) = @_;
12750: my @recurseup = ();
12751: if ($mapname) {
12752: if (($cachedmapkey eq $courseid) &&
12753: (abs($cachedmaptime-time)<5)) {
12754: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12755: return @{$cachedmaps{$mapname}};
12756: }
12757: }
12758: my $navmap = Apache::lonnavmaps::navmap->new();
12759: if (ref($navmap)) {
12760: @recurseup = $navmap->recurseup_maps($mapname);
12761: undef($navmap);
12762: $cachedmaps{$mapname} = \@recurseup;
12763: $cachedmaptime=time;
12764: $cachedmapkey=$courseid;
12765: }
12766: }
12767: return @recurseup;
12768: }
12769:
12770: }
12771:
12772: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
12773: my ($courseid,@groups) = @_;
12774: @groups = sort(@groups);
12775: return @groups;
12776: }
12777:
12778: sub packages_tab_default {
12779: my ($uri,$varname,$toolsymb)=@_;
12780: my (undef,$part,$name)=split(/\./,$varname);
12781:
12782: my (@extension,@specifics,$do_default);
12783: foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
12784: my ($pack_type,$pack_part)=split(/_/,$package,2);
12785: if ($pack_type eq 'default') {
12786: $do_default=1;
12787: } elsif ($pack_type eq 'extension') {
12788: push(@extension,[$package,$pack_type,$pack_part]);
12789: } elsif ($pack_part eq $part || $pack_type eq 'part') {
12790: # only look at packages defaults for packages that this id is
12791: push(@specifics,[$package,$pack_type,$pack_part]);
12792: }
12793: }
12794: # first look for a package that matches the requested part id
12795: foreach my $package (@specifics) {
12796: my (undef,$pack_type,$pack_part)=@{$package};
12797: next if ($pack_part ne $part);
12798: if (defined($packagetab{"$pack_type&$name&default"})) {
12799: return $packagetab{"$pack_type&$name&default"};
12800: }
12801: }
12802: # look for any possible matching non extension_ package
12803: foreach my $package (@specifics) {
12804: my (undef,$pack_type,$pack_part)=@{$package};
12805: if (defined($packagetab{"$pack_type&$name&default"})) {
12806: return $packagetab{"$pack_type&$name&default"};
12807: }
12808: if ($pack_type eq 'part') { $pack_part='0'; }
12809: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12810: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
12811: }
12812: }
12813: # look for any posible extension_ match
12814: foreach my $package (@extension) {
12815: my ($package,$pack_type)=@{$package};
12816: if (defined($packagetab{"$pack_type&$name&default"})) {
12817: return $packagetab{"$pack_type&$name&default"};
12818: }
12819: if (defined($packagetab{$package."&$name&default"})) {
12820: return $packagetab{$package."&$name&default"};
12821: }
12822: }
12823: # look for a global default setting
12824: if ($do_default && defined($packagetab{"default&$name&default"})) {
12825: return $packagetab{"default&$name&default"};
12826: }
12827: return undef;
12828: }
12829:
12830: sub add_prefix_and_part {
12831: my ($prefix,$part)=@_;
12832: my $keyroot;
12833: if (defined($prefix) && $prefix !~ /^__/) {
12834: # prefix that has a part already
12835: $keyroot=$prefix;
12836: } elsif (defined($prefix)) {
12837: # prefix that is missing a part
12838: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12839: } else {
12840: # no prefix at all
12841: if (defined($part)) { $keyroot='_'.$part; }
12842: }
12843: return $keyroot;
12844: }
12845:
12846: # ---------------------------------------------------------------- Get metadata
12847:
12848: my %metaentry;
12849: my %importedpartids;
12850: my %importedrespids;
12851: sub metadata {
12852: my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
12853: $uri=&declutter($uri);
12854: # if it is a non metadata possible uri return quickly
12855: if (($uri eq '') ||
12856: (($uri =~ m|^/*adm/|) &&
12857: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
12858: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
12859: return undef;
12860: }
12861: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
12862: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
12863: return undef;
12864: }
12865: my $filename=$uri;
12866: $uri=~s/\.meta$//;
12867: #
12868: # Is the metadata already cached?
12869: # Look at timestamp of caching
12870: # Everything is cached by the main uri, libraries are never directly cached
12871: #
12872: if (!defined($liburi)) {
12873: my ($result,$cached)=&is_cached_new('meta',$uri);
12874: if (defined($cached)) { return $result->{':'.$what}; }
12875: }
12876:
12877: #
12878: # If the uri is for an external tool the file from
12879: # which metadata should be retrieved depends on whether
12880: # the tool had been configured to be gradable (set in the Course
12881: # Editor or Resource Editor).
12882: #
12883: # If a valid symb has been included as the third arg in the call
12884: # to &metadata() that can be used to retrieve the value of
12885: # parameter_0_gradable set for the resource, and included in the
12886: # uploaded map containing the tool. The value is retrieved via
12887: # &EXT(), if a valid symb is available. Otherwise the value of
12888: # gradable in the exttool_$marker.db file for the tool instance
12889: # is retrieved via &get().
12890: #
12891: # When lonuserstate::traceroute() calls lonnet::EXT() for
12892: # hiddenresource and encrypturl (during course initialization)
12893: # the map-level parameter for resource.0.gradable included in the
12894: # uploaded map containing the tool will not yet have been stored
12895: # in the user_course_parms.db file for the user's session, so in
12896: # this case fall back to retrieving gradable status from the
12897: # exttool_$marker.db file.
12898: #
12899: # In order to avoid an infinite loop, &metadata() will return
12900: # before a call to &EXT(), if the uri is for an external tool
12901: # and the $what for which metadata is being requested is
12902: # parameter_0_gradable or 0_gradable.
12903: #
12904:
12905: if ($uri =~ /ext\.tool$/) {
12906: if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12907: return;
12908: } else {
12909: my ($checked,$use_passback);
12910: if ($toolsymb ne '') {
12911: (undef,undef,my $tooluri) = &decode_symb($toolsymb);
12912: if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
12913: $checked = 1;
12914: if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12915: $use_passback = 1;
12916: }
12917: }
12918: }
12919: unless ($checked) {
12920: my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12921: $marker=~s/\D//g;
12922: if ($marker) {
12923: my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12924: $use_passback = $toolsettings{'gradable'};
12925: }
12926: }
12927: if ($use_passback) {
12928: $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12929: } else {
12930: $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12931: }
12932: }
12933: }
12934:
12935: {
12936: # Imported parts would go here
12937: my @origfiletagids=();
12938: my $importedparts=0;
12939:
12940: # Imported responseids would go here
12941: my $importedresponses=0;
12942: #
12943: # Is this a recursive call for a library?
12944: #
12945: # if (! exists($metacache{$uri})) {
12946: # $metacache{$uri}={};
12947: # }
12948: my $cachetime = 60*60;
12949: if ($liburi) {
12950: $liburi=&declutter($liburi);
12951: $filename=$liburi;
12952: } else {
12953: &devalidate_cache_new('meta',$uri);
12954: undef(%metaentry);
12955: }
12956: my %metathesekeys=();
12957: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
12958: my $metastring;
12959: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
12960: my $which = &hreflocation('','/'.($liburi || $uri));
12961: $metastring =
12962: &Apache::lonnet::ssi_body($which,
12963: ('grade_target' => 'meta'));
12964: $cachetime = 1; # only want this cached in the child not long term
12965: } elsif (($uri !~ m -^(editupload)/-) &&
12966: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
12967: my $file=&filelocation('',&clutter($filename));
12968: #push(@{$metaentry{$uri.'.file'}},$file);
12969: $metastring=&getfile($file);
12970: }
12971: my $parser=HTML::LCParser->new(\$metastring);
12972: my $token;
12973: undef %metathesekeys;
12974: while ($token=$parser->get_token) {
12975: if ($token->[0] eq 'S') {
12976: if (defined($token->[2]->{'package'})) {
12977: #
12978: # This is a package - get package info
12979: #
12980: my $package=$token->[2]->{'package'};
12981: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12982: if (defined($token->[2]->{'id'})) {
12983: $keyroot.='_'.$token->[2]->{'id'};
12984: }
12985: if ($metaentry{':packages'}) {
12986: $metaentry{':packages'}.=','.$package.$keyroot;
12987: } else {
12988: $metaentry{':packages'}=$package.$keyroot;
12989: }
12990: foreach my $pack_entry (keys(%packagetab)) {
12991: my $part=$keyroot;
12992: $part=~s/^\_//;
12993: if ($pack_entry=~/^\Q$package\E\&/ ||
12994: $pack_entry=~/^\Q$package\E_0\&/) {
12995: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
12996: # ignore package.tab specified default values
12997: # here &package_tab_default() will fetch those
12998: if ($subp eq 'default') { next; }
12999: my $value=$packagetab{$pack_entry};
13000: my $unikey;
13001: if ($pack =~ /_0$/) {
13002: $unikey='parameter_0_'.$name;
13003: $part=0;
13004: } else {
13005: $unikey='parameter'.$keyroot.'_'.$name;
13006: }
13007: if ($subp eq 'display') {
13008: $value.=' [Part: '.$part.']';
13009: }
13010: $metaentry{':'.$unikey.'.part'}=$part;
13011: $metathesekeys{$unikey}=1;
13012: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13013: $metaentry{':'.$unikey.'.'.$subp}=$value;
13014: }
13015: if (defined($metaentry{':'.$unikey.'.default'})) {
13016: $metaentry{':'.$unikey}=
13017: $metaentry{':'.$unikey.'.default'};
13018: }
13019: }
13020: }
13021: } else {
13022: #
13023: # This is not a package - some other kind of start tag
13024: #
13025: my $entry=$token->[1];
13026: my $unikey='';
13027:
13028: if ($entry eq 'import') {
13029: #
13030: # Importing a library here
13031: #
13032: my $location=$parser->get_text('/import');
13033: my $dir=$filename;
13034: $dir=~s|[^/]*$||;
13035: $location=&filelocation($dir,$location);
13036:
13037: my $importid=$token->[2]->{'id'};
13038: my $importmode=$token->[2]->{'importmode'};
13039: #
13040: # Check metadata for imported file to
13041: # see if it contained response items
13042: #
13043: my ($origfile,@libfilekeys);
13044: my %currmetaentry = %metaentry;
13045: @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
13046: $depthcount+1));
13047: if (grep(/^responseorder$/,@libfilekeys)) {
13048: my $libresponseorder = &metadata($location,'responseorder',undef,undef,
13049: undef,$depthcount+1);
13050: if ($libresponseorder ne '') {
13051: if ($#origfiletagids<0) {
13052: undef(%importedrespids);
13053: undef(%importedpartids);
13054: }
13055: my @respids = split(/\s*,\s*/,$libresponseorder);
13056: if (@respids) {
13057: $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
13058: }
13059: if ($importedrespids{$importid} ne '') {
13060: $importedresponses = 1;
13061: # We need to get the original file and the imported file to get the response order correct
13062: # Load and inspect original file
13063: if ($#origfiletagids<0) {
13064: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13065: $origfile=&getfile($origfilelocation);
13066: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13067: }
13068: }
13069: }
13070: }
13071: # Do not overwrite contents of %metaentry hash for resource itself with
13072: # hash populated for imported library file
13073: %metaentry = %currmetaentry;
13074: undef(%currmetaentry);
13075: if ($importmode eq 'part') {
13076: # Import as part(s)
13077: $importedparts=1;
13078: # We need to get the original file and the imported file to get the part order correct
13079: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
13080: # Load and inspect original file if we didn't do that already
13081: if ($#origfiletagids<0) {
13082: undef(%importedrespids);
13083: undef(%importedpartids);
13084: if ($origfile eq '') {
13085: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13086: $origfile=&getfile($origfilelocation);
13087: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13088: }
13089: }
13090: my @impfilepartids;
13091: # If <partorder> tag is included in metadata for the imported file
13092: # get the parts in the imported file from that.
13093: if (grep(/^partorder$/,@libfilekeys)) {
13094: %currmetaentry = %metaentry;
13095: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13096: $depthcount+1);
13097: %metaentry = %currmetaentry;
13098: undef(%currmetaentry);
13099: if ($libpartorder ne '') {
13100: @impfilepartids=split(/\s*,\s*/,$libpartorder);
13101: }
13102: } else {
13103: # If no <partorder> tag available, load and inspect imported file
13104: my $impfile=&getfile($location);
13105: @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13106: }
13107: if ($#impfilepartids>=0) {
13108: # This problem had parts
13109: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
13110: } else {
13111: # Importing by turning a single problem into a problem part
13112: # It gets the import-tags ID as part-ID
13113: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
13114: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
13115: }
13116: } else {
13117: # Import as problem or as normal import
13118: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13119: unless ($importmode eq 'problem') {
13120: # Normal import
13121: if (defined($token->[2]->{'id'})) {
13122: $unikey.='_'.$token->[2]->{'id'};
13123: }
13124: }
13125: # Check metadata for imported file to
13126: # see if it contained parts
13127: if (grep(/^partorder$/,@libfilekeys)) {
13128: %currmetaentry = %metaentry;
13129: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13130: $depthcount+1);
13131: %metaentry = %currmetaentry;
13132: undef(%currmetaentry);
13133: if ($libpartorder ne '') {
13134: $importedparts = 1;
13135: $importedpartids{$token->[2]->{'id'}}=$libpartorder;
13136: }
13137: }
13138: }
13139: if ($depthcount<20) {
13140: my $metadata =
13141: &metadata($uri,'keys',$toolsymb,$location,$unikey,
13142: $depthcount+1);
13143: foreach my $meta (split(',',$metadata)) {
13144: $metaentry{':'.$meta}=$metaentry{':'.$meta};
13145: $metathesekeys{$meta}=1;
13146: }
13147: }
13148: } else {
13149: #
13150: # Not importing, some other kind of non-package, non-library start tag
13151: #
13152: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
13153: if (defined($token->[2]->{'id'})) {
13154: $unikey.='_'.$token->[2]->{'id'};
13155: }
13156: if (defined($token->[2]->{'name'})) {
13157: $unikey.='_'.$token->[2]->{'name'};
13158: }
13159: $metathesekeys{$unikey}=1;
13160: foreach my $param (@{$token->[3]}) {
13161: $metaentry{':'.$unikey.'.'.$param} =
13162: $token->[2]->{$param};
13163: }
13164: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
13165: my $default=$metaentry{':'.$unikey.'.default'};
13166: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
13167: # only ws inside the tag, and not in default, so use default
13168: # as value
13169: $metaentry{':'.$unikey}=$default;
13170: } elsif ( $internaltext =~ /\S/ ) {
13171: # something interesting inside the tag
13172: $metaentry{':'.$unikey}=$internaltext;
13173: } else {
13174: # no interesting values, don't set a default
13175: }
13176: # end of not-a-package not-a-library import
13177: }
13178: # end of not-a-package start tag
13179: }
13180: # the next is the end of "start tag"
13181: }
13182: }
13183: my ($extension) = ($uri =~ /\.(\w+)$/);
13184: $extension = lc($extension);
13185: if ($extension eq 'htm') { $extension='html'; }
13186:
13187: foreach my $key (keys(%packagetab)) {
13188: #no specific packages #how's our extension
13189: if ($key!~/^extension_\Q$extension\E&/) { next; }
13190: &metadata_create_package_def($uri,$key,'extension_'.$extension,
13191: \%metathesekeys);
13192: }
13193:
13194: if (!exists($metaentry{':packages'})
13195: || $packagetab{"import_defaults&extension_$extension"}) {
13196: foreach my $key (keys(%packagetab)) {
13197: #no specific packages well let's get default then
13198: if ($key!~/^default&/) { next; }
13199: &metadata_create_package_def($uri,$key,'default',
13200: \%metathesekeys);
13201: }
13202: }
13203: # are there custom rights to evaluate
13204: if ($metaentry{':copyright'} eq 'custom') {
13205:
13206: #
13207: # Importing a rights file here
13208: #
13209: unless ($depthcount) {
13210: my $location=$metaentry{':customdistributionfile'};
13211: my $dir=$filename;
13212: $dir=~s|[^/]*$||;
13213: $location=&filelocation($dir,$location);
13214: my $rights_metadata =
13215: &metadata($uri,'keys',$toolsymb,$location,'_rights',
13216: $depthcount+1);
13217: foreach my $rights (split(',',$rights_metadata)) {
13218: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
13219: $metathesekeys{$rights}=1;
13220: }
13221: }
13222: }
13223: # uniqifiy package listing
13224: my %seen;
13225: my @uniq_packages =
13226: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
13227: $metaentry{':packages'} = join(',',@uniq_packages);
13228:
13229: if (($importedresponses) || ($importedparts)) {
13230: if ($importedparts) {
13231: # We had imported parts and need to rebuild partorder
13232: $metaentry{':partorder'}='';
13233: $metathesekeys{'partorder'}=1;
13234: }
13235: if ($importedresponses) {
13236: # We had imported responses and need to rebuil responseorder
13237: $metaentry{':responseorder'}='';
13238: $metathesekeys{'responseorder'}=1;
13239: }
13240: for (my $index=0;$index<$#origfiletagids;$index+=2) {
13241: my $origid = $origfiletagids[$index+1];
13242: if ($origfiletagids[$index] eq 'part') {
13243: # Original part, part of the problem
13244: if ($importedparts) {
13245: $metaentry{':partorder'}.=','.$origid;
13246: }
13247: } elsif ($origfiletagids[$index] eq 'import') {
13248: if ($importedparts) {
13249: # We have imported parts at this position
13250: if ($importedpartids{$origid} ne '') {
13251: $metaentry{':partorder'}.=','.$importedpartids{$origid};
13252: }
13253: }
13254: if ($importedresponses) {
13255: # We have imported responses at this position
13256: if ($importedrespids{$origid} ne '') {
13257: $metaentry{':responseorder'}.=','.$importedrespids{$origid};
13258: }
13259: }
13260: } else {
13261: # Original response item, part of the problem
13262: if ($importedresponses) {
13263: $metaentry{':responseorder'}.=','.$origid;
13264: }
13265: }
13266: }
13267: if ($importedparts) {
13268: $metaentry{':partorder'}=~s/^\,//;
13269: }
13270: if ($importedresponses) {
13271: $metaentry{':responseorder'}=~s/^\,//;
13272: }
13273: }
13274: $metaentry{':keys'} = join(',',keys(%metathesekeys));
13275: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
13276: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
13277: unless ($liburi) {
13278: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
13279: }
13280: # this is the end of "was not already recently cached
13281: }
13282: return $metaentry{':'.$what};
13283: }
13284:
13285: sub metadata_create_package_def {
13286: my ($uri,$key,$package,$metathesekeys)=@_;
13287: my ($pack,$name,$subp)=split(/\&/,$key);
13288: if ($subp eq 'default') { next; }
13289:
13290: if (defined($metaentry{':packages'})) {
13291: $metaentry{':packages'}.=','.$package;
13292: } else {
13293: $metaentry{':packages'}=$package;
13294: }
13295: my $value=$packagetab{$key};
13296: my $unikey;
13297: $unikey='parameter_0_'.$name;
13298: $metaentry{':'.$unikey.'.part'}=0;
13299: $$metathesekeys{$unikey}=1;
13300: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13301: $metaentry{':'.$unikey.'.'.$subp}=$value;
13302: }
13303: if (defined($metaentry{':'.$unikey.'.default'})) {
13304: $metaentry{':'.$unikey}=
13305: $metaentry{':'.$unikey.'.default'};
13306: }
13307: }
13308:
13309: sub metadata_generate_part0 {
13310: my ($metadata,$metacache,$uri) = @_;
13311: my %allnames;
13312: foreach my $metakey (keys(%$metadata)) {
13313: if ($metakey=~/^parameter\_(.*)/) {
13314: my $part=$$metacache{':'.$metakey.'.part'};
13315: my $name=$$metacache{':'.$metakey.'.name'};
13316: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
13317: $allnames{$name}=$part;
13318: }
13319: }
13320: }
13321: foreach my $name (keys(%allnames)) {
13322: $$metadata{"parameter_0_$name"}=1;
13323: my $key=":parameter_0_$name";
13324: $$metacache{"$key.part"}='0';
13325: $$metacache{"$key.name"}=$name;
13326: $$metacache{"$key.type"}=$$metacache{':parameter_'.
13327: $allnames{$name}.'_'.$name.
13328: '.type'};
13329: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
13330: '.display'};
13331: my $expr='[Part: '.$allnames{$name}.']';
13332: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
13333: $$metacache{"$key.display"}=$olddis;
13334: }
13335: }
13336:
13337: # ------------------------------------------------------ Devalidate title cache
13338:
13339: sub devalidate_title_cache {
13340: my ($url)=@_;
13341: if (!$env{'request.course.id'}) { return; }
13342: my $symb=&symbread($url);
13343: if (!$symb) { return; }
13344: my $key=$env{'request.course.id'}."\0".$symb;
13345: &devalidate_cache_new('title',$key);
13346: }
13347:
13348: # ------------------------------------------------- Get the title of a course
13349:
13350: sub current_course_title {
13351: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
13352: }
13353: # ------------------------------------------------- Get the title of a resource
13354:
13355: sub gettitle {
13356: my $urlsymb=shift;
13357: my $symb=&symbread($urlsymb);
13358: if ($symb) {
13359: my $key=$env{'request.course.id'}."\0".$symb;
13360: my ($result,$cached)=&is_cached_new('title',$key);
13361: if (defined($cached)) {
13362: return $result;
13363: }
13364: my ($map,$resid,$url)=&decode_symb($symb);
13365: my $title='';
13366: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13367: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13368: } else {
13369: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13370: &GDBM_READER(),0640)) {
13371: my $mapid=$bighash{'map_pc_'.&clutter($map)};
13372: $title=$bighash{'title_'.$mapid.'.'.$resid};
13373: untie(%bighash);
13374: }
13375: }
13376: $title=~s/\&colon\;/\:/gs;
13377: if ($title) {
13378: # Remember both $symb and $title for dynamic metadata
13379: $accesshash{$symb.'___crstitle'}=$title;
13380: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
13381: # Cache this title and then return it
13382: return &do_cache_new('title',$key,$title,600);
13383: }
13384: $urlsymb=$url;
13385: }
13386: my $title=&metadata($urlsymb,'title');
13387: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
13388: return $title;
13389: }
13390:
13391: sub get_slot {
13392: my ($which,$cnum,$cdom)=@_;
13393: if (!$cnum || !$cdom) {
13394: (undef,my $courseid)=&whichuser();
13395: $cdom=$env{'course.'.$courseid.'.domain'};
13396: $cnum=$env{'course.'.$courseid.'.num'};
13397: }
13398: my $key=join("\0",'slots',$cdom,$cnum,$which);
13399: my %slotinfo;
13400: if (exists($remembered{$key})) {
13401: $slotinfo{$which} = $remembered{$key};
13402: } else {
13403: %slotinfo=&get('slots',[$which],$cdom,$cnum);
13404: &Apache::lonhomework::showhash(%slotinfo);
13405: my ($tmp)=keys(%slotinfo);
13406: if ($tmp=~/^error:/) { return (); }
13407: $remembered{$key} = $slotinfo{$which};
13408: }
13409: if (ref($slotinfo{$which}) eq 'HASH') {
13410: return %{$slotinfo{$which}};
13411: }
13412: return $slotinfo{$which};
13413: }
13414:
13415: sub get_reservable_slots {
13416: my ($cnum,$cdom,$uname,$udom) = @_;
13417: my $now = time;
13418: my $reservable_info;
13419: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13420: if (exists($remembered{$key})) {
13421: $reservable_info = $remembered{$key};
13422: } else {
13423: my %resv;
13424: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13425: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13426: $reservable_info = \%resv;
13427: $remembered{$key} = $reservable_info;
13428: }
13429: return $reservable_info;
13430: }
13431:
13432: sub get_course_slots {
13433: my ($cnum,$cdom) = @_;
13434: my $hashid=$cnum.':'.$cdom;
13435: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
13436: if (defined($cached)) {
13437: if (ref($result) eq 'HASH') {
13438: return %{$result};
13439: }
13440: } else {
13441: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
13442: my ($tmp) = keys(%slots);
13443: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
13444: &do_cache_new('allslots',$hashid,\%slots,600);
13445: return %slots;
13446: }
13447: }
13448: return;
13449: }
13450:
13451: sub devalidate_slots_cache {
13452: my ($cnum,$cdom)=@_;
13453: my $hashid=$cnum.':'.$cdom;
13454: &devalidate_cache_new('allslots',$hashid);
13455: }
13456:
13457: sub get_coursechange {
13458: my ($cdom,$cnum) = @_;
13459: if ($cdom eq '' || $cnum eq '') {
13460: return unless ($env{'request.course.id'});
13461: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13462: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13463: }
13464: my $hashid=$cdom.'_'.$cnum;
13465: my ($change,$cached)=&is_cached_new('crschange',$hashid);
13466: if ((defined($cached)) && ($change ne '')) {
13467: return $change;
13468: } else {
13469: my %crshash;
13470: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13471: if ($crshash{'internal.contentchange'} eq '') {
13472: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13473: if ($change eq '') {
13474: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13475: $change = $crshash{'internal.created'};
13476: }
13477: } else {
13478: $change = $crshash{'internal.contentchange'};
13479: }
13480: my $cachetime = 600;
13481: &do_cache_new('crschange',$hashid,$change,$cachetime);
13482: }
13483: return $change;
13484: }
13485:
13486: sub devalidate_coursechange_cache {
13487: my ($cnum,$cdom)=@_;
13488: my $hashid=$cnum.':'.$cdom;
13489: &devalidate_cache_new('crschange',$hashid);
13490: }
13491:
13492: # ------------------------------------------------- Update symbolic store links
13493:
13494: sub symblist {
13495: my ($mapname,%newhash)=@_;
13496: $mapname=&deversion(&declutter($mapname));
13497: my %hash;
13498: if (($env{'request.course.fn'}) && (%newhash)) {
13499: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13500: &GDBM_WRCREAT(),0640)) {
13501: foreach my $url (keys(%newhash)) {
13502: next if ($url eq 'last_known'
13503: && $env{'form.no_update_last_known'});
13504: $hash{declutter($url)}=&encode_symb($mapname,
13505: $newhash{$url}->[1],
13506: $newhash{$url}->[0]);
13507: }
13508: if (untie(%hash)) {
13509: return 'ok';
13510: }
13511: }
13512: }
13513: return 'error';
13514: }
13515:
13516: # --------------------------------------------------------------- Verify a symb
13517:
13518: sub symbverify {
13519: my ($symb,$thisurl,$encstate)=@_;
13520: my $thisfn=$thisurl;
13521: $thisfn=&declutter($thisfn);
13522: # direct jump to resource in page or to a sequence - will construct own symbs
13523: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13524: # check URL part
13525: my ($map,$resid,$url)=&decode_symb($symb);
13526:
13527: unless ($url eq $thisfn) { return 0; }
13528:
13529: $symb=&symbclean($symb);
13530: $thisurl=&deversion($thisurl);
13531: $thisfn=&deversion($thisfn);
13532:
13533: my %bighash;
13534: my $okay=0;
13535:
13536: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13537: &GDBM_READER(),0640)) {
13538: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13539: $thisurl =~ s/\?.+$//;
13540: if ($map =~ m{^uploaded/.+\.page$}) {
13541: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13542: $thisurl =~ s{^\Qhttp://https://\E}{https://};
13543: }
13544: }
13545: my $ids;
13546: if ($map =~ m{^uploaded/.+\.page$}) {
13547: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
13548: } else {
13549: $ids=$bighash{'ids_'.&clutter($thisurl)};
13550: }
13551: unless ($ids) {
13552: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
13553: $ids=$bighash{$idkey};
13554: }
13555: if ($ids) {
13556: # ------------------------------------------------------------------- Has ID(s)
13557: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
13558: $symb =~ s/\?.+$//;
13559: }
13560: foreach my $id (split(/\,/,$ids)) {
13561: my ($mapid,$resid)=split(/\./,$id);
13562: if (
13563: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
13564: eq $symb) {
13565: if (ref($encstate)) {
13566: $$encstate = $bighash{'encrypted_'.$id};
13567: }
13568: if (($env{'request.role.adv'}) ||
13569: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13570: ($thisurl eq '/adm/navmaps')) {
13571: $okay=1;
13572: last;
13573: }
13574: }
13575: }
13576: }
13577: untie(%bighash);
13578: }
13579: return $okay;
13580: }
13581:
13582: # --------------------------------------------------------------- Clean-up symb
13583:
13584: sub symbclean {
13585: my $symb=shift;
13586: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13587: # remove version from map
13588: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
13589:
13590: # remove version from URL
13591: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
13592:
13593: # remove wrapper
13594:
13595: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
13596: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
13597: return $symb;
13598: }
13599:
13600: # ---------------------------------------------- Split symb to find map and url
13601:
13602: sub encode_symb {
13603: my ($map,$resid,$url)=@_;
13604: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13605: }
13606:
13607: sub decode_symb {
13608: my $symb=shift;
13609: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13610: my ($map,$resid,$url)=split(/___/,$symb);
13611: return (&fixversion($map),$resid,&fixversion($url));
13612: }
13613:
13614: sub fixversion {
13615: my $fn=shift;
13616: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
13617: my %bighash;
13618: my $uri=&clutter($fn);
13619: my $key=$env{'request.course.id'}.'_'.$uri;
13620: # is this cached?
13621: my ($result,$cached)=&is_cached_new('courseresversion',$key);
13622: if (defined($cached)) { return $result; }
13623: # unfortunately not cached, or expired
13624: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13625: &GDBM_READER(),0640)) {
13626: if ($bighash{'version_'.$uri}) {
13627: my $version=$bighash{'version_'.$uri};
13628: unless (($version eq 'mostrecent') ||
13629: ($version==&getversion($uri))) {
13630: $uri=~s/\.(\w+)$/\.$version\.$1/;
13631: }
13632: }
13633: untie %bighash;
13634: }
13635: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
13636: }
13637:
13638: sub deversion {
13639: my $url=shift;
13640: $url=~s/\.\d+\.(\w+)$/\.$1/;
13641: return $url;
13642: }
13643:
13644: # ------------------------------------------------------ Return symb list entry
13645:
13646: sub symbread {
13647: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
13648: $ignoresymbdb,$noenccheck)=@_;
13649: my $cache_str='request.symbread.cached.'.$thisfn;
13650: if (defined($env{$cache_str})) {
13651: unless (ref($possibles) eq 'HASH') {
13652: if ($ignorecachednull) {
13653: return $env{$cache_str} unless ($env{$cache_str} eq '');
13654: } else {
13655: return $env{$cache_str};
13656: }
13657: }
13658: }
13659: # no filename provided? try from environment
13660: unless ($thisfn) {
13661: if ($env{'request.symb'}) {
13662: return $env{$cache_str}=&symbclean($env{'request.symb'});
13663: }
13664: $thisfn=$env{'request.filename'};
13665: }
13666: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13667: # is that filename actually a symb? Verify, clean, and return
13668: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
13669: if (&symbverify($thisfn,$1)) {
13670: return $env{$cache_str}=&symbclean($thisfn);
13671: }
13672: }
13673: $thisfn=declutter($thisfn);
13674: my %hash;
13675: my %bighash;
13676: my $syval='';
13677: if (($env{'request.course.fn'}) && ($thisfn)) {
13678: my $targetfn = $thisfn;
13679: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
13680: $targetfn = 'adm/wrapper/'.$thisfn;
13681: }
13682: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
13683: $targetfn=$1;
13684: }
13685: unless ($ignoresymbdb) {
13686: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13687: &GDBM_READER(),0640)) {
13688: $syval=$hash{$targetfn};
13689: untie(%hash);
13690: }
13691: if ($syval && $checkforblock) {
13692: my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
13693: if (@blockers) {
13694: $syval='';
13695: }
13696: }
13697: }
13698: # ---------------------------------------------------------- There was an entry
13699: if ($syval) {
13700: #unless ($syval=~/\_\d+$/) {
13701: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
13702: #&appenv({'request.ambiguous' => $thisfn});
13703: #return $env{$cache_str}='';
13704: #}
13705: #$syval.=$1;
13706: #}
13707: } else {
13708: # ------------------------------------------------------- Was not in symb table
13709: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13710: &GDBM_READER(),0640)) {
13711: # ---------------------------------------------- Get ID(s) for current resource
13712: my $ids=$bighash{'ids_'.&clutter($thisfn)};
13713: unless ($ids) {
13714: $ids=$bighash{'ids_/'.$thisfn};
13715: }
13716: unless ($ids) {
13717: # alias?
13718: $ids=$bighash{'mapalias_'.$thisfn};
13719: }
13720: if ($ids) {
13721: # ------------------------------------------------------------------- Has ID(s)
13722: my @possibilities=split(/\,/,$ids);
13723: if ($#possibilities==0) {
13724: # ----------------------------------------------- There is only one possibility
13725: my ($mapid,$resid)=split(/\./,$ids);
13726: $syval=&encode_symb($bighash{'map_id_'.$mapid},
13727: $resid,$thisfn);
13728: if (ref($possibles) eq 'HASH') {
13729: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13730: $possibles->{$syval} = 1;
13731: }
13732: }
13733: if ($checkforblock) {
13734: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13735: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
13736: if (@blockers) {
13737: $syval = '';
13738: untie(%bighash);
13739: return $env{$cache_str}='';
13740: }
13741: }
13742: }
13743: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13744: # ------------------------------------------ There is more than one possibility
13745: my $realpossible=0;
13746: foreach my $id (@possibilities) {
13747: my $file=$bighash{'src_'.$id};
13748: my $canaccess;
13749: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13750: $canaccess = 1;
13751: } else {
13752: $canaccess = &allowed('bre',$file);
13753: }
13754: if ($canaccess) {
13755: my ($mapid,$resid)=split(/\./,$id);
13756: if ($bighash{'map_type_'.$mapid} ne 'page') {
13757: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13758: $resid,$thisfn);
13759: next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
13760: next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
13761: if ($checkforblock) {
13762: my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
13763: if (@blockers > 0) {
13764: $syval = '';
13765: } else {
13766: $syval = $poss_syval;
13767: $realpossible++;
13768: }
13769: } else {
13770: $syval = $poss_syval;
13771: $realpossible++;
13772: }
13773: if ($syval) {
13774: if (ref($possibles) eq 'HASH') {
13775: $possibles->{$syval} = 1;
13776: }
13777: }
13778: }
13779: }
13780: }
13781: if ($realpossible!=1) { $syval=''; }
13782: } else {
13783: $syval='';
13784: }
13785: }
13786: untie(%bighash);
13787: }
13788: }
13789: if ($syval) {
13790: return $env{$cache_str}=$syval;
13791: }
13792: }
13793: &appenv({'request.ambiguous' => $thisfn});
13794: return $env{$cache_str}='';
13795: }
13796:
13797: # ---------------------------------------------------------- Return random seed
13798:
13799: sub numval {
13800: my $txt=shift;
13801: $txt=~tr/A-J/0-9/;
13802: $txt=~tr/a-j/0-9/;
13803: $txt=~tr/K-T/0-9/;
13804: $txt=~tr/k-t/0-9/;
13805: $txt=~tr/U-Z/0-5/;
13806: $txt=~tr/u-z/0-5/;
13807: $txt=~s/\D//g;
13808: if ($_64bit) { if ($txt > 2**32) { return -1; } }
13809: return int($txt);
13810: }
13811:
13812: sub numval2 {
13813: my $txt=shift;
13814: $txt=~tr/A-J/0-9/;
13815: $txt=~tr/a-j/0-9/;
13816: $txt=~tr/K-T/0-9/;
13817: $txt=~tr/k-t/0-9/;
13818: $txt=~tr/U-Z/0-5/;
13819: $txt=~tr/u-z/0-5/;
13820: $txt=~s/\D//g;
13821: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13822: my $total;
13823: foreach my $val (@txts) { $total+=$val; }
13824: if ($_64bit) { if ($total > 2**32) { return -1; } }
13825: return int($total);
13826: }
13827:
13828: sub numval3 {
13829: use integer;
13830: my $txt=shift;
13831: $txt=~tr/A-J/0-9/;
13832: $txt=~tr/a-j/0-9/;
13833: $txt=~tr/K-T/0-9/;
13834: $txt=~tr/k-t/0-9/;
13835: $txt=~tr/U-Z/0-5/;
13836: $txt=~tr/u-z/0-5/;
13837: $txt=~s/\D//g;
13838: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13839: my $total;
13840: foreach my $val (@txts) { $total+=$val; }
13841: if ($_64bit) { $total=(($total<<32)>>32); }
13842: return $total;
13843: }
13844:
13845: sub digest {
13846: my ($data)=@_;
13847: my $digest=&Digest::MD5::md5($data);
13848: my ($a,$b,$c,$d)=unpack("iiii",$digest);
13849: my ($e,$f);
13850: {
13851: use integer;
13852: $e=($a+$b);
13853: $f=($c+$d);
13854: if ($_64bit) {
13855: $e=(($e<<32)>>32);
13856: $f=(($f<<32)>>32);
13857: }
13858: }
13859: if (wantarray) {
13860: return ($e,$f);
13861: } else {
13862: my $g;
13863: {
13864: use integer;
13865: $g=($e+$f);
13866: if ($_64bit) {
13867: $g=(($g<<32)>>32);
13868: }
13869: }
13870: return $g;
13871: }
13872: }
13873:
13874: sub latest_rnd_algorithm_id {
13875: return '64bit5';
13876: }
13877:
13878: sub get_rand_alg {
13879: my ($courseid)=@_;
13880: if (!$courseid) { $courseid=(&whichuser())[1]; }
13881: if ($courseid) {
13882: return $env{"course.$courseid.rndseed"};
13883: }
13884: return &latest_rnd_algorithm_id();
13885: }
13886:
13887: sub validCODE {
13888: my ($CODE)=@_;
13889: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13890: return 0;
13891: }
13892:
13893: sub getCODE {
13894: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
13895: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13896: defined($Apache::lonhomework::parsing_a_task) ) &&
13897: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
13898: return $Apache::lonhomework::history{'resource.CODE'};
13899: }
13900: return undef;
13901: }
13902: #
13903: # Determines the random seed for a specific context:
13904: #
13905: # parameters:
13906: # symb - in course context the symb for the seed.
13907: # course_id - The course id of the form domain_coursenum.
13908: # domain - Domain for the user.
13909: # course - Course for the user.
13910: # cenv - environment of the course.
13911: #
13912: # NOTE:
13913: # All parameters are picked out of the environment if missing
13914: # or not defined.
13915: # If a symb cannot be determined the current time is used instead.
13916: #
13917: # For a given well defined symb, courside, domain, username,
13918: # and course environment, the seed is reproducible.
13919: #
13920: sub rndseed {
13921: my ($symb,$courseid,$domain,$username, $cenv)=@_;
13922: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
13923: if (!defined($symb)) {
13924: unless ($symb=$wsymb) { return time; }
13925: }
13926: if (!defined $courseid) {
13927: $courseid=$wcourseid;
13928: }
13929: if (!defined $domain) { $domain=$wdomain; }
13930: if (!defined $username) { $username=$wusername }
13931:
13932: my $which;
13933: if (defined($cenv->{'rndseed'})) {
13934: $which = $cenv->{'rndseed'};
13935: } else {
13936: $which =&get_rand_alg($courseid);
13937: }
13938: if (defined(&getCODE())) {
13939:
13940: if ($which eq '64bit5') {
13941: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
13942: } elsif ($which eq '64bit4') {
13943: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
13944: } else {
13945: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
13946: }
13947: } elsif ($which eq '64bit5') {
13948: return &rndseed_64bit5($symb,$courseid,$domain,$username);
13949: } elsif ($which eq '64bit4') {
13950: return &rndseed_64bit4($symb,$courseid,$domain,$username);
13951: } elsif ($which eq '64bit3') {
13952: return &rndseed_64bit3($symb,$courseid,$domain,$username);
13953: } elsif ($which eq '64bit2') {
13954: return &rndseed_64bit2($symb,$courseid,$domain,$username);
13955: } elsif ($which eq '64bit') {
13956: return &rndseed_64bit($symb,$courseid,$domain,$username);
13957: }
13958: return &rndseed_32bit($symb,$courseid,$domain,$username);
13959: }
13960:
13961: sub rndseed_32bit {
13962: my ($symb,$courseid,$domain,$username)=@_;
13963: {
13964: use integer;
13965: my $symbchck=unpack("%32C*",$symb) << 27;
13966: my $symbseed=numval($symb) << 22;
13967: my $namechck=unpack("%32C*",$username) << 17;
13968: my $nameseed=numval($username) << 12;
13969: my $domainseed=unpack("%32C*",$domain) << 7;
13970: my $courseseed=unpack("%32C*",$courseid);
13971: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
13972: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13973: #&logthis("rndseed :$num:$symb");
13974: if ($_64bit) { $num=(($num<<32)>>32); }
13975: return $num;
13976: }
13977: }
13978:
13979: sub rndseed_64bit {
13980: my ($symb,$courseid,$domain,$username)=@_;
13981: {
13982: use integer;
13983: my $symbchck=unpack("%32S*",$symb) << 21;
13984: my $symbseed=numval($symb) << 10;
13985: my $namechck=unpack("%32S*",$username);
13986:
13987: my $nameseed=numval($username) << 21;
13988: my $domainseed=unpack("%32S*",$domain) << 10;
13989: my $courseseed=unpack("%32S*",$courseid);
13990:
13991: my $num1=$symbchck+$symbseed+$namechck;
13992: my $num2=$nameseed+$domainseed+$courseseed;
13993: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13994: #&logthis("rndseed :$num:$symb");
13995: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13996: return "$num1,$num2";
13997: }
13998: }
13999:
14000: sub rndseed_64bit2 {
14001: my ($symb,$courseid,$domain,$username)=@_;
14002: {
14003: use integer;
14004: # strings need to be an even # of cahracters long, it it is odd the
14005: # last characters gets thrown away
14006: my $symbchck=unpack("%32S*",$symb.' ') << 21;
14007: my $symbseed=numval($symb) << 10;
14008: my $namechck=unpack("%32S*",$username.' ');
14009:
14010: my $nameseed=numval($username) << 21;
14011: my $domainseed=unpack("%32S*",$domain.' ') << 10;
14012: my $courseseed=unpack("%32S*",$courseid.' ');
14013:
14014: my $num1=$symbchck+$symbseed+$namechck;
14015: my $num2=$nameseed+$domainseed+$courseseed;
14016: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14017: #&logthis("rndseed :$num:$symb");
14018: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14019: return "$num1,$num2";
14020: }
14021: }
14022:
14023: sub rndseed_64bit3 {
14024: my ($symb,$courseid,$domain,$username)=@_;
14025: {
14026: use integer;
14027: # strings need to be an even # of cahracters long, it it is odd the
14028: # last characters gets thrown away
14029: my $symbchck=unpack("%32S*",$symb.' ') << 21;
14030: my $symbseed=numval2($symb) << 10;
14031: my $namechck=unpack("%32S*",$username.' ');
14032:
14033: my $nameseed=numval2($username) << 21;
14034: my $domainseed=unpack("%32S*",$domain.' ') << 10;
14035: my $courseseed=unpack("%32S*",$courseid.' ');
14036:
14037: my $num1=$symbchck+$symbseed+$namechck;
14038: my $num2=$nameseed+$domainseed+$courseseed;
14039: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14040: #&logthis("rndseed :$num1:$num2:$_64bit");
14041: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14042:
14043: return "$num1:$num2";
14044: }
14045: }
14046:
14047: sub rndseed_64bit4 {
14048: my ($symb,$courseid,$domain,$username)=@_;
14049: {
14050: use integer;
14051: # strings need to be an even # of cahracters long, it it is odd the
14052: # last characters gets thrown away
14053: my $symbchck=unpack("%32S*",$symb.' ') << 21;
14054: my $symbseed=numval3($symb) << 10;
14055: my $namechck=unpack("%32S*",$username.' ');
14056:
14057: my $nameseed=numval3($username) << 21;
14058: my $domainseed=unpack("%32S*",$domain.' ') << 10;
14059: my $courseseed=unpack("%32S*",$courseid.' ');
14060:
14061: my $num1=$symbchck+$symbseed+$namechck;
14062: my $num2=$nameseed+$domainseed+$courseseed;
14063: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14064: #&logthis("rndseed :$num1:$num2:$_64bit");
14065: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14066:
14067: return "$num1:$num2";
14068: }
14069: }
14070:
14071: sub rndseed_64bit5 {
14072: my ($symb,$courseid,$domain,$username)=@_;
14073: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
14074: return "$num1:$num2";
14075: }
14076:
14077: sub rndseed_CODE_64bit {
14078: my ($symb,$courseid,$domain,$username)=@_;
14079: {
14080: use integer;
14081: my $symbchck=unpack("%32S*",$symb.' ') << 16;
14082: my $symbseed=numval2($symb);
14083: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14084: my $CODEseed=numval(&getCODE());
14085: my $courseseed=unpack("%32S*",$courseid.' ');
14086: my $num1=$symbseed+$CODEchck;
14087: my $num2=$CODEseed+$courseseed+$symbchck;
14088: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14089: #&logthis("rndseed :$num1:$num2:$symb");
14090: if ($_64bit) { $num1=(($num1<<32)>>32); }
14091: if ($_64bit) { $num2=(($num2<<32)>>32); }
14092: return "$num1:$num2";
14093: }
14094: }
14095:
14096: sub rndseed_CODE_64bit4 {
14097: my ($symb,$courseid,$domain,$username)=@_;
14098: {
14099: use integer;
14100: my $symbchck=unpack("%32S*",$symb.' ') << 16;
14101: my $symbseed=numval3($symb);
14102: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14103: my $CODEseed=numval3(&getCODE());
14104: my $courseseed=unpack("%32S*",$courseid.' ');
14105: my $num1=$symbseed+$CODEchck;
14106: my $num2=$CODEseed+$courseseed+$symbchck;
14107: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14108: #&logthis("rndseed :$num1:$num2:$symb");
14109: if ($_64bit) { $num1=(($num1<<32)>>32); }
14110: if ($_64bit) { $num2=(($num2<<32)>>32); }
14111: return "$num1:$num2";
14112: }
14113: }
14114:
14115: sub rndseed_CODE_64bit5 {
14116: my ($symb,$courseid,$domain,$username)=@_;
14117: my $code = &getCODE();
14118: my ($num1,$num2)=&digest("$symb,$courseid,$code");
14119: return "$num1:$num2";
14120: }
14121:
14122: sub setup_random_from_rndseed {
14123: my ($rndseed)=@_;
14124: if ($rndseed =~/([,:])/) {
14125: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
14126: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
14127: &Math::Random::random_set_seed_from_phrase($rndseed);
14128: } else {
14129: &Math::Random::random_set_seed($num1,$num2);
14130: }
14131: } else {
14132: &Math::Random::random_set_seed_from_phrase($rndseed);
14133: }
14134: }
14135:
14136: sub latest_receipt_algorithm_id {
14137: return 'receipt3';
14138: }
14139:
14140: sub recunique {
14141: my $fucourseid=shift;
14142: my $unique;
14143: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
14144: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14145: $unique=$env{"course.$fucourseid.internal.encseed"};
14146: } else {
14147: $unique=$perlvar{'lonReceipt'};
14148: }
14149: return unpack("%32C*",$unique);
14150: }
14151:
14152: sub recprefix {
14153: my $fucourseid=shift;
14154: my $prefix;
14155: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
14156: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14157: $prefix=$env{"course.$fucourseid.internal.encpref"};
14158: } else {
14159: $prefix=$perlvar{'lonHostID'};
14160: }
14161: return unpack("%32C*",$prefix);
14162: }
14163:
14164: sub ireceipt {
14165: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
14166:
14167: my $return =&recprefix($fucourseid).'-';
14168:
14169: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
14170: $env{'request.state'} eq 'construct') {
14171: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
14172: return $return;
14173: }
14174:
14175: my $cuname=unpack("%32C*",$funame);
14176: my $cudom=unpack("%32C*",$fudom);
14177: my $cucourseid=unpack("%32C*",$fucourseid);
14178: my $cusymb=unpack("%32C*",$fusymb);
14179: my $cunique=&recunique($fucourseid);
14180: my $cpart=unpack("%32S*",$part);
14181: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
14182:
14183: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
14184:
14185: $return.= ($cunique%$cuname+
14186: $cunique%$cudom+
14187: $cusymb%$cuname+
14188: $cusymb%$cudom+
14189: $cucourseid%$cuname+
14190: $cucourseid%$cudom+
14191: $cpart%$cuname+
14192: $cpart%$cudom);
14193: } else {
14194: $return.= ($cunique%$cuname+
14195: $cunique%$cudom+
14196: $cusymb%$cuname+
14197: $cusymb%$cudom+
14198: $cucourseid%$cuname+
14199: $cucourseid%$cudom);
14200: }
14201: return $return;
14202: }
14203:
14204: sub receipt {
14205: my ($part)=@_;
14206: my ($symb,$courseid,$domain,$name) = &whichuser();
14207: return &ireceipt($name,$domain,$courseid,$symb,$part);
14208: }
14209:
14210: sub whichuser {
14211: my ($passedsymb)=@_;
14212: my ($symb,$courseid,$domain,$name,$publicuser);
14213: if (defined($env{'form.grade_symb'})) {
14214: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
14215: my $allowed=&allowed('vgr',$tmp_courseid);
14216: if (!$allowed &&
14217: exists($env{'request.course.sec'}) &&
14218: $env{'request.course.sec'} !~ /^\s*$/) {
14219: $allowed=&allowed('vgr',$tmp_courseid.
14220: '/'.$env{'request.course.sec'});
14221: }
14222: if ($allowed) {
14223: ($symb)=&get_env_multiple('form.grade_symb');
14224: $courseid=$tmp_courseid;
14225: ($domain)=&get_env_multiple('form.grade_domain');
14226: ($name)=&get_env_multiple('form.grade_username');
14227: return ($symb,$courseid,$domain,$name,$publicuser);
14228: }
14229: }
14230: if (!$passedsymb) {
14231: $symb=&symbread();
14232: } else {
14233: $symb=$passedsymb;
14234: }
14235: $courseid=$env{'request.course.id'};
14236: $domain=$env{'user.domain'};
14237: $name=$env{'user.name'};
14238: if ($name eq 'public' && $domain eq 'public') {
14239: if (!defined($env{'form.username'})) {
14240: $env{'form.username'}.=time.rand(10000000);
14241: }
14242: $name.=$env{'form.username'};
14243: }
14244: return ($symb,$courseid,$domain,$name,$publicuser);
14245:
14246: }
14247:
14248: # ------------------------------------------------------------ Serves up a file
14249: # returns either the contents of the file or
14250: # -1 if the file doesn't exist
14251: #
14252: # if the target is a file that was uploaded via DOCS,
14253: # a check will be made to see if a current copy exists on the local server,
14254: # if it does this will be served, otherwise a copy will be retrieved from
14255: # the home server for the course and stored in /home/httpd/html/userfiles on
14256: # the local server.
14257:
14258: sub getfile {
14259: my ($file) = @_;
14260: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
14261: &repcopy($file);
14262: return &readfile($file);
14263: }
14264:
14265: sub repcopy_userfile {
14266: my ($file)=@_;
14267: my $londocroot = $perlvar{'lonDocRoot'};
14268: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
14269: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
14270: my ($cdom,$cnum,$filename) =
14271: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
14272: my $uri="/uploaded/$cdom/$cnum/$filename";
14273: if (-e "$file") {
14274: # we already have a local copy, check it out
14275: my @fileinfo = stat($file);
14276: my $rtncode;
14277: my $info;
14278: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
14279: if ($lwpresp ne 'ok') {
14280: # there is no such file anymore, even though we had a local copy
14281: if ($rtncode eq '404') {
14282: unlink($file);
14283: }
14284: return -1;
14285: }
14286: if ($info < $fileinfo[9]) {
14287: # nice, the file we have is up-to-date, just say okay
14288: return 'ok';
14289: } else {
14290: # the file is outdated, get rid of it
14291: unlink($file);
14292: }
14293: }
14294: # one way or the other, at this point, we don't have the file
14295: # construct the correct path for the file
14296: my @parts = ($cdom,$cnum);
14297: if ($filename =~ m|^(.+)/[^/]+$|) {
14298: push @parts, split(/\//,$1);
14299: }
14300: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
14301: foreach my $part (@parts) {
14302: $path .= '/'.$part;
14303: if (!-e $path) {
14304: mkdir($path,0770);
14305: }
14306: }
14307: # now the path exists for sure
14308: # get a user agent
14309: my $transferfile=$file.'.in.transfer';
14310: # FIXME: this should flock
14311: if (-e $transferfile) { return 'ok'; }
14312: my $request;
14313: $uri=~s/^\///;
14314: my $homeserver = &homeserver($cnum,$cdom);
14315: my $hostname = &hostname($homeserver);
14316: my $protocol = $protocol{$homeserver};
14317: $protocol = 'http' if ($protocol ne 'https');
14318: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
14319: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
14320: # did it work?
14321: if ($response->is_error()) {
14322: unlink($transferfile);
14323: &logthis("Userfile repcopy failed for $uri");
14324: return -1;
14325: }
14326: # worked, rename the transfer file
14327: rename($transferfile,$file);
14328: return 'ok';
14329: }
14330:
14331: sub tokenwrapper {
14332: my $uri=shift;
14333: $uri=~s|^https?\://([^/]+)||;
14334: $uri=~s|^/||;
14335: $env{'user.environment'}=~/\/([^\/]+)\.id/;
14336: my $token=$1;
14337: my (undef,$udom,$uname,$file)=split('/',$uri,4);
14338: if ($udom && $uname && $file) {
14339: $file=~s|(\?\.*)*$||;
14340: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
14341: my $homeserver = &homeserver($uname,$udom);
14342: my $hostname = &hostname($homeserver);
14343: my $protocol = $protocol{$homeserver};
14344: $protocol = 'http' if ($protocol ne 'https');
14345: return $protocol.'://'.$hostname.'/'.$uri.
14346: (($uri=~/\?/)?'&':'?').'token='.$token.
14347: '&tokenissued='.$perlvar{'lonHostID'};
14348: } else {
14349: return '/adm/notfound.html';
14350: }
14351: }
14352:
14353: # call with reqtype HEAD: get last modification time
14354: # call with reqtype GET: get the file contents
14355: # Do not call this with reqtype GET for large files! It loads everything into memory
14356: #
14357: sub getuploaded {
14358: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
14359: $uri=~s/^\///;
14360: my $homeserver = &homeserver($cnum,$cdom);
14361: my $hostname = &hostname($homeserver);
14362: my $protocol = $protocol{$homeserver};
14363: $protocol = 'http' if ($protocol ne 'https');
14364: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
14365: my $request=new HTTP::Request($reqtype,$uri);
14366: my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
14367: $$rtncode = $response->code;
14368: if (! $response->is_success()) {
14369: return 'failed';
14370: }
14371: if ($reqtype eq 'HEAD') {
14372: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
14373: } elsif ($reqtype eq 'GET') {
14374: $$info = $response->content;
14375: }
14376: return 'ok';
14377: }
14378:
14379: sub readfile {
14380: my $file = shift;
14381: if ( (! -e $file ) || ($file eq '') ) { return -1; };
14382: my $fh;
14383: open($fh,"<",$file);
14384: my $a='';
14385: while (my $line = <$fh>) { $a .= $line; }
14386: return $a;
14387: }
14388:
14389: sub filelocation {
14390: my ($dir,$file) = @_;
14391: my $location;
14392: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
14393:
14394: if ($file =~ m-^/adm/-) {
14395: $file=~s-^/adm/wrapper/-/-;
14396: $file=~s-^/adm/coursedocs/showdoc/-/-;
14397: }
14398:
14399: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
14400: $location = $file;
14401: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
14402: my ($udom,$uname,$filename)=
14403: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
14404: my $home=&homeserver($uname,$udom);
14405: my $is_me=0;
14406: my @ids=¤t_machine_ids();
14407: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
14408: if ($is_me) {
14409: $location=propath($udom,$uname).'/userfiles/'.$filename;
14410: } else {
14411: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14412: $udom.'/'.$uname.'/'.$filename;
14413: }
14414: } elsif ($file =~ m-^/adm/-) {
14415: $location = $perlvar{'lonDocRoot'}.'/'.$file;
14416: } else {
14417: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
14418: $file=~s:^/(res|priv)/:/:;
14419: my $space=$1;
14420: if ( !( $file =~ m:^/:) ) {
14421: $location = $dir. '/'.$file;
14422: } else {
14423: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
14424: }
14425: }
14426: $location=~s://+:/:g; # remove duplicate /
14427: while ($location=~m{/\.\./}) {
14428: if ($location =~ m{/[^/]+/\.\./}) {
14429: $location=~ s{/[^/]+/\.\./}{/}g;
14430: } else {
14431: $location=~ s{/\.\./}{/}g;
14432: }
14433: } #remove dir/..
14434: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14435: return $location;
14436: }
14437:
14438: sub hreflocation {
14439: my ($dir,$file)=@_;
14440: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
14441: $file=filelocation($dir,$file);
14442: } elsif ($file=~m-^/adm/-) {
14443: $file=~s-^/adm/wrapper/-/-;
14444: $file=~s-^/adm/coursedocs/showdoc/-/-;
14445: }
14446: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14447: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14448: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
14449: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14450: {/uploaded/$1/$2/}x;
14451: }
14452: if ($file=~ m{^/userfiles/}) {
14453: $file =~ s{^/userfiles/}{/uploaded/};
14454: }
14455: return $file;
14456: }
14457:
14458:
14459:
14460:
14461:
14462: sub current_machine_domains {
14463: return &machine_domains(&hostname($perlvar{'lonHostID'}));
14464: }
14465:
14466: sub machine_domains {
14467: my ($hostname) = @_;
14468: my @domains;
14469: my %hostname = &all_hostnames();
14470: while( my($id, $name) = each(%hostname)) {
14471: # &logthis("-$id-$name-$hostname-");
14472: if ($hostname eq $name) {
14473: push(@domains,&host_domain($id));
14474: }
14475: }
14476: return @domains;
14477: }
14478:
14479: sub current_machine_ids {
14480: return &machine_ids(&hostname($perlvar{'lonHostID'}));
14481: }
14482:
14483: sub machine_ids {
14484: my ($hostname) = @_;
14485: $hostname ||= &hostname($perlvar{'lonHostID'});
14486: my @ids;
14487: my %name_to_host = &all_names();
14488: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14489: return @{ $name_to_host{$hostname} };
14490: }
14491: return;
14492: }
14493:
14494: sub additional_machine_domains {
14495: my @domains;
14496: if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
14497: if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
14498: while (my $line = <$fh>) {
14499: chomp($line);
14500: $line =~ s/\s//g;
14501: push(@domains,$line);
14502: }
14503: close($fh);
14504: }
14505: }
14506: return @domains;
14507: }
14508:
14509: sub default_login_domain {
14510: my $domain = $perlvar{'lonDefDomain'};
14511: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14512: foreach my $posdom (¤t_machine_domains(),
14513: &additional_machine_domains()) {
14514: if (lc($posdom) eq lc($testdomain)) {
14515: $domain=$posdom;
14516: last;
14517: }
14518: }
14519: return $domain;
14520: }
14521:
14522: sub shared_institution {
14523: my ($dom,$lonhost) = @_;
14524: if ($lonhost eq '') {
14525: $lonhost = $perlvar{'lonHostID'};
14526: }
14527: my $same_intdom;
14528: my $hostintdom = &internet_dom($lonhost);
14529: if ($hostintdom ne '') {
14530: my %iphost = &get_iphost();
14531: my $primary_id = &domain($dom,'primary');
14532: my $primary_ip = &get_host_ip($primary_id);
14533: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14534: foreach my $id (@{$iphost{$primary_ip}}) {
14535: my $intdom = &internet_dom($id);
14536: if ($intdom eq $hostintdom) {
14537: $same_intdom = 1;
14538: last;
14539: }
14540: }
14541: }
14542: }
14543: return $same_intdom;
14544: }
14545:
14546: sub uses_sts {
14547: my ($ignore_cache) = @_;
14548: my $lonhost = $perlvar{'lonHostID'};
14549: my $hostname = &hostname($lonhost);
14550: my $sts_on;
14551: if ($protocol{$lonhost} eq 'https') {
14552: my $cachetime = 12*3600;
14553: if (!$ignore_cache) {
14554: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14555: if (defined($cached)) {
14556: return $sts_on;
14557: }
14558: }
14559: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14560: my $request=new HTTP::Request('HEAD',$url);
14561: my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14562: if ($response->is_success) {
14563: my $has_sts = $response->header('Strict-Transport-Security');
14564: if ($has_sts eq '') {
14565: $sts_on = 0;
14566: } else {
14567: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14568: my $maxage = $1;
14569: if ($maxage) {
14570: $sts_on = 1;
14571: } else {
14572: $sts_on = 0;
14573: }
14574: } else {
14575: $sts_on = 0;
14576: }
14577: }
14578: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14579: }
14580: }
14581: return;
14582: }
14583:
14584: sub waf_allssl {
14585: my ($host_name) = @_;
14586: my $alias = &get_proxy_alias();
14587: if ($host_name eq '') {
14588: $host_name = $ENV{'SERVER_NAME'};
14589: }
14590: if (($host_name ne '') && ($alias eq $host_name)) {
14591: my $serverhomedom = &host_domain($perlvar{'lonHostID'});
14592: my %defdomdefaults = &get_domain_defaults($serverhomedom);
14593: if ($defdomdefaults{'waf_sslopt'}) {
14594: return $defdomdefaults{'waf_sslopt'};
14595: }
14596: }
14597: return;
14598: }
14599:
14600: sub get_requestor_ip {
14601: my ($r,$nolookup,$noproxy) = @_;
14602: my $from_ip;
14603: if (ref($r)) {
14604: if ($r->can('useragent_ip')) {
14605: if ($noproxy && $r->can('client_ip')) {
14606: $from_ip = $r->client_ip();
14607: } else {
14608: $from_ip = $r->useragent_ip();
14609: }
14610: } elsif ($r->connection->can('remote_ip')) {
14611: $from_ip = $r->connection->remote_ip();
14612: } else {
14613: $from_ip = $r->get_remote_host($nolookup);
14614: }
14615: } else {
14616: $from_ip = $ENV{'REMOTE_ADDR'};
14617: }
14618: return $from_ip if ($noproxy);
14619: # Who controls proxy settings for server
14620: my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
14621: my $proxyinfo = &get_proxy_settings($dom_in_use);
14622: if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
14623: if ($proxyinfo->{'vpnint'}) {
14624: if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
14625: return $from_ip;
14626: }
14627: }
14628: if ($proxyinfo->{'trusted'}) {
14629: if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
14630: my $ipheader = $proxyinfo->{'ipheader'};
14631: my ($ip,$xfor);
14632: if (ref($r)) {
14633: if ($ipheader) {
14634: $ip = $r->headers_in->{$ipheader};
14635: }
14636: $xfor = $r->headers_in->{'X-Forwarded-For'};
14637: } else {
14638: if ($ipheader) {
14639: $ip = $ENV{'HTTP_'.uc($ipheader)};
14640: }
14641: $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
14642: }
14643: if (($ip eq '') && ($xfor ne '')) {
14644: foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
14645: unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
14646: $ip = $poss_ip;
14647: last;
14648: }
14649: }
14650: }
14651: if ($ip ne '') {
14652: return $ip;
14653: }
14654: }
14655: }
14656: }
14657: return $from_ip;
14658: }
14659:
14660: sub get_proxy_settings {
14661: my ($dom_in_use) = @_;
14662: my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
14663: my $proxyinfo = {
14664: ipheader => $domdefaults{'waf_ipheader'},
14665: trusted => $domdefaults{'waf_trusted'},
14666: vpnint => $domdefaults{'waf_vpnint'},
14667: vpnext => $domdefaults{'waf_vpnext'},
14668: sslopt => $domdefaults{'waf_sslopt'},
14669: };
14670: return $proxyinfo;
14671: }
14672:
14673: sub ip_match {
14674: my ($ip,$pattern_str) = @_;
14675: $ip=Net::CIDR::cidrvalidate($ip);
14676: if ($ip) {
14677: return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
14678: }
14679: return;
14680: }
14681:
14682: sub get_proxy_alias {
14683: my ($lonid) = @_;
14684: if ($lonid eq '') {
14685: $lonid = $perlvar{'lonHostID'};
14686: }
14687: if (!defined(&hostname($lonid))) {
14688: return;
14689: }
14690: if ($lonid ne '') {
14691: my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
14692: if ($cached) {
14693: return $alias;
14694: }
14695: my $dom = &Apache::lonnet::host_domain($lonid);
14696: if ($dom ne '') {
14697: my $cachetime = 60*60*24;
14698: my %domconfig =
14699: &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
14700: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14701: if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
14702: $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
14703: }
14704: }
14705: return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
14706: }
14707: }
14708: return;
14709: }
14710:
14711: sub use_proxy_alias {
14712: my ($r,$lonid) = @_;
14713: my $alias = &get_proxy_alias($lonid);
14714: if ($alias) {
14715: my $dom = &host_domain($lonid);
14716: if ($dom ne '') {
14717: my $proxyinfo = &get_proxy_settings($dom);
14718: my ($vpnint,$remote_ip);
14719: if (ref($proxyinfo) eq 'HASH') {
14720: $vpnint = $proxyinfo->{'vpnint'};
14721: if ($vpnint) {
14722: $remote_ip = &get_requestor_ip($r,1,1);
14723: }
14724: }
14725: unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
14726: return $alias;
14727: }
14728: }
14729: }
14730: return;
14731: }
14732:
14733: sub alias_sso {
14734: my ($lonid) = @_;
14735: if ($lonid eq '') {
14736: $lonid = $perlvar{'lonHostID'};
14737: }
14738: if (!defined(&hostname($lonid))) {
14739: return;
14740: }
14741: if ($lonid ne '') {
14742: my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
14743: if ($cached) {
14744: return $use_alias;
14745: }
14746: my $dom = &Apache::lonnet::host_domain($lonid);
14747: if ($dom ne '') {
14748: my $cachetime = 60*60*24;
14749: my %domconfig =
14750: &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
14751: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14752: if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
14753: $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
14754: }
14755: }
14756: return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
14757: }
14758: }
14759: return;
14760: }
14761:
14762: sub get_saml_landing {
14763: my ($lonid) = @_;
14764: if ($lonid eq '') {
14765: my $defdom = &default_login_domain();
14766: my @hosts = ¤t_machine_ids();
14767: if (@hosts > 1) {
14768: foreach my $hostid (@hosts) {
14769: if (&host_domain($hostid) eq $defdom) {
14770: $lonid = $hostid;
14771: last;
14772: }
14773: }
14774: } else {
14775: $lonid = $perlvar{'lonHostID'};
14776: }
14777: if ($lonid) {
14778: unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
14779: return;
14780: }
14781: } else {
14782: return;
14783: }
14784: } elsif (!defined(&hostname($lonid))) {
14785: return;
14786: }
14787: my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
14788: if ($cached) {
14789: return $landing;
14790: }
14791: my $dom = &Apache::lonnet::host_domain($lonid);
14792: if ($dom ne '') {
14793: my $cachetime = 60*60*24;
14794: my %domconfig =
14795: &Apache::lonnet::get_dom('configuration',['login'],$dom);
14796: if (ref($domconfig{'login'}) eq 'HASH') {
14797: if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
14798: if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
14799: $landing = 1;
14800: }
14801: }
14802: }
14803: return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
14804: }
14805: return;
14806: }
14807:
14808: # ------------------------------------------------------------- Declutters URLs
14809:
14810: sub declutter {
14811: my $thisfn=shift;
14812: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14813: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
14814: $thisfn=~s{^/home/httpd/html}{};
14815: }
14816: $thisfn=~s/^\///;
14817: $thisfn=~s|^adm/wrapper/||;
14818: $thisfn=~s|^adm/coursedocs/showdoc/||;
14819: $thisfn=~s/^res\///;
14820: $thisfn=~s/^priv\///;
14821: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
14822: $thisfn=~s/\?.+$//;
14823: }
14824: return $thisfn;
14825: }
14826:
14827: # ------------------------------------------------------------- Clutter up URLs
14828:
14829: sub clutter {
14830: my $thisfn='/'.&declutter(shift);
14831: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
14832: || $thisfn =~ m{^/adm/(includes|pages)} ) {
14833: $thisfn='/res'.$thisfn;
14834: }
14835: if ($thisfn !~m|^/adm|) {
14836: if ($thisfn =~ m|^/ext/|) {
14837: $thisfn='/adm/wrapper'.$thisfn;
14838: } else {
14839: my ($ext) = ($thisfn =~ /\.(\w+)$/);
14840: my $embstyle=&Apache::loncommon::fileembstyle($ext);
14841: if ($embstyle eq 'ssi'
14842: || ($embstyle eq 'hdn')
14843: || ($embstyle eq 'rat')
14844: || ($embstyle eq 'prv')
14845: || ($embstyle eq 'ign')) {
14846: #do nothing with these
14847: } elsif (($embstyle eq 'img')
14848: || ($embstyle eq 'emb')
14849: || ($embstyle eq 'wrp')) {
14850: $thisfn='/adm/wrapper'.$thisfn;
14851: } elsif ($embstyle eq 'unk'
14852: && $thisfn!~/\.(sequence|page)$/) {
14853: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
14854: } else {
14855: # &logthis("Got a blank emb style");
14856: }
14857: }
14858: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
14859: $thisfn='/adm/wrapper'.$thisfn;
14860: }
14861: return $thisfn;
14862: }
14863:
14864: sub clutter_with_no_wrapper {
14865: my $uri = &clutter(shift);
14866: if ($uri =~ m-^/adm/-) {
14867: $uri =~ s-^/adm/wrapper/-/-;
14868: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
14869: }
14870: return $uri;
14871: }
14872:
14873: sub freeze_escape {
14874: my ($value)=@_;
14875: if (ref($value)) {
14876: $value=&nfreeze($value);
14877: return '__FROZEN__'.&escape($value);
14878: }
14879: return &escape($value);
14880: }
14881:
14882:
14883: sub thaw_unescape {
14884: my ($value)=@_;
14885: if ($value =~ /^__FROZEN__/) {
14886: substr($value,0,10,undef);
14887: $value=&unescape($value);
14888: return &thaw($value);
14889: }
14890: return &unescape($value);
14891: }
14892:
14893: sub correct_line_ends {
14894: my ($result)=@_;
14895: $$result =~s/\r\n/\n/mg;
14896: $$result =~s/\r/\n/mg;
14897: }
14898: # ================================================================ Main Program
14899:
14900: sub goodbye {
14901: &logthis("Starting Shut down");
14902: #not converted to using infrastruture and probably shouldn't be
14903: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
14904: #converted
14905: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
14906: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14907: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14908: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
14909: #1.1 only
14910: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14911: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14912: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14913: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14914: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
14915: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14916: &logthis(sprintf("%-20s is %s",'hits',$hits));
14917: &flushcourselogs();
14918: &logthis("Shutting down");
14919: }
14920:
14921: sub get_dns {
14922: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
14923: if (!$ignore_cache) {
14924: my ($content,$cached)=
14925: &Apache::lonnet::is_cached_new('dns',$url);
14926: if ($cached) {
14927: &$func($content,$hashref);
14928: return;
14929: }
14930: }
14931:
14932: my %alldns;
14933: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
14934: foreach my $dns (<$config>) {
14935: next if ($dns !~ /^\^(\S*)/x);
14936: my $line = $1;
14937: my ($host,$protocol) = split(/:/,$line);
14938: if ($protocol ne 'https') {
14939: $protocol = 'http';
14940: }
14941: $alldns{$host} = $protocol;
14942: }
14943: close($config);
14944: }
14945: while (%alldns) {
14946: my ($dns) = sort { $b cmp $a } keys(%alldns);
14947: my ($contents,@content);
14948: if ($dns eq Sys::Hostname::FQDN::fqdn()) {
14949: my $command = (split('/',$url))[3];
14950: my ($dir,$file) = &parse_getdns_url($command,$url);
14951: delete($alldns{$dns});
14952: next if (($dir eq '') || ($file eq ''));
14953: if (open(my $config,'<',"$dir/$file")) {
14954: @content = <$config>;
14955: close($config);
14956: }
14957: if ($url eq '/adm/dns/loncapaCRL') {
14958: $contents = join('',@content);
14959: }
14960: } else {
14961: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
14962: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
14963: delete($alldns{$dns});
14964: next if ($response->is_error());
14965: if ($url eq '/adm/dns/loncapaCRL') {
14966: $contents = $response->content;
14967: } else {
14968: @content = split("\n",$response->content);
14969: }
14970: }
14971: if ($url eq '/adm/dns/loncapaCRL') {
14972: return &$func($contents);
14973: } else {
14974: unless ($nocache) {
14975: &do_cache_new('dns',$url,\@content,30*24*60*60);
14976: }
14977: &$func(\@content,$hashref);
14978: return;
14979: }
14980: }
14981: my $which = (split('/',$url,4))[3];
14982: if ($which eq 'loncapaCRL') {
14983: my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14984: if (-e $diskfile) {
14985: &logthis("unable to contact DNS, on disk file $diskfile not updated");
14986: } else {
14987: &logthis("unable to contact DNS, no on disk file $diskfile available");
14988: }
14989: } else {
14990: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
14991: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14992: my @content = <$config>;
14993: close($config);
14994: &$func(\@content,$hashref);
14995: }
14996: }
14997: return;
14998: }
14999:
15000: # ------------------------------------------------------Get DNS checksums file
15001: sub parse_dns_checksums_tab {
15002: my ($lines,$hashref) = @_;
15003: my $lonhost = $perlvar{'lonHostID'};
15004: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
15005: my $loncaparev = &get_server_loncaparev($machine_dom);
15006: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
15007: my $webconfdir = '/etc/httpd/conf';
15008: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
15009: $webconfdir = '/etc/apache2';
15010: } elsif ($distro =~ /^sles(\d+)$/) {
15011: if ($1 >= 10) {
15012: $webconfdir = '/etc/apache2';
15013: }
15014: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
15015: if ($1 >= 10.0) {
15016: $webconfdir = '/etc/apache2';
15017: }
15018: }
15019: my ($release,$timestamp) = split(/\-/,$loncaparev);
15020: my (%chksum,%revnum);
15021: if (ref($lines) eq 'ARRAY') {
15022: chomp(@{$lines});
15023: my $version = shift(@{$lines});
15024: if ($version eq $release) {
15025: foreach my $line (@{$lines}) {
15026: my ($file,$version,$shasum) = split(/,/,$line);
15027: if ($file =~ m{^/etc/httpd/conf}) {
15028: if ($webconfdir eq '/etc/apache2') {
15029: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
15030: }
15031: }
15032: $chksum{$file} = $shasum;
15033: $revnum{$file} = $version;
15034: }
15035: if (ref($hashref) eq 'HASH') {
15036: %{$hashref} = (
15037: sums => \%chksum,
15038: versions => \%revnum,
15039: );
15040: }
15041: }
15042: }
15043: return;
15044: }
15045:
15046: sub fetch_dns_checksums {
15047: my %checksums;
15048: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
15049: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
15050: my ($release,$timestamp) = split(/\-/,$loncaparev);
15051: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
15052: \%checksums);
15053: return \%checksums;
15054: }
15055:
15056: sub fetch_crl_pemfile {
15057: return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
15058: }
15059:
15060: sub save_crl_pem {
15061: my ($content) = @_;
15062: my ($msg,$hadchanges);
15063: if ($content ne '') {
15064: my $now = time;
15065: my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
15066: my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
15067: if (open(my $fh,'>',"$tmpcrl")) {
15068: print $fh $content;
15069: close($fh);
15070: if (-e $lonca) {
15071: if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
15072: my $check = <PIPE>;
15073: close(PIPE);
15074: chomp($check);
15075: if ($check eq 'verify OK') {
15076: my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15077: my $backup;
15078: if (-e $dest) {
15079: if (&File::Copy::move($dest,"$dest.bak")) {
15080: $backup = 'ok';
15081: }
15082: }
15083: if (&File::Copy::move($tmpcrl,$dest)) {
15084: $msg = 'ok';
15085: if ($backup) {
15086: my (%oldnums,%newnums);
15087: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
15088: while (<PIPE>) {
15089: $oldnums{(split(/:/))[1]} = 1;
15090: }
15091: close(PIPE);
15092: }
15093: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
15094: while(<PIPE>) {
15095: $newnums{(split(/:/))[1]} = 1;
15096: }
15097: close(PIPE);
15098: }
15099: foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
15100: unless (exists($oldnums{$key})) {
15101: $hadchanges = 1;
15102: last;
15103: }
15104: }
15105: unless ($hadchanges) {
15106: foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
15107: unless (exists($newnums{$key})) {
15108: $hadchanges = 1;
15109: last;
15110: }
15111: }
15112: }
15113: }
15114: }
15115: } else {
15116: unlink($tmpcrl);
15117: }
15118: } else {
15119: unlink($tmpcrl);
15120: }
15121: } else {
15122: unlink($tmpcrl);
15123: }
15124: }
15125: }
15126: return ($msg,$hadchanges);
15127: }
15128:
15129: sub parse_getdns_url {
15130: my ($command,$url) = @_;
15131: my $dir = $perlvar{'lonTabDir'};
15132: my $file;
15133: if ($command eq 'hosts') {
15134: $file = 'dns_hosts.tab';
15135: } elsif ($command eq 'domain') {
15136: $file = 'dns_domain.tab';
15137: } elsif ($command eq 'checksums') {
15138: my $version = (split('/',$url))[4];
15139: $file = "dns_checksums/$version.tab",
15140: } elsif ($command eq 'loncapaCRL') {
15141: $dir = $perlvar{'lonCertificateDirectory'};
15142: $file = $perlvar{'lonnetCertRevocationList'};
15143: }
15144: return ($dir,$file);
15145: }
15146:
15147: # ------------------------------------------------------------ Read domain file
15148: {
15149: my $loaded;
15150: my %domain;
15151:
15152: sub parse_domain_tab {
15153: my ($lines) = @_;
15154: foreach my $line (@$lines) {
15155: next if ($line =~ /^(\#|\s*$ )/x);
15156:
15157: chomp($line);
15158: my ($name,@elements) = split(/:/,$line,9);
15159: my %this_domain;
15160: foreach my $field ('description', 'auth_def', 'auth_arg_def',
15161: 'lang_def', 'city', 'longi', 'lati',
15162: 'primary') {
15163: $this_domain{$field} = shift(@elements);
15164: }
15165: $domain{$name} = \%this_domain;
15166: }
15167: }
15168:
15169: sub reset_domain_info {
15170: undef($loaded);
15171: undef(%domain);
15172: }
15173:
15174: sub load_domain_tab {
15175: my ($ignore_cache,$nocache) = @_;
15176: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
15177: my $fh;
15178: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
15179: my @lines = <$fh>;
15180: &parse_domain_tab(\@lines);
15181: }
15182: close($fh);
15183: $loaded = 1;
15184: }
15185:
15186: sub domain {
15187: &load_domain_tab() if (!$loaded);
15188:
15189: my ($name,$what) = @_;
15190: return if ( !exists($domain{$name}) );
15191:
15192: if (!$what) {
15193: return $domain{$name}{'description'};
15194: }
15195: return $domain{$name}{$what};
15196: }
15197:
15198: sub domain_info {
15199: &load_domain_tab() if (!$loaded);
15200: return %domain;
15201: }
15202:
15203: }
15204:
15205:
15206: # ------------------------------------------------------------- Read hosts file
15207: {
15208: my %hostname;
15209: my %hostdom;
15210: my %libserv;
15211: my $loaded;
15212: my %name_to_host;
15213: my %internetdom;
15214: my %LC_dns_serv;
15215:
15216: sub parse_hosts_tab {
15217: my ($file) = @_;
15218: foreach my $configline (@$file) {
15219: next if ($configline =~ /^(\#|\s*$ )/x);
15220: chomp($configline);
15221: if ($configline =~ /^\^/) {
15222: if ($configline =~ /^\^([\w.\-]+)/) {
15223: $LC_dns_serv{$1} = 1;
15224: }
15225: next;
15226: }
15227: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
15228: $name=~s/\s//g;
15229: if ($id && $domain && $role && $name) {
15230: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
15231: my $curr = $hostname{$id};
15232: my $skip;
15233: if (ref($name_to_host{$curr}) eq 'ARRAY') {
15234: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
15235: $skip = 1;
15236: } else {
15237: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
15238: }
15239: }
15240: unless ($skip) {
15241: push(@{$name_to_host{$name}},$id);
15242: }
15243: } else {
15244: push(@{$name_to_host{$name}},$id);
15245: }
15246: $hostname{$id}=$name;
15247: $hostdom{$id}=$domain;
15248: if ($role eq 'library') { $libserv{$id}=$name; }
15249: if (defined($protocol)) {
15250: if ($protocol eq 'https') {
15251: $protocol{$id} = $protocol;
15252: } else {
15253: $protocol{$id} = 'http';
15254: }
15255: } else {
15256: $protocol{$id} = 'http';
15257: }
15258: if (defined($intdom)) {
15259: $internetdom{$id} = $intdom;
15260: }
15261: }
15262: }
15263: }
15264:
15265: sub reset_hosts_info {
15266: &purge_remembered();
15267: &reset_domain_info();
15268: &reset_hosts_ip_info();
15269: undef(%internetdom);
15270: undef(%name_to_host);
15271: undef(%hostname);
15272: undef(%hostdom);
15273: undef(%libserv);
15274: undef($loaded);
15275: }
15276:
15277: sub load_hosts_tab {
15278: my ($ignore_cache,$nocache) = @_;
15279: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
15280: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
15281: my @config = <$config>;
15282: &parse_hosts_tab(\@config);
15283: close($config);
15284: $loaded=1;
15285: }
15286:
15287: sub hostname {
15288: &load_hosts_tab() if (!$loaded);
15289:
15290: my ($lonid) = @_;
15291: return $hostname{$lonid};
15292: }
15293:
15294: sub all_hostnames {
15295: &load_hosts_tab() if (!$loaded);
15296:
15297: return %hostname;
15298: }
15299:
15300: sub all_names {
15301: my ($ignore_cache,$nocache) = @_;
15302: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
15303:
15304: return %name_to_host;
15305: }
15306:
15307: sub all_host_domain {
15308: &load_hosts_tab() if (!$loaded);
15309: return %hostdom;
15310: }
15311:
15312: sub all_host_intdom {
15313: &load_hosts_tab() if (!$loaded);
15314: return %internetdom;
15315: }
15316:
15317: sub is_library {
15318: &load_hosts_tab() if (!$loaded);
15319:
15320: return exists($libserv{$_[0]});
15321: }
15322:
15323: sub all_library {
15324: &load_hosts_tab() if (!$loaded);
15325:
15326: return %libserv;
15327: }
15328:
15329: sub unique_library {
15330: #2x reverse removes all hostnames that appear more than once
15331: my %unique = reverse &all_library();
15332: return reverse %unique;
15333: }
15334:
15335: sub get_servers {
15336: &load_hosts_tab() if (!$loaded);
15337:
15338: my ($domain,$type) = @_;
15339: my %possible_hosts = ($type eq 'library') ? %libserv
15340: : %hostname;
15341: my %result;
15342: if (ref($domain) eq 'ARRAY') {
15343: while ( my ($host,$hostname) = each(%possible_hosts)) {
15344: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
15345: $result{$host} = $hostname;
15346: }
15347: }
15348: } else {
15349: while ( my ($host,$hostname) = each(%possible_hosts)) {
15350: if ($hostdom{$host} eq $domain) {
15351: $result{$host} = $hostname;
15352: }
15353: }
15354: }
15355: return %result;
15356: }
15357:
15358: sub get_unique_servers {
15359: my %unique = reverse &get_servers(@_);
15360: return reverse %unique;
15361: }
15362:
15363: sub host_domain {
15364: &load_hosts_tab() if (!$loaded);
15365:
15366: my ($lonid) = @_;
15367: return $hostdom{$lonid};
15368: }
15369:
15370: sub all_domains {
15371: &load_hosts_tab() if (!$loaded);
15372:
15373: my %seen;
15374: my @uniq = grep(!$seen{$_}++, values(%hostdom));
15375: return @uniq;
15376: }
15377:
15378: sub internet_dom {
15379: &load_hosts_tab() if (!$loaded);
15380:
15381: my ($lonid) = @_;
15382: return $internetdom{$lonid};
15383: }
15384:
15385: sub is_LC_dns {
15386: &load_hosts_tab() if (!$loaded);
15387:
15388: my ($hostname) = @_;
15389: return exists($LC_dns_serv{$hostname});
15390: }
15391:
15392: }
15393:
15394: {
15395: my %iphost;
15396: my %name_to_ip;
15397: my %lonid_to_ip;
15398:
15399: sub get_hosts_from_ip {
15400: my ($ip) = @_;
15401: my %iphosts = &get_iphost();
15402: if (ref($iphosts{$ip})) {
15403: return @{$iphosts{$ip}};
15404: }
15405: return;
15406: }
15407:
15408: sub reset_hosts_ip_info {
15409: undef(%iphost);
15410: undef(%name_to_ip);
15411: undef(%lonid_to_ip);
15412: }
15413:
15414: sub get_host_ip {
15415: my ($lonid) = @_;
15416: if (exists($lonid_to_ip{$lonid})) {
15417: return $lonid_to_ip{$lonid};
15418: }
15419: my $name=&hostname($lonid);
15420: my $ip = gethostbyname($name);
15421: return if (!$ip || length($ip) ne 4);
15422: $ip=inet_ntoa($ip);
15423: $name_to_ip{$name} = $ip;
15424: $lonid_to_ip{$lonid} = $ip;
15425: return $ip;
15426: }
15427:
15428: sub get_iphost {
15429: my ($ignore_cache,$nocache) = @_;
15430:
15431: if (!$ignore_cache) {
15432: if (%iphost) {
15433: return %iphost;
15434: }
15435: my ($ip_info,$cached)=
15436: &Apache::lonnet::is_cached_new('iphost','iphost');
15437: if ($cached) {
15438: %iphost = %{$ip_info->[0]};
15439: %name_to_ip = %{$ip_info->[1]};
15440: %lonid_to_ip = %{$ip_info->[2]};
15441: return %iphost;
15442: }
15443: }
15444:
15445: # get yesterday's info for fallback
15446: my %old_name_to_ip;
15447: my ($ip_info,$cached)=
15448: &Apache::lonnet::is_cached_new('iphost','iphost');
15449: if ($cached) {
15450: %old_name_to_ip = %{$ip_info->[1]};
15451: }
15452:
15453: my %name_to_host = &all_names($ignore_cache,$nocache);
15454: foreach my $name (keys(%name_to_host)) {
15455: my $ip;
15456: if (!exists($name_to_ip{$name})) {
15457: $ip = gethostbyname($name);
15458: if (!$ip || length($ip) ne 4) {
15459: if (defined($old_name_to_ip{$name})) {
15460: $ip = $old_name_to_ip{$name};
15461: &logthis("Can't find $name defaulting to old $ip");
15462: } else {
15463: &logthis("Name $name no IP found");
15464: next;
15465: }
15466: } else {
15467: $ip=inet_ntoa($ip);
15468: }
15469: $name_to_ip{$name} = $ip;
15470: } else {
15471: $ip = $name_to_ip{$name};
15472: }
15473: foreach my $id (@{ $name_to_host{$name} }) {
15474: $lonid_to_ip{$id} = $ip;
15475: }
15476: push(@{$iphost{$ip}},@{$name_to_host{$name}});
15477: }
15478: unless ($nocache) {
15479: &do_cache_new('iphost','iphost',
15480: [\%iphost,\%name_to_ip,\%lonid_to_ip],
15481: 48*60*60);
15482: }
15483:
15484: return %iphost;
15485: }
15486:
15487: #
15488: # Given a DNS returns the loncapa host name for that DNS
15489: #
15490: sub host_from_dns {
15491: my ($dns) = @_;
15492: my @hosts;
15493: my $ip;
15494:
15495: if (exists($name_to_ip{$dns})) {
15496: $ip = $name_to_ip{$dns};
15497: }
15498: if (!$ip) {
15499: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
15500: if (length($ip) == 4) {
15501: $ip = &IO::Socket::inet_ntoa($ip);
15502: }
15503: }
15504: if ($ip) {
15505: @hosts = get_hosts_from_ip($ip);
15506: return $hosts[0];
15507: }
15508: return undef;
15509: }
15510:
15511: sub get_internet_names {
15512: my ($lonid) = @_;
15513: return if ($lonid eq '');
15514: my ($idnref,$cached)=
15515: &Apache::lonnet::is_cached_new('internetnames',$lonid);
15516: if ($cached) {
15517: return $idnref;
15518: }
15519: my $ip = &get_host_ip($lonid);
15520: my @hosts = &get_hosts_from_ip($ip);
15521: my %iphost = &get_iphost();
15522: my (@idns,%seen);
15523: foreach my $id (@hosts) {
15524: my $dom = &host_domain($id);
15525: my $prim_id = &domain($dom,'primary');
15526: my $prim_ip = &get_host_ip($prim_id);
15527: next if ($seen{$prim_ip});
15528: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
15529: foreach my $id (@{$iphost{$prim_ip}}) {
15530: my $intdom = &internet_dom($id);
15531: unless (grep(/^\Q$intdom\E$/,@idns)) {
15532: push(@idns,$intdom);
15533: }
15534: }
15535: }
15536: $seen{$prim_ip} = 1;
15537: }
15538: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
15539: }
15540:
15541: }
15542:
15543: sub all_loncaparevs {
15544: 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);
15545: }
15546:
15547: # ---------------------------------------------------------- Read loncaparev table
15548: {
15549: sub load_loncaparevs {
15550: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
15551: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
15552: while (my $configline=<$config>) {
15553: chomp($configline);
15554: my ($hostid,$loncaparev)=split(/:/,$configline);
15555: $loncaparevs{$hostid}=$loncaparev;
15556: }
15557: close($config);
15558: }
15559: }
15560: }
15561: }
15562:
15563: # ---------------------------------------------------------- Read serverhostID table
15564: {
15565: sub load_serverhomeIDs {
15566: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
15567: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
15568: while (my $configline=<$config>) {
15569: chomp($configline);
15570: my ($name,$id)=split(/:/,$configline);
15571: $serverhomeIDs{$name}=$id;
15572: }
15573: close($config);
15574: }
15575: }
15576: }
15577: }
15578:
15579:
15580: BEGIN {
15581:
15582: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
15583: unless ($readit) {
15584: {
15585: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
15586: %perlvar = (%perlvar,%{$configvars});
15587: }
15588:
15589:
15590: # ------------------------------------------------------ Read spare server file
15591: {
15592: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
15593:
15594: while (my $configline=<$config>) {
15595: chomp($configline);
15596: if ($configline) {
15597: my ($host,$type) = split(':',$configline,2);
15598: if (!defined($type) || $type eq '') { $type = 'default' };
15599: push(@{ $spareid{$type} }, $host);
15600: }
15601: }
15602: close($config);
15603: }
15604: # ------------------------------------------------------------ Read permissions
15605: {
15606: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
15607:
15608: while (my $configline=<$config>) {
15609: chomp($configline);
15610: if ($configline) {
15611: my ($role,$perm)=split(/ /,$configline);
15612: if ($perm ne '') { $pr{$role}=$perm; }
15613: }
15614: }
15615: close($config);
15616: }
15617:
15618: # -------------------------------------------- Read plain texts for permissions
15619: {
15620: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
15621:
15622: while (my $configline=<$config>) {
15623: chomp($configline);
15624: if ($configline) {
15625: my ($short,@plain)=split(/:/,$configline);
15626: %{$prp{$short}} = ();
15627: if (@plain > 0) {
15628: $prp{$short}{'std'} = $plain[0];
15629: for (my $i=1; $i<@plain; $i++) {
15630: $prp{$short}{'alt'.$i} = $plain[$i];
15631: }
15632: }
15633: }
15634: }
15635: close($config);
15636: }
15637:
15638: # ---------------------------------------------------------- Read package table
15639: {
15640: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
15641:
15642: while (my $configline=<$config>) {
15643: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
15644: chomp($configline);
15645: my ($short,$plain)=split(/:/,$configline);
15646: my ($pack,$name)=split(/\&/,$short);
15647: if ($plain ne '') {
15648: $packagetab{$pack.'&'.$name.'&name'}=$name;
15649: $packagetab{$short}=$plain;
15650: }
15651: }
15652: close($config);
15653: }
15654:
15655: # ---------------------------------------------------------- Read loncaparev table
15656:
15657: &load_loncaparevs();
15658:
15659: # ---------------------------------------------------------- Read serverhostID table
15660:
15661: &load_serverhomeIDs();
15662:
15663: # ---------------------------------------------------------- Read releaseslist XML
15664: {
15665: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
15666: if (-e $file) {
15667: my $parser = HTML::LCParser->new($file);
15668: while (my $token = $parser->get_token()) {
15669: if ($token->[0] eq 'S') {
15670: my $item = $token->[1];
15671: my $name = $token->[2]{'name'};
15672: my $value = $token->[2]{'value'};
15673: my $valuematch = $token->[2]{'valuematch'};
15674: my $namematch = $token->[2]{'namematch'};
15675: if ($item eq 'parameter') {
15676: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
15677: my $release = $parser->get_text();
15678: $release =~ s/(^\s*|\s*$ )//gx;
15679: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
15680: }
15681: } elsif ($item ne '' && $name ne '') {
15682: my $release = $parser->get_text();
15683: $release =~ s/(^\s*|\s*$ )//gx;
15684: $needsrelease{$item.':'.$name.':'.$value} = $release;
15685: }
15686: }
15687: }
15688: }
15689: }
15690:
15691: # ---------------------------------------------------------- Read managers table
15692: {
15693: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
15694: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
15695: while (my $configline=<$config>) {
15696: chomp($configline);
15697: next if ($configline =~ /^\#/);
15698: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
15699: $managerstab{$configline} = 1;
15700: }
15701: }
15702: close($config);
15703: }
15704: }
15705: }
15706:
15707: # ------------- set up temporary directory
15708: {
15709: $tmpdir = LONCAPA::tempdir();
15710:
15711: }
15712:
15713: # ------------- set default texengine (domain default overrides this)
15714: {
15715: $deftex = LONCAPA::texengine();
15716: }
15717:
15718: # ------------- set default minimum length for passwords for internal auth users
15719: {
15720: $passwdmin = LONCAPA::passwd_min();
15721: }
15722:
15723: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
15724: 'compress_threshold'=> 20_000,
15725: });
15726:
15727: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
15728: $dumpcount=0;
15729: $locknum=0;
15730:
15731: &logtouch();
15732: &logthis('<font color="yellow">INFO: Read configuration</font>');
15733: $readit=1;
15734: {
15735: use integer;
15736: my $test=(2**32)+1;
15737: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
15738: &logthis(" Detected 64bit platform ($_64bit)");
15739: }
15740: }
15741: }
15742:
15743: 1;
15744: __END__
15745:
15746: =pod
15747:
15748: =head1 NAME
15749:
15750: Apache::lonnet - Subroutines to ask questions about things in the network.
15751:
15752: =head1 SYNOPSIS
15753:
15754: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
15755:
15756: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
15757:
15758: Common parameters:
15759:
15760: =over 4
15761:
15762: =item *
15763:
15764: $uname : an internal username (if $cname expecting a course Id specifically)
15765:
15766: =item *
15767:
15768: $udom : a domain (if $cdom expecting a course's domain specifically)
15769:
15770: =item *
15771:
15772: $symb : a resource instance identifier
15773:
15774: =item *
15775:
15776: $namespace : the name of a .db file that contains the data needed or
15777: being set.
15778:
15779: =back
15780:
15781: =head1 OVERVIEW
15782:
15783: lonnet provides subroutines which interact with the
15784: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
15785: about classes, users, and resources.
15786:
15787: For many of these objects you can also use this to store data about
15788: them or modify them in various ways.
15789:
15790: =head2 Symbs
15791:
15792: To identify a specific instance of a resource, LON-CAPA uses symbols
15793: or "symbs"X<symb>. These identifiers are built from the URL of the
15794: map, the resource number of the resource in the map, and the URL of
15795: the resource itself. The latter is somewhat redundant, but might help
15796: if maps change.
15797:
15798: An example is
15799:
15800: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
15801:
15802: The respective map entry is
15803:
15804: <resource id="19" src="/res/msu/korte/tests/part12.problem"
15805: title="Problem 2">
15806: </resource>
15807:
15808: Symbs are used by the random number generator, as well as to store and
15809: restore data specific to a certain instance of for example a problem.
15810:
15811: =head2 Storing And Retrieving Data
15812:
15813: X<store()>X<cstore()>X<restore()>Three of the most important functions
15814: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
15815: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
15816: is is the non-critical message twin of cstore. These functions are for
15817: handlers to store a perl hash to a user's permanent data space in an
15818: easy manner, and to retrieve it again on another call. It is expected
15819: that a handler would use this once at the beginning to retrieve data,
15820: and then again once at the end to send only the new data back.
15821:
15822: The data is stored in the user's data directory on the user's
15823: homeserver under the ID of the course.
15824:
15825: The hash that is returned by restore will have all of the previous
15826: value for all of the elements of the hash.
15827:
15828: Example:
15829:
15830: #creating a hash
15831: my %hash;
15832: $hash{'foo'}='bar';
15833:
15834: #storing it
15835: &Apache::lonnet::cstore(\%hash);
15836:
15837: #changing a value
15838: $hash{'foo'}='notbar';
15839:
15840: #adding a new value
15841: $hash{'bar'}='foo';
15842: &Apache::lonnet::cstore(\%hash);
15843:
15844: #retrieving the hash
15845: my %history=&Apache::lonnet::restore();
15846:
15847: #print the hash
15848: foreach my $key (sort(keys(%history))) {
15849: print("\%history{$key} = $history{$key}");
15850: }
15851:
15852: Will print out:
15853:
15854: %history{1:foo} = bar
15855: %history{1:keys} = foo:timestamp
15856: %history{1:timestamp} = 990455579
15857: %history{2:bar} = foo
15858: %history{2:foo} = notbar
15859: %history{2:keys} = foo:bar:timestamp
15860: %history{2:timestamp} = 990455580
15861: %history{bar} = foo
15862: %history{foo} = notbar
15863: %history{timestamp} = 990455580
15864: %history{version} = 2
15865:
15866: Note that the special hash entries C<keys>, C<version> and
15867: C<timestamp> were added to the hash. C<version> will be equal to the
15868: total number of versions of the data that have been stored. The
15869: C<timestamp> attribute will be the UNIX time the hash was
15870: stored. C<keys> is available in every historical section to list which
15871: keys were added or changed at a specific historical revision of a
15872: hash.
15873:
15874: B<Warning>: do not store the hash that restore returns directly. This
15875: will cause a mess since it will restore the historical keys as if the
15876: were new keys. I.E. 1:foo will become 1:1:foo etc.
15877:
15878: Calling convention:
15879:
15880: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
15881: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
15882:
15883: For more detailed information, see lonnet specific documentation.
15884:
15885: =head1 RETURN MESSAGES
15886:
15887: =over 4
15888:
15889: =item * B<con_lost>: unable to contact remote host
15890:
15891: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15892: when the connection is brought back up
15893:
15894: =item * B<con_failed>: unable to contact remote host and unable to save message
15895: for later delivery
15896:
15897: =item * B<error:>: an error a occurred, a description of the error follows the :
15898:
15899: =item * B<no_such_host>: unable to fund a host associated with the user/domain
15900: that was requested
15901:
15902: =back
15903:
15904: =head1 PUBLIC SUBROUTINES
15905:
15906: =head2 Session Environment Functions
15907:
15908: =over 4
15909:
15910: =item *
15911: X<appenv()>
15912: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
15913: the user envirnoment file, and will be restored for each access this
15914: user makes during this session, also modifies the %env for the current
15915: process. Optional rolesarrayref - if defined contains a reference to an array
15916: of roles which are exempt from the restriction on modifying user.role entries
15917: in the user's environment.db and in %env.
15918:
15919: =item *
15920: X<delenv()>
15921: B<delenv($delthis,$regexp)>: removes all items from the session
15922: environment file that begin with $delthis. If the
15923: optional second arg - $regexp - is true, $delthis is treated as a
15924: regular expression, otherwise \Q$delthis\E is used.
15925: The values are also deleted from the current processes %env.
15926:
15927: =item * get_env_multiple($name)
15928:
15929: gets $name from the %env hash, it seemlessly handles the cases where multiple
15930: values may be defined and end up as an array ref.
15931:
15932: returns an array of values
15933:
15934: =back
15935:
15936: =head2 User Information
15937:
15938: =over 4
15939:
15940: =item *
15941: X<queryauthenticate()>
15942: B<queryauthenticate($uname,$udom)>: try to determine user's current
15943: authentication scheme
15944:
15945: =item *
15946: X<authenticate()>
15947: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
15948: authenticate user from domain's lib servers (first use the current
15949: one). C<$upass> should be the users password.
15950: $checkdefauth is optional (value is 1 if a check should be made to
15951: authenticate user using default authentication method, and allow
15952: account creation if username does not have account in the domain).
15953: $clientcancheckhost is optional (value is 1 if checking whether the
15954: server can host will occur on the client side in lonauth.pm).
15955:
15956: =item *
15957: X<homeserver()>
15958: B<homeserver($uname,$udom)>: find the server which has
15959: the user's directory and files (there must be only one), this caches
15960: the answer, and also caches if there is a borken connection.
15961:
15962: =item *
15963: X<idget()>
15964: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
15965: a list of student/employee IDs or clicker IDs
15966: (student/employee IDs are a unique resource in a domain, there must be
15967: only 1 ID per username, and only 1 username per ID in a specific domain).
15968: clickerIDs are not necessarily unique, as students might share clickers.
15969: (returns hash: id=>name,id=>name)
15970:
15971: =item *
15972: X<idrget()>
15973: B<idrget($udom,@unames)>: find the IDs behind a list of
15974: usernames (returns hash: name=>id,name=>id)
15975:
15976: =item *
15977: X<idput()>
15978: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
15979: names and associated student/employee IDs or clicker IDs.
15980:
15981: =item *
15982: X<iddel()>
15983: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
15984: student/employee ID or clicker ID username look-ups from domain.
15985: The homeserver ($uhome) and namespace ($namespace) are optional.
15986: If no $uhome is provided, it will be determined usig &homeserver()
15987: for each user. If no $namespace is provided, the default is ids.
15988:
15989: =item *
15990: X<updateclickers()>
15991: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
15992: clicker ID-to-username look-ups in clickers.db on library server.
15993: Permitted actions are add or del (i.e., add or delete). The
15994: clickers.db contains clickerID as keys (escaped), and each corresponding
15995: value is an escaped comma-separated list of usernames (for whom the
15996: library server is the homeserver), who registered that particular ID.
15997: If $critical is true, the update will be sent via &critical, otherwise
15998: &reply() will be used.
15999:
16000: =item *
16001: X<rolesinit()>
16002: B<rolesinit($udom,$username)>: get user privileges.
16003: returns user role, first access and timer interval hashes
16004:
16005: =item *
16006: X<privileged()>
16007: B<privileged($username,$domain)>: returns a true if user has a
16008: privileged and active role (i.e. su or dc), false otherwise.
16009:
16010: =item *
16011: X<getsection()>
16012: B<getsection($udom,$uname,$cname)>: finds the section of student in the
16013: course $cname, return section name/number or '' for "not in course"
16014: and '-1' for "no section"
16015:
16016: =item *
16017: X<userenvironment()>
16018: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
16019: passed in @what from the requested user's environment, returns a hash
16020:
16021: =item *
16022: X<userlog_query()>
16023: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
16024: activity.log file. %filters defines filters applied when parsing the
16025: log file. These can be start or end timestamps, or the type of action
16026: - log to look for Login or Logout events, check for Checkin or
16027: Checkout, role for role selection. The response is in the form
16028: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
16029: escaped strings of the action recorded in the activity.log file.
16030:
16031: =back
16032:
16033: =head2 User Roles
16034:
16035: =over 4
16036:
16037: =item *
16038:
16039: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
16040: returns codes for allowed actions.
16041:
16042: The first argument is required, all others are optional.
16043:
16044: $priv is the privilege being checked.
16045: $uri contains additional information about what is being checked for access (e.g.,
16046: URL, course ID etc.).
16047: $symb is the unique resource instance identifier in a course; if needed,
16048: but not provided, it will be retrieved via a call to &symbread().
16049: $role is the role for which a priv is being checked (only used if priv is evb).
16050: $clientip is the user's IP address (only used when checking for access to portfolio
16051: files).
16052: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
16053: prevents recursive calls to &allowed.
16054:
16055: F: full access
16056: U,I,K: authentication modes (cxx only)
16057: '': forbidden
16058: 1: user needs to choose course
16059: 2: browse allowed
16060: A: passphrase authentication needed
16061: B: access temporarily blocked because of a blocking event in a course.
16062: D: access blocked because access is required via session initiated via deep-link
16063:
16064: =item *
16065:
16066: constructaccess($url,$setpriv) : check for access to construction space URL
16067:
16068: See if the owner domain and name in the URL match those in the
16069: expected environment. If so, return three element list
16070: ($ownername,$ownerdomain,$ownerhome).
16071:
16072: Otherwise return the null string.
16073:
16074: If second argument 'setpriv' is true, it assigns the privileges,
16075: and returns the same three element list, unless the owner has
16076: blocked "ad hoc" Domain Coordinator access to the Author Space,
16077: in which case the null string is returned.
16078:
16079: =item *
16080:
16081: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
16082: define a custom role rolename set privileges in format of lonTabs/roles.tab
16083: for system, domain, and course level. $uname and $udom are optional (current
16084: user's username and domain will be used when either of $uname or $udom are absent.
16085:
16086: =item *
16087:
16088: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
16089: (rolesplain.tab); plain text explanation of a user role term.
16090: $type is Course (default) or Community.
16091: If $forcedefault evaluates to true, text returned will be default
16092: text for $type. Otherwise, if this is a course, the text returned
16093: will be a custom name for the role (if defined in the course's
16094: environment). If no custom name is defined the default is returned.
16095:
16096: =item *
16097:
16098: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
16099: All arguments are optional. Returns a hash of a roles, either for
16100: co-author/assistant author roles for a user's Construction Space
16101: (default), or if $context is 'userroles', roles for the user himself,
16102: In the hash, keys are set to colon-separated $uname,$udom,$role, and
16103: (optionally) if $withsec is true, a fourth colon-separated item - $section.
16104: For each key, value is set to colon-separated start and end times for
16105: the role. If no username and domain are specified, will default to
16106: current user/domain. Types, roles, and roledoms are references to arrays
16107: of role statuses (active, future or previous), roles
16108: (e.g., cc,in, st etc.) and domains of the roles which can be used
16109: to restrict the list of roles reported. If no array ref is
16110: provided for types, will default to return only active roles.
16111:
16112: =item *
16113:
16114: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
16115: user: $uname:$udom has a role in the course: $cdom_$cnum.
16116:
16117: Additional optional arguments are: $type (if role checking is to be restricted
16118: to certain user status types -- previous (expired roles), active (currently
16119: available roles) or future (roles available in the future), and
16120: $hideprivileged -- if true will not report course roles for users who
16121: have active Domain Coordinator role in course's domain or in additional
16122: domains (specified in 'Domains to check for privileged users' in course
16123: environment -- set via: Course Settings -> Classlists and staff listing).
16124:
16125: =item *
16126:
16127: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
16128: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
16129: $possdomains and $possroles are optional array refs -- to domains to check and
16130: roles to check. If $possdomains is not specified, a dump will be done of the
16131: users' roles.db to check for a dc or su role in any domain. This can be
16132: time consuming if &privileged is called repeatedly (e.g., when displaying a
16133: classlist), so in such cases, supplying a $possdomains array is preferred, as
16134: this then allows &privileged_by_domain() to be used, which caches the identity
16135: of privileged users, eliminating the need for repeated calls to &dump().
16136:
16137: =item *
16138:
16139: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
16140: where the outer hash keys are domains specified in the $possdomains array ref,
16141: next inner hash keys are privileged roles specified in the $roles array ref,
16142: and the innermost hash contains key = value pairs for username:domain = end:start
16143: for active or future "privileged" users with that role in that domain. To avoid
16144: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
16145: innerhash are cached using priv_$role and $dom as the identifiers.
16146:
16147: =back
16148:
16149: =head2 User Modification
16150:
16151: =over 4
16152:
16153: =item *
16154:
16155: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
16156: user for the level given by URL. Optional start and end dates (leave empty
16157: string or zero for "no date")
16158:
16159: =item *
16160:
16161: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
16162: change a users, password, possible return values are: ok,
16163: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
16164: refused
16165:
16166: =item *
16167:
16168: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
16169:
16170: =item *
16171:
16172: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
16173: $forceid,$desiredhome,$email,$inststatus,$candelete) :
16174:
16175: will update user information (firstname,middlename,lastname,generation,
16176: permanentemail), and if forceid is true, student/employee ID also.
16177: A user's institutional affiliation(s) can also be updated.
16178: User information fields will not be overwritten with empty entries
16179: unless the field is included in the $candelete array reference.
16180: This array is included when a single user is modified via "Manage Users",
16181: or when Autoupdate.pl is run by cron in a domain.
16182:
16183: =item *
16184:
16185: modifystudent
16186:
16187: modify a student's enrollment and identification information.
16188: The course id is resolved based on the current user's environment.
16189: This means the invoking user must be a course coordinator or otherwise
16190: associated with a course.
16191:
16192: This call is essentially a wrapper for lonnet::modifyuser and
16193: lonnet::modify_student_enrollment
16194:
16195: Inputs:
16196:
16197: =over 4
16198:
16199: =item B<$udom> Student's loncapa domain
16200:
16201: =item B<$uname> Student's loncapa login name
16202:
16203: =item B<$uid> Student/Employee ID
16204:
16205: =item B<$umode> Student's authentication mode
16206:
16207: =item B<$upass> Student's password
16208:
16209: =item B<$first> Student's first name
16210:
16211: =item B<$middle> Student's middle name
16212:
16213: =item B<$last> Student's last name
16214:
16215: =item B<$gene> Student's generation
16216:
16217: =item B<$usec> Student's section in course
16218:
16219: =item B<$end> Unix time of the roles expiration
16220:
16221: =item B<$start> Unix time of the roles start date
16222:
16223: =item B<$forceid> If defined, allow $uid to be changed
16224:
16225: =item B<$desiredhome> server to use as home server for student
16226:
16227: =item B<$email> Student's permanent e-mail address
16228:
16229: =item B<$type> Type of enrollment (auto or manual)
16230:
16231: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
16232:
16233: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
16234:
16235: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
16236:
16237: =item B<$context> role change context (shown in User Management Logs display in a course)
16238:
16239: =item B<$inststatus> institutional status of user - : separated string of escaped status types
16240:
16241: =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.
16242:
16243: =back
16244:
16245: =item *
16246:
16247: modify_student_enrollment
16248:
16249: Change a student's enrollment status in a class. The environment variable
16250: 'role.request.course' must be defined for this function to proceed.
16251:
16252: Inputs:
16253:
16254: =over 4
16255:
16256: =item $udom, student's domain
16257:
16258: =item $uname, student's name
16259:
16260: =item $uid, student's user id
16261:
16262: =item $first, student's first name
16263:
16264: =item $middle
16265:
16266: =item $last
16267:
16268: =item $gene
16269:
16270: =item $usec
16271:
16272: =item $end
16273:
16274: =item $start
16275:
16276: =item $type
16277:
16278: =item $locktype
16279:
16280: =item $cid
16281:
16282: =item $selfenroll
16283:
16284: =item $context
16285:
16286: =item $credits, number of credits student will earn from this class
16287:
16288: =item $instsec, institutional course section code for student
16289:
16290: =back
16291:
16292:
16293: =item *
16294:
16295: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
16296: custom role; give a custom role to a user for the level given by URL. Specify
16297: name and domain of role author, and role name
16298:
16299: =item *
16300:
16301: revokerole($udom,$uname,$url,$role) : revoke a role for url
16302:
16303: =item *
16304:
16305: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
16306:
16307: =back
16308:
16309: =head2 Course Infomation
16310:
16311: =over 4
16312:
16313: =item *
16314:
16315: coursedescription($courseid,$options) : returns a hash of information about the
16316: specified course id, including all environment settings for the
16317: course, the description of the course will be in the hash under the
16318: key 'description'
16319:
16320: $options is an optional parameter that if supplied is a hash reference that controls
16321: what how this function works. It has the following key/values:
16322:
16323: =over 4
16324:
16325: =item freshen_cache
16326:
16327: If defined, and the environment cache for the course is valid, it is
16328: returned in the returned hash.
16329:
16330: =item one_time
16331:
16332: If defined, the last cache time is set to _now_
16333:
16334: =item user
16335:
16336: If defined, the supplied username is used instead of the current user.
16337:
16338:
16339: =back
16340:
16341: =item *
16342:
16343: resdata($name,$domain,$type,@which) : request for current parameter
16344: setting for a specific $type, where $type is either 'course' or 'user',
16345: @what should be a list of parameters to ask about. This routine caches
16346: answers for 10 minutes.
16347:
16348: =item *
16349:
16350: get_courseresdata($courseid, $domain) : dump the entire course resource
16351: data base, returning a hash that is keyed by the resource name and has
16352: values that are the resource value. I believe that the timestamps and
16353: versions are also returned.
16354:
16355: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
16356: supplemental content area. This routine caches the number of files for
16357: 10 minutes.
16358:
16359: =back
16360:
16361: =head2 Course Modification
16362:
16363: =over 4
16364:
16365: =item *
16366:
16367: writecoursepref($courseid,%prefs) : write preferences (environment
16368: database) for a course
16369:
16370: =item *
16371:
16372: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
16373:
16374: =item *
16375:
16376: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
16377:
16378: =item *
16379:
16380: is_course($courseid), is_course($cdom, $cnum)
16381:
16382: Accepts either a combined $courseid (in the form of domain_courseid) or the
16383: two component version $cdom, $cnum. It checks if the specified course exists.
16384:
16385: Returns:
16386: undef if the course doesn't exist, otherwise
16387: in scalar context the combined courseid.
16388: in list context the two components of the course identifier, domain and
16389: courseid.
16390:
16391: =back
16392:
16393: =head2 Bubblesheet Configuration
16394:
16395: =over 4
16396:
16397: =item *
16398:
16399: get_scantron_config($which)
16400:
16401: $which - the name of the configuration to parse from the file.
16402:
16403: Parses and returns the bubblesheet configuration line selected as a
16404: hash of configuration file fields.
16405:
16406:
16407: Returns:
16408: If the named configuration is not in the file, an empty
16409: hash is returned.
16410:
16411: a hash with the fields
16412: name - internal name for the this configuration setup
16413: description - text to display to operator that describes this config
16414: CODElocation - if 0 or the string 'none'
16415: - no CODE exists for this config
16416: if -1 || the string 'letter'
16417: - a CODE exists for this config and is
16418: a string of letters
16419: Unsupported value (but planned for future support)
16420: if a positive integer
16421: - The CODE exists as the first n items from
16422: the question section of the form
16423: if the string 'number'
16424: - The CODE exists for this config and is
16425: a string of numbers
16426: CODEstart - (only matter if a CODE exists) column in the line where
16427: the CODE starts
16428: CODElength - length of the CODE
16429: IDstart - column where the student/employee ID starts
16430: IDlength - length of the student/employee ID info
16431: Qstart - column where the information from the bubbled
16432: 'questions' start
16433: Qlength - number of columns comprising a single bubble line from
16434: the sheet. (usually either 1 or 10)
16435: Qon - either a single character representing the character used
16436: to signal a bubble was chosen in the positional setup, or
16437: the string 'letter' if the letter of the chosen bubble is
16438: in the final, or 'number' if a number representing the
16439: chosen bubble is in the file (1->A 0->J)
16440: Qoff - the character used to represent that a bubble was
16441: left blank
16442: PaperID - if the scanning process generates a unique number for each
16443: sheet scanned the column that this ID number starts in
16444: PaperIDlength - number of columns that comprise the unique ID number
16445: for the sheet of paper
16446: FirstName - column that the first name starts in
16447: FirstNameLength - number of columns that the first name spans
16448: LastName - column that the last name starts in
16449: LastNameLength - number of columns that the last name spans
16450: BubblesPerRow - number of bubbles available in each row used to
16451: bubble an answer. (If not specified, 10 assumed).
16452:
16453:
16454: =item *
16455:
16456: get_scantronformat_file($cdom)
16457:
16458: $cdom - the course's domain (optional); if not supplied, uses
16459: domain for current $env{'request.course.id'}.
16460:
16461: Returns an array containing lines from the scantron format file for
16462: the domain of the course.
16463:
16464: If a url for a custom.tab file is listed in domain's configuration.db,
16465: lines are from this file.
16466:
16467: Otherwise, if a default.tab has been published in RES space by the
16468: domainconfig user, lines are from this file.
16469:
16470: Otherwise, fall back to getting lines from the legacy file on the
16471: local server: /home/httpd/lonTabs/default_scantronformat.tab
16472:
16473: =back
16474:
16475: =head2 Resource Subroutines
16476:
16477: =over 4
16478:
16479: =item *
16480:
16481: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
16482:
16483: =item *
16484:
16485: repcopy($filename) : subscribes to the requested file, and attempts to
16486: replicate from the owning library server, Might return
16487: 'unavailable', 'not_found', 'forbidden', 'ok', or
16488: 'bad_request', also attempts to grab the metadata for the
16489: resource. Expects the local filesystem pathname
16490: (/home/httpd/html/res/....)
16491:
16492: =back
16493:
16494: =head2 Resource Information
16495:
16496: =over 4
16497:
16498: =item *
16499:
16500: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
16501: and returns the value of a variety of different possible values,
16502: $varname should be a request string, and the other parameters can be
16503: used to specify who and what one is asking about. Ordinarily, $cid
16504: does not need to be specified, as it is retrived from
16505: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
16506: within lonuserstate::loadmap() when initializing a course, before
16507: $env{'request.course.id'} has been set, so it needs to be provided
16508: in that one case.
16509:
16510: Possible values for $varname are environment.lastname (or other item
16511: from the envirnment hash), user.name (or someother aspect about the
16512: user), resource.0.maxtries (or some other part and parameter of a
16513: resource)
16514:
16515: =item *
16516:
16517: directcondval($number) : get current value of a condition; reads from a state
16518: string
16519:
16520: =item *
16521:
16522: condval($condidx) : value of condition index based on state
16523:
16524: =item *
16525:
16526: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
16527: resource's metadata, $what should be either a specific key, or either
16528: 'keys' (to get a list of possible keys) or 'packages' to get a list of
16529: packages that this resource currently uses, the last 3 arguments are
16530: only used internally for recursive metadata.
16531:
16532: the toolsymb is only used where the uri is for an external tool (for which
16533: the uri as well as the symb are guaranteed to be unique).
16534:
16535: this function automatically caches all requests except any made recursively
16536: to retrieve a list of metadata keys for an imported library file ($liburi is
16537: defined).
16538:
16539: =item *
16540:
16541: metadata_query($query,$custom,$customshow) : make a metadata query against the
16542: network of library servers; returns file handle of where SQL and regex results
16543: will be stored for query
16544:
16545: =item *
16546:
16547: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
16548: return symbolic list entry (all arguments optional).
16549:
16550: Args: filename is the filename (including path) for the file for which a symb
16551: is required; donotrecurse, if true will prevent calls to allowed() being made
16552: to check access status if more than one resource was found in the bighash
16553: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
16554: a randompick); ignorecachednull, if true will prevent a symb of '' being
16555: returned if $env{$cache_str} is defined as ''; checkforblock if true will
16556: cause possible symbs to be checked to determine if they are subject to content
16557: blocking, if so they will not be included as possible symbs; possibles is a
16558: ref to a hash, which, as a side effect, will be populated with all possible
16559: symbs (content blocking not tested).
16560:
16561: returns the data handle
16562:
16563: =item *
16564:
16565: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
16566: and is a possible symb for the URL in $thisfn, and if is an encrypted
16567: resource that the user accessed using /enc/ returns a 1 on success, 0
16568: on failure, user must be in a course, as it assumes the existence of
16569: the course initial hash, and uses $env('request.course.id'}. The third
16570: arg is an optional reference to a scalar. If this arg is passed in the
16571: call to symbverify, it will be set to 1 if the symb has been set to be
16572: encrypted; otherwise it will be null.
16573:
16574: =item *
16575:
16576: symbclean($symb) : removes versions numbers from a symb, returns the
16577: cleaned symb
16578:
16579: =item *
16580:
16581: is_on_map($uri) : checks if the $uri is somewhere on the current
16582: course map, user must be in a course for it to work.
16583:
16584: =item *
16585:
16586: numval($salt) : return random seed value (addend for rndseed)
16587:
16588: =item *
16589:
16590: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
16591: a random seed, all arguments are optional, if they aren't sent it uses the
16592: environment to derive them. Note: if symb isn't sent and it can't get one
16593: from &symbread it will use the current time as its return value
16594:
16595: =item *
16596:
16597: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
16598: unfakeable, receipt
16599:
16600: =item *
16601:
16602: receipt() : API to ireceipt working off of env values; given out to users
16603:
16604: =item *
16605:
16606: countacc($url) : count the number of accesses to a given URL
16607:
16608: =item *
16609:
16610: 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
16611:
16612: =item *
16613:
16614: 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)
16615:
16616: =item *
16617:
16618: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
16619:
16620: =item *
16621:
16622: devalidate($symb) : devalidate temporary spreadsheet calculations,
16623: forcing spreadsheet to reevaluate the resource scores next time.
16624:
16625: =item *
16626:
16627: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
16628: when viewing in course context.
16629:
16630: input: six args -- filename (decluttered), course number, course domain,
16631: url, symb (if registered) and group (if this is a
16632: group item -- e.g., bulletin board, group page etc.).
16633:
16634: output: array of five scalars --
16635: $cfile -- url for file editing if editable on current server
16636: $home -- homeserver of resource (i.e., for author if published,
16637: or course if uploaded.).
16638: $switchserver -- 1 if server switch will be needed.
16639: $forceedit -- 1 if icon/link should be to go to edit mode
16640: $forceview -- 1 if icon/link should be to go to view mode
16641:
16642: =item *
16643:
16644: is_course_upload($file,$cnum,$cdom)
16645:
16646: Used in course context to determine if current file was uploaded to
16647: the course (i.e., would be found in /userfiles/docs on the course's
16648: homeserver.
16649:
16650: input: 3 args -- filename (decluttered), course number and course domain.
16651: output: boolean -- 1 if file was uploaded.
16652:
16653: =back
16654:
16655: =head2 Storing/Retreiving Data
16656:
16657: =over 4
16658:
16659: =item *
16660:
16661: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
16662: permanently for this url; hashref needs to be given and should be a \%hashname;
16663: the remaining args aren't required and if they aren't passed or are '' they will
16664: be derived from the env (with the exception of $laststore, which is an
16665: optional arg used when a user's submission is stored in grading).
16666: $laststore is $version=$timestamp, where $version is the most recent version
16667: number retrieved for the corresponding $symb in the $namespace db file, and
16668: $timestamp is the timestamp for that transaction (UNIX time).
16669: $laststore is currently only passed when cstore() is called by
16670: structuretags::finalize_storage().
16671:
16672: =item *
16673:
16674: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
16675: but uses critical subroutine
16676:
16677: =item *
16678:
16679: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
16680: all args are optional
16681:
16682: =item *
16683:
16684: dumpstore($namespace,$udom,$uname,$regexp,$range) :
16685: dumps the complete (or key matching regexp) namespace into a hash
16686: ($udom, $uname, $regexp, $range are optional) for a namespace that is
16687: normally &store()ed into
16688:
16689: $range should be either an integer '100' (give me the first 100
16690: matching records)
16691: or be two integers sperated by a - with no spaces
16692: '30-50' (give me the 30th through the 50th matching
16693: records)
16694:
16695:
16696: =item *
16697:
16698: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
16699: replaces a &store() version of data with a replacement set of data
16700: for a particular resource in a namespace passed in the $storehash hash
16701: reference. If $tolog is true, the transaction is logged in the courselog
16702: with an action=PUTSTORE.
16703:
16704: =item *
16705:
16706: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
16707: works very similar to store/cstore, but all data is stored in a
16708: temporary location and can be reset using tmpreset, $storehash should
16709: be a hash reference, returns nothing on success
16710:
16711: =item *
16712:
16713: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
16714: similar to restore, but all data is stored in a temporary location and
16715: can be reset using tmpreset. Returns a hash of values on success,
16716: error string otherwise.
16717:
16718: =item *
16719:
16720: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
16721: deltes all keys for $symb form the temporary storage hash.
16722:
16723: =item *
16724:
16725: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16726: reference filled in from namesp ($udom and $uname are optional)
16727:
16728: =item *
16729:
16730: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
16731: namesp ($udom and $uname are optional)
16732:
16733: =item *
16734:
16735: dump($namespace,$udom,$uname,$regexp,$range) :
16736: dumps the complete (or key matching regexp) namespace into a hash
16737: ($udom, $uname, $regexp, $range are optional)
16738:
16739: $range should be either an integer '100' (give me the first 100
16740: matching records)
16741: or be two integers sperated by a - with no spaces
16742: '30-50' (give me the 30th through the 50th matching
16743: records)
16744: =item *
16745:
16746: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
16747: $store can be a scalar, an array reference, or if the amount to be
16748: incremented is > 1, a hash reference.
16749:
16750: ($udom and $uname are optional)
16751:
16752: =item *
16753:
16754: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
16755: ($udom and $uname are optional)
16756:
16757: =item *
16758:
16759: cput($namespace,$storehash,$udom,$uname) : critical put
16760: ($udom and $uname are optional)
16761:
16762: =item *
16763:
16764: newput($namespace,$storehash,$udom,$uname) :
16765:
16766: Attempts to store the items in the $storehash, but only if they don't
16767: currently exist, if this succeeds you can be certain that you have
16768: successfully created a new key value pair in the $namespace db.
16769:
16770:
16771: Args:
16772: $namespace: name of database to store values to
16773: $storehash: hashref to store to the db
16774: $udom: (optional) domain of user containing the db
16775: $uname: (optional) name of user caontaining the db
16776:
16777: Returns:
16778: 'ok' -> succeeded in storing all keys of $storehash
16779: 'key_exists: <key>' -> failed to anything out of $storehash, as at
16780: least <key> already existed in the db (other
16781: requested keys may also already exist)
16782: 'error: <msg>' -> unable to tie the DB or other error occurred
16783: 'con_lost' -> unable to contact request server
16784: 'refused' -> action was not allowed by remote machine
16785:
16786:
16787: =item *
16788:
16789: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16790: reference filled in from namesp (encrypts the return communication)
16791: ($udom and $uname are optional)
16792:
16793: =item *
16794:
16795: log($udom,$name,$home,$message) : write to permanent log for user; use
16796: critical subroutine
16797:
16798: =item *
16799:
16800: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
16801: array reference filled in from namespace found in domain level on either
16802: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
16803:
16804: =item *
16805:
16806: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
16807: domain level either on specified domain server ($uhome) or primary domain
16808: server ($udom and $uhome are optional)
16809:
16810: =item *
16811:
16812: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
16813: for: authentication, language, quotas, timezone, date locale, and portal URL in
16814: the target domain.
16815:
16816: May also include additional key => value pairs for the following groups:
16817:
16818: =over
16819:
16820: =item
16821: disk quotas (MB allocated by default to portfolios and authoring spaces).
16822:
16823: =over
16824:
16825: =item defaultquota, authorquota
16826:
16827: =back
16828:
16829: =item
16830: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
16831: portfolio for users).
16832:
16833: =over
16834:
16835: =item
16836: aboutme, blog, webdav, portfolio
16837:
16838: =back
16839:
16840: =item
16841: requestcourses: ability to request courses, and how requests are processed.
16842:
16843: =over
16844:
16845: =item
16846: official, unofficial, community, textbook, placement
16847:
16848: =back
16849:
16850: =item
16851: inststatus: types of institutional affiliation, and order in which they are displayed.
16852:
16853: =over
16854:
16855: =item
16856: inststatustypes, inststatusorder, inststatusguest
16857:
16858: =back
16859:
16860: =item
16861: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
16862: for course's uploaded content.
16863:
16864: =over
16865:
16866: =item
16867: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
16868: communityquota, textbookquota, placementquota
16869:
16870: =back
16871:
16872: =item
16873: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16874: on your servers.
16875:
16876: =over
16877:
16878: =item
16879: remotesessions, hostedsessions
16880:
16881: =back
16882:
16883: =back
16884:
16885: In cases where a domain coordinator has never used the "Set Domain Configuration"
16886: utility to create a configuration.db file on a domain's primary library server
16887: only the following domain defaults: auth_def, auth_arg_def, lang_def
16888: -- corresponding values are authentication type (internal, krb4, krb5,
16889: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
16890: will be available. Values are retrieved from cache (if current), unless the
16891: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16892: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16893:
16894: Typical usage:
16895:
16896: %domdefaults = &get_domain_defaults($target_domain);
16897:
16898: =back
16899:
16900: =head2 Network Status Functions
16901:
16902: =over 4
16903:
16904: =item *
16905:
16906: dirlist() : return directory list based on URI (first arg).
16907:
16908: Inputs: 1 required, 5 optional.
16909:
16910: =over
16911:
16912: =item
16913: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16914:
16915: =item
16916: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
16917:
16918: =item
16919: $username - username of user/course to be listed. Extracted from $uri if absent.
16920:
16921: =item
16922: $getpropath - boolean: 1 if prepend path using &propath().
16923:
16924: =item
16925: $getuserdir - boolean: 1 if prepend path for "userfiles".
16926:
16927: =item
16928: $alternateRoot - path to prepend in place of path from $uri.
16929:
16930: =back
16931:
16932: Returns: Array of up to two items.
16933:
16934: =over
16935:
16936: a reference to an array of files/subdirectories
16937:
16938: =over
16939:
16940: Each element in the array of files/subdirectories is a & separated list of
16941: item name and the result of running stat on the item. If dirlist was requested
16942: for a file instead of a directory, the item name will be ''. For a directory
16943: listing, if the item is a metadata file, the element will end &N&M
16944: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
16945: default copyright set (1).
16946:
16947: =back
16948:
16949: a scalar containing error condition (if encountered).
16950:
16951: =over
16952:
16953: =item
16954: no_host (no homeserver identified for $username:$domain).
16955:
16956: =item
16957: no_such_host (server contacted for listing not identified as valid host).
16958:
16959: =item
16960: con_lost (connection to remote server failed).
16961:
16962: =item
16963: refused (invalid $username:$domain received on lond side).
16964:
16965: =item
16966: no_such_dir (directory at specified path on lond side does not exist).
16967:
16968: =item
16969: empty (directory at specified path on lond side is empty).
16970:
16971: =over
16972:
16973: This is currently not encountered because the &ls3, &ls2,
16974: &ls (_handler) routines on the lond side do not filter out
16975: . and .. from a directory listing.
16976:
16977: =back
16978:
16979: =back
16980:
16981: =back
16982:
16983: =item *
16984:
16985: spareserver() : find server with least workload from spare.tab
16986:
16987:
16988: =item *
16989:
16990: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
16991: if there is no corresponding loncapa host.
16992:
16993: =back
16994:
16995:
16996: =head2 Apache Request
16997:
16998: =over 4
16999:
17000: =item *
17001:
17002: ssi($url,%hash) : server side include, does a complete request cycle on url to
17003: localhost, posts hash
17004:
17005: =back
17006:
17007: =head2 Data to String to Data
17008:
17009: =over 4
17010:
17011: =item *
17012:
17013: hash2str(%hash) : convert a hash into a string complete with escaping and '='
17014: and '&' separators, supports elements that are arrayrefs and hashrefs
17015:
17016: =item *
17017:
17018: hashref2str($hashref) : convert a hashref into a string complete with
17019: escaping and '=' and '&' separators, supports elements that are
17020: arrayrefs and hashrefs
17021:
17022: =item *
17023:
17024: arrayref2str($arrayref) : convert an arrayref into a string complete
17025: with escaping and '&' separators, supports elements that are arrayrefs
17026: and hashrefs
17027:
17028: =item *
17029:
17030: str2hash($string) : convert string to hash using unescaping and
17031: splitting on '=' and '&', supports elements that are arrayrefs and
17032: hashrefs
17033:
17034: =item *
17035:
17036: str2array($string) : convert string to hash using unescaping and
17037: splitting on '&', supports elements that are arrayrefs and hashrefs
17038:
17039: =back
17040:
17041: =head2 Logging Routines
17042:
17043:
17044: These routines allow one to make log messages in the lonnet.log and
17045: lonnet.perm logfiles.
17046:
17047: =over 4
17048:
17049: =item *
17050:
17051: logtouch() : make sure the logfile, lonnet.log, exists
17052:
17053: =item *
17054:
17055: logthis() : append message to the normal lonnet.log file, it gets
17056: preiodically rolled over and deleted.
17057:
17058: =item *
17059:
17060: logperm() : append a permanent message to lonnet.perm.log, this log
17061: file never gets deleted by any automated portion of the system, only
17062: messages of critical importance should go in here.
17063:
17064:
17065: =back
17066:
17067: =head2 General File Helper Routines
17068:
17069: =over 4
17070:
17071: =item *
17072:
17073: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
17074: (a) files in /uploaded
17075: (i) If a local copy of the file exists -
17076: compares modification date of local copy with last-modified date for
17077: definitive version stored on home server for course. If local copy is
17078: stale, requests a new version from the home server and stores it.
17079: If the original has been removed from the home server, then local copy
17080: is unlinked.
17081: (ii) If local copy does not exist -
17082: requests the file from the home server and stores it.
17083:
17084: If $caller is 'uploadrep':
17085: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
17086: for request for files originally uploaded via DOCS.
17087: - returns 'ok' if fresh local copy now available, -1 otherwise.
17088:
17089: Otherwise:
17090: This indicates a call from the content generation phase of the request.
17091: - returns the entire contents of the file or -1.
17092:
17093: (b) files in /res
17094: - returns the entire contents of a file or -1;
17095: it properly subscribes to and replicates the file if neccessary.
17096:
17097:
17098: =item *
17099:
17100: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
17101: reference
17102:
17103: returns either a stat() list of data about the file or an empty list
17104: if the file doesn't exist or couldn't find out about it (connection
17105: problems or user unknown)
17106:
17107: =item *
17108:
17109: filelocation($dir,$file) : returns file system location of a file
17110: based on URI; meant to be "fairly clean" absolute reference, $dir is a
17111: directory that relative $file lookups are to looked in ($dir of /a/dir
17112: and a file of ../bob will become /a/bob)
17113:
17114: =item *
17115:
17116: hreflocation($dir,$file) : returns file system location or a URL; same as
17117: filelocation except for hrefs
17118:
17119: =item *
17120:
17121: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
17122: also removes beginning /home/httpd/html unless /priv/ follows it.
17123:
17124: =back
17125:
17126: =head2 Usererfile file routines (/uploaded*)
17127:
17128: =over 4
17129:
17130: =item *
17131:
17132: userfileupload(): main rotine for putting a file in a user or course's
17133: filespace, arguments are,
17134:
17135: formname - required - this is the name of the element in $env where the
17136: filename, and the contents of the file to create/modifed exist
17137: the filename is in $env{'form.'.$formname.'.filename'} and the
17138: contents of the file is located in $env{'form.'.$formname}
17139: context - if coursedoc, store the file in the course of the active role
17140: of the current user;
17141: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
17142: if 'canceloverwrite': delete file in tmp/overwrites directory
17143: subdir - required - subdirectory to put the file in under ../userfiles/
17144: if undefined, it will be placed in "unknown"
17145:
17146: (This routine calls clean_filename() to remove any dangerous
17147: characters from the filename, and then calls finuserfileupload() to
17148: complete the transaction)
17149:
17150: returns either the url of the uploaded file (/uploaded/....) if successful
17151: and /adm/notfound.html if unsuccessful
17152:
17153: =item *
17154:
17155: clean_filename(): routine for cleaing a filename up for storage in
17156: userfile space, argument is:
17157:
17158: filename - proposed filename
17159:
17160: returns: the new clean filename
17161:
17162: =item *
17163:
17164: finishuserfileupload(): routine that creates and sends the file to
17165: userspace, probably shouldn't be called directly
17166:
17167: docuname: username or courseid of destination for the file
17168: docudom: domain of user/course of destination for the file
17169: formname: same as for userfileupload()
17170: fname: filename (including subdirectories) for the file
17171: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
17172: if hashref, and context is scantron, will convert csv format to standard format
17173: allfiles: reference to hash used to store objects found by parser
17174: codebase: reference to hash used for codebases of java objects found by parser
17175: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
17176: thumbheight: height (pixels) of thumbnail to be created for uploaded image
17177: resizewidth: width to be used to resize image using resizeImage from ImageMagick
17178: resizeheight: height to be used to resize image using resizeImage from ImageMagick
17179: context: if 'overwrite', will move the uploaded file from its temporary location to
17180: userfiles to facilitate overwriting a previously uploaded file with same name.
17181: mimetype: reference to scalar to accommodate mime type determined
17182: from File::MMagic if $parser = parse.
17183:
17184: returns either the url of the uploaded file (/uploaded/....) if successful
17185: and /adm/notfound.html if unsuccessful (or an error message if context
17186: was 'overwrite').
17187:
17188:
17189: =item *
17190:
17191: renameuserfile(): renames an existing userfile to a new name
17192:
17193: Args:
17194: docuname: username or courseid of destination for the file
17195: docudom: domain of user/course of destination for the file
17196: old: current file name (including any subdirs under userfiles)
17197: new: desired file name (including any subdirs under userfiles)
17198:
17199: =item *
17200:
17201: mkdiruserfile(): creates a directory is a userfiles dir
17202:
17203: Args:
17204: docuname: username or courseid of destination for the file
17205: docudom: domain of user/course of destination for the file
17206: dir: dir to create (including any subdirs under userfiles)
17207:
17208: =item *
17209:
17210: removeuserfile(): removes a file that exists in userfiles
17211:
17212: Args:
17213: docuname: username or courseid of destination for the file
17214: docudom: domain of user/course of destination for the file
17215: fname: filname to delete (including any subdirs under userfiles)
17216:
17217: =item *
17218:
17219: removeuploadedurl(): convience function for removeuserfile()
17220:
17221: Args:
17222: url: a full /uploaded/... url to delete
17223:
17224: =item *
17225:
17226: get_portfile_permissions():
17227: Args:
17228: domain: domain of user or course contain the portfolio files
17229: user: name of user or num of course contain the portfolio files
17230: Returns:
17231: hashref of a dump of the proper file_permissions.db
17232:
17233:
17234: =item *
17235:
17236: get_access_controls():
17237:
17238: Args:
17239: current_permissions: the hash ref returned from get_portfile_permissions()
17240: group: (optional) the group you want the files associated with
17241: file: (optional) the file you want access info on
17242:
17243: Returns:
17244: a hash (keys are file names) of hashes containing
17245: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
17246: values are XML containing access control settings (see below)
17247:
17248: Internal notes:
17249:
17250: access controls are stored in file_permissions.db as key=value pairs.
17251: key -> path to file/file_name\0uniqueID:scope_end_start
17252: where scope -> public,guest,course,group,domains or users.
17253: end -> UNIX time for end of access (0 -> no end date)
17254: start -> UNIX time for start of access
17255:
17256: value -> XML description of access control
17257: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
17258: <start></start>
17259: <end></end>
17260:
17261: <password></password> for scope type = guest
17262:
17263: <domain></domain> for scope type = course or group
17264: <number></number>
17265: <roles id="">
17266: <role></role>
17267: <access></access>
17268: <section></section>
17269: <group></group>
17270: </roles>
17271:
17272: <dom></dom> for scope type = domains
17273:
17274: <users> for scope type = users
17275: <user>
17276: <uname></uname>
17277: <udom></udom>
17278: </user>
17279: </users>
17280: </scope>
17281:
17282: Access data is also aggregated for each file in an additional key=value pair:
17283: key -> path to file/file_name\0accesscontrol
17284: value -> reference to hash
17285: hash contains key = value pairs
17286: where key = uniqueID:scope_end_start
17287: value = UNIX time record was last updated
17288:
17289: Used to improve speed of look-ups of access controls for each file.
17290:
17291: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
17292:
17293: =item *
17294:
17295: modify_access_controls():
17296:
17297: Modifies access controls for a portfolio file
17298: Args
17299: 1. file name
17300: 2. reference to hash of required changes,
17301: 3. domain
17302: 4. username
17303: where domain,username are the domain of the portfolio owner
17304: (either a user or a course)
17305:
17306: Returns:
17307: 1. result of additions or updates ('ok' or 'error', with error message).
17308: 2. result of deletions ('ok' or 'error', with error message).
17309: 3. reference to hash of any new or updated access controls.
17310: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
17311: key = integer (inbound ID)
17312: value = uniqueID
17313:
17314: =item *
17315:
17316: get_timebased_id():
17317:
17318: Attempts to get a unique timestamp-based suffix for use with items added to a
17319: course via the Course Editor (e.g., folders, composite pages,
17320: group bulletin boards).
17321:
17322: Args: (first three required; six others optional)
17323:
17324: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
17325: docssequence, or name of group
17326:
17327: 2. keyid (alphanumeric): name of temporary locking key in hash,
17328: e.g., num, boardids
17329:
17330: 3. namespace: name of gdbm file used to store suffixes already assigned;
17331: file will be named nohist_namespace.db
17332:
17333: 4. cdom: domain of course; default is current course domain from %env
17334:
17335: 5. cnum: course number; default is current course number from %env
17336:
17337: 6. idtype: set to concat if an additional digit is to be appended to the
17338: unix timestamp to form the suffix, if the plain timestamp is already
17339: in use. Default is to not do this, but simply increment the unix
17340: timestamp by 1 until a unique key is obtained.
17341:
17342: 7. who: holder of locking key; defaults to user:domain for user.
17343:
17344: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
17345: retrying); default is 3.
17346:
17347: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
17348:
17349: Returns:
17350:
17351: 1. suffix obtained (numeric)
17352:
17353: 2. result of deleting locking key (ok if deleted, or lock never obtained)
17354:
17355: 3. error: contains (localized) error message if an error occurred.
17356:
17357:
17358: =back
17359:
17360: =head2 HTTP Helper Routines
17361:
17362: =over 4
17363:
17364: =item *
17365:
17366: escape() : unpack non-word characters into CGI-compatible hex codes
17367:
17368: =item *
17369:
17370: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
17371:
17372: =back
17373:
17374: =head1 PRIVATE SUBROUTINES
17375:
17376: =head2 Underlying communication routines (Shouldn't call)
17377:
17378: =over 4
17379:
17380: =item *
17381:
17382: subreply() : tries to pass a message to lonc, returns con_lost if incapable
17383:
17384: =item *
17385:
17386: reply() : uses subreply to send a message to remote machine, logs all failures
17387:
17388: =item *
17389:
17390: critical() : passes a critical message to another server; if cannot
17391: get through then place message in connection buffer directory and
17392: returns con_delayed, if incapable of saving message, returns
17393: con_failed
17394:
17395: =item *
17396:
17397: reconlonc() : tries to reconnect lonc client processes.
17398:
17399: =back
17400:
17401: =head2 Resource Access Logging
17402:
17403: =over 4
17404:
17405: =item *
17406:
17407: flushcourselogs() : flush (save) buffer logs and access logs
17408:
17409: =item *
17410:
17411: courselog($what) : save message for course in hash
17412:
17413: =item *
17414:
17415: courseacclog($what) : save message for course using &courselog(). Perform
17416: special processing for specific resource types (problems, exams, quizzes, etc).
17417:
17418: =item *
17419:
17420: goodbye() : flush course logs and log shutting down; it is called in srm.conf
17421: as a PerlChildExitHandler
17422:
17423: =back
17424:
17425: =head2 Other
17426:
17427: =over 4
17428:
17429: =item *
17430:
17431: symblist($mapname,%newhash) : update symbolic storage links
17432:
17433: =back
17434:
17435: =cut
17436:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>