1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.1442 2021/02/08 14:50: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 LONCAPA qw(:DEFAULT :match);
101: use LONCAPA::Configuration;
102: use LONCAPA::lonmetadata;
103: use LONCAPA::Lond;
104: use LONCAPA::LWPReq;
105: use LONCAPA::transliterate;
106:
107: use File::Copy;
108:
109: my $readit;
110: my $max_connection_retries = 20; # Or some such value.
111:
112: require Exporter;
113:
114: our @ISA = qw (Exporter);
115: our @EXPORT = qw(%env);
116:
117:
118: # ------------------------------------ Logging (parameters, docs, slots, roles)
119: {
120: my $logid;
121: sub write_log {
122: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
123: if ($context eq 'course') {
124: if (($cnum eq '') || ($cdom eq '')) {
125: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
126: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
127: }
128: }
129: $logid ++;
130: my $now = time();
131: my $id=$now.'00000'.$$.'00000'.$logid;
132: my $ip = &get_requestor_ip();
133: my $logentry = {
134: $id => {
135: 'exe_uname' => $env{'user.name'},
136: 'exe_udom' => $env{'user.domain'},
137: 'exe_time' => $now,
138: 'exe_ip' => $ip,
139: 'delflag' => $delflag,
140: 'logentry' => $storehash,
141: 'uname' => $uname,
142: 'udom' => $udom,
143: }
144: };
145: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
146: }
147: }
148:
149: sub logtouch {
150: my $execdir=$perlvar{'lonDaemons'};
151: unless (-e "$execdir/logs/lonnet.log") {
152: open(my $fh,">>","$execdir/logs/lonnet.log");
153: close $fh;
154: }
155: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
156: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
157: }
158:
159: sub logthis {
160: my $message=shift;
161: my $execdir=$perlvar{'lonDaemons'};
162: my $now=time;
163: my $local=localtime($now);
164: if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
165: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
166: print $fh $logstring;
167: close($fh);
168: }
169: return 1;
170: }
171:
172: sub logperm {
173: my $message=shift;
174: my $execdir=$perlvar{'lonDaemons'};
175: my $now=time;
176: my $local=localtime($now);
177: if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
178: print $fh "$now:$message:$local\n";
179: close($fh);
180: }
181: return 1;
182: }
183:
184: sub create_connection {
185: my ($hostname,$lonid) = @_;
186: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
187: Type => SOCK_STREAM,
188: Timeout => 10);
189: return 0 if (!$client);
190: print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
191: my $result = <$client>;
192: chomp($result);
193: return 1 if ($result eq 'done');
194: return 0;
195: }
196:
197: sub get_server_timezone {
198: my ($cnum,$cdom) = @_;
199: my $home=&homeserver($cnum,$cdom);
200: if ($home ne 'no_host') {
201: my $cachetime = 24*3600;
202: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
203: if (defined($cached)) {
204: return $timezone;
205: } else {
206: my $timezone = &reply('servertimezone',$home);
207: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
208: }
209: }
210: }
211:
212: sub get_server_distarch {
213: my ($lonhost,$ignore_cache) = @_;
214: if (defined($lonhost)) {
215: if (!defined(&hostname($lonhost))) {
216: return;
217: }
218: my $cachetime = 12*3600;
219: if (!$ignore_cache) {
220: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
221: if (defined($cached)) {
222: return $distarch;
223: }
224: }
225: my $rep = &reply('serverdistarch',$lonhost);
226: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
227: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
228: $rep eq '') {
229: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
230: }
231: }
232: return;
233: }
234:
235: sub get_servercerts_info {
236: my ($lonhost,$hostname,$context) = @_;
237: return if ($lonhost eq '');
238: if ($hostname eq '') {
239: $hostname = &hostname($lonhost);
240: }
241: return if ($hostname eq '');
242: my ($rep,$uselocal);
243: if ($context eq 'install') {
244: $uselocal = 1;
245: } elsif (grep { $_ eq $lonhost } ¤t_machine_ids()) {
246: $uselocal = 1;
247: }
248: if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
249: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
250: if ($distro eq '') {
251: $uselocal = 0;
252: } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
253: if ($1 < 6) {
254: $uselocal = 0;
255: }
256: } elsif ($distro =~ /^(?:sles)(\d+)$/) {
257: if ($1 < 12) {
258: $uselocal = 0;
259: }
260: }
261: }
262: if ($uselocal) {
263: $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
264: } else {
265: $rep=&reply('servercerts',$lonhost);
266: }
267: my ($result,%returnhash);
268: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
269: ($rep eq 'unknown_cmd')) {
270: $result = $rep;
271: } else {
272: $result = 'ok';
273: my @pairs=split(/\&/,$rep);
274: foreach my $item (@pairs) {
275: my ($key,$value)=split(/=/,$item,2);
276: my $what = &unescape($key);
277: $returnhash{$what}=&thaw_unescape($value);
278: }
279: }
280: return ($result,\%returnhash);
281: }
282:
283: sub get_server_loncaparev {
284: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
285: if (defined($lonhost)) {
286: if (!defined(&hostname($lonhost))) {
287: undef($lonhost);
288: }
289: }
290: if (!defined($lonhost)) {
291: if (defined(&domain($dom,'primary'))) {
292: $lonhost=&domain($dom,'primary');
293: if ($lonhost eq 'no_host') {
294: undef($lonhost);
295: }
296: }
297: }
298: if (defined($lonhost)) {
299: my $cachetime = 12*3600;
300: if (!$ignore_cache) {
301: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
302: if (defined($cached)) {
303: return $loncaparev;
304: }
305: }
306: my ($answer,$loncaparev);
307: my @ids=¤t_machine_ids();
308: if (grep(/^\Q$lonhost\E$/,@ids)) {
309: $answer = $perlvar{'lonVersion'};
310: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
311: $loncaparev = $1;
312: }
313: } else {
314: $answer = &reply('serverloncaparev',$lonhost);
315: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
316: if ($caller eq 'loncron') {
317: my $hostname = &hostname($lonhost);
318: my $protocol = $protocol{$lonhost};
319: $protocol = 'http' if ($protocol ne 'https');
320: my $url = $protocol.'://'.$hostname.'/adm/about.html';
321: my $request=new HTTP::Request('GET',$url);
322: my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
323: unless ($response->is_error()) {
324: my $content = $response->content;
325: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
326: $loncaparev = $1;
327: }
328: }
329: } else {
330: $loncaparev = $loncaparevs{$lonhost};
331: }
332: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
333: $loncaparev = $1;
334: }
335: }
336: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
337: }
338: }
339:
340: sub get_server_homeID {
341: my ($hostname,$ignore_cache,$caller) = @_;
342: unless ($ignore_cache) {
343: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
344: if (defined($cached)) {
345: return $serverhomeID;
346: }
347: }
348: my $cachetime = 12*3600;
349: my $serverhomeID;
350: if ($caller eq 'loncron') {
351: my @machine_ids = &machine_ids($hostname);
352: foreach my $id (@machine_ids) {
353: my $response = &reply('serverhomeID',$id);
354: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
355: $serverhomeID = $response;
356: last;
357: }
358: }
359: if ($serverhomeID eq '') {
360: $serverhomeID = $machine_ids[-1];
361: }
362: } else {
363: $serverhomeID = $serverhomeIDs{$hostname};
364: }
365: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
366: }
367:
368: sub get_remote_globals {
369: my ($lonhost,$whathash,$ignore_cache) = @_;
370: my ($result,%returnhash,%whatneeded);
371: if (ref($whathash) eq 'HASH') {
372: foreach my $what (sort(keys(%{$whathash}))) {
373: my $hashid = $lonhost.'-'.$what;
374: my ($response,$cached);
375: unless ($ignore_cache) {
376: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
377: }
378: if (defined($cached)) {
379: $returnhash{$what} = $response;
380: } else {
381: $whatneeded{$what} = 1;
382: }
383: }
384: if (keys(%whatneeded) == 0) {
385: $result = 'ok';
386: } else {
387: my $requested = &freeze_escape(\%whatneeded);
388: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
389: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
390: ($rep eq 'unknown_cmd')) {
391: $result = $rep;
392: } else {
393: $result = 'ok';
394: my @pairs=split(/\&/,$rep);
395: foreach my $item (@pairs) {
396: my ($key,$value)=split(/=/,$item,2);
397: my $what = &unescape($key);
398: my $hashid = $lonhost.'-'.$what;
399: $returnhash{$what}=&thaw_unescape($value);
400: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
401: }
402: }
403: }
404: }
405: return ($result,\%returnhash);
406: }
407:
408: sub remote_devalidate_cache {
409: my ($lonhost,$cachekeys) = @_;
410: my $items;
411: return unless (ref($cachekeys) eq 'ARRAY');
412: my $cachestr = join('&',@{$cachekeys});
413: my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
414: return $response;
415: }
416:
417: # -------------------------------------------------- Non-critical communication
418: sub subreply {
419: my ($cmd,$server)=@_;
420: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
421: #
422: # With loncnew process trimming, there's a timing hole between lonc server
423: # process exit and the master server picking up the listen on the AF_UNIX
424: # socket. In that time interval, a lock file will exist:
425:
426: my $lockfile=$peerfile.".lock";
427: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
428: sleep(0.1);
429: }
430: # At this point, either a loncnew parent is listening or an old lonc
431: # or loncnew child is listening so we can connect or everything's dead.
432: #
433: # We'll give the connection a few tries before abandoning it. If
434: # connection is not possible, we'll con_lost back to the client.
435: #
436: my $client;
437: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
438: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
439: Type => SOCK_STREAM,
440: Timeout => 10);
441: if ($client) {
442: last; # Connected!
443: } else {
444: &create_connection(&hostname($server),$server);
445: }
446: sleep(0.1); # Try again later if failed connection.
447: }
448: my $answer;
449: if ($client) {
450: print $client "sethost:$server:$cmd\n";
451: $answer=<$client>;
452: if (!$answer) { $answer="con_lost"; }
453: chomp($answer);
454: } else {
455: $answer = 'con_lost'; # Failed connection.
456: }
457: return $answer;
458: }
459:
460: sub reply {
461: my ($cmd,$server)=@_;
462: unless (defined(&hostname($server))) { return 'no_such_host'; }
463: my $answer=subreply($cmd,$server);
464: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
465: my $logged = $cmd;
466: if ($cmd =~ /^encrypt:([^:]+):/) {
467: my $subcmd = $1;
468: if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
469: ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
470: ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
471: (undef,undef,my @rest) = split(/:/,$cmd);
472: if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
473: splice(@rest,2,1,'Hidden');
474: } elsif ($subcmd eq 'passwd') {
475: splice(@rest,2,2,('Hidden','Hidden'));
476: } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
477: ($subcmd eq 'autoexportgrades')) {
478: splice(@rest,3,1,'Hidden');
479: }
480: $logged = join(':',('encrypt:'.$subcmd,@rest));
481: }
482: }
483: &logthis("<font color=\"blue\">WARNING:".
484: " $logged to $server returned $answer</font>");
485: }
486: return $answer;
487: }
488:
489: # ----------------------------------------------------------- Send USR1 to lonc
490:
491: sub reconlonc {
492: my ($lonid) = @_;
493: if ($lonid) {
494: my $hostname = &hostname($lonid);
495: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
496: if ($hostname && -e $peerfile) {
497: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
498: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
499: Type => SOCK_STREAM,
500: Timeout => 10);
501: if ($client) {
502: print $client ("reset_retries\n");
503: my $answer=<$client>;
504: #reset just this one.
505: }
506: }
507: return;
508: }
509:
510: &logthis("Trying to reconnect lonc");
511: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
512: if (open(my $fh,"<",$loncfile)) {
513: my $loncpid=<$fh>;
514: chomp($loncpid);
515: if (kill 0 => $loncpid) {
516: &logthis("lonc at pid $loncpid responding, sending USR1");
517: kill USR1 => $loncpid;
518: sleep 1;
519: } else {
520: &logthis(
521: "<font color=\"blue\">WARNING:".
522: " lonc at pid $loncpid not responding, giving up</font>");
523: }
524: } else {
525: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
526: }
527: }
528:
529: # ------------------------------------------------------ Critical communication
530:
531: sub critical {
532: my ($cmd,$server)=@_;
533: unless (&hostname($server)) {
534: &logthis("<font color=\"blue\">WARNING:".
535: " Critical message to unknown server ($server)</font>");
536: return 'no_such_host';
537: }
538: my $answer=reply($cmd,$server);
539: if ($answer eq 'con_lost') {
540: &reconlonc($server);
541: my $answer=reply($cmd,$server);
542: if ($answer eq 'con_lost') {
543: my $now=time;
544: my $middlename=$cmd;
545: $middlename=substr($middlename,0,16);
546: $middlename=~s/\W//g;
547: my $dfilename=
548: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
549: $dumpcount++;
550: {
551: my $dfh;
552: if (open($dfh,">",$dfilename)) {
553: print $dfh "$cmd\n";
554: close($dfh);
555: }
556: }
557: sleep 1;
558: my $wcmd='';
559: {
560: my $dfh;
561: if (open($dfh,"<",$dfilename)) {
562: $wcmd=<$dfh>;
563: close($dfh);
564: }
565: }
566: chomp($wcmd);
567: if ($wcmd eq $cmd) {
568: &logthis("<font color=\"blue\">WARNING: ".
569: "Connection buffer $dfilename: $cmd</font>");
570: &logperm("D:$server:$cmd");
571: return 'con_delayed';
572: } else {
573: &logthis("<font color=\"red\">CRITICAL:"
574: ." Critical connection failed: $server $cmd</font>");
575: &logperm("F:$server:$cmd");
576: return 'con_failed';
577: }
578: }
579: }
580: return $answer;
581: }
582:
583: # ------------------------------------------- check if return value is an error
584:
585: sub error {
586: my ($result) = @_;
587: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
588: if ($2 == 2) { return undef; }
589: return $1;
590: }
591: return undef;
592: }
593:
594: sub convert_and_load_session_env {
595: my ($lonidsdir,$handle)=@_;
596: my @profile;
597: {
598: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
599: if (!$opened) {
600: return 0;
601: }
602: flock($idf,LOCK_SH);
603: @profile=<$idf>;
604: close($idf);
605: }
606: my %temp_env;
607: foreach my $line (@profile) {
608: if ($line !~ m/=/) {
609: return 0;
610: }
611: chomp($line);
612: my ($envname,$envvalue)=split(/=/,$line,2);
613: $temp_env{&unescape($envname)} = &unescape($envvalue);
614: }
615: unlink("$lonidsdir/$handle.id");
616: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
617: 0640)) {
618: %disk_env = %temp_env;
619: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
620: untie(%disk_env);
621: }
622: return 1;
623: }
624:
625: # ------------------------------------------- Transfer profile into environment
626: my $env_loaded;
627: sub transfer_profile_to_env {
628: my ($lonidsdir,$handle,$force_transfer) = @_;
629: if (!$force_transfer && $env_loaded) { return; }
630:
631: if (!defined($lonidsdir)) {
632: $lonidsdir = $perlvar{'lonIDsDir'};
633: }
634: if (!defined($handle)) {
635: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
636: }
637:
638: my $convert;
639: {
640: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
641: if (!$opened) {
642: return;
643: }
644: flock($idf,LOCK_SH);
645: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
646: &GDBM_READER(),0640)) {
647: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
648: untie(%disk_env);
649: } else {
650: $convert = 1;
651: }
652: }
653: if ($convert) {
654: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
655: &logthis("Failed to load session, or convert session.");
656: }
657: }
658:
659: my %remove;
660: while ( my $envname = each(%env) ) {
661: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
662: if ($time < time-300) {
663: $remove{$key}++;
664: }
665: }
666: }
667:
668: $env{'user.environment'} = "$lonidsdir/$handle.id";
669: $env_loaded=1;
670: foreach my $expired_key (keys(%remove)) {
671: &delenv($expired_key);
672: }
673: }
674:
675: # ---------------------------------------------------- Check for valid session
676: sub check_for_valid_session {
677: my ($r,$name,$userhashref,$domref) = @_;
678: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
679: my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
680: if ($name eq 'lonDAV') {
681: $lonidsdir=$r->dir_config('lonDAVsessDir');
682: } else {
683: $lonidsdir=$r->dir_config('lonIDsDir');
684: if ($name eq '') {
685: $name = 'lonID';
686: }
687: }
688: if ($name eq 'lonID') {
689: $secure = 'lonSID';
690: $linkname = 'lonLinkID';
691: $pubname = 'lonPubID';
692: if (exists($cookies{$secure})) {
693: $lonid=$cookies{$secure};
694: } elsif (exists($cookies{$name})) {
695: $lonid=$cookies{$name};
696: } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
697: $lonid=$cookies{$linkname};
698: } elsif (exists($cookies{$pubname})) {
699: $lonid=$cookies{$pubname};
700: }
701: } else {
702: $lonid=$cookies{$name};
703: }
704: return undef if (!$lonid);
705:
706: my $handle=&LONCAPA::clean_handle($lonid->value);
707: if (-l "$lonidsdir/$handle.id") {
708: my $link = readlink("$lonidsdir/$handle.id");
709: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
710: $handle = $1;
711: }
712: }
713: if (!-e "$lonidsdir/$handle.id") {
714: if ((ref($domref)) && ($name eq 'lonID') &&
715: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
716: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
717: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
718: $$domref = $possudom;
719: }
720: }
721: return undef;
722: }
723:
724: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
725: return undef if (!$opened);
726:
727: flock($idf,LOCK_SH);
728: my %disk_env;
729: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
730: &GDBM_READER(),0640)) {
731: return undef;
732: }
733:
734: if (!defined($disk_env{'user.name'})
735: || !defined($disk_env{'user.domain'})) {
736: untie(%disk_env);
737: return undef;
738: }
739:
740: if (ref($userhashref) eq 'HASH') {
741: $userhashref->{'name'} = $disk_env{'user.name'};
742: $userhashref->{'domain'} = $disk_env{'user.domain'};
743: $userhashref->{'lti'} = $disk_env{'request.lti.login'};
744: if ($userhashref->{'lti'}) {
745: $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
746: $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
747: }
748: }
749: untie(%disk_env);
750:
751: return $handle;
752: }
753:
754: sub timed_flock {
755: my ($file,$lock_type) = @_;
756: my $failed=0;
757: eval {
758: local $SIG{__DIE__}='DEFAULT';
759: local $SIG{ALRM}=sub {
760: $failed=1;
761: die("failed lock");
762: };
763: alarm(13);
764: flock($file,$lock_type);
765: alarm(0);
766: };
767: if ($failed) {
768: return undef;
769: } else {
770: return 1;
771: }
772: }
773:
774: sub get_sessionfile_vars {
775: my ($handle,$lonidsdir,$storearr) = @_;
776: my %returnhash;
777: unless (ref($storearr) eq 'ARRAY') {
778: return %returnhash;
779: }
780: if (-l "$lonidsdir/$handle.id") {
781: my $link = readlink("$lonidsdir/$handle.id");
782: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
783: $handle = $1;
784: }
785: }
786: if ((-e "$lonidsdir/$handle.id") &&
787: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
788: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
789: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
790: if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
791: flock($idf,LOCK_SH);
792: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
793: &GDBM_READER(),0640)) {
794: foreach my $item (@{$storearr}) {
795: $returnhash{$item} = $disk_env{$item};
796: }
797: untie(%disk_env);
798: }
799: }
800: }
801: }
802: return %returnhash;
803: }
804:
805: # ---------------------------------------------------------- Append Environment
806:
807: sub appenv {
808: my ($newenv,$roles) = @_;
809: if (ref($newenv) eq 'HASH') {
810: foreach my $key (keys(%{$newenv})) {
811: my $refused = 0;
812: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
813: $refused = 1;
814: if (ref($roles) eq 'ARRAY') {
815: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
816: if (grep(/^\Q$role\E$/,@{$roles})) {
817: $refused = 0;
818: }
819: }
820: }
821: if ($refused) {
822: &logthis("<font color=\"blue\">WARNING: ".
823: "Attempt to modify environment ".$key." to ".$newenv->{$key}
824: .'</font>');
825: delete($newenv->{$key});
826: } else {
827: $env{$key}=$newenv->{$key};
828: }
829: }
830: my $lonids = $perlvar{'lonIDsDir'};
831: if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
832: my $opened = open(my $env_file,'+<',$env{'user.environment'});
833: if ($opened
834: && &timed_flock($env_file,LOCK_EX)
835: &&
836: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
837: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
838: while (my ($key,$value) = each(%{$newenv})) {
839: $disk_env{$key} = $value;
840: }
841: untie(%disk_env);
842: }
843: }
844: }
845: return 'ok';
846: }
847: # ----------------------------------------------------- Delete from Environment
848:
849: sub delenv {
850: my ($delthis,$regexp,$roles) = @_;
851: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
852: my $refused = 1;
853: if (ref($roles) eq 'ARRAY') {
854: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
855: if (grep(/^\Q$role\E$/,@{$roles})) {
856: $refused = 0;
857: }
858: }
859: if ($refused) {
860: &logthis("<font color=\"blue\">WARNING: ".
861: "Attempt to delete from environment ".$delthis);
862: return 'error';
863: }
864: }
865: my $opened = open(my $env_file,'+<',$env{'user.environment'});
866: if ($opened
867: && &timed_flock($env_file,LOCK_EX)
868: &&
869: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
870: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
871: foreach my $key (keys(%disk_env)) {
872: if ($regexp) {
873: if ($key=~/^$delthis/) {
874: delete($env{$key});
875: delete($disk_env{$key});
876: }
877: } else {
878: if ($key=~/^\Q$delthis\E/) {
879: delete($env{$key});
880: delete($disk_env{$key});
881: }
882: }
883: }
884: untie(%disk_env);
885: }
886: return 'ok';
887: }
888:
889: sub get_env_multiple {
890: my ($name) = @_;
891: my @values;
892: if (defined($env{$name})) {
893: # exists is it an array
894: if (ref($env{$name})) {
895: @values=@{ $env{$name} };
896: } else {
897: $values[0]=$env{$name};
898: }
899: }
900: return(@values);
901: }
902:
903: # ------------------------------------------------------------------- Locking
904:
905: sub set_lock {
906: my ($text)=@_;
907: $locknum++;
908: my $id=$$.'-'.$locknum;
909: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
910: 'session.lock.'.$id => $text});
911: return $id;
912: }
913:
914: sub get_locks {
915: my $num=0;
916: my %texts=();
917: foreach my $lock (split(/\,/,$env{'session.locks'})) {
918: if ($lock=~/\w/) {
919: $num++;
920: $texts{$lock}=$env{'session.lock.'.$lock};
921: }
922: }
923: return ($num,%texts);
924: }
925:
926: sub remove_lock {
927: my ($id)=@_;
928: my $newlocks='';
929: foreach my $lock (split(/\,/,$env{'session.locks'})) {
930: if (($lock=~/\w/) && ($lock ne $id)) {
931: $newlocks.=','.$lock;
932: }
933: }
934: &appenv({'session.locks' => $newlocks});
935: &delenv('session.lock.'.$id);
936: }
937:
938: sub remove_all_locks {
939: my $activelocks=$env{'session.locks'};
940: foreach my $lock (split(/\,/,$env{'session.locks'})) {
941: if ($lock=~/\w/) {
942: &remove_lock($lock);
943: }
944: }
945: }
946:
947:
948: # ------------------------------------------ Find out current server userload
949: sub userload {
950: my $numusers=0;
951: {
952: opendir(LONIDS,$perlvar{'lonIDsDir'});
953: my $filename;
954: my $curtime=time;
955: while ($filename=readdir(LONIDS)) {
956: next if ($filename eq '.' || $filename eq '..');
957: next if ($filename =~ /publicuser_\d+\.id/);
958: next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
959: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
960: if ($curtime-$mtime < 1800) { $numusers++; }
961: }
962: closedir(LONIDS);
963: }
964: my $userloadpercent=0;
965: my $maxuserload=$perlvar{'lonUserLoadLim'};
966: if ($maxuserload) {
967: $userloadpercent=100*$numusers/$maxuserload;
968: }
969: $userloadpercent=sprintf("%.2f",$userloadpercent);
970: return $userloadpercent;
971: }
972:
973: # ------------------------------ Find server with least workload from spare.tab
974:
975: sub spareserver {
976: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
977: my $spare_server;
978: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
979: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
980: : $userloadpercent;
981: my ($uint_dom,$remotesessions);
982: if (($udom ne '') && (&domain($udom) ne '')) {
983: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
984: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
985: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
986: $remotesessions = $udomdefaults{'remotesessions'};
987: }
988: my $spareshash = &this_host_spares($udom);
989: if (ref($spareshash) eq 'HASH') {
990: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
991: foreach my $try_server (@{ $spareshash->{'primary'} }) {
992: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
993: $try_server));
994: ($spare_server, $lowest_load) =
995: &compare_server_load($try_server, $spare_server, $lowest_load);
996: }
997: }
998:
999: my $found_server = ($spare_server ne '' && $lowest_load < 100);
1000:
1001: if (!$found_server) {
1002: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1003: foreach my $try_server (@{ $spareshash->{'default'} }) {
1004: next unless (&spare_can_host($udom,$uint_dom,
1005: $remotesessions,$try_server));
1006: ($spare_server, $lowest_load) =
1007: &compare_server_load($try_server, $spare_server, $lowest_load);
1008: }
1009: }
1010: }
1011: }
1012:
1013: if (!$want_server_name) {
1014: if (defined($spare_server)) {
1015: my $hostname = &hostname($spare_server);
1016: if (defined($hostname)) {
1017: my $protocol = 'http';
1018: if ($protocol{$spare_server} eq 'https') {
1019: $protocol = $protocol{$spare_server};
1020: }
1021: $spare_server = $protocol.'://'.$hostname;
1022: }
1023: }
1024: }
1025: return $spare_server;
1026: }
1027:
1028: sub compare_server_load {
1029: my ($try_server, $spare_server, $lowest_load, $required) = @_;
1030:
1031: if ($required) {
1032: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
1033: my $remoterev = &get_server_loncaparev(undef,$try_server);
1034: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
1035: if (($major eq '' && $minor eq '') ||
1036: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
1037: return ($spare_server,$lowest_load);
1038: }
1039: }
1040:
1041: my $loadans = &reply('load', $try_server);
1042: my $userloadans = &reply('userload',$try_server);
1043:
1044: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1045: return ($spare_server, $lowest_load); #didn't get a number from the server
1046: }
1047:
1048: my $load;
1049: if ($loadans =~ /\d/) {
1050: if ($userloadans =~ /\d/) {
1051: #both are numbers, pick the bigger one
1052: $load = ($loadans > $userloadans) ? $loadans
1053: : $userloadans;
1054: } else {
1055: $load = $loadans;
1056: }
1057: } else {
1058: $load = $userloadans;
1059: }
1060:
1061: if (($load =~ /\d/) && ($load < $lowest_load)) {
1062: $spare_server = $try_server;
1063: $lowest_load = $load;
1064: }
1065: return ($spare_server,$lowest_load);
1066: }
1067:
1068: # --------------------------- ask offload servers if user already has a session
1069: sub find_existing_session {
1070: my ($udom,$uname) = @_;
1071: my $spareshash = &this_host_spares($udom);
1072: if (ref($spareshash) eq 'HASH') {
1073: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
1074: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1075: return $try_server if (&has_user_session($try_server, $udom, $uname));
1076: }
1077: }
1078: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1079: foreach my $try_server (@{ $spareshash->{'default'} }) {
1080: return $try_server if (&has_user_session($try_server, $udom, $uname));
1081: }
1082: }
1083: }
1084: return;
1085: }
1086:
1087: sub delusersession {
1088: my ($lonid,$udom,$uname) = @_;
1089: my $uprimary_id = &domain($udom,'primary');
1090: my $uintdom = &internet_dom($uprimary_id);
1091: my $intdom = &internet_dom($lonid);
1092: my $serverhomedom = &host_domain($lonid);
1093: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1094: return &reply(join(':','delusersession',
1095: map {&escape($_)} ($udom,$uname)),$lonid);
1096: }
1097: return;
1098: }
1099:
1100: # check if user's browser sent load balancer cookie and server still has session
1101: # and is not overloaded.
1102: sub check_for_balancer_cookie {
1103: my ($r,$update_mtime) = @_;
1104: my ($otherserver,$cookie);
1105: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1106: if (exists($cookies{'balanceID'})) {
1107: my $balid = $cookies{'balanceID'};
1108: $cookie=&LONCAPA::clean_handle($balid->value);
1109: my $balancedir=$r->dir_config('lonBalanceDir');
1110: if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
1111: if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
1112: my ($possudom,$possuname) = ($1,$2);
1113: my $has_session = 0;
1114: if ((&domain($possudom) ne '') &&
1115: (&homeserver($possuname,$possudom) ne 'no_host')) {
1116: my $try_server;
1117: my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
1118: if ($opened) {
1119: flock($idf,LOCK_SH);
1120: while (my $line = <$idf>) {
1121: chomp($line);
1122: if (&hostname($line) ne '') {
1123: $try_server = $line;
1124: last;
1125: }
1126: }
1127: close($idf);
1128: if (($try_server) &&
1129: (&has_user_session($try_server,$possudom,$possuname))) {
1130: my $lowest_load = 30000;
1131: ($otherserver,$lowest_load) =
1132: &compare_server_load($try_server,undef,$lowest_load);
1133: if ($otherserver ne '' && $lowest_load < 100) {
1134: $has_session = 1;
1135: } else {
1136: undef($otherserver);
1137: }
1138: }
1139: }
1140: }
1141: if ($has_session) {
1142: if ($update_mtime) {
1143: my $atime = my $mtime = time;
1144: utime($atime,$mtime,"$balancedir/$cookie.id");
1145: }
1146: } else {
1147: unlink("$balancedir/$cookie.id");
1148: }
1149: }
1150: }
1151: }
1152: return ($otherserver,$cookie);
1153: }
1154:
1155: sub updatebalcookie {
1156: my ($cookie,$balancer,$lastentry)=@_;
1157: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1158: my ($udom,$uname) = ($1,$2);
1159: my $uprimary_id = &domain($udom,'primary');
1160: my $uintdom = &internet_dom($uprimary_id);
1161: my $intdom = &internet_dom($balancer);
1162: my $serverhomedom = &host_domain($balancer);
1163: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1164: return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
1165: }
1166: }
1167: return;
1168: }
1169:
1170: sub delbalcookie {
1171: my ($cookie,$balancer) =@_;
1172: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1173: my ($udom,$uname) = ($1,$2);
1174: my $uprimary_id = &domain($udom,'primary');
1175: my $uintdom = &internet_dom($uprimary_id);
1176: my $intdom = &internet_dom($balancer);
1177: my $serverhomedom = &host_domain($balancer);
1178: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1179: return &reply('delbalcookie:'.&escape($cookie),$balancer);
1180: }
1181: }
1182: }
1183:
1184: # -------------------------------- ask if server already has a session for user
1185: sub has_user_session {
1186: my ($lonid,$udom,$uname) = @_;
1187: my $result = &reply(join(':','userhassession',
1188: map {&escape($_)} ($udom,$uname)),$lonid);
1189: return 1 if ($result eq 'ok');
1190:
1191: return 0;
1192: }
1193:
1194: # --------- determine least loaded server in a user's domain which allows login
1195:
1196: sub choose_server {
1197: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1198: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1199: my %servers = &get_servers($udom);
1200: my $lowest_load = 30000;
1201: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1202: if ($skiploadbal) {
1203: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1204: unless (defined($cached)) {
1205: my $cachetime = 60*60*24;
1206: my %domconfig =
1207: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1208: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1209: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1210: $cachetime);
1211: }
1212: }
1213: }
1214: foreach my $lonhost (keys(%servers)) {
1215: if ($skiploadbal) {
1216: if (ref($balancers) eq 'HASH') {
1217: next if (exists($balancers->{$lonhost}));
1218: }
1219: }
1220: my $loginvia;
1221: if ($checkloginvia) {
1222: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1223: if ($loginvia) {
1224: my ($server,$path) = split(/:/,$loginvia);
1225: ($login_host, $lowest_load) =
1226: &compare_server_load($server, $login_host, $lowest_load, $required);
1227: if ($login_host eq $server) {
1228: $portal_path = $path;
1229: $isredirect = 1;
1230: }
1231: } else {
1232: ($login_host, $lowest_load) =
1233: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1234: if ($login_host eq $lonhost) {
1235: $portal_path = '';
1236: $isredirect = '';
1237: }
1238: }
1239: } else {
1240: ($login_host, $lowest_load) =
1241: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1242: }
1243: }
1244: if ($login_host ne '') {
1245: $hostname = &hostname($login_host);
1246: }
1247: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1248: }
1249:
1250: sub get_course_sessions {
1251: my ($cnum,$cdom,$lastactivity) = @_;
1252: my %servers = &internet_dom_servers($cdom);
1253: my %returnhash;
1254: foreach my $server (sort(keys(%servers))) {
1255: my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
1256: my @pairs=split(/\&/,$rep);
1257: unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
1258: foreach my $item (@pairs) {
1259: my ($key,$value)=split(/=/,$item,2);
1260: $key = &unescape($key);
1261: next if ($key =~ /^error: 2 /);
1262: if (exists($returnhash{$key})) {
1263: next if ($value < $returnhash{$key});
1264: }
1265: $returnhash{$key}=$value;
1266: }
1267: }
1268: }
1269: return %returnhash;
1270: }
1271:
1272: # --------------------------------------------- Try to change a user's password
1273:
1274: sub changepass {
1275: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1276: $currentpass = &escape($currentpass);
1277: $newpass = &escape($newpass);
1278: my $lonhost = $perlvar{'lonHostID'};
1279: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1280: $server);
1281: if (! $answer) {
1282: &logthis("No reply on password change request to $server ".
1283: "by $uname in domain $udom.");
1284: } elsif ($answer =~ "^ok") {
1285: &logthis("$uname in $udom successfully changed their password ".
1286: "on $server.");
1287: } elsif ($answer =~ "^pwchange_failure") {
1288: &logthis("$uname in $udom was unable to change their password ".
1289: "on $server. The action was blocked by either lcpasswd ".
1290: "or pwchange");
1291: } elsif ($answer =~ "^non_authorized") {
1292: &logthis("$uname in $udom did not get their password correct when ".
1293: "attempting to change it on $server.");
1294: } elsif ($answer =~ "^auth_mode_error") {
1295: &logthis("$uname in $udom attempted to change their password despite ".
1296: "not being locally or internally authenticated on $server.");
1297: } elsif ($answer =~ "^unknown_user") {
1298: &logthis("$uname in $udom attempted to change their password ".
1299: "on $server but were unable to because $server is not ".
1300: "their home server.");
1301: } elsif ($answer =~ "^refused") {
1302: &logthis("$server refused to change $uname in $udom password because ".
1303: "it was sent an unencrypted request to change the password.");
1304: } elsif ($answer =~ "invalid_client") {
1305: &logthis("$server refused to change $uname in $udom password because ".
1306: "it was a reset by e-mail originating from an invalid server.");
1307: } elsif ($answer =~ "^prioruse") {
1308: &logthis("$server refused to change $uname in $udom password because ".
1309: "the password had been used before");
1310: }
1311: return $answer;
1312: }
1313:
1314: # ----------------------- Try to determine user's current authentication scheme
1315:
1316: sub queryauthenticate {
1317: my ($uname,$udom)=@_;
1318: my $uhome=&homeserver($uname,$udom);
1319: if (!$uhome) {
1320: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1321: return 'no_host';
1322: }
1323: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1324: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1325: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1326: }
1327: return $answer;
1328: }
1329:
1330: # --------- Try to authenticate user from domain's lib servers (first this one)
1331:
1332: sub authenticate {
1333: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1334: $upass=&escape($upass);
1335: $uname= &LONCAPA::clean_username($uname);
1336: my $uhome=&homeserver($uname,$udom,1);
1337: my $newhome;
1338: if ((!$uhome) || ($uhome eq 'no_host')) {
1339: # Maybe the machine was offline and only re-appeared again recently?
1340: &reconlonc();
1341: # One more
1342: $uhome=&homeserver($uname,$udom,1);
1343: if (($uhome eq 'no_host') && $checkdefauth) {
1344: if (defined(&domain($udom,'primary'))) {
1345: $newhome=&domain($udom,'primary');
1346: }
1347: if ($newhome ne '') {
1348: $uhome = $newhome;
1349: }
1350: }
1351: if ((!$uhome) || ($uhome eq 'no_host')) {
1352: &logthis("User $uname at $udom is unknown in authenticate");
1353: return 'no_host';
1354: }
1355: }
1356: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1357: if ($answer eq 'authorized') {
1358: if ($newhome) {
1359: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1360: return 'no_account_on_host';
1361: } else {
1362: &logthis("User $uname at $udom authorized by $uhome");
1363: return $uhome;
1364: }
1365: }
1366: if ($answer eq 'non_authorized') {
1367: &logthis("User $uname at $udom rejected by $uhome");
1368: return 'no_host';
1369: }
1370: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1371: return 'no_host';
1372: }
1373:
1374: sub can_host_session {
1375: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1376: my $canhost = 1;
1377: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1378: if (ref($remotesessions) eq 'HASH') {
1379: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1380: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1381: $canhost = 0;
1382: } else {
1383: $canhost = 1;
1384: }
1385: }
1386: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1387: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1388: $canhost = 1;
1389: } else {
1390: $canhost = 0;
1391: }
1392: }
1393: if ($canhost) {
1394: if ($remotesessions->{'version'} ne '') {
1395: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1396: if ($reqmajor ne '' && $reqminor ne '') {
1397: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1398: my $major = $1;
1399: my $minor = $2;
1400: if (($major < $reqmajor ) ||
1401: (($major == $reqmajor) && ($minor < $reqminor))) {
1402: $canhost = 0;
1403: }
1404: } else {
1405: $canhost = 0;
1406: }
1407: }
1408: }
1409: }
1410: }
1411: if ($canhost) {
1412: if (ref($hostedsessions) eq 'HASH') {
1413: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1414: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1415: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1416: if (($uint_dom ne '') &&
1417: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1418: $canhost = 0;
1419: } else {
1420: $canhost = 1;
1421: }
1422: }
1423: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1424: if (($uint_dom ne '') &&
1425: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1426: $canhost = 1;
1427: } else {
1428: $canhost = 0;
1429: }
1430: }
1431: }
1432: }
1433: return $canhost;
1434: }
1435:
1436: sub spare_can_host {
1437: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1438: my $canhost=1;
1439: my $try_server_hostname = &hostname($try_server);
1440: my $serverhomeID = &get_server_homeID($try_server_hostname);
1441: my $serverhomedom = &host_domain($serverhomeID);
1442: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1443: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1444: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1445: $canhost = 0;
1446: }
1447: }
1448: if ($canhost) {
1449: if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
1450: if ($defdomdefaults{'offloadoth'}{$try_server}) {
1451: unless (&shared_institution($udom,$try_server)) {
1452: $canhost = 0;
1453: }
1454: }
1455: }
1456: }
1457: if (($canhost) && ($uint_dom)) {
1458: my @intdoms;
1459: my $internet_names = &get_internet_names($try_server);
1460: if (ref($internet_names) eq 'ARRAY') {
1461: @intdoms = @{$internet_names};
1462: }
1463: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1464: my $remoterev = &get_server_loncaparev(undef,$try_server);
1465: $canhost = &can_host_session($udom,$try_server,$remoterev,
1466: $remotesessions,
1467: $defdomdefaults{'hostedsessions'});
1468: }
1469: }
1470: return $canhost;
1471: }
1472:
1473: sub this_host_spares {
1474: my ($dom) = @_;
1475: my ($dom_in_use,$lonhost_in_use,$result);
1476: my @hosts = ¤t_machine_ids();
1477: foreach my $lonhost (@hosts) {
1478: if (&host_domain($lonhost) eq $dom) {
1479: $dom_in_use = $dom;
1480: $lonhost_in_use = $lonhost;
1481: last;
1482: }
1483: }
1484: if ($dom_in_use ne '') {
1485: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1486: }
1487: if (ref($result) ne 'HASH') {
1488: $lonhost_in_use = $perlvar{'lonHostID'};
1489: $dom_in_use = &host_domain($lonhost_in_use);
1490: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1491: if (ref($result) ne 'HASH') {
1492: $result = \%spareid;
1493: }
1494: }
1495: return $result;
1496: }
1497:
1498: sub spares_for_offload {
1499: my ($dom_in_use,$lonhost_in_use) = @_;
1500: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1501: if (defined($cached)) {
1502: return $result;
1503: } else {
1504: my $cachetime = 60*60*24;
1505: my %domconfig =
1506: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1507: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1508: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1509: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1510: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1511: }
1512: }
1513: }
1514: }
1515: return;
1516: }
1517:
1518: sub get_lonbalancer_config {
1519: my ($servers) = @_;
1520: my ($currbalancer,$currtargets);
1521: if (ref($servers) eq 'HASH') {
1522: foreach my $server (keys(%{$servers})) {
1523: my %what = (
1524: spareid => 1,
1525: perlvar => 1,
1526: );
1527: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1528: if ($result eq 'ok') {
1529: if (ref($returnhash) eq 'HASH') {
1530: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1531: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1532: $currbalancer = $server;
1533: $currtargets = {};
1534: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1535: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1536: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1537: }
1538: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1539: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1540: }
1541: }
1542: last;
1543: }
1544: }
1545: }
1546: }
1547: }
1548: }
1549: return ($currbalancer,$currtargets);
1550: }
1551:
1552: sub check_loadbalancing {
1553: my ($uname,$udom,$caller) = @_;
1554: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1555: $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1556: my $lonhost = $perlvar{'lonHostID'};
1557: my @hosts = ¤t_machine_ids();
1558: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1559: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1560: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1561: my $serverhomedom = &host_domain($lonhost);
1562: my $domneedscache;
1563: my $cachetime = 60*60*24;
1564:
1565: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1566: $dom_in_use = $udom;
1567: $homeintdom = 1;
1568: } else {
1569: $dom_in_use = $serverhomedom;
1570: }
1571: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1572: unless (defined($cached)) {
1573: my %domconfig =
1574: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1575: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1576: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1577: } else {
1578: $domneedscache = $dom_in_use;
1579: }
1580: }
1581: if (ref($result) eq 'HASH') {
1582: ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1583: &check_balancer_result($result,@hosts);
1584: if ($is_balancer) {
1585: if (ref($currrules) eq 'HASH') {
1586: if ($homeintdom) {
1587: if ($uname ne '') {
1588: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1589: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1590: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1591: $rule_in_effect = $currrules->{'_LC_author'};
1592: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1593: $rule_in_effect = $currrules->{'_LC_adv'}
1594: }
1595: }
1596: if ($rule_in_effect eq '') {
1597: my %userenv = &userenvironment($udom,$uname,'inststatus');
1598: if ($userenv{'inststatus'} ne '') {
1599: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1600: my ($othertitle,$usertypes,$types) =
1601: &Apache::loncommon::sorted_inst_types($udom);
1602: if (ref($types) eq 'ARRAY') {
1603: foreach my $type (@{$types}) {
1604: if (grep(/^\Q$type\E$/,@statuses)) {
1605: if (exists($currrules->{$type})) {
1606: $rule_in_effect = $currrules->{$type};
1607: }
1608: }
1609: }
1610: }
1611: } else {
1612: if (exists($currrules->{'default'})) {
1613: $rule_in_effect = $currrules->{'default'};
1614: }
1615: }
1616: }
1617: } else {
1618: if (exists($currrules->{'default'})) {
1619: $rule_in_effect = $currrules->{'default'};
1620: }
1621: }
1622: } else {
1623: if ($currrules->{'_LC_external'} ne '') {
1624: $rule_in_effect = $currrules->{'_LC_external'};
1625: }
1626: }
1627: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1628: $uname,$udom);
1629: }
1630: }
1631: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1632: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1633: unless (defined($cached)) {
1634: my %domconfig =
1635: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1636: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1637: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1638: } else {
1639: $domneedscache = $serverhomedom;
1640: }
1641: }
1642: if (ref($result) eq 'HASH') {
1643: ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1644: &check_balancer_result($result,@hosts);
1645: if ($is_balancer) {
1646: if (ref($currrules) eq 'HASH') {
1647: if ($currrules->{'_LC_internetdom'} ne '') {
1648: $rule_in_effect = $currrules->{'_LC_internetdom'};
1649: }
1650: }
1651: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1652: $uname,$udom);
1653: }
1654: } else {
1655: if ($perlvar{'lonBalancer'} eq 'yes') {
1656: $is_balancer = 1;
1657: $offloadto = &this_host_spares($dom_in_use);
1658: }
1659: unless (defined($cached)) {
1660: $domneedscache = $serverhomedom;
1661: }
1662: }
1663: } else {
1664: if ($perlvar{'lonBalancer'} eq 'yes') {
1665: $is_balancer = 1;
1666: $offloadto = &this_host_spares($dom_in_use);
1667: }
1668: unless (defined($cached)) {
1669: $domneedscache = $serverhomedom;
1670: }
1671: }
1672: if ($domneedscache) {
1673: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1674: }
1675: if (($is_balancer) && ($caller ne 'switchserver')) {
1676: my $lowest_load = 30000;
1677: if (ref($offloadto) eq 'HASH') {
1678: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1679: foreach my $try_server (@{$offloadto->{'primary'}}) {
1680: ($otherserver,$lowest_load) =
1681: &compare_server_load($try_server,$otherserver,$lowest_load);
1682: }
1683: }
1684: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1685:
1686: if (!$found_server) {
1687: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1688: foreach my $try_server (@{$offloadto->{'default'}}) {
1689: ($otherserver,$lowest_load) =
1690: &compare_server_load($try_server,$otherserver,$lowest_load);
1691: }
1692: }
1693: }
1694: } elsif (ref($offloadto) eq 'ARRAY') {
1695: if (@{$offloadto} == 1) {
1696: $otherserver = $offloadto->[0];
1697: } elsif (@{$offloadto} > 1) {
1698: foreach my $try_server (@{$offloadto}) {
1699: ($otherserver,$lowest_load) =
1700: &compare_server_load($try_server,$otherserver,$lowest_load);
1701: }
1702: }
1703: }
1704: unless ($caller eq 'login') {
1705: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1706: $is_balancer = 0;
1707: if ($uname ne '' && $udom ne '') {
1708: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1709: &appenv({'user.loadbalexempt' => $lonhost,
1710: 'user.loadbalcheck.time' => time});
1711: }
1712: }
1713: }
1714: }
1715: }
1716: if (($is_balancer) && (!$homeintdom)) {
1717: undef($setcookie);
1718: }
1719: return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1720: }
1721:
1722: sub check_balancer_result {
1723: my ($result,@hosts) = @_;
1724: my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1725: if (ref($result) eq 'HASH') {
1726: if ($result->{'lonhost'} ne '') {
1727: my $currbalancer = $result->{'lonhost'};
1728: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1729: $is_balancer = 1;
1730: $currtargets = $result->{'targets'};
1731: $currrules = $result->{'rules'};
1732: }
1733: $dom_balancers = $currbalancer;
1734: } else {
1735: if (keys(%{$result})) {
1736: foreach my $key (keys(%{$result})) {
1737: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1738: (ref($result->{$key}) eq 'HASH')) {
1739: $is_balancer = 1;
1740: $currrules = $result->{$key}{'rules'};
1741: $currtargets = $result->{$key}{'targets'};
1742: $setcookie = $result->{$key}{'cookie'};
1743: last;
1744: }
1745: }
1746: $dom_balancers = join(',',sort(keys(%{$result})));
1747: }
1748: }
1749: }
1750: return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1751: }
1752:
1753: sub get_loadbalancer_targets {
1754: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1755: my $offloadto;
1756: if ($rule_in_effect eq 'none') {
1757: return [$perlvar{'lonHostID'}];
1758: } elsif ($rule_in_effect eq '') {
1759: $offloadto = $currtargets;
1760: } else {
1761: if ($rule_in_effect eq 'homeserver') {
1762: my $homeserver = &homeserver($uname,$udom);
1763: if ($homeserver ne 'no_host') {
1764: $offloadto = [$homeserver];
1765: }
1766: } elsif ($rule_in_effect eq 'externalbalancer') {
1767: my %domconfig =
1768: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1769: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1770: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1771: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1772: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1773: }
1774: }
1775: } else {
1776: my %servers = &internet_dom_servers($udom);
1777: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1778: if (&hostname($remotebalancer) ne '') {
1779: $offloadto = [$remotebalancer];
1780: }
1781: }
1782: } elsif (&hostname($rule_in_effect) ne '') {
1783: $offloadto = [$rule_in_effect];
1784: }
1785: }
1786: return $offloadto;
1787: }
1788:
1789: sub internet_dom_servers {
1790: my ($dom) = @_;
1791: my (%uniqservers,%servers);
1792: my $primaryserver = &hostname(&domain($dom,'primary'));
1793: my @machinedoms = &machine_domains($primaryserver);
1794: foreach my $mdom (@machinedoms) {
1795: my %currservers = %servers;
1796: my %server = &get_servers($mdom);
1797: %servers = (%currservers,%server);
1798: }
1799: my %by_hostname;
1800: foreach my $id (keys(%servers)) {
1801: push(@{$by_hostname{$servers{$id}}},$id);
1802: }
1803: foreach my $hostname (sort(keys(%by_hostname))) {
1804: if (@{$by_hostname{$hostname}} > 1) {
1805: my $match = 0;
1806: foreach my $id (@{$by_hostname{$hostname}}) {
1807: if (&host_domain($id) eq $dom) {
1808: $uniqservers{$id} = $hostname;
1809: $match = 1;
1810: }
1811: }
1812: unless ($match) {
1813: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1814: }
1815: } else {
1816: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1817: }
1818: }
1819: return %uniqservers;
1820: }
1821:
1822: sub trusted_domains {
1823: my ($cmdtype,$calldom) = @_;
1824: my ($trusted,$untrusted);
1825: if (&domain($calldom) eq '') {
1826: return ($trusted,$untrusted);
1827: }
1828: unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
1829: return ($trusted,$untrusted);
1830: }
1831: my $callprimary = &domain($calldom,'primary');
1832: my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
1833: if ($intcalldom eq '') {
1834: return ($trusted,$untrusted);
1835: }
1836:
1837: my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
1838: unless (defined($cached)) {
1839: my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
1840: &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
1841: $trustconfig = $domconfig{'trust'};
1842: }
1843: if (ref($trustconfig)) {
1844: my (%possexc,%possinc,@allexc,@allinc);
1845: if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
1846: if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
1847: map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}};
1848: }
1849: if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1850: $possinc{$intcalldom} = 1;
1851: map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
1852: }
1853: }
1854: if (keys(%possexc)) {
1855: if (keys(%possinc)) {
1856: foreach my $key (sort(keys(%possexc))) {
1857: next if ($key eq $intcalldom);
1858: unless ($possinc{$key}) {
1859: push(@allexc,$key);
1860: }
1861: }
1862: } else {
1863: @allexc = sort(keys(%possexc));
1864: }
1865: }
1866: if (keys(%possinc)) {
1867: $possinc{$intcalldom} = 1;
1868: @allinc = sort(keys(%possinc));
1869: }
1870: if ((@allexc > 0) || (@allinc > 0)) {
1871: my %doms_by_intdom;
1872: my %allintdoms = &all_host_intdom();
1873: my %alldoms = &all_host_domain();
1874: foreach my $key (%allintdoms) {
1875: if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
1876: unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
1877: push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
1878: }
1879: } else {
1880: $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}];
1881: }
1882: }
1883: foreach my $exc (@allexc) {
1884: if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1885: push(@{$untrusted},@{$doms_by_intdom{$exc}});
1886: }
1887: }
1888: foreach my $inc (@allinc) {
1889: if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1890: push(@{$trusted},@{$doms_by_intdom{$inc}});
1891: }
1892: }
1893: }
1894: }
1895: return ($trusted,$untrusted);
1896: }
1897:
1898: sub will_trust {
1899: my ($cmdtype,$domain,$possdom) = @_;
1900: return 1 if ($domain eq $possdom);
1901: my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
1902: my $willtrust;
1903: if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
1904: if (grep(/^\Q$domain\E$/,@{$trustedref})) {
1905: $willtrust = 1;
1906: }
1907: } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
1908: unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
1909: $willtrust = 1;
1910: }
1911: } else {
1912: $willtrust = 1;
1913: }
1914: return $willtrust;
1915: }
1916:
1917: # ---------------------- Find the homebase for a user from domain's lib servers
1918:
1919: my %homecache;
1920: sub homeserver {
1921: my ($uname,$udom,$ignoreBadCache)=@_;
1922: my $index="$uname:$udom";
1923:
1924: if (exists($homecache{$index})) { return $homecache{$index}; }
1925:
1926: my %servers = &get_servers($udom,'library');
1927: foreach my $tryserver (keys(%servers)) {
1928: next if ($ignoreBadCache ne 'true' &&
1929: exists($badServerCache{$tryserver}));
1930:
1931: my $answer=reply("home:$udom:$uname",$tryserver);
1932: if ($answer eq 'found') {
1933: delete($badServerCache{$tryserver});
1934: return $homecache{$index}=$tryserver;
1935: } elsif ($answer eq 'no_host') {
1936: $badServerCache{$tryserver}=1;
1937: }
1938: }
1939: return 'no_host';
1940: }
1941:
1942: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1943:
1944: sub idget {
1945: my ($udom,$idsref,$namespace)=@_;
1946: my %returnhash=();
1947: my @ids=();
1948: if (ref($idsref) eq 'ARRAY') {
1949: @ids = @{$idsref};
1950: } else {
1951: return %returnhash;
1952: }
1953: if ($namespace eq '') {
1954: $namespace = 'ids';
1955: }
1956:
1957: my %servers = &get_servers($udom,'library');
1958: foreach my $tryserver (keys(%servers)) {
1959: my $idlist=join('&', map { &escape($_); } @ids);
1960: if ($namespace eq 'ids') {
1961: $idlist=~tr/A-Z/a-z/;
1962: }
1963: my $reply;
1964: if ($namespace eq 'ids') {
1965: $reply=&reply("idget:$udom:".$idlist,$tryserver);
1966: } else {
1967: $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
1968: }
1969: my @answer=();
1970: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1971: @answer=split(/\&/,$reply);
1972: } ;
1973: my $i;
1974: for ($i=0;$i<=$#ids;$i++) {
1975: if ($answer[$i]) {
1976: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1977: }
1978: }
1979: }
1980: return %returnhash;
1981: }
1982:
1983: # ------------------------------------- Find the IDs behind a list of usernames
1984:
1985: sub idrget {
1986: my ($udom,@unames)=@_;
1987: my %returnhash=();
1988: foreach my $uname (@unames) {
1989: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1990: }
1991: return %returnhash;
1992: }
1993:
1994: # Store away a list of names and associated student/employee IDs or clicker IDs
1995:
1996: sub idput {
1997: my ($udom,$idsref,$uhom,$namespace)=@_;
1998: my %servers=();
1999: my %ids=();
2000: my %byid = ();
2001: if (ref($idsref) eq 'HASH') {
2002: %ids=%{$idsref};
2003: }
2004: if ($namespace eq '') {
2005: $namespace = 'ids';
2006: }
2007: foreach my $uname (keys(%ids)) {
2008: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
2009: if ($uhom eq '') {
2010: $uhom=&homeserver($uname,$udom);
2011: }
2012: if ($uhom ne 'no_host') {
2013: my $esc_unam=&escape($uname);
2014: if ($namespace eq 'ids') {
2015: my $id=&escape($ids{$uname});
2016: $id=~tr/A-Z/a-z/;
2017: my $esc_unam=&escape($uname);
2018: $servers{$uhom}.=$id.'='.$esc_unam.'&';
2019: } else {
2020: my @currids = split(/,/,$ids{$uname});
2021: foreach my $id (@currids) {
2022: $byid{$uhom}{$id} .= $uname.',';
2023: }
2024: }
2025: }
2026: }
2027: if ($namespace eq 'clickers') {
2028: foreach my $server (keys(%byid)) {
2029: if (ref($byid{$server}) eq 'HASH') {
2030: foreach my $id (keys(%{$byid{$server}})) {
2031: $byid{$server} =~ s/,$//;
2032: $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&';
2033: }
2034: }
2035: }
2036: }
2037: foreach my $server (keys(%servers)) {
2038: $servers{$server} =~ s/\&$//;
2039: if ($namespace eq 'ids') {
2040: &critical('idput:'.$udom.':'.$servers{$server},$server);
2041: } else {
2042: &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
2043: }
2044: }
2045: }
2046:
2047: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
2048:
2049: sub iddel {
2050: my ($udom,$idshashref,$uhome,$namespace)=@_;
2051: my %result=();
2052: my %ids=();
2053: my %byid = ();
2054: if (ref($idshashref) eq 'HASH') {
2055: %ids=%{$idshashref};
2056: } else {
2057: return %result;
2058: }
2059: if ($namespace eq '') {
2060: $namespace = 'ids';
2061: }
2062: my %servers=();
2063: while (my ($id,$unamestr) = each(%ids)) {
2064: if ($namespace eq 'ids') {
2065: my $uhom = $uhome;
2066: if ($uhom eq '') {
2067: $uhom=&homeserver($unamestr,$udom);
2068: }
2069: if ($uhom ne 'no_host') {
2070: $servers{$uhom}.='&'.&escape($id);
2071: }
2072: } else {
2073: my @curritems = split(/,/,$ids{$id});
2074: foreach my $uname (@curritems) {
2075: my $uhom = $uhome;
2076: if ($uhom eq '') {
2077: $uhom=&homeserver($uname,$udom);
2078: }
2079: if ($uhom ne 'no_host') {
2080: $byid{$uhom}{$id} .= $uname.',';
2081: }
2082: }
2083: }
2084: }
2085: if ($namespace eq 'clickers') {
2086: foreach my $server (keys(%byid)) {
2087: if (ref($byid{$server}) eq 'HASH') {
2088: foreach my $id (keys(%{$byid{$server}})) {
2089: $byid{$server}{$id} =~ s/,$//;
2090: $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
2091: }
2092: }
2093: }
2094: }
2095: foreach my $server (keys(%servers)) {
2096: $servers{$server} =~ s/\&$//;
2097: if ($namespace eq 'ids') {
2098: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
2099: } elsif ($namespace eq 'clickers') {
2100: $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
2101: }
2102: }
2103: return %result;
2104: }
2105:
2106: # ----- Update clicker ID-to-username look-ups in clickers.db on library server
2107:
2108: sub updateclickers {
2109: my ($udom,$action,$idshashref,$uhome,$critical) = @_;
2110: my %clickers;
2111: if (ref($idshashref) eq 'HASH') {
2112: %clickers=%{$idshashref};
2113: } else {
2114: return;
2115: }
2116: my $items='';
2117: foreach my $item (keys(%clickers)) {
2118: $items.=&escape($item).'='.&escape($clickers{$item}).'&';
2119: }
2120: $items=~s/\&$//;
2121: my $request = "updateclickers:$udom:$action:$items";
2122: if ($critical) {
2123: return &critical($request,$uhome);
2124: } else {
2125: return &reply($request,$uhome);
2126: }
2127: }
2128:
2129: # ------------------------------dump from db file owned by domainconfig user
2130: sub dump_dom {
2131: my ($namespace, $udom, $regexp) = @_;
2132:
2133: $udom ||= $env{'user.domain'};
2134:
2135: return () unless $udom;
2136:
2137: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
2138: }
2139:
2140: # ------------------------------------------ get items from domain db files
2141:
2142: sub get_dom {
2143: my ($namespace,$storearr,$udom,$uhome)=@_;
2144: return if ($udom eq 'public');
2145: my $items='';
2146: foreach my $item (@$storearr) {
2147: $items.=&escape($item).'&';
2148: }
2149: $items=~s/\&$//;
2150: if (!$udom) {
2151: $udom=$env{'user.domain'};
2152: return if ($udom eq 'public');
2153: if (defined(&domain($udom,'primary'))) {
2154: $uhome=&domain($udom,'primary');
2155: } else {
2156: undef($uhome);
2157: }
2158: } else {
2159: if (!$uhome) {
2160: if (defined(&domain($udom,'primary'))) {
2161: $uhome=&domain($udom,'primary');
2162: }
2163: }
2164: }
2165: if ($udom && $uhome && ($uhome ne 'no_host')) {
2166: my $rep;
2167: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
2168: # domain information is hosted on this machine
2169: my $cmd = 'getdom';
2170: if ($namespace =~ /^enc/) {
2171: $cmd = 'egetdom';
2172: }
2173: $rep = &LONCAPA::Lond::get_dom("$cmd:$udom:$namespace:$items");
2174: } else {
2175: if ($namespace =~ /^enc/) {
2176: $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
2177: } else {
2178: $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
2179: }
2180: }
2181: my %returnhash;
2182: if ($rep eq '' || $rep =~ /^error: 2 /) {
2183: return %returnhash;
2184: }
2185: my @pairs=split(/\&/,$rep);
2186: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
2187: return @pairs;
2188: }
2189: my $i=0;
2190: foreach my $item (@$storearr) {
2191: $returnhash{$item}=&thaw_unescape($pairs[$i]);
2192: $i++;
2193: }
2194: return %returnhash;
2195: } else {
2196: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
2197: }
2198: }
2199:
2200: # -------------------------------------------- put items in domain db files
2201:
2202: sub put_dom {
2203: my ($namespace,$storehash,$udom,$uhome)=@_;
2204: if (!$udom) {
2205: $udom=$env{'user.domain'};
2206: if (defined(&domain($udom,'primary'))) {
2207: $uhome=&domain($udom,'primary');
2208: } else {
2209: undef($uhome);
2210: }
2211: } else {
2212: if (!$uhome) {
2213: if (defined(&domain($udom,'primary'))) {
2214: $uhome=&domain($udom,'primary');
2215: }
2216: }
2217: }
2218: if ($udom && $uhome && ($uhome ne 'no_host')) {
2219: my $items='';
2220: foreach my $item (keys(%$storehash)) {
2221: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
2222: }
2223: $items=~s/\&$//;
2224: if ($namespace =~ /^enc/) {
2225: return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
2226: } else {
2227: return &reply("putdom:$udom:$namespace:$items",$uhome);
2228: }
2229: } else {
2230: &logthis("put_dom failed - no homeserver and/or domain");
2231: }
2232: }
2233:
2234: # --------------------- newput for items in db file owned by domainconfig user
2235: sub newput_dom {
2236: my ($namespace,$storehash,$udom) = @_;
2237: my $result;
2238: if (!$udom) {
2239: $udom=$env{'user.domain'};
2240: }
2241: if ($udom) {
2242: my $uname = &get_domainconfiguser($udom);
2243: $result = &newput($namespace,$storehash,$udom,$uname);
2244: }
2245: return $result;
2246: }
2247:
2248: # --------------------- delete for items in db file owned by domainconfig user
2249: sub del_dom {
2250: my ($namespace,$storearr,$udom)=@_;
2251: if (ref($storearr) eq 'ARRAY') {
2252: if (!$udom) {
2253: $udom=$env{'user.domain'};
2254: }
2255: if ($udom) {
2256: my $uname = &get_domainconfiguser($udom);
2257: return &del($namespace,$storearr,$udom,$uname);
2258: }
2259: }
2260: }
2261:
2262: # ----------------------------------construct domainconfig user for a domain
2263: sub get_domainconfiguser {
2264: my ($udom) = @_;
2265: return $udom.'-domainconfig';
2266: }
2267:
2268: sub retrieve_inst_usertypes {
2269: my ($udom) = @_;
2270: my (%returnhash,@order);
2271: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
2272: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
2273: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
2274: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
2275: } else {
2276: if (defined(&domain($udom,'primary'))) {
2277: my $uhome=&domain($udom,'primary');
2278: my $rep=&reply("inst_usertypes:$udom",$uhome);
2279: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
2280: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
2281: return (\%returnhash,\@order);
2282: }
2283: my ($hashitems,$orderitems) = split(/:/,$rep);
2284: my @pairs=split(/\&/,$hashitems);
2285: foreach my $item (@pairs) {
2286: my ($key,$value)=split(/=/,$item,2);
2287: $key = &unescape($key);
2288: next if ($key =~ /^error: 2 /);
2289: $returnhash{$key}=&thaw_unescape($value);
2290: }
2291: my @esc_order = split(/\&/,$orderitems);
2292: foreach my $item (@esc_order) {
2293: push(@order,&unescape($item));
2294: }
2295: } else {
2296: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
2297: }
2298: return (\%returnhash,\@order);
2299: }
2300: }
2301:
2302: sub is_domainimage {
2303: my ($url) = @_;
2304: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
2305: if (&domain($1) ne '') {
2306: return '1';
2307: }
2308: }
2309: return;
2310: }
2311:
2312: sub inst_directory_query {
2313: my ($srch) = @_;
2314: my $udom = $srch->{'srchdomain'};
2315: my %results;
2316: my $homeserver = &domain($udom,'primary');
2317: my $outcome;
2318: if ($homeserver ne '') {
2319: unless ($homeserver eq $perlvar{'lonHostID'}) {
2320: if ($srch->{'srchby'} eq 'email') {
2321: my $lcrev = &get_server_loncaparev($udom,$homeserver);
2322: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2323: if (($major eq '' && $minor eq '') || ($major < 2) ||
2324: (($major == 2) && ($minor < 12))) {
2325: return;
2326: }
2327: }
2328: }
2329: my $queryid=&reply("querysend:instdirsearch:".
2330: &escape($srch->{'srchby'}).':'.
2331: &escape($srch->{'srchterm'}).':'.
2332: &escape($srch->{'srchtype'}),$homeserver);
2333: my $host=&hostname($homeserver);
2334: if ($queryid !~/^\Q$host\E\_/) {
2335: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
2336: return;
2337: }
2338: my $response = &get_query_reply($queryid);
2339: my $maxtries = 5;
2340: my $tries = 1;
2341: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2342: $response = &get_query_reply($queryid);
2343: $tries ++;
2344: }
2345:
2346: if (!&error($response) && $response ne 'refused') {
2347: if ($response eq 'unavailable') {
2348: $outcome = $response;
2349: } else {
2350: $outcome = 'ok';
2351: my @matches = split(/\n/,$response);
2352: foreach my $match (@matches) {
2353: my ($key,$value) = split(/=/,$match);
2354: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2355: }
2356: }
2357: }
2358: }
2359: return ($outcome,%results);
2360: }
2361:
2362: sub usersearch {
2363: my ($srch) = @_;
2364: my $dom = $srch->{'srchdomain'};
2365: my %results;
2366: my %libserv = &all_library();
2367: my $query = 'usersearch';
2368: foreach my $tryserver (keys(%libserv)) {
2369: if (&host_domain($tryserver) eq $dom) {
2370: unless ($tryserver eq $perlvar{'lonHostID'}) {
2371: if ($srch->{'srchby'} eq 'email') {
2372: my $lcrev = &get_server_loncaparev($dom,$tryserver);
2373: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2374: next if (($major eq '' && $minor eq '') || ($major < 2) ||
2375: (($major == 2) && ($minor < 12)));
2376: }
2377: }
2378: my $host=&hostname($tryserver);
2379: my $queryid=
2380: &reply("querysend:".&escape($query).':'.
2381: &escape($srch->{'srchby'}).':'.
2382: &escape($srch->{'srchtype'}).':'.
2383: &escape($srch->{'srchterm'}),$tryserver);
2384: if ($queryid !~/^\Q$host\E\_/) {
2385: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
2386: next;
2387: }
2388: my $reply = &get_query_reply($queryid);
2389: my $maxtries = 1;
2390: my $tries = 1;
2391: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2392: $reply = &get_query_reply($queryid);
2393: $tries ++;
2394: }
2395: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2396: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2397: } else {
2398: my @matches;
2399: if ($reply =~ /\n/) {
2400: @matches = split(/\n/,$reply);
2401: } else {
2402: @matches = split(/\&/,$reply);
2403: }
2404: foreach my $match (@matches) {
2405: my ($uname,$udom,%userhash);
2406: foreach my $entry (split(/:/,$match)) {
2407: my ($key,$value) =
2408: map {&unescape($_);} split(/=/,$entry);
2409: $userhash{$key} = $value;
2410: if ($key eq 'username') {
2411: $uname = $value;
2412: } elsif ($key eq 'domain') {
2413: $udom = $value;
2414: }
2415: }
2416: $results{$uname.':'.$udom} = \%userhash;
2417: }
2418: }
2419: }
2420: }
2421: return %results;
2422: }
2423:
2424: sub get_instuser {
2425: my ($udom,$uname,$id) = @_;
2426: my $homeserver = &domain($udom,'primary');
2427: my ($outcome,%results);
2428: if ($homeserver ne '') {
2429: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2430: &escape($id).':'.&escape($udom),$homeserver);
2431: my $host=&hostname($homeserver);
2432: if ($queryid !~/^\Q$host\E\_/) {
2433: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2434: return;
2435: }
2436: my $response = &get_query_reply($queryid);
2437: my $maxtries = 5;
2438: my $tries = 1;
2439: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2440: $response = &get_query_reply($queryid);
2441: $tries ++;
2442: }
2443: if (!&error($response) && $response ne 'refused') {
2444: if ($response eq 'unavailable') {
2445: $outcome = $response;
2446: } else {
2447: $outcome = 'ok';
2448: my @matches = split(/\n/,$response);
2449: foreach my $match (@matches) {
2450: my ($key,$value) = split(/=/,$match);
2451: $results{&unescape($key)} = &thaw_unescape($value);
2452: }
2453: }
2454: }
2455: }
2456: my %userinfo;
2457: if (ref($results{$uname}) eq 'HASH') {
2458: %userinfo = %{$results{$uname}};
2459: }
2460: return ($outcome,%userinfo);
2461: }
2462:
2463: sub get_multiple_instusers {
2464: my ($udom,$users,$caller) = @_;
2465: my ($outcome,$results);
2466: if (ref($users) eq 'HASH') {
2467: my $count = keys(%{$users});
2468: my $requested = &freeze_escape($users);
2469: my $homeserver = &domain($udom,'primary');
2470: if ($homeserver ne '') {
2471: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2472: my $host=&hostname($homeserver);
2473: if ($queryid !~/^\Q$host\E\_/) {
2474: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2475: ' for host: '.$homeserver.'in domain '.$udom);
2476: return ($outcome,$results);
2477: }
2478: my $response = &get_query_reply($queryid);
2479: my $maxtries = 5;
2480: if ($count > 100) {
2481: $maxtries = 1+int($count/20);
2482: }
2483: my $tries = 1;
2484: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2485: $response = &get_query_reply($queryid);
2486: $tries ++;
2487: }
2488: if ($response eq '') {
2489: $results = {};
2490: foreach my $key (keys(%{$users})) {
2491: my ($uname,$id);
2492: if ($caller eq 'id') {
2493: $id = $key;
2494: } else {
2495: $uname = $key;
2496: }
2497: my ($resp,%info) = &get_instuser($udom,$uname,$id);
2498: $outcome = $resp;
2499: if ($resp eq 'ok') {
2500: %{$results} = (%{$results}, %info);
2501: } else {
2502: last;
2503: }
2504: }
2505: } elsif(!&error($response) && ($response ne 'refused')) {
2506: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2507: $outcome = $response;
2508: } else {
2509: ($outcome,my $userdata) = split(/=/,$response,2);
2510: if ($outcome eq 'ok') {
2511: $results = &thaw_unescape($userdata);
2512: }
2513: }
2514: }
2515: }
2516: }
2517: return ($outcome,$results);
2518: }
2519:
2520: sub inst_rulecheck {
2521: my ($udom,$uname,$id,$item,$rules) = @_;
2522: my %returnhash;
2523: if ($udom ne '') {
2524: if (ref($rules) eq 'ARRAY') {
2525: @{$rules} = map {&escape($_);} (@{$rules});
2526: my $rulestr = join(':',@{$rules});
2527: my $homeserver=&domain($udom,'primary');
2528: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
2529: my $response;
2530: if ($item eq 'username') {
2531: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2532: ':'.&escape($uname).':'.$rulestr,
2533: $homeserver));
2534: } elsif ($item eq 'id') {
2535: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2536: ':'.&escape($id).':'.$rulestr,
2537: $homeserver));
2538: } elsif ($item eq 'selfcreate') {
2539: $response=&unescape(&reply('instselfcreatecheck:'.
2540: &escape($udom).':'.&escape($uname).
2541: ':'.$rulestr,$homeserver));
2542: }
2543: if ($response ne 'refused') {
2544: my @pairs=split(/\&/,$response);
2545: foreach my $item (@pairs) {
2546: my ($key,$value)=split(/=/,$item,2);
2547: $key = &unescape($key);
2548: next if ($key =~ /^error: 2 /);
2549: $returnhash{$key}=&thaw_unescape($value);
2550: }
2551: }
2552: }
2553: }
2554: }
2555: return %returnhash;
2556: }
2557:
2558: sub inst_userrules {
2559: my ($udom,$check) = @_;
2560: my (%ruleshash,@ruleorder);
2561: if ($udom ne '') {
2562: my $homeserver=&domain($udom,'primary');
2563: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
2564: my $response;
2565: if ($check eq 'id') {
2566: $response=&reply('instidrules:'.&escape($udom),
2567: $homeserver);
2568: } elsif ($check eq 'email') {
2569: $response=&reply('instemailrules:'.&escape($udom),
2570: $homeserver);
2571: } else {
2572: $response=&reply('instuserrules:'.&escape($udom),
2573: $homeserver);
2574: }
2575: if (($response ne 'refused') && ($response ne 'error') &&
2576: ($response ne 'unknown_cmd') &&
2577: ($response ne 'no_such_host')) {
2578: my ($hashitems,$orderitems) = split(/:/,$response);
2579: my @pairs=split(/\&/,$hashitems);
2580: foreach my $item (@pairs) {
2581: my ($key,$value)=split(/=/,$item,2);
2582: $key = &unescape($key);
2583: next if ($key =~ /^error: 2 /);
2584: $ruleshash{$key}=&thaw_unescape($value);
2585: }
2586: my @esc_order = split(/\&/,$orderitems);
2587: foreach my $item (@esc_order) {
2588: push(@ruleorder,&unescape($item));
2589: }
2590: }
2591: }
2592: }
2593: return (\%ruleshash,\@ruleorder);
2594: }
2595:
2596: # ------------- Get Authentication, Language and User Tools Defaults for Domain
2597:
2598: sub get_domain_defaults {
2599: my ($domain,$ignore_cache) = @_;
2600: return if (($domain eq '') || ($domain eq 'public'));
2601: my $cachetime = 60*60*24;
2602: unless ($ignore_cache) {
2603: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2604: if (defined($cached)) {
2605: if (ref($result) eq 'HASH') {
2606: return %{$result};
2607: }
2608: }
2609: }
2610: my %domdefaults;
2611: my %domconfig =
2612: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
2613: 'requestcourses','inststatus',
2614: 'coursedefaults','usersessions',
2615: 'requestauthor','selfenrollment',
2616: 'coursecategories','ssl','autoenroll',
2617: 'trust','helpsettings','wafproxy'],$domain);
2618: my @coursetypes = ('official','unofficial','community','textbook','placement');
2619: if (ref($domconfig{'defaults'}) eq 'HASH') {
2620: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2621: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2622: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
2623: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
2624: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
2625: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
2626: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2627: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2628: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
2629: } else {
2630: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2631: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2632: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2633: }
2634: if (ref($domconfig{'quotas'}) eq 'HASH') {
2635: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2636: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2637: } else {
2638: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
2639: }
2640: my @usertools = ('aboutme','blog','webdav','portfolio');
2641: foreach my $item (@usertools) {
2642: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2643: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2644: }
2645: }
2646: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2647: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2648: }
2649: }
2650: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
2651: foreach my $item ('official','unofficial','community','textbook','placement') {
2652: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2653: }
2654: }
2655: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2656: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2657: }
2658: if (ref($domconfig{'inststatus'}) eq 'HASH') {
2659: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
2660: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2661: }
2662: }
2663: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
2664: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
2665: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2666: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2667: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2668: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2669: }
2670: foreach my $type (@coursetypes) {
2671: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2672: unless ($type eq 'community') {
2673: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2674: }
2675: }
2676: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2677: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2678: }
2679: if ($domdefaults{'postsubmit'} eq 'on') {
2680: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2681: $domdefaults{$type.'postsubtimeout'} =
2682: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2683: }
2684: }
2685: }
2686: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2687: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2688: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2689: if (@clonecodes) {
2690: $domdefaults{'canclone'} = join('+',@clonecodes);
2691: }
2692: }
2693: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2694: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2695: }
2696: if ($domconfig{'coursedefaults'}{'texengine'}) {
2697: $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
2698: }
2699: }
2700: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2701: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2702: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2703: }
2704: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2705: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2706: }
2707: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2708: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2709: }
2710: if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
2711: $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
2712: }
2713: }
2714: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2715: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2716: my @settings = ('types','registered','enroll_dates','access_dates','section',
2717: 'approval','limit');
2718: foreach my $type (@coursetypes) {
2719: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2720: my @mgrdc = ();
2721: foreach my $item (@settings) {
2722: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2723: push(@mgrdc,$item);
2724: }
2725: }
2726: if (@mgrdc) {
2727: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2728: }
2729: }
2730: }
2731: }
2732: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2733: foreach my $type (@coursetypes) {
2734: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2735: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2736: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2737: }
2738: }
2739: }
2740: }
2741: }
2742: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2743: $domdefaults{'catauth'} = 'std';
2744: $domdefaults{'catunauth'} = 'std';
2745: if ($domconfig{'coursecategories'}{'auth'}) {
2746: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2747: }
2748: if ($domconfig{'coursecategories'}{'unauth'}) {
2749: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2750: }
2751: }
2752: if (ref($domconfig{'ssl'}) eq 'HASH') {
2753: if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
2754: $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
2755: }
2756: if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
2757: $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
2758: }
2759: if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
2760: $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
2761: }
2762: }
2763: if (ref($domconfig{'trust'}) eq 'HASH') {
2764: my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
2765: foreach my $prefix (@prefixes) {
2766: if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
2767: $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
2768: }
2769: }
2770: }
2771: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2772: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2773: }
2774: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2775: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2776: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2777: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2778: }
2779: }
2780: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
2781: foreach my $item ('ipheader','trusted','vpnint','vpnext') {
2782: if ($domconfig{'wafproxy'}{$item}) {
2783: $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
2784: }
2785: }
2786: }
2787: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
2788: return %domdefaults;
2789: }
2790:
2791: sub get_dom_cats {
2792: my ($dom) = @_;
2793: return unless (&domain($dom));
2794: my ($cats,$cached)=&is_cached_new('cats',$dom);
2795: unless (defined($cached)) {
2796: my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
2797: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2798: if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
2799: %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
2800: } else {
2801: $cats = {};
2802: }
2803: } else {
2804: $cats = {};
2805: }
2806: &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
2807: }
2808: return $cats;
2809: }
2810:
2811: sub get_dom_instcats {
2812: my ($dom) = @_;
2813: return unless (&domain($dom));
2814: my ($instcats,$cached)=&is_cached_new('instcats',$dom);
2815: unless (defined($cached)) {
2816: my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
2817: my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
2818: if ($totcodes > 0) {
2819: my $caller = 'global';
2820: if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
2821: \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
2822: $instcats = {
2823: codes => \%codes,
2824: codetitles => \@codetitles,
2825: cat_titles => \%cat_titles,
2826: cat_order => \%cat_order,
2827: };
2828: &do_cache_new('instcats',$dom,$instcats,3600);
2829: }
2830: }
2831: }
2832: return $instcats;
2833: }
2834:
2835: sub retrieve_instcodes {
2836: my ($coursecodes,$dom) = @_;
2837: my $totcodes;
2838: my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
2839: foreach my $course (keys(%courses)) {
2840: if (ref($courses{$course}) eq 'HASH') {
2841: if ($courses{$course}{'inst_code'} ne '') {
2842: $$coursecodes{$course} = $courses{$course}{'inst_code'};
2843: $totcodes ++;
2844: }
2845: }
2846: }
2847: return $totcodes;
2848: }
2849:
2850: sub course_portal_url {
2851: my ($cnum,$cdom) = @_;
2852: my $chome = &homeserver($cnum,$cdom);
2853: my $hostname = &hostname($chome);
2854: my $protocol = $protocol{$chome};
2855: $protocol = 'http' if ($protocol ne 'https');
2856: my %domdefaults = &get_domain_defaults($cdom);
2857: my $firsturl;
2858: if ($domdefaults{'portal_def'}) {
2859: $firsturl = $domdefaults{'portal_def'};
2860: } else {
2861: $firsturl = $protocol.'://'.$hostname;
2862: }
2863: return $firsturl;
2864: }
2865:
2866: # --------------------------------------------- Get domain config for passwords
2867:
2868: sub get_passwdconf {
2869: my ($dom) = @_;
2870: my (%passwdconf,$gotconf,$lookup);
2871: my ($result,$cached)=&is_cached_new('passwdconf',$dom);
2872: if (defined($cached)) {
2873: if (ref($result) eq 'HASH') {
2874: %passwdconf = %{$result};
2875: $gotconf = 1;
2876: }
2877: }
2878: unless ($gotconf) {
2879: my %domconfig = &get_dom('configuration',['passwords'],$dom);
2880: if (ref($domconfig{'passwords'}) eq 'HASH') {
2881: %passwdconf = %{$domconfig{'passwords'}};
2882: }
2883: my $cachetime = 24*60*60;
2884: &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
2885: }
2886: return %passwdconf;
2887: }
2888:
2889: # --------------------------------------------------- Assign a key to a student
2890:
2891: sub assign_access_key {
2892: #
2893: # a valid key looks like uname:udom#comments
2894: # comments are being appended
2895: #
2896: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2897: $kdom=
2898: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
2899: $knum=
2900: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
2901: $cdom=
2902: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2903: $cnum=
2904: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2905: $udom=$env{'user.name'} unless (defined($udom));
2906: $uname=$env{'user.domain'} unless (defined($uname));
2907: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
2908: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
2909: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
2910: # assigned to this person
2911: # - this should not happen,
2912: # unless something went wrong
2913: # the first time around
2914: # ready to assign
2915: $logentry=$1.'; '.$logentry;
2916: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
2917: $kdom,$knum) eq 'ok') {
2918: # key now belongs to user
2919: my $envkey='key.'.$cdom.'_'.$cnum;
2920: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
2921: &appenv({'environment.'.$envkey => $ckey});
2922: return 'ok';
2923: } else {
2924: return
2925: 'error: Count not permanently assign key, will need to be re-entered later.';
2926: }
2927: } else {
2928: return 'error: Could not assign key, try again later.';
2929: }
2930: } elsif (!$existing{$ckey}) {
2931: # the key does not exist
2932: return 'error: The key does not exist';
2933: } else {
2934: # the key is somebody else's
2935: return 'error: The key is already in use';
2936: }
2937: }
2938:
2939: # ------------------------------------------ put an additional comment on a key
2940:
2941: sub comment_access_key {
2942: #
2943: # a valid key looks like uname:udom#comments
2944: # comments are being appended
2945: #
2946: my ($ckey,$cdom,$cnum,$logentry)=@_;
2947: $cdom=
2948: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2949: $cnum=
2950: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2951: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2952: if ($existing{$ckey}) {
2953: $existing{$ckey}.='; '.$logentry;
2954: # ready to assign
2955: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
2956: $cdom,$cnum) eq 'ok') {
2957: return 'ok';
2958: } else {
2959: return 'error: Count not store comment.';
2960: }
2961: } else {
2962: # the key does not exist
2963: return 'error: The key does not exist';
2964: }
2965: }
2966:
2967: # ------------------------------------------------------ Generate a set of keys
2968:
2969: sub generate_access_keys {
2970: my ($number,$cdom,$cnum,$logentry)=@_;
2971: $cdom=
2972: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2973: $cnum=
2974: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2975: unless (&allowed('mky',$cdom)) { return 0; }
2976: unless (($cdom) && ($cnum)) { return 0; }
2977: if ($number>10000) { return 0; }
2978: sleep(2); # make sure don't get same seed twice
2979: srand(time()^($$+($$<<15))); # from "Programming Perl"
2980: my $total=0;
2981: for (my $i=1;$i<=$number;$i++) {
2982: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2983: sprintf("%lx",int(100000*rand)).'-'.
2984: sprintf("%lx",int(100000*rand));
2985: $newkey=~s/1/g/g; # folks mix up 1 and l
2986: $newkey=~s/0/h/g; # and also 0 and O
2987: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2988: if ($existing{$newkey}) {
2989: $i--;
2990: } else {
2991: if (&put('accesskeys',
2992: { $newkey => '# generated '.localtime().
2993: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
2994: '; '.$logentry },
2995: $cdom,$cnum) eq 'ok') {
2996: $total++;
2997: }
2998: }
2999: }
3000: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
3001: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
3002: return $total;
3003: }
3004:
3005: # ------------------------------------------------------- Validate an accesskey
3006:
3007: sub validate_access_key {
3008: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
3009: $cdom=
3010: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
3011: $cnum=
3012: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
3013: $udom=$env{'user.domain'} unless (defined($udom));
3014: $uname=$env{'user.name'} unless (defined($uname));
3015: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
3016: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
3017: }
3018:
3019: # ------------------------------------- Find the section of student in a course
3020: sub devalidate_getsection_cache {
3021: my ($udom,$unam,$courseid)=@_;
3022: my $hashid="$udom:$unam:$courseid";
3023: &devalidate_cache_new('getsection',$hashid);
3024: }
3025:
3026: sub courseid_to_courseurl {
3027: my ($courseid) = @_;
3028: #already url style courseid
3029: return $courseid if ($courseid =~ m{^/});
3030:
3031: if (exists($env{'course.'.$courseid.'.num'})) {
3032: my $cnum = $env{'course.'.$courseid.'.num'};
3033: my $cdom = $env{'course.'.$courseid.'.domain'};
3034: return "/$cdom/$cnum";
3035: }
3036:
3037: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
3038: if (exists($courseinfo{'num'})) {
3039: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
3040: }
3041:
3042: return undef;
3043: }
3044:
3045: sub getsection {
3046: my ($udom,$unam,$courseid)=@_;
3047: my $cachetime=1800;
3048:
3049: my $hashid="$udom:$unam:$courseid";
3050: my ($result,$cached)=&is_cached_new('getsection',$hashid);
3051: if (defined($cached)) { return $result; }
3052:
3053: my %Pending;
3054: my %Expired;
3055: #
3056: # Each role can either have not started yet (pending), be active,
3057: # or have expired.
3058: #
3059: # If there is an active role, we are done.
3060: #
3061: # If there is more than one role which has not started yet,
3062: # choose the one which will start sooner
3063: # If there is one role which has not started yet, return it.
3064: #
3065: # If there is more than one expired role, choose the one which ended last.
3066: # If there is a role which has expired, return it.
3067: #
3068: $courseid = &courseid_to_courseurl($courseid);
3069: my %roleshash = &dump('roles',$udom,$unam,$courseid);
3070: foreach my $key (keys(%roleshash)) {
3071: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
3072: my $section=$1;
3073: if ($key eq $courseid.'_st') { $section=''; }
3074: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
3075: my $now=time;
3076: if (defined($end) && $end && ($now > $end)) {
3077: $Expired{$end}=$section;
3078: next;
3079: }
3080: if (defined($start) && $start && ($now < $start)) {
3081: $Pending{$start}=$section;
3082: next;
3083: }
3084: return &do_cache_new('getsection',$hashid,$section,$cachetime);
3085: }
3086: #
3087: # Presumedly there will be few matching roles from the above
3088: # loop and the sorting time will be negligible.
3089: if (scalar(keys(%Pending))) {
3090: my ($time) = sort {$a <=> $b} keys(%Pending);
3091: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
3092: }
3093: if (scalar(keys(%Expired))) {
3094: my @sorted = sort {$a <=> $b} keys(%Expired);
3095: my $time = pop(@sorted);
3096: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
3097: }
3098: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
3099: }
3100:
3101: sub save_cache {
3102: &purge_remembered();
3103: #&Apache::loncommon::validate_page();
3104: undef(%env);
3105: undef($env_loaded);
3106: }
3107:
3108: my $to_remember=-1;
3109: my %remembered;
3110: my %accessed;
3111: my $kicks=0;
3112: my $hits=0;
3113: sub make_key {
3114: my ($name,$id) = @_;
3115: if (length($id) > 65
3116: && length(&escape($id)) > 200) {
3117: $id=length($id).':'.&Digest::MD5::md5_hex($id);
3118: }
3119: return &escape($name.':'.$id);
3120: }
3121:
3122: sub devalidate_cache_new {
3123: my ($name,$id,$debug) = @_;
3124: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
3125: my $remembered_id=$name.':'.$id;
3126: $id=&make_key($name,$id);
3127: $memcache->delete($id);
3128: delete($remembered{$remembered_id});
3129: delete($accessed{$remembered_id});
3130: }
3131:
3132: sub is_cached_new {
3133: my ($name,$id,$debug) = @_;
3134: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
3135: if (exists($remembered{$remembered_id})) {
3136: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
3137: $accessed{$remembered_id}=[&gettimeofday()];
3138: $hits++;
3139: return ($remembered{$remembered_id},1);
3140: }
3141: $id=&make_key($name,$id);
3142: my $value = $memcache->get($id);
3143: if (!(defined($value))) {
3144: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
3145: return (undef,undef);
3146: }
3147: if ($value eq '__undef__') {
3148: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
3149: $value=undef;
3150: }
3151: &make_room($remembered_id,$value,$debug);
3152: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
3153: return ($value,1);
3154: }
3155:
3156: sub do_cache_new {
3157: my ($name,$id,$value,$time,$debug) = @_;
3158: my $remembered_id=$name.':'.$id;
3159: $id=&make_key($name,$id);
3160: my $setvalue=$value;
3161: if (!defined($setvalue)) {
3162: $setvalue='__undef__';
3163: }
3164: if (!defined($time) ) {
3165: $time=600;
3166: }
3167: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
3168: my $result = $memcache->set($id,$setvalue,$time);
3169: if (! $result) {
3170: &logthis("caching of id -> $id failed");
3171: $memcache->disconnect_all();
3172: }
3173: # need to make a copy of $value
3174: &make_room($remembered_id,$value,$debug);
3175: return $value;
3176: }
3177:
3178: sub make_room {
3179: my ($remembered_id,$value,$debug)=@_;
3180:
3181: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
3182: : $value;
3183: if ($to_remember<0) { return; }
3184: $accessed{$remembered_id}=[&gettimeofday()];
3185: if (scalar(keys(%remembered)) <= $to_remember) { return; }
3186: my $to_kick;
3187: my $max_time=0;
3188: foreach my $other (keys(%accessed)) {
3189: if (&tv_interval($accessed{$other}) > $max_time) {
3190: $to_kick=$other;
3191: $max_time=&tv_interval($accessed{$other});
3192: }
3193: }
3194: delete($remembered{$to_kick});
3195: delete($accessed{$to_kick});
3196: $kicks++;
3197: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
3198: return;
3199: }
3200:
3201: sub purge_remembered {
3202: #&logthis("Tossing ".scalar(keys(%remembered)));
3203: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
3204: undef(%remembered);
3205: undef(%accessed);
3206: }
3207: # ------------------------------------- Read an entry from a user's environment
3208:
3209: sub userenvironment {
3210: my ($udom,$unam,@what)=@_;
3211: my $items;
3212: foreach my $item (@what) {
3213: $items.=&escape($item).'&';
3214: }
3215: $items=~s/\&$//;
3216: my %returnhash=();
3217: my $uhome = &homeserver($unam,$udom);
3218: unless ($uhome eq 'no_host') {
3219: my @answer=split(/\&/,
3220: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
3221: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
3222: return %returnhash;
3223: }
3224: my $i;
3225: for ($i=0;$i<=$#what;$i++) {
3226: $returnhash{$what[$i]}=&unescape($answer[$i]);
3227: }
3228: }
3229: return %returnhash;
3230: }
3231:
3232: # ---------------------------------------------------------- Get a studentphoto
3233: sub studentphoto {
3234: my ($udom,$unam,$ext) = @_;
3235: my $home=&Apache::lonnet::homeserver($unam,$udom);
3236: if (defined($env{'request.course.id'})) {
3237: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
3238: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
3239: return(&retrievestudentphoto($udom,$unam,$ext));
3240: } else {
3241: my ($result,$perm_reqd)=
3242: &Apache::lonnet::auto_photo_permission($unam,$udom);
3243: if ($result eq 'ok') {
3244: if (!($perm_reqd eq 'yes')) {
3245: return(&retrievestudentphoto($udom,$unam,$ext));
3246: }
3247: }
3248: }
3249: }
3250: } else {
3251: my ($result,$perm_reqd) =
3252: &Apache::lonnet::auto_photo_permission($unam,$udom);
3253: if ($result eq 'ok') {
3254: if (!($perm_reqd eq 'yes')) {
3255: return(&retrievestudentphoto($udom,$unam,$ext));
3256: }
3257: }
3258: }
3259: return '/adm/lonKaputt/lonlogo_broken.gif';
3260: }
3261:
3262: sub retrievestudentphoto {
3263: my ($udom,$unam,$ext,$type) = @_;
3264: my $home=&Apache::lonnet::homeserver($unam,$udom);
3265: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
3266: if ($ret eq 'ok') {
3267: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
3268: if ($type eq 'thumbnail') {
3269: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
3270: }
3271: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
3272: return $tokenurl;
3273: } else {
3274: if ($type eq 'thumbnail') {
3275: return '/adm/lonKaputt/genericstudent_tn.gif';
3276: } else {
3277: return '/adm/lonKaputt/lonlogo_broken.gif';
3278: }
3279: }
3280: }
3281:
3282: # -------------------------------------------------------------------- New chat
3283:
3284: sub chatsend {
3285: my ($newentry,$anon,$group)=@_;
3286: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
3287: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3288: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
3289: &reply('chatsend:'.$cdom.':'.$cnum.':'.
3290: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
3291: &escape($newentry)).':'.$group,$chome);
3292: }
3293:
3294: # ------------------------------------------ Find current version of a resource
3295:
3296: sub getversion {
3297: my $fname=&clutter(shift);
3298: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
3299: return ¤tversion(&filelocation('',$fname));
3300: }
3301:
3302: sub currentversion {
3303: my $fname=shift;
3304: my $author=$fname;
3305: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3306: my ($udom,$uname)=split(/\//,$author);
3307: my $home=&homeserver($uname,$udom);
3308: if ($home eq 'no_host') {
3309: return -1;
3310: }
3311: my $answer=&reply("currentversion:$fname",$home);
3312: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3313: return -1;
3314: }
3315: return $answer;
3316: }
3317:
3318: #
3319: # Return special version number of resource if set by override, empty otherwise
3320: #
3321: sub usedversion {
3322: my $fname=shift;
3323: unless ($fname) { $fname=$env{'request.uri'}; }
3324: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
3325: if ($urlversion) { return $urlversion; }
3326: return '';
3327: }
3328:
3329: # ----------------------------- Subscribe to a resource, return URL if possible
3330:
3331: sub subscribe {
3332: my $fname=shift;
3333: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
3334: $fname=~s/[\n\r]//g;
3335: my $author=$fname;
3336: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3337: my ($udom,$uname)=split(/\//,$author);
3338: my $home=homeserver($uname,$udom);
3339: if ($home eq 'no_host') {
3340: return 'not_found';
3341: }
3342: my $answer=reply("sub:$fname",$home);
3343: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3344: $answer.=' by '.$home;
3345: }
3346: return $answer;
3347: }
3348:
3349: # -------------------------------------------------------------- Replicate file
3350:
3351: sub repcopy {
3352: my $filename=shift;
3353: $filename=~s/\/+/\//g;
3354: my $londocroot = $perlvar{'lonDocRoot'};
3355: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
3356: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
3357: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3358: $filename=~m{^/*(uploaded|editupload)/}) {
3359: return &repcopy_userfile($filename);
3360: }
3361: $filename=~s/[\n\r]//g;
3362: my $transname="$filename.in.transfer";
3363: # FIXME: this should flock
3364: if ((-e $filename) || (-e $transname)) { return 'ok'; }
3365: my $remoteurl=subscribe($filename);
3366: if ($remoteurl =~ /^con_lost by/) {
3367: &logthis("Subscribe returned $remoteurl: $filename");
3368: return 'unavailable';
3369: } elsif ($remoteurl eq 'not_found') {
3370: #&logthis("Subscribe returned not_found: $filename");
3371: return 'not_found';
3372: } elsif ($remoteurl =~ /^rejected by/) {
3373: &logthis("Subscribe returned $remoteurl: $filename");
3374: return 'forbidden';
3375: } elsif ($remoteurl eq 'directory') {
3376: return 'ok';
3377: } else {
3378: my $author=$filename;
3379: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3380: my ($udom,$uname)=split(/\//,$author);
3381: my $home=homeserver($uname,$udom);
3382: unless ($home eq $perlvar{'lonHostID'}) {
3383: my @parts=split(/\//,$filename);
3384: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
3385: if ($path ne "$londocroot/res") {
3386: &logthis("Malconfiguration for replication: $filename");
3387: return 'bad_request';
3388: }
3389: my $count;
3390: for ($count=5;$count<$#parts;$count++) {
3391: $path.="/$parts[$count]";
3392: if ((-e $path)!=1) {
3393: mkdir($path,0777);
3394: }
3395: }
3396: my $request=new HTTP::Request('GET',"$remoteurl");
3397: my $response;
3398: if ($remoteurl =~ m{/raw/}) {
3399: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
3400: } else {
3401: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
3402: }
3403: if ($response->is_error()) {
3404: unlink($transname);
3405: my $message=$response->status_line;
3406: &logthis("<font color=\"blue\">WARNING:"
3407: ." LWP get: $message: $filename</font>");
3408: return 'unavailable';
3409: } else {
3410: if ($remoteurl!~/\.meta$/) {
3411: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
3412: my $mresponse;
3413: if ($remoteurl =~ m{/raw/}) {
3414: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
3415: } else {
3416: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
3417: }
3418: if ($mresponse->is_error()) {
3419: unlink($filename.'.meta');
3420: &logthis(
3421: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
3422: }
3423: }
3424: rename($transname,$filename);
3425: return 'ok';
3426: }
3427: }
3428: }
3429: }
3430:
3431: # ------------------------------------------------- Unsubscribe from a resource
3432:
3433: sub unsubscribe {
3434: my ($fname) = @_;
3435: my $answer;
3436: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
3437: $fname=~s/[\n\r]//g;
3438: my $author=$fname;
3439: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3440: my ($udom,$uname)=split(/\//,$author);
3441: my $home=homeserver($uname,$udom);
3442: if ($home eq 'no_host') {
3443: $answer = 'no_host';
3444: } elsif (grep { $_ eq $home } ¤t_machine_ids()) {
3445: $answer = 'home';
3446: } else {
3447: my $defdom = $perlvar{'lonDefDomain'};
3448: if (&will_trust('content',$defdom,$udom)) {
3449: $answer = reply("unsub:$fname",$home);
3450: } else {
3451: $answer = 'untrusted';
3452: }
3453: }
3454: return $answer;
3455: }
3456:
3457: # ------------------------------------------------ Get server side include body
3458: sub ssi_body {
3459: my ($filelink,%form)=@_;
3460: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3461: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3462: }
3463: my $output='';
3464: my $response;
3465: if ($filelink=~/^https?\:/) {
3466: ($output,$response)=&externalssi($filelink);
3467: } else {
3468: $filelink .= $filelink=~/\?/ ? '&' : '?';
3469: $filelink .= 'inhibitmenu=yes';
3470: ($output,$response)=&ssi($filelink,%form);
3471: }
3472: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
3473: $output=~s/^.*?\<body[^\>]*\>//si;
3474: $output=~s/\<\/body\s*\>.*?$//si;
3475: if (wantarray) {
3476: return ($output, $response);
3477: } else {
3478: return $output;
3479: }
3480: }
3481:
3482: # --------------------------------------------------------- Server Side Include
3483:
3484: sub absolute_url {
3485: my ($host_name) = @_;
3486: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3487: if ($host_name eq '') {
3488: $host_name = $ENV{'SERVER_NAME'};
3489: }
3490: return $protocol.$host_name;
3491: }
3492:
3493: #
3494: # Server side include.
3495: # Parameters:
3496: # fn Possibly encrypted resource name/id.
3497: # form Hash that describes how the rendering should be done
3498: # and other things.
3499: # Returns:
3500: # Scalar context: The content of the response.
3501: # Array context: 2 element list of the content and the full response object.
3502: #
3503: sub ssi {
3504:
3505: my ($fn,%form)=@_;
3506: my $request;
3507:
3508: $form{'no_update_last_known'}=1;
3509: &Apache::lonenc::check_encrypt(\$fn);
3510: if (%form) {
3511: $request=new HTTP::Request('POST',&absolute_url().$fn);
3512: $request->content(join('&',map {
3513: my $name = escape($_);
3514: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3515: ? join("&$name=", map {escape($_) } @{$form{$_}})
3516: : &escape($form{$_}) );
3517: } keys(%form)));
3518: } else {
3519: $request=new HTTP::Request('GET',&absolute_url().$fn);
3520: }
3521:
3522: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
3523: my $lonhost = $perlvar{'lonHostID'};
3524: my $islocal;
3525: if (($env{'request.course.id'}) &&
3526: ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
3527: ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
3528: ($form{'grade_symb'} ne '') &&
3529: (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
3530: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
3531: $islocal = 1;
3532: }
3533: my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
3534: '','','',$islocal);
3535:
3536: if (wantarray) {
3537: return ($response->content, $response);
3538: } else {
3539: return $response->content;
3540: }
3541: }
3542:
3543: sub externalssi {
3544: my ($url)=@_;
3545: my $request=new HTTP::Request('GET',$url);
3546: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
3547: if (wantarray) {
3548: return ($response->content, $response);
3549: } else {
3550: return $response->content;
3551: }
3552: }
3553:
3554:
3555: # If the local copy of a replicated resource is outdated, trigger a
3556: # connection from the homeserver to flush the delayed queue. If no update
3557: # happens, remove local copies of outdated resource (and corresponding
3558: # metadata file).
3559:
3560: sub remove_stale_resfile {
3561: my ($url) = @_;
3562: my $removed;
3563: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3564: my $audom = $1;
3565: my $auname = $2;
3566: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
3567: my $homeserver = &homeserver($auname,$audom);
3568: unless (($homeserver eq 'no_host') ||
3569: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3570: my $fname = &filelocation('',$url);
3571: if (-e $fname) {
3572: my $hostname = &hostname($homeserver);
3573: if ($hostname) {
3574: my $protocol = $protocol{$homeserver};
3575: $protocol = 'http' if ($protocol ne 'https');
3576: my $uri = &declutter($url);
3577: my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
3578: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
3579: if ($response->is_success()) {
3580: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3581: my $locmodtime = (stat($fname))[9];
3582: if ($locmodtime < $remmodtime) {
3583: my $stale;
3584: my $answer = &reply('pong',$homeserver);
3585: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3586: sleep(0.2);
3587: $locmodtime = (stat($fname))[9];
3588: if ($locmodtime < $remmodtime) {
3589: my $posstransfer = $fname.'.in.transfer';
3590: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3591: $removed = 1;
3592: } else {
3593: $stale = 1;
3594: }
3595: } else {
3596: $removed = 1;
3597: }
3598: } else {
3599: $stale = 1;
3600: }
3601: if ($stale) {
3602: if (unlink($fname)) {
3603: if ($uri!~/\.meta$/) {
3604: if (-e $fname.'.meta') {
3605: unlink($fname.'.meta');
3606: }
3607: }
3608: my $unsubresult = &unsubscribe($fname);
3609: unless ($unsubresult eq 'ok') {
3610: &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
3611: }
3612: $removed = 1;
3613: }
3614: }
3615: }
3616: }
3617: }
3618: }
3619: }
3620: }
3621: }
3622: return $removed;
3623: }
3624:
3625: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3626:
3627: sub allowuploaded {
3628: my ($srcurl,$url)=@_;
3629: $url=&clutter(&declutter($url));
3630: my $dir=$url;
3631: $dir=~s/\/[^\/]+$//;
3632: my %httpref=();
3633: my $httpurl=&hreflocation('',$url);
3634: $httpref{'httpref.'.$httpurl}=$srcurl;
3635: &Apache::lonnet::appenv(\%httpref);
3636: }
3637:
3638: #
3639: # Determine if the current user should be able to edit a particular resource,
3640: # when viewing in course context.
3641: # (a) When viewing resource used to determine if "Edit" item is included in
3642: # Functions.
3643: # (b) When displaying folder contents in course editor, used to determine if
3644: # "Edit" link will be displayed alongside resource.
3645: #
3646: # input: six args -- filename (decluttered), course number, course domain,
3647: # url, symb (if registered) and group (if this is a group
3648: # item -- e.g., bulletin board, group page etc.).
3649: # output: array of five scalars --
3650: # $cfile -- url for file editing if editable on current server
3651: # $home -- homeserver of resource (i.e., for author if published,
3652: # or course if uploaded.).
3653: # $switchserver -- 1 if server switch will be needed.
3654: # $forceedit -- 1 if icon/link should be to go to edit mode
3655: # $forceview -- 1 if icon/link should be to go to view mode
3656: #
3657:
3658: sub can_edit_resource {
3659: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3660: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3661: #
3662: # For aboutme pages user can only edit his/her own.
3663: #
3664: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
3665: my ($sdom,$sname) = ($1,$2);
3666: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3667: $home = $env{'user.home'};
3668: $cfile = $resurl;
3669: if ($env{'form.forceedit'}) {
3670: $forceview = 1;
3671: } else {
3672: $forceedit = 1;
3673: }
3674: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3675: } else {
3676: return;
3677: }
3678: }
3679:
3680: if ($env{'request.course.id'}) {
3681: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3682: if ($group ne '') {
3683: # if this is a group homepage or group bulletin board, check group privs
3684: my $allowed = 0;
3685: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3686: if ((&allowed('mdg',$env{'request.course.id'}.
3687: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3688: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3689: $allowed = 1;
3690: }
3691: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3692: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3693: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3694: $allowed = 1;
3695: }
3696: }
3697: if ($allowed) {
3698: $home=&homeserver($cnum,$cdom);
3699: if ($env{'form.forceedit'}) {
3700: $forceview = 1;
3701: } else {
3702: $forceedit = 1;
3703: }
3704: $cfile = $resurl;
3705: } else {
3706: return;
3707: }
3708: } else {
3709: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3710: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3711: return;
3712: }
3713: } elsif (!$crsedit) {
3714: #
3715: # No edit allowed where CC has switched to student role.
3716: #
3717: return;
3718: }
3719: }
3720: }
3721:
3722: if ($file ne '') {
3723: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
3724: if (&is_course_upload($file,$cnum,$cdom)) {
3725: $uploaded = 1;
3726: $incourse = 1;
3727: if ($file =~/\.(htm|html|css|js|txt)$/) {
3728: $cfile = &hreflocation('',$file);
3729: if ($env{'form.forceedit'}) {
3730: $forceview = 1;
3731: } else {
3732: $forceedit = 1;
3733: }
3734: }
3735: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3736: $incourse = 1;
3737: if ($env{'form.forceedit'}) {
3738: $forceview = 1;
3739: } else {
3740: $forceedit = 1;
3741: }
3742: $cfile = $resurl;
3743: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3744: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3745: $incourse = 1;
3746: if ($env{'form.forceedit'}) {
3747: $forceview = 1;
3748: } else {
3749: $forceedit = 1;
3750: }
3751: $cfile = $resurl;
3752: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
3753: $incourse = 1;
3754: $cfile = $resurl.'/smpedit';
3755: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
3756: $incourse = 1;
3757: if ($env{'form.forceedit'}) {
3758: $forceview = 1;
3759: } else {
3760: $forceedit = 1;
3761: }
3762: $cfile = $resurl;
3763: } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
3764: my ($map,$id,$res) = &decode_symb($symb);
3765: if ($map =~ /\.page$/) {
3766: $incourse = 1;
3767: if ($env{'form.forceedit'}) {
3768: $forceview = 1;
3769: $cfile = $map;
3770: } else {
3771: $forceedit = 1;
3772: $cfile = '/adm/wrapper'.$resurl;
3773: }
3774: }
3775: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
3776: $incourse = 1;
3777: if ($env{'form.forceedit'}) {
3778: $forceview = 1;
3779: } else {
3780: $forceedit = 1;
3781: }
3782: $cfile = $resurl;
3783: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3784: $incourse = 1;
3785: if ($env{'form.forceedit'}) {
3786: $forceview = 1;
3787: } else {
3788: $forceedit = 1;
3789: }
3790: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
3791: }
3792: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3793: my $template = '/res/lib/templates/simpleproblem.problem';
3794: if (&is_on_map($template)) {
3795: $incourse = 1;
3796: $forceview = 1;
3797: $cfile = $template;
3798: }
3799: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3800: $incourse = 1;
3801: if ($env{'form.forceedit'}) {
3802: $forceview = 1;
3803: } else {
3804: $forceedit = 1;
3805: }
3806: $cfile = $resurl;
3807: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3808: $incourse = 1;
3809: if ($env{'form.forceedit'}) {
3810: $forceview = 1;
3811: } else {
3812: $forceedit = 1;
3813: }
3814: $cfile = $resurl;
3815: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3816: $incourse = 1;
3817: $forceview = 1;
3818: if ($symb) {
3819: my ($map,$id,$res)=&decode_symb($symb);
3820: $env{'request.symb'} = $symb;
3821: $cfile = &clutter($res);
3822: } else {
3823: $cfile = $env{'form.suppurl'};
3824: my $escfile = &unescape($cfile);
3825: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
3826: $cfile = '/adm/wrapper'.$escfile;
3827: } else {
3828: $escfile =~ s{^http://}{};
3829: $cfile = &escape("/adm/wrapper/ext/$escfile");
3830: }
3831: }
3832: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3833: if ($env{'form.forceedit'}) {
3834: $forceview = 1;
3835: } else {
3836: $forceedit = 1;
3837: }
3838: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
3839: }
3840: }
3841: if ($uploaded || $incourse) {
3842: $home=&homeserver($cnum,$cdom);
3843: } elsif ($file !~ m{/$}) {
3844: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3845: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3846: # Check that the user has permission to edit this resource
3847: my $setpriv = 1;
3848: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3849: if (defined($cfudom)) {
3850: $home=&homeserver($cfuname,$cfudom);
3851: $cfile=$file;
3852: }
3853: }
3854: if (($cfile ne '') && (!$incourse || $uploaded) &&
3855: (($home ne '') && ($home ne 'no_host'))) {
3856: my @ids=¤t_machine_ids();
3857: unless (grep(/^\Q$home\E$/,@ids)) {
3858: $switchserver=1;
3859: }
3860: }
3861: }
3862: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3863: }
3864:
3865: sub is_course_upload {
3866: my ($file,$cnum,$cdom) = @_;
3867: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3868: $uploadpath =~ s{^\/}{};
3869: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3870: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3871: return 1;
3872: }
3873: return;
3874: }
3875:
3876: sub in_course {
3877: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3878: if ($hideprivileged) {
3879: my $skipuser;
3880: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3881: my @possdoms = ($cdom);
3882: if ($coursehash{'checkforpriv'}) {
3883: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3884: }
3885: if (&privileged($uname,$udom,\@possdoms)) {
3886: $skipuser = 1;
3887: if ($coursehash{'nothideprivileged'}) {
3888: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3889: my $user;
3890: if ($item =~ /:/) {
3891: $user = $item;
3892: } else {
3893: $user = join(':',split(/[\@]/,$item));
3894: }
3895: if ($user eq $uname.':'.$udom) {
3896: undef($skipuser);
3897: last;
3898: }
3899: }
3900: }
3901: if ($skipuser) {
3902: return 0;
3903: }
3904: }
3905: }
3906: $type ||= 'any';
3907: if (!defined($cdom) || !defined($cnum)) {
3908: my $cid = $env{'request.course.id'};
3909: $cdom = $env{'course.'.$cid.'.domain'};
3910: $cnum = $env{'course.'.$cid.'.num'};
3911: }
3912: my $typesref;
3913: if (($type eq 'any') || ($type eq 'all')) {
3914: $typesref = ['active','previous','future'];
3915: } elsif ($type eq 'previous' || $type eq 'future') {
3916: $typesref = [$type];
3917: }
3918: my %roles = &get_my_roles($uname,$udom,'userroles',
3919: $typesref,undef,[$cdom]);
3920: my ($tmp) = keys(%roles);
3921: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3922: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3923: if (@course_roles > 0) {
3924: return 1;
3925: }
3926: return 0;
3927: }
3928:
3929: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
3930: # input: action, courseID, current domain, intended
3931: # path to file, source of file, instruction to parse file for objects,
3932: # ref to hash for embedded objects,
3933: # ref to hash for codebase of java objects.
3934: # reference to scalar to accommodate mime type determined
3935: # from File::MMagic if $parser = parse.
3936: #
3937: # output: url to file (if action was uploaddoc),
3938: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
3939: #
3940: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3941: # course.
3942: #
3943: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3944: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3945: # course's home server.
3946: #
3947: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3948: # be copied from $source (current location) to
3949: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3950: # and will then be copied to
3951: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3952: # course's home server.
3953: #
3954: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3955: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
3956: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3957: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3958: # in course's home server.
3959: #
3960:
3961: sub process_coursefile {
3962: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3963: $mimetype)=@_;
3964: my $fetchresult;
3965: my $home=&homeserver($docuname,$docudom);
3966: if ($action eq 'propagate') {
3967: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3968: $home);
3969: } else {
3970: my $fpath = '';
3971: my $fname = $file;
3972: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3973: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3974: my $filepath = &build_filepath($fpath);
3975: if ($action eq 'copy') {
3976: if ($source eq '') {
3977: $fetchresult = 'no source file';
3978: return $fetchresult;
3979: } else {
3980: my $destination = $filepath.'/'.$fname;
3981: rename($source,$destination);
3982: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3983: $home);
3984: }
3985: } elsif ($action eq 'uploaddoc') {
3986: open(my $fh,'>',$filepath.'/'.$fname);
3987: print $fh $env{'form.'.$source};
3988: close($fh);
3989: if ($parser eq 'parse') {
3990: my $mm = new File::MMagic;
3991: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3992: if ($type eq 'text/html') {
3993: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3994: unless ($parse_result eq 'ok') {
3995: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3996: }
3997: }
3998: if (ref($mimetype)) {
3999: $$mimetype = $type;
4000: }
4001: }
4002: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
4003: $home);
4004: if ($fetchresult eq 'ok') {
4005: return '/uploaded/'.$fpath.'/'.$fname;
4006: } else {
4007: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
4008: ' to host '.$home.': '.$fetchresult);
4009: return '/adm/notfound.html';
4010: }
4011: }
4012: }
4013: unless ( $fetchresult eq 'ok') {
4014: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
4015: ' to host '.$home.': '.$fetchresult);
4016: }
4017: return $fetchresult;
4018: }
4019:
4020: sub build_filepath {
4021: my ($fpath) = @_;
4022: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
4023: unless ($fpath eq '') {
4024: my @parts=split('/',$fpath);
4025: foreach my $part (@parts) {
4026: $filepath.= '/'.$part;
4027: if ((-e $filepath)!=1) {
4028: mkdir($filepath,0777);
4029: }
4030: }
4031: }
4032: return $filepath;
4033: }
4034:
4035: sub store_edited_file {
4036: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
4037: my $file = $primary_url;
4038: $file =~ s#^/uploaded/$docudom/$docuname/##;
4039: my $fpath = '';
4040: my $fname = $file;
4041: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
4042: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
4043: my $filepath = &build_filepath($fpath);
4044: open(my $fh,'>',$filepath.'/'.$fname);
4045: print $fh $content;
4046: close($fh);
4047: my $home=&homeserver($docuname,$docudom);
4048: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
4049: $home);
4050: if ($$fetchresult eq 'ok') {
4051: return '/uploaded/'.$fpath.'/'.$fname;
4052: } else {
4053: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
4054: ' to host '.$home.': '.$$fetchresult);
4055: return '/adm/notfound.html';
4056: }
4057: }
4058:
4059: sub clean_filename {
4060: my ($fname,$args)=@_;
4061: # Replace Windows backslashes by forward slashes
4062: $fname=~s/\\/\//g;
4063: if (!$args->{'keep_path'}) {
4064: # Get rid of everything but the actual filename
4065: $fname=~s/^.*\/([^\/]+)$/$1/;
4066: }
4067: # Replace spaces by underscores
4068: $fname=~s/\s+/\_/g;
4069: # Transliterate non-ascii text to ascii
4070: my $lang = &Apache::lonlocal::current_language();
4071: $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
4072: # Replace all other weird characters by nothing
4073: $fname=~s{[^/\w\.\-]}{}g;
4074: # Replace all .\d. sequences with _\d. so they no longer look like version
4075: # numbers
4076: $fname=~s/\.(\d+)(?=\.)/_$1/g;
4077: return $fname;
4078: }
4079:
4080: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
4081: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
4082: # image with the same aspect ratio as the original, but with dimensions which do
4083: # not exceed $resizewidth and $resizeheight.
4084:
4085: sub resizeImage {
4086: my ($img_path,$resizewidth,$resizeheight) = @_;
4087: my $ima = Image::Magick->new;
4088: my $resized;
4089: if (-e $img_path) {
4090: $ima->Read($img_path);
4091: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
4092: my $width = $ima->Get('width');
4093: my $height = $ima->Get('height');
4094: if ($width > $resizewidth) {
4095: my $factor = $width/$resizewidth;
4096: my $newheight = $height/$factor;
4097: $ima->Scale(width=>$resizewidth,height=>$newheight);
4098: $resized = 1;
4099: }
4100: }
4101: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
4102: my $width = $ima->Get('width');
4103: my $height = $ima->Get('height');
4104: if ($height > $resizeheight) {
4105: my $factor = $height/$resizeheight;
4106: my $newwidth = $width/$factor;
4107: $ima->Scale(width=>$newwidth,height=>$resizeheight);
4108: $resized = 1;
4109: }
4110: }
4111: if ($resized) {
4112: $ima->Write($img_path);
4113: }
4114: }
4115: return;
4116: }
4117:
4118: # --------------- Take an uploaded file and put it into the userfiles directory
4119: # input: $formname - the contents of the file are in $env{"form.$formname"}
4120: # the desired filename is in $env{"form.$formname.filename"}
4121: # $context - possible values: coursedoc, existingfile, overwrite,
4122: # canceloverwrite, scantron or ''.
4123: # if 'coursedoc': upload to the current course
4124: # if 'existingfile': write file to tmp/overwrites directory
4125: # if 'canceloverwrite': delete file written to tmp/overwrites directory
4126: # $context is passed as argument to &finishuserfileupload
4127: # $subdir - directory in userfile to store the file into
4128: # $parser - instruction to parse file for objects ($parser = parse) or
4129: # if context is 'scantron', $parser is hashref of csv column mapping
4130: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
4131: # Section => 4, CODE => 5, FirstQuestion => 9 }).
4132: # $allfiles - reference to hash for embedded objects
4133: # $codebase - reference to hash for codebase of java objects
4134: # $desuname - username for permanent storage of uploaded file
4135: # $dsetudom - domain for permanaent storage of uploaded file
4136: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
4137: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
4138: # $resizewidth - width (pixels) to which to resize uploaded image
4139: # $resizeheight - height (pixels) to which to resize uploaded image
4140: # $mimetype - reference to scalar to accommodate mime type determined
4141: # from File::MMagic.
4142: #
4143: # output: url of file in userspace, or error: <message>
4144: # or /adm/notfound.html if failure to upload occurse
4145:
4146: sub userfileupload {
4147: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
4148: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
4149: if (!defined($subdir)) { $subdir='unknown'; }
4150: my $fname=$env{'form.'.$formname.'.filename'};
4151: $fname=&clean_filename($fname);
4152: # See if there is anything left
4153: unless ($fname) { return 'error: no uploaded file'; }
4154: # If filename now begins with a . prepend unix timestamp _ milliseconds
4155: if ($fname =~ /^\./) {
4156: my ($s,$usec) = &gettimeofday();
4157: while (length($usec) < 6) {
4158: $usec = '0'.$usec;
4159: }
4160: $fname = $s.'_'.substr($usec,0,3).$fname;
4161: }
4162: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
4163: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
4164: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
4165: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
4166: my $now = time;
4167: my $filepath;
4168: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
4169: $filepath = 'tmp/helprequests/'.$now;
4170: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
4171: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
4172: '_'.$env{'user.domain'}.'/pending';
4173: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
4174: my ($docuname,$docudom);
4175: if ($destudom =~ /^$match_domain$/) {
4176: $docudom = $destudom;
4177: } else {
4178: $docudom = $env{'user.domain'};
4179: }
4180: if ($destuname =~ /^$match_username$/) {
4181: $docuname = $destuname;
4182: } else {
4183: $docuname = $env{'user.name'};
4184: }
4185: if (exists($env{'form.group'})) {
4186: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4187: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4188: }
4189: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
4190: if ($context eq 'canceloverwrite') {
4191: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
4192: if (-e $tempfile) {
4193: my @info = stat($tempfile);
4194: if ($info[9] eq $env{'form.timestamp'}) {
4195: unlink($tempfile);
4196: }
4197: }
4198: return;
4199: }
4200: }
4201: # Create the directory if not present
4202: my @parts=split(/\//,$filepath);
4203: my $fullpath = $perlvar{'lonDaemons'};
4204: for (my $i=0;$i<@parts;$i++) {
4205: $fullpath .= '/'.$parts[$i];
4206: if ((-e $fullpath)!=1) {
4207: mkdir($fullpath,0777);
4208: }
4209: }
4210: open(my $fh,'>',$fullpath.'/'.$fname);
4211: print $fh $env{'form.'.$formname};
4212: close($fh);
4213: if ($context eq 'existingfile') {
4214: my @info = stat($fullpath.'/'.$fname);
4215: return ($fullpath.'/'.$fname,$info[9]);
4216: } else {
4217: return $fullpath.'/'.$fname;
4218: }
4219: }
4220: if ($subdir eq 'scantron') {
4221: $fname = 'scantron_orig_'.$fname;
4222: } else {
4223: $fname="$subdir/$fname";
4224: }
4225: if ($context eq 'coursedoc') {
4226: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4227: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4228: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
4229: return &finishuserfileupload($docuname,$docudom,
4230: $formname,$fname,$parser,$allfiles,
4231: $codebase,$thumbwidth,$thumbheight,
4232: $resizewidth,$resizeheight,$context,$mimetype);
4233: } else {
4234: if ($env{'form.folder'}) {
4235: $fname=$env{'form.folder'}.'/'.$fname;
4236: }
4237: return &process_coursefile('uploaddoc',$docuname,$docudom,
4238: $fname,$formname,$parser,
4239: $allfiles,$codebase,$mimetype);
4240: }
4241: } elsif (defined($destuname)) {
4242: my $docuname=$destuname;
4243: my $docudom=$destudom;
4244: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4245: $parser,$allfiles,$codebase,
4246: $thumbwidth,$thumbheight,
4247: $resizewidth,$resizeheight,$context,$mimetype);
4248: } else {
4249: my $docuname=$env{'user.name'};
4250: my $docudom=$env{'user.domain'};
4251: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
4252: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4253: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4254: }
4255: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4256: $parser,$allfiles,$codebase,
4257: $thumbwidth,$thumbheight,
4258: $resizewidth,$resizeheight,$context,$mimetype);
4259: }
4260: }
4261:
4262: sub finishuserfileupload {
4263: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
4264: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
4265: my $path=$docudom.'/'.$docuname.'/';
4266: my $filepath=$perlvar{'lonDocRoot'};
4267:
4268: my ($fnamepath,$file,$fetchthumb);
4269: $file=$fname;
4270: if ($fname=~m|/|) {
4271: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
4272: $path.=$fnamepath.'/';
4273: }
4274: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
4275: my $count;
4276: for ($count=4;$count<=$#parts;$count++) {
4277: $filepath.="/$parts[$count]";
4278: if ((-e $filepath)!=1) {
4279: mkdir($filepath,0777);
4280: }
4281: }
4282:
4283: # Save the file
4284: {
4285: if (!open(FH,'>',$filepath.'/'.$file)) {
4286: &logthis('Failed to create '.$filepath.'/'.$file);
4287: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
4288: return '/adm/notfound.html';
4289: }
4290: if ($context eq 'overwrite') {
4291: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
4292: my $target = $filepath.'/'.$file;
4293: if (-e $source) {
4294: my @info = stat($source);
4295: if ($info[9] eq $env{'form.timestamp'}) {
4296: unless (&File::Copy::move($source,$target)) {
4297: &logthis('Failed to overwrite '.$filepath.'/'.$file);
4298: return "Moving from $source failed";
4299: }
4300: } else {
4301: return "Temporary file: $source had unexpected date/time for last modification";
4302: }
4303: } else {
4304: return "Temporary file: $source missing";
4305: }
4306: } elsif (!print FH ($env{'form.'.$formname})) {
4307: &logthis('Failed to write to '.$filepath.'/'.$file);
4308: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
4309: return '/adm/notfound.html';
4310: }
4311: close(FH);
4312: if ($resizewidth && $resizeheight) {
4313: my $mm = new File::MMagic;
4314: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
4315: if ($mime_type =~ m{^image/}) {
4316: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
4317: }
4318: }
4319: }
4320: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
4321: if (ref($mimetype)) {
4322: if ($$mimetype eq '') {
4323: my $mm = new File::MMagic;
4324: my $type = $mm->checktype_filename($filepath.'/'.$file);
4325: $$mimetype = $type;
4326: }
4327: }
4328: }
4329: if (($context ne 'scantron') && ($parser eq 'parse')) {
4330: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
4331: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
4332: $allfiles,$codebase);
4333: unless ($parse_result eq 'ok') {
4334: &logthis('Failed to parse '.$filepath.$file.
4335: ' for embedded media: '.$parse_result);
4336: }
4337: }
4338: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
4339: my $format = $env{'form.scantron_format'};
4340: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
4341: }
4342: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
4343: my $input = $filepath.'/'.$file;
4344: my $output = $filepath.'/'.'tn-'.$file;
4345: my $thumbsize = $thumbwidth.'x'.$thumbheight;
4346: my @args = ('convert','-sample',$thumbsize,$input,$output);
4347: system({$args[0]} @args);
4348: if (-e $filepath.'/'.'tn-'.$file) {
4349: $fetchthumb = 1;
4350: }
4351: }
4352:
4353: # Notify homeserver to grep it
4354: #
4355: my $docuhome=&homeserver($docuname,$docudom);
4356: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
4357: if ($fetchresult eq 'ok') {
4358: if ($fetchthumb) {
4359: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
4360: if ($thumbresult ne 'ok') {
4361: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
4362: $docuhome.': '.$thumbresult);
4363: }
4364: }
4365: #
4366: # Return the URL to it
4367: return '/uploaded/'.$path.$file;
4368: } else {
4369: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
4370: ': '.$fetchresult);
4371: return '/adm/notfound.html';
4372: }
4373: }
4374:
4375: sub extract_embedded_items {
4376: my ($fullpath,$allfiles,$codebase,$content) = @_;
4377: my @state = ();
4378: my (%lastids,%related,%shockwave,%flashvars);
4379: my %javafiles = (
4380: codebase => '',
4381: code => '',
4382: archive => ''
4383: );
4384: my %mediafiles = (
4385: src => '',
4386: movie => '',
4387: );
4388: my $p;
4389: if ($content) {
4390: $p = HTML::LCParser->new($content);
4391: } else {
4392: $p = HTML::LCParser->new($fullpath);
4393: }
4394: while (my $t=$p->get_token()) {
4395: if ($t->[0] eq 'S') {
4396: my ($tagname, $attr) = ($t->[1],$t->[2]);
4397: push(@state, $tagname);
4398: if (lc($tagname) eq 'allow') {
4399: &add_filetype($allfiles,$attr->{'src'},'src');
4400: }
4401: if (lc($tagname) eq 'img') {
4402: &add_filetype($allfiles,$attr->{'src'},'src');
4403: }
4404: if (lc($tagname) eq 'a') {
4405: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
4406: &add_filetype($allfiles,$attr->{'href'},'href');
4407: }
4408: }
4409: if (lc($tagname) eq 'script') {
4410: my $src;
4411: if ($attr->{'archive'} =~ /\.jar$/i) {
4412: &add_filetype($allfiles,$attr->{'archive'},'archive');
4413: } else {
4414: if ($attr->{'src'} ne '') {
4415: $src = $attr->{'src'};
4416: &add_filetype($allfiles,$src,'src');
4417: }
4418: }
4419: my $text = $p->get_trimmed_text();
4420: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4421: my @swfargs = split(/,/,$1);
4422: foreach my $item (@swfargs) {
4423: $item =~ s/["']//g;
4424: $item =~ s/^\s+//;
4425: $item =~ s/\s+$//;
4426: }
4427: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4428: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4429: push(@{$related{$swfargs[0]}},$swfargs[2]);
4430: } else {
4431: $related{$swfargs[0]} = [$swfargs[2]];
4432: }
4433: }
4434: }
4435: }
4436: if (lc($tagname) eq 'link') {
4437: if (lc($attr->{'rel'}) eq 'stylesheet') {
4438: &add_filetype($allfiles,$attr->{'href'},'href');
4439: }
4440: }
4441: if (lc($tagname) eq 'object' ||
4442: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4443: foreach my $item (keys(%javafiles)) {
4444: $javafiles{$item} = '';
4445: }
4446: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4447: $lastids{lc($tagname)} = $attr->{'id'};
4448: }
4449: }
4450: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4451: my $name = lc($attr->{'name'});
4452: foreach my $item (keys(%javafiles)) {
4453: if ($name eq $item) {
4454: $javafiles{$item} = $attr->{'value'};
4455: last;
4456: }
4457: }
4458: my $pathfrom;
4459: foreach my $item (keys(%mediafiles)) {
4460: if ($name eq $item) {
4461: $pathfrom = $attr->{'value'};
4462: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4463: &add_filetype($allfiles,$pathfrom,$name);
4464: last;
4465: }
4466: }
4467: if ($name eq 'flashvars') {
4468: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4469: }
4470: if ($pathfrom ne '') {
4471: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4472: $pathfrom);
4473: }
4474: }
4475: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4476: foreach my $item (keys(%javafiles)) {
4477: if ($attr->{$item}) {
4478: $javafiles{$item} = $attr->{$item};
4479: last;
4480: }
4481: }
4482: foreach my $item (keys(%mediafiles)) {
4483: if ($attr->{$item}) {
4484: &add_filetype($allfiles,$attr->{$item},$item);
4485: last;
4486: }
4487: }
4488: if (lc($tagname) eq 'embed') {
4489: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4490: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4491: $attr->{'src'});
4492: }
4493: }
4494: }
4495: if (lc($tagname) eq 'iframe') {
4496: my $src = $attr->{'src'} ;
4497: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4498: &add_filetype($allfiles,$src,'src');
4499: } elsif ($src =~ m{^/}) {
4500: if ($env{'request.course.id'}) {
4501: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4502: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4503: my $url = &hreflocation('',$fullpath);
4504: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4505: my $relpath = $1;
4506: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4507: &add_filetype($allfiles,$1,'src');
4508: }
4509: }
4510: }
4511: }
4512: }
4513: if ($t->[4] =~ m{/>$}) {
4514: pop(@state);
4515: }
4516: } elsif ($t->[0] eq 'E') {
4517: my ($tagname) = ($t->[1]);
4518: if ($javafiles{'codebase'} ne '') {
4519: $javafiles{'codebase'} .= '/';
4520: }
4521: if (lc($tagname) eq 'applet' ||
4522: lc($tagname) eq 'object' ||
4523: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4524: ) {
4525: foreach my $item (keys(%javafiles)) {
4526: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4527: my $file=$javafiles{'codebase'}.$javafiles{$item};
4528: &add_filetype($allfiles,$file,$item);
4529: }
4530: }
4531: }
4532: pop @state;
4533: }
4534: }
4535: foreach my $id (sort(keys(%flashvars))) {
4536: if ($shockwave{$id} ne '') {
4537: my @pairs = split(/\&/,$flashvars{$id});
4538: foreach my $pair (@pairs) {
4539: my ($key,$value) = split(/\=/,$pair);
4540: if ($key eq 'thumb') {
4541: &add_filetype($allfiles,$value,$key);
4542: } elsif ($key eq 'content') {
4543: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4544: my ($ext) = ($value =~ /\.([^.]+)$/);
4545: if ($ext ne '') {
4546: &add_filetype($allfiles,$path.$value,$ext);
4547: }
4548: }
4549: }
4550: }
4551: }
4552: return 'ok';
4553: }
4554:
4555: sub add_filetype {
4556: my ($allfiles,$file,$type)=@_;
4557: if (exists($allfiles->{$file})) {
4558: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4559: push(@{$allfiles->{$file}}, &escape($type));
4560: }
4561: } else {
4562: @{$allfiles->{$file}} = (&escape($type));
4563: }
4564: }
4565:
4566: sub embedded_dependency {
4567: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4568: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4569: if (($identifier ne '') &&
4570: (ref($related->{$identifier}) eq 'ARRAY') &&
4571: ($pathfrom ne '')) {
4572: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4573: foreach my $dep (@{$related->{$identifier}}) {
4574: &add_filetype($allfiles,$path.$dep,'object');
4575: }
4576: }
4577: }
4578: return;
4579: }
4580:
4581: sub bubblesheet_converter {
4582: my ($cdom,$fullpath,$config,$format) = @_;
4583: if ((&domain($cdom) ne '') &&
4584: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
4585: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
4586: my (%csvcols,%csvoptions);
4587: if (ref($config->{'fields'}) eq 'HASH') {
4588: %csvcols = %{$config->{'fields'}};
4589: }
4590: if (ref($config->{'options'}) eq 'HASH') {
4591: %csvoptions = %{$config->{'options'}};
4592: }
4593: my %csvbynum = reverse(%csvcols);
4594: my %scantronconf = &get_scantron_config($format,$cdom);
4595: if (keys(%scantronconf)) {
4596: my %bynum = (
4597: $scantronconf{CODEstart} => 'CODEstart',
4598: $scantronconf{IDstart} => 'IDstart',
4599: $scantronconf{PaperID} => 'PaperID',
4600: $scantronconf{FirstName} => 'FirstName',
4601: $scantronconf{LastName} => 'LastName',
4602: $scantronconf{Qstart} => 'Qstart',
4603: );
4604: my @ordered;
4605: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
4606: push(@ordered,$bynum{$item});
4607: }
4608: my %mapstart = (
4609: CODEstart => 'CODE',
4610: IDstart => 'ID',
4611: PaperID => 'PaperID',
4612: FirstName => 'FirstName',
4613: LastName => 'LastName',
4614: Qstart => 'FirstQuestion',
4615: );
4616: my %maplength = (
4617: CODEstart => 'CODElength',
4618: IDstart => 'IDlength',
4619: PaperID => 'PaperIDlength',
4620: FirstName => 'FirstNamelength',
4621: LastName => 'LastNamelength',
4622: );
4623: if (open(my $fh,'<',$fullpath)) {
4624: my $output;
4625: my %lettdig = &letter_to_digits();
4626: my %diglett = reverse(%lettdig);
4627: my $numletts = scalar(keys(%lettdig));
4628: my $num = 0;
4629: while (my $line=<$fh>) {
4630: $num ++;
4631: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
4632: $line =~ s{[\r\n]+$}{};
4633: my %found;
4634: my @values = split(/,/,$line);
4635: my ($qstart,$record);
4636: for (my $i=0; $i<@values; $i++) {
4637: if ((($qstart ne '') && ($i > $qstart)) ||
4638: ($csvbynum{$i} eq 'FirstQuestion')) {
4639: if ($values[$i] eq '') {
4640: $values[$i] = $scantronconf{'Qoff'};
4641: } elsif ($scantronconf{'Qon'} eq 'number') {
4642: if ($values[$i] =~ /^[A-Ja-j]$/) {
4643: $values[$i] = $lettdig{uc($values[$i])};
4644: }
4645: } elsif ($scantronconf{'Qon'} eq 'letter') {
4646: if ($values[$i] =~ /^[0-9]$/) {
4647: $values[$i] = $diglett{$values[$i]};
4648: }
4649: } else {
4650: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4651: my $digit;
4652: if ($values[$i] =~ /^[A-Ja-j]$/) {
4653: $digit = $lettdig{uc($values[$i])}-1;
4654: if ($values[$i] eq 'J') {
4655: $digit += $numletts;
4656: }
4657: } elsif ($values[$i] =~ /^[0-9]$/) {
4658: $digit = $values[$i]-1;
4659: if ($values[$i] eq '0') {
4660: $digit += $numletts;
4661: }
4662: }
4663: my $qval='';
4664: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
4665: if ($j == $digit) {
4666: $qval .= $scantronconf{'Qon'};
4667: } else {
4668: $qval .= $scantronconf{'Qoff'};
4669: }
4670: }
4671: $values[$i] = $qval;
4672: }
4673: }
4674: if (length($values[$i]) > $scantronconf{'Qlength'}) {
4675: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
4676: }
4677: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
4678: if ($numblank > 0) {
4679: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
4680: }
4681: if ($csvbynum{$i} eq 'FirstQuestion') {
4682: $qstart = $i;
4683: $found{$csvbynum{$i}} = $values[$i];
4684: } else {
4685: $found{'FirstQuestion'} .= $values[$i];
4686: }
4687: } elsif (exists($csvbynum{$i})) {
4688: if ($csvoptions{'rem'}) {
4689: $values[$i] =~ s/^\s+//;
4690: }
4691: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
4692: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
4693: $values[$i] = '0'.$values[$i];
4694: }
4695: }
4696: $found{$csvbynum{$i}} = $values[$i];
4697: }
4698: }
4699: foreach my $item (@ordered) {
4700: my $currlength = 1+length($record);
4701: my $numspaces = $scantronconf{$item} - $currlength;
4702: if ($numspaces > 0) {
4703: $record .= (' ' x $numspaces);
4704: }
4705: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
4706: unless ($item eq 'Qstart') {
4707: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
4708: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
4709: }
4710: }
4711: $record .= $found{$mapstart{$item}};
4712: }
4713: }
4714: $output .= "$record\n";
4715: }
4716: close($fh);
4717: if ($output) {
4718: if (open(my $fh,'>',$fullpath)) {
4719: print $fh $output;
4720: close($fh);
4721: }
4722: }
4723: }
4724: }
4725: return;
4726: }
4727: }
4728:
4729: sub letter_to_digits {
4730: my %lettdig = (
4731: A => 1,
4732: B => 2,
4733: C => 3,
4734: D => 4,
4735: E => 5,
4736: F => 6,
4737: G => 7,
4738: H => 8,
4739: I => 9,
4740: J => 0,
4741: );
4742: return %lettdig;
4743: }
4744:
4745: sub get_scantron_config {
4746: my ($which,$cdom) = @_;
4747: my @lines = &get_scantronformat_file($cdom);
4748: my %config;
4749: #FIXME probably should move to XML it has already gotten a bit much now
4750: foreach my $line (@lines) {
4751: my ($name,$descrip)=split(/:/,$line);
4752: if ($name ne $which ) { next; }
4753: chomp($line);
4754: my @config=split(/:/,$line);
4755: $config{'name'}=$config[0];
4756: $config{'description'}=$config[1];
4757: $config{'CODElocation'}=$config[2];
4758: $config{'CODEstart'}=$config[3];
4759: $config{'CODElength'}=$config[4];
4760: $config{'IDstart'}=$config[5];
4761: $config{'IDlength'}=$config[6];
4762: $config{'Qstart'}=$config[7];
4763: $config{'Qlength'}=$config[8];
4764: $config{'Qoff'}=$config[9];
4765: $config{'Qon'}=$config[10];
4766: $config{'PaperID'}=$config[11];
4767: $config{'PaperIDlength'}=$config[12];
4768: $config{'FirstName'}=$config[13];
4769: $config{'FirstNamelength'}=$config[14];
4770: $config{'LastName'}=$config[15];
4771: $config{'LastNamelength'}=$config[16];
4772: $config{'BubblesPerRow'}=$config[17];
4773: last;
4774: }
4775: return %config;
4776: }
4777:
4778: sub get_scantronformat_file {
4779: my ($cdom) = @_;
4780: if ($cdom eq '') {
4781: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4782: }
4783: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4784: my $gottab = 0;
4785: my @lines;
4786: if (ref($domconfig{'scantron'}) eq 'HASH') {
4787: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4788: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4789: if ($formatfile ne '-1') {
4790: @lines = split("\n",$formatfile,-1);
4791: $gottab = 1;
4792: }
4793: }
4794: }
4795: if (!$gottab) {
4796: my $confname = $cdom.'-domainconfig';
4797: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4798: my $formatfile = &getfile($default);
4799: if ($formatfile ne '-1') {
4800: @lines = split("\n",$formatfile,-1);
4801: $gottab = 1;
4802: }
4803: }
4804: if (!$gottab) {
4805: my @domains = ¤t_machine_domains();
4806: if (grep(/^\Q$cdom\E$/,@domains)) {
4807: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
4808: @lines = <$fh>;
4809: close($fh);
4810: }
4811: } else {
4812: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
4813: @lines = <$fh>;
4814: close($fh);
4815: }
4816: }
4817: }
4818: return @lines;
4819: }
4820:
4821: sub removeuploadedurl {
4822: my ($url)=@_;
4823: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
4824: return &removeuserfile($uname,$udom,$fname);
4825: }
4826:
4827: sub removeuserfile {
4828: my ($docuname,$docudom,$fname)=@_;
4829: my $home=&homeserver($docuname,$docudom);
4830: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
4831: if ($result eq 'ok') {
4832: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4833: my $metafile = $fname.'.meta';
4834: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
4835: my $url = "/uploaded/$docudom/$docuname/$fname";
4836: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
4837: my $sqlresult =
4838: &update_portfolio_table($docuname,$docudom,$file,
4839: 'portfolio_metadata',$group,
4840: 'delete');
4841: }
4842: }
4843: return $result;
4844: }
4845:
4846: sub mkdiruserfile {
4847: my ($docuname,$docudom,$dir)=@_;
4848: my $home=&homeserver($docuname,$docudom);
4849: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4850: }
4851:
4852: sub renameuserfile {
4853: my ($docuname,$docudom,$old,$new)=@_;
4854: my $home=&homeserver($docuname,$docudom);
4855: my $result = &reply("renameuserfile:$docudom:$docuname:".
4856: &escape("$old").':'.&escape("$new"),$home);
4857: if ($result eq 'ok') {
4858: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4859: my $oldmeta = $old.'.meta';
4860: my $newmeta = $new.'.meta';
4861: my $metaresult =
4862: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
4863: my $url = "/uploaded/$docudom/$docuname/$old";
4864: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
4865: my $sqlresult =
4866: &update_portfolio_table($docuname,$docudom,$file,
4867: 'portfolio_metadata',$group,
4868: 'delete');
4869: }
4870: }
4871: return $result;
4872: }
4873:
4874: # ------------------------------------------------------------------------- Log
4875:
4876: sub log {
4877: my ($dom,$nam,$hom,$what)=@_;
4878: return critical("log:$dom:$nam:$what",$hom);
4879: }
4880:
4881: # ------------------------------------------------------------------ Course Log
4882: #
4883: # This routine flushes several buffers of non-mission-critical nature
4884: #
4885:
4886: sub flushcourselogs {
4887: &logthis('Flushing log buffers');
4888: #
4889: # course logs
4890: # This is a log of all transactions in a course, which can be used
4891: # for data mining purposes
4892: #
4893: # It also collects the courseid database, which lists last transaction
4894: # times and course titles for all courseids
4895: #
4896: my %courseidbuffer=();
4897: foreach my $crsid (keys(%courselogs)) {
4898: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
4899: &escape($courselogs{$crsid}),
4900: $coursehombuf{$crsid}) eq 'ok') {
4901: delete $courselogs{$crsid};
4902: } else {
4903: &logthis('Failed to flush log buffer for '.$crsid);
4904: if (length($courselogs{$crsid})>40000) {
4905: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
4906: " exceeded maximum size, deleting.</font>");
4907: delete $courselogs{$crsid};
4908: }
4909: }
4910: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
4911: 'description' => $coursedescrbuf{$crsid},
4912: 'inst_code' => $courseinstcodebuf{$crsid},
4913: 'type' => $coursetypebuf{$crsid},
4914: 'owner' => $courseownerbuf{$crsid},
4915: };
4916: }
4917: #
4918: # Write course id database (reverse lookup) to homeserver of courses
4919: # Is used in pickcourse
4920: #
4921: foreach my $crs_home (keys(%courseidbuffer)) {
4922: my $response = &courseidput(&host_domain($crs_home),
4923: $courseidbuffer{$crs_home},
4924: $crs_home,'timeonly');
4925: }
4926: #
4927: # File accesses
4928: # Writes to the dynamic metadata of resources to get hit counts, etc.
4929: #
4930: foreach my $entry (keys(%accesshash)) {
4931: if ($entry =~ /___count$/) {
4932: my ($dom,$name);
4933: ($dom,$name,undef)=
4934: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
4935: if (! defined($dom) || $dom eq '' ||
4936: ! defined($name) || $name eq '') {
4937: my $cid = $env{'request.course.id'};
4938: $dom = $env{'request.'.$cid.'.domain'};
4939: $name = $env{'request.'.$cid.'.num'};
4940: }
4941: my $value = $accesshash{$entry};
4942: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4943: my %temphash=($url => $value);
4944: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4945: if ($result eq 'ok') {
4946: delete $accesshash{$entry};
4947: }
4948: } else {
4949: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
4950: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
4951: my %temphash=($entry => $accesshash{$entry});
4952: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4953: delete $accesshash{$entry};
4954: }
4955: }
4956: }
4957: #
4958: # Roles
4959: # Reverse lookup of user roles for course faculty/staff and co-authorship
4960: #
4961: foreach my $entry (keys(%userrolehash)) {
4962: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
4963: split(/\:/,$entry);
4964: if (&Apache::lonnet::put('nohist_userroles',
4965: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
4966: $rudom,$runame) eq 'ok') {
4967: delete $userrolehash{$entry};
4968: }
4969: }
4970: #
4971: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
4972: #
4973: my %domrolebuffer = ();
4974: foreach my $entry (keys(%domainrolehash)) {
4975: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
4976: if ($domrolebuffer{$rudom}) {
4977: $domrolebuffer{$rudom}.='&'.&escape($entry).
4978: '='.&escape($domainrolehash{$entry});
4979: } else {
4980: $domrolebuffer{$rudom}.=&escape($entry).
4981: '='.&escape($domainrolehash{$entry});
4982: }
4983: delete $domainrolehash{$entry};
4984: }
4985: foreach my $dom (keys(%domrolebuffer)) {
4986: my %servers;
4987: if (defined(&domain($dom,'primary'))) {
4988: my $primary=&domain($dom,'primary');
4989: my $hostname=&hostname($primary);
4990: $servers{$primary} = $hostname;
4991: } else {
4992: %servers = &get_servers($dom,'library');
4993: }
4994: foreach my $tryserver (keys(%servers)) {
4995: if (&reply('domroleput:'.$dom.':'.
4996: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4997: last;
4998: } else {
4999: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
5000: }
5001: }
5002: }
5003: $dumpcount++;
5004: }
5005:
5006: sub courselog {
5007: my $what=shift;
5008: $what=time.':'.$what;
5009: unless ($env{'request.course.id'}) { return ''; }
5010: $coursedombuf{$env{'request.course.id'}}=
5011: $env{'course.'.$env{'request.course.id'}.'.domain'};
5012: $coursenumbuf{$env{'request.course.id'}}=
5013: $env{'course.'.$env{'request.course.id'}.'.num'};
5014: $coursehombuf{$env{'request.course.id'}}=
5015: $env{'course.'.$env{'request.course.id'}.'.home'};
5016: $coursedescrbuf{$env{'request.course.id'}}=
5017: $env{'course.'.$env{'request.course.id'}.'.description'};
5018: $courseinstcodebuf{$env{'request.course.id'}}=
5019: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
5020: $courseownerbuf{$env{'request.course.id'}}=
5021: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
5022: $coursetypebuf{$env{'request.course.id'}}=
5023: $env{'course.'.$env{'request.course.id'}.'.type'};
5024: if (defined $courselogs{$env{'request.course.id'}}) {
5025: $courselogs{$env{'request.course.id'}}.='&'.$what;
5026: } else {
5027: $courselogs{$env{'request.course.id'}}.=$what;
5028: }
5029: if (length($courselogs{$env{'request.course.id'}})>4048) {
5030: &flushcourselogs();
5031: }
5032: }
5033:
5034: sub courseacclog {
5035: my $fnsymb=shift;
5036: unless ($env{'request.course.id'}) { return ''; }
5037: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
5038: if ($fnsymb=~/$LONCAPA::assess_re/) {
5039: $what.=':POST';
5040: # FIXME: Probably ought to escape things....
5041: foreach my $key (keys(%env)) {
5042: if ($key=~/^form\.(.*)/) {
5043: my $formitem = $1;
5044: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
5045: $what.=':'.$formitem.'='.$env{$key};
5046: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
5047: if ($formitem eq 'proctorpassword') {
5048: $what.=':'.$formitem.'=' . '*' x length($env{$key});
5049: } else {
5050: $what.=':'.$formitem.'='.$env{$key};
5051: }
5052: }
5053: }
5054: }
5055: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
5056: # FIXME: We should not be depending on a form parameter that someone
5057: # editing lonsearchcat.pm might change in the future.
5058: if ($env{'form.phase'} eq 'course_search') {
5059: $what.= ':POST';
5060: # FIXME: Probably ought to escape things....
5061: foreach my $element ('courseexp','crsfulltext','crsrelated',
5062: 'crsdiscuss') {
5063: $what.=':'.$element.'='.$env{'form.'.$element};
5064: }
5065: }
5066: }
5067: &courselog($what);
5068: }
5069:
5070: sub countacc {
5071: my $url=&declutter(shift);
5072: return if (! defined($url) || $url eq '');
5073: unless ($env{'request.course.id'}) { return ''; }
5074: #
5075: # Mark that this url was used in this course
5076: #
5077: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
5078: #
5079: # Increase the access count for this resource in this child process
5080: #
5081: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
5082: $accesshash{$key}++;
5083: }
5084:
5085: sub linklog {
5086: my ($from,$to)=@_;
5087: $from=&declutter($from);
5088: $to=&declutter($to);
5089: $accesshash{$from.'___'.$to.'___comefrom'}=1;
5090: $accesshash{$to.'___'.$from.'___goto'}=1;
5091: }
5092:
5093: sub statslog {
5094: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
5095: if ($users<2) { return; }
5096: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
5097: 'course' => $env{'request.course.id'},
5098: 'sections' => '"all"',
5099: 'num_students' => $users,
5100: 'part' => $part,
5101: 'symb' => $symb,
5102: 'mean_tries' => $av_attempts,
5103: 'deg_of_diff' => $degdiff});
5104: foreach my $key (keys(%dynstore)) {
5105: $accesshash{$key}=$dynstore{$key};
5106: }
5107: }
5108:
5109: sub userrolelog {
5110: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
5111: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
5112: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5113: $userrolehash
5114: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
5115: =$tend.':'.$tstart;
5116: }
5117: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
5118: $userrolehash
5119: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
5120: =$tend.':'.$tstart;
5121: }
5122: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
5123: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5124: $domainrolehash
5125: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
5126: = $tend.':'.$tstart;
5127: }
5128: }
5129:
5130: sub courserolelog {
5131: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
5132: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
5133: my $cdom = $1;
5134: my $cnum = $2;
5135: my $sec = $3;
5136: my $namespace = 'rolelog';
5137: my %storehash = (
5138: role => $trole,
5139: start => $tstart,
5140: end => $tend,
5141: selfenroll => $selfenroll,
5142: context => $context,
5143: );
5144: if ($trole eq 'gr') {
5145: $namespace = 'groupslog';
5146: $storehash{'group'} = $sec;
5147: } else {
5148: $storehash{'section'} = $sec;
5149: }
5150: &write_log('course',$namespace,\%storehash,$delflag,$username,
5151: $domain,$cnum,$cdom);
5152: if (($trole ne 'st') || ($sec ne '')) {
5153: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
5154: }
5155: }
5156: return;
5157: }
5158:
5159: sub domainrolelog {
5160: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5161: if ($area =~ m{^/($match_domain)/$}) {
5162: my $cdom = $1;
5163: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
5164: my $namespace = 'rolelog';
5165: my %storehash = (
5166: role => $trole,
5167: start => $tstart,
5168: end => $tend,
5169: context => $context,
5170: );
5171: &write_log('domain',$namespace,\%storehash,$delflag,$username,
5172: $domain,$domconfiguser,$cdom);
5173: }
5174: return;
5175:
5176: }
5177:
5178: sub coauthorrolelog {
5179: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5180: if ($area =~ m{^/($match_domain)/($match_username)$}) {
5181: my $audom = $1;
5182: my $auname = $2;
5183: my $namespace = 'rolelog';
5184: my %storehash = (
5185: role => $trole,
5186: start => $tstart,
5187: end => $tend,
5188: context => $context,
5189: );
5190: &write_log('author',$namespace,\%storehash,$delflag,$username,
5191: $domain,$auname,$audom);
5192: }
5193: return;
5194: }
5195:
5196: sub get_course_adv_roles {
5197: my ($cid,$codes) = @_;
5198: $cid=$env{'request.course.id'} unless (defined($cid));
5199: my %coursehash=&coursedescription($cid);
5200: my $crstype = &Apache::loncommon::course_type($cid);
5201: my %nothide=();
5202: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
5203: if ($user !~ /:/) {
5204: $nothide{join(':',split(/[\@]/,$user))}=1;
5205: } else {
5206: $nothide{$user}=1;
5207: }
5208: }
5209: my @possdoms = ($coursehash{'domain'});
5210: if ($coursehash{'checkforpriv'}) {
5211: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
5212: }
5213: my %returnhash=();
5214: my %dumphash=
5215: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
5216: my $now=time;
5217: my %privileged;
5218: foreach my $entry (keys(%dumphash)) {
5219: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
5220: if (($tstart) && ($tstart<0)) { next; }
5221: if (($tend) && ($tend<$now)) { next; }
5222: if (($tstart) && ($now<$tstart)) { next; }
5223: my ($role,$username,$domain,$section)=split(/\:/,$entry);
5224: if ($username eq '' || $domain eq '') { next; }
5225: if ((&privileged($username,$domain,\@possdoms)) &&
5226: (!$nothide{$username.':'.$domain})) { next; }
5227: if ($role eq 'cr') { next; }
5228: if ($codes) {
5229: if ($section) { $role .= ':'.$section; }
5230: if ($returnhash{$role}) {
5231: $returnhash{$role}.=','.$username.':'.$domain;
5232: } else {
5233: $returnhash{$role}=$username.':'.$domain;
5234: }
5235: } else {
5236: my $key=&plaintext($role,$crstype);
5237: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
5238: if ($returnhash{$key}) {
5239: $returnhash{$key}.=','.$username.':'.$domain;
5240: } else {
5241: $returnhash{$key}=$username.':'.$domain;
5242: }
5243: }
5244: }
5245: return %returnhash;
5246: }
5247:
5248: sub get_my_roles {
5249: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
5250: unless (defined($uname)) { $uname=$env{'user.name'}; }
5251: unless (defined($udom)) { $udom=$env{'user.domain'}; }
5252: my (%dumphash,%nothide);
5253: if ($context eq 'userroles') {
5254: %dumphash = &dump('roles',$udom,$uname);
5255: } else {
5256: %dumphash = &dump('nohist_userroles',$udom,$uname);
5257: if ($hidepriv) {
5258: my %coursehash=&coursedescription($udom.'_'.$uname);
5259: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
5260: if ($user !~ /:/) {
5261: $nothide{join(':',split(/[\@]/,$user))} = 1;
5262: } else {
5263: $nothide{$user} = 1;
5264: }
5265: }
5266: }
5267: }
5268: my %returnhash=();
5269: my $now=time;
5270: my %privileged;
5271: foreach my $entry (keys(%dumphash)) {
5272: my ($role,$tend,$tstart);
5273: if ($context eq 'userroles') {
5274: next if ($entry =~ /^rolesdef/);
5275: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
5276: } else {
5277: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
5278: }
5279: if (($tstart) && ($tstart<0)) { next; }
5280: my $status = 'active';
5281: if (($tend) && ($tend<=$now)) {
5282: $status = 'previous';
5283: }
5284: if (($tstart) && ($now<$tstart)) {
5285: $status = 'future';
5286: }
5287: if (ref($types) eq 'ARRAY') {
5288: if (!grep(/^\Q$status\E$/,@{$types})) {
5289: next;
5290: }
5291: } else {
5292: if ($status ne 'active') {
5293: next;
5294: }
5295: }
5296: my ($rolecode,$username,$domain,$section,$area);
5297: if ($context eq 'userroles') {
5298: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
5299: (undef,$domain,$username,$section) = split(/\//,$area);
5300: } else {
5301: ($role,$username,$domain,$section) = split(/\:/,$entry);
5302: }
5303: if (ref($roledoms) eq 'ARRAY') {
5304: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
5305: next;
5306: }
5307: }
5308: if (ref($roles) eq 'ARRAY') {
5309: if (!grep(/^\Q$role\E$/,@{$roles})) {
5310: if ($role =~ /^cr\//) {
5311: if (!grep(/^cr$/,@{$roles})) {
5312: next;
5313: }
5314: } elsif ($role =~ /^gr\//) {
5315: if (!grep(/^gr$/,@{$roles})) {
5316: next;
5317: }
5318: } else {
5319: next;
5320: }
5321: }
5322: }
5323: if ($hidepriv) {
5324: my @privroles = ('dc','su');
5325: if ($context eq 'userroles') {
5326: next if (grep(/^\Q$role\E$/,@privroles));
5327: } else {
5328: my $possdoms = [$domain];
5329: if (ref($roledoms) eq 'ARRAY') {
5330: push(@{$possdoms},@{$roledoms});
5331: }
5332: if (&privileged($username,$domain,$possdoms,\@privroles)) {
5333: if (!$nothide{$username.':'.$domain}) {
5334: next;
5335: }
5336: }
5337: }
5338: }
5339: if ($withsec) {
5340: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
5341: $tstart.':'.$tend;
5342: } else {
5343: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
5344: }
5345: }
5346: return %returnhash;
5347: }
5348:
5349: sub get_all_adhocroles {
5350: my ($dom) = @_;
5351: my @roles_by_num = ();
5352: my %domdefaults = &get_domain_defaults($dom);
5353: my (%description,%access_in_dom,%access_info);
5354: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
5355: my $count = 0;
5356: my %domcurrent = %{$domdefaults{'adhocroles'}};
5357: my %ordered;
5358: foreach my $role (sort(keys(%domcurrent))) {
5359: my ($order,$desc,$access_in_dom);
5360: if (ref($domcurrent{$role}) eq 'HASH') {
5361: $order = $domcurrent{$role}{'order'};
5362: $desc = $domcurrent{$role}{'desc'};
5363: $access_in_dom{$role} = $domcurrent{$role}{'access'};
5364: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
5365: }
5366: if ($order eq '') {
5367: $order = $count;
5368: }
5369: $ordered{$order} = $role;
5370: if ($desc ne '') {
5371: $description{$role} = $desc;
5372: } else {
5373: $description{$role}= $role;
5374: }
5375: $count++;
5376: }
5377: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
5378: push(@roles_by_num,$ordered{$item});
5379: }
5380: }
5381: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
5382: }
5383:
5384: sub get_my_adhocroles {
5385: my ($cid,$checkreg) = @_;
5386: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
5387: if ($env{'request.course.id'} eq $cid) {
5388: $cdom = $env{'course.'.$cid.'.domain'};
5389: $cnum = $env{'course.'.$cid.'.num'};
5390: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
5391: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
5392: $cdom = $1;
5393: $cnum = $2;
5394: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
5395: $cdom,$cnum);
5396: }
5397: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
5398: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5399: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
5400: if ($rosterhash{$user} ne '') {
5401: my $type = (split(/:/,$rosterhash{$user}))[5];
5402: return ([],{}) if ($type eq 'auto');
5403: }
5404: }
5405: if (($cdom ne '') && ($cnum ne '')) {
5406: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
5407: my $then=$env{'user.login.time'};
5408: my $update=$env{'user.update.time'};
5409: if (!$update) {
5410: $update = $then;
5411: }
5412: my @liveroles;
5413: foreach my $role ('dh','da') {
5414: if ($env{"user.role.$role./$cdom/"}) {
5415: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
5416: my $limit = $update;
5417: if ($env{'request.role'} eq "$role./$cdom/") {
5418: $limit = $then;
5419: }
5420: my $activerole = 1;
5421: if ($tstart && $tstart>$limit) { $activerole = 0; }
5422: if ($tend && $tend <$limit) { $activerole = 0; }
5423: if ($activerole) {
5424: push(@liveroles,$role);
5425: }
5426: }
5427: }
5428: if (@liveroles) {
5429: if (&homeserver($cnum,$cdom) ne 'no_host') {
5430: my ($accessref,$accessinfo,%access_in_dom);
5431: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5432: if (ref($roles_by_num) eq 'ARRAY') {
5433: if (@{$roles_by_num}) {
5434: my %settings;
5435: if ($env{'request.course.id'} eq $cid) {
5436: foreach my $envkey (keys(%env)) {
5437: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5438: $settings{$1} = $env{$envkey};
5439: }
5440: }
5441: } else {
5442: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5443: }
5444: my %setincrs;
5445: if ($settings{'internal.adhocaccess'}) {
5446: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5447: }
5448: my @statuses;
5449: if ($env{'environment.inststatus'}) {
5450: @statuses = split(/,/,$env{'environment.inststatus'});
5451: }
5452: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5453: if (ref($accessref) eq 'HASH') {
5454: %access_in_dom = %{$accessref};
5455: }
5456: foreach my $role (@{$roles_by_num}) {
5457: my ($curraccess,@okstatus,@personnel);
5458: if ($setincrs{$role}) {
5459: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5460: if ($curraccess eq 'status') {
5461: @okstatus = split(/\&/,$rest);
5462: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5463: @personnel = split(/\&/,$rest);
5464: }
5465: } else {
5466: $curraccess = $access_in_dom{$role};
5467: if (ref($accessinfo) eq 'HASH') {
5468: if ($curraccess eq 'status') {
5469: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5470: @okstatus = @{$accessinfo->{$role}};
5471: }
5472: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5473: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5474: @personnel = @{$accessinfo->{$role}};
5475: }
5476: }
5477: }
5478: }
5479: if ($curraccess eq 'none') {
5480: next;
5481: } elsif ($curraccess eq 'all') {
5482: push(@possroles,$role);
5483: } elsif ($curraccess eq 'dh') {
5484: if (grep(/^dh$/,@liveroles)) {
5485: push(@possroles,$role);
5486: } else {
5487: next;
5488: }
5489: } elsif ($curraccess eq 'da') {
5490: if (grep(/^da$/,@liveroles)) {
5491: push(@possroles,$role);
5492: } else {
5493: next;
5494: }
5495: } elsif ($curraccess eq 'status') {
5496: if (@okstatus) {
5497: if (!@statuses) {
5498: if (grep(/^default$/,@okstatus)) {
5499: push(@possroles,$role);
5500: }
5501: } else {
5502: foreach my $status (@okstatus) {
5503: if (grep(/^\Q$status\E$/,@statuses)) {
5504: push(@possroles,$role);
5505: last;
5506: }
5507: }
5508: }
5509: }
5510: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5511: if (grep(/^\Q$user\E$/,@personnel)) {
5512: if ($curraccess eq 'exc') {
5513: push(@possroles,$role);
5514: }
5515: } elsif ($curraccess eq 'inc') {
5516: push(@possroles,$role);
5517: }
5518: }
5519: }
5520: }
5521: }
5522: }
5523: }
5524: }
5525: }
5526: unless (ref($description) eq 'HASH') {
5527: if (ref($roles_by_num) eq 'ARRAY') {
5528: my %desc;
5529: map { $desc{$_} = $_; } (@{$roles_by_num});
5530: $description = \%desc;
5531: } else {
5532: $description = {};
5533: }
5534: }
5535: return (\@possroles,$description);
5536: }
5537:
5538: # ----------------------------------------------------- Frontpage Announcements
5539: #
5540: #
5541:
5542: sub postannounce {
5543: my ($server,$text)=@_;
5544: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
5545: unless ($text=~/\w/) { $text=''; }
5546: return &reply('setannounce:'.&escape($text),$server);
5547: }
5548:
5549: sub getannounce {
5550:
5551: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
5552: my $announcement='';
5553: while (my $line = <$fh>) { $announcement .= $line; }
5554: close($fh);
5555: if ($announcement=~/\w/) {
5556: return
5557: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
5558: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
5559: } else {
5560: return '';
5561: }
5562: } else {
5563: return '';
5564: }
5565: }
5566:
5567: # ---------------------------------------------------------- Course ID routines
5568: # Deal with domain's nohist_courseid.db files
5569: #
5570:
5571: sub courseidput {
5572: my ($domain,$storehash,$coursehome,$caller) = @_;
5573: return unless (ref($storehash) eq 'HASH');
5574: my $outcome;
5575: if ($caller eq 'timeonly') {
5576: my $cids = '';
5577: foreach my $item (keys(%$storehash)) {
5578: $cids.=&escape($item).'&';
5579: }
5580: $cids=~s/\&$//;
5581: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5582: $coursehome);
5583: } else {
5584: my $items = '';
5585: foreach my $item (keys(%$storehash)) {
5586: $items.= &escape($item).'='.
5587: &freeze_escape($$storehash{$item}).'&';
5588: }
5589: $items=~s/\&$//;
5590: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5591: $coursehome);
5592: }
5593: if ($outcome eq 'unknown_cmd') {
5594: my $what;
5595: foreach my $cid (keys(%$storehash)) {
5596: $what .= &escape($cid).'=';
5597: foreach my $item ('description','inst_code','owner','type') {
5598: $what .= &escape($storehash->{$cid}{$item}).':';
5599: }
5600: $what =~ s/\:$/&/;
5601: }
5602: $what =~ s/\&$//;
5603: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5604: } else {
5605: return $outcome;
5606: }
5607: }
5608:
5609: sub courseiddump {
5610: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
5611: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
5612: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
5613: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
5614: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
5615: my $as_hash = 1;
5616: my %returnhash;
5617: if (!$domfilter) { $domfilter=''; }
5618: my %libserv = &all_library();
5619: foreach my $tryserver (keys(%libserv)) {
5620: if ( ( $hostidflag == 1
5621: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5622: || (!defined($hostidflag)) ) {
5623:
5624: if (($domfilter eq '') ||
5625: (&host_domain($tryserver) eq $domfilter)) {
5626: my $rep;
5627: if (grep { $_ eq $tryserver } current_machine_ids()) {
5628: $rep = LONCAPA::Lond::dump_course_id_handler(
5629: join(":", (&host_domain($tryserver), $sincefilter,
5630: &escape($descfilter), &escape($instcodefilter),
5631: &escape($ownerfilter), &escape($coursefilter),
5632: &escape($typefilter), &escape($regexp_ok),
5633: $as_hash, &escape($selfenrollonly),
5634: &escape($catfilter), $showhidden, $caller,
5635: &escape($cloner), &escape($cc_clone), $cloneonly,
5636: &escape($createdbefore), &escape($createdafter),
5637: &escape($creationcontext),$domcloner,$hasuniquecode,
5638: $reqcrsdom,&escape($reqinstcode))));
5639: } else {
5640: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5641: $sincefilter.':'.&escape($descfilter).':'.
5642: &escape($instcodefilter).':'.&escape($ownerfilter).
5643: ':'.&escape($coursefilter).':'.&escape($typefilter).
5644: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5645: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5646: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5647: &escape($cc_clone).':'.$cloneonly.':'.
5648: &escape($createdbefore).':'.&escape($createdafter).':'.
5649: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5650: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
5651: }
5652:
5653: my @pairs=split(/\&/,$rep);
5654: foreach my $item (@pairs) {
5655: my ($key,$value)=split(/\=/,$item,2);
5656: $key = &unescape($key);
5657: next if ($key =~ /^error: 2 /);
5658: my $result = &thaw_unescape($value);
5659: if (ref($result) eq 'HASH') {
5660: $returnhash{$key}=$result;
5661: } else {
5662: my @responses = split(/:/,$value);
5663: my @items = ('description','inst_code','owner','type');
5664: for (my $i=0; $i<@responses; $i++) {
5665: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
5666: }
5667: }
5668: }
5669: }
5670: }
5671: }
5672: return %returnhash;
5673: }
5674:
5675: sub courselastaccess {
5676: my ($cdom,$cnum,$hostidref) = @_;
5677: my %returnhash;
5678: if ($cdom && $cnum) {
5679: my $chome = &homeserver($cnum,$cdom);
5680: if ($chome ne 'no_host') {
5681: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5682: &extract_lastaccess(\%returnhash,$rep);
5683: }
5684: } else {
5685: if (!$cdom) { $cdom=''; }
5686: my %libserv = &all_library();
5687: foreach my $tryserver (keys(%libserv)) {
5688: if (ref($hostidref) eq 'ARRAY') {
5689: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5690: }
5691: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5692: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5693: &extract_lastaccess(\%returnhash,$rep);
5694: }
5695: }
5696: }
5697: return %returnhash;
5698: }
5699:
5700: sub extract_lastaccess {
5701: my ($returnhash,$rep) = @_;
5702: if (ref($returnhash) eq 'HASH') {
5703: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5704: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5705: $rep eq '') {
5706: my @pairs=split(/\&/,$rep);
5707: foreach my $item (@pairs) {
5708: my ($key,$value)=split(/\=/,$item,2);
5709: $key = &unescape($key);
5710: next if ($key =~ /^error: 2 /);
5711: $returnhash->{$key} = &thaw_unescape($value);
5712: }
5713: }
5714: }
5715: return;
5716: }
5717:
5718: # ---------------------------------------------------------- DC e-mail
5719:
5720: sub dcmailput {
5721: my ($domain,$msgid,$message,$server)=@_;
5722: my $status = &Apache::lonnet::critical(
5723: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5724: &escape($message),$server);
5725: return $status;
5726: }
5727:
5728: sub dcmaildump {
5729: my ($dom,$startdate,$enddate,$senders) = @_;
5730: my %returnhash=();
5731:
5732: if (defined(&domain($dom,'primary'))) {
5733: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5734: &escape($enddate).':';
5735: my @esc_senders=map { &escape($_)} @$senders;
5736: $cmd.=&escape(join('&',@esc_senders));
5737: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
5738: my ($key,$value) = split(/\=/,$line,2);
5739: if (($key) && ($value)) {
5740: $returnhash{&unescape($key)} = &unescape($value);
5741: }
5742: }
5743: }
5744: return %returnhash;
5745: }
5746: # ---------------------------------------------------------- Domain roles
5747:
5748: sub get_domain_roles {
5749: my ($dom,$roles,$startdate,$enddate)=@_;
5750: if ((!defined($startdate)) || ($startdate eq '')) {
5751: $startdate = '.';
5752: }
5753: if ((!defined($enddate)) || ($enddate eq '')) {
5754: $enddate = '.';
5755: }
5756: my $rolelist;
5757: if (ref($roles) eq 'ARRAY') {
5758: $rolelist = join('&',@{$roles});
5759: }
5760: my %personnel = ();
5761:
5762: my %servers = &get_servers($dom,'library');
5763: foreach my $tryserver (keys(%servers)) {
5764: %{$personnel{$tryserver}}=();
5765: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5766: &escape($startdate).':'.
5767: &escape($enddate).':'.
5768: &escape($rolelist), $tryserver))) {
5769: my ($key,$value) = split(/\=/,$line,2);
5770: if (($key) && ($value)) {
5771: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5772: }
5773: }
5774: }
5775: return %personnel;
5776: }
5777:
5778: sub get_active_domroles {
5779: my ($dom,$roles) = @_;
5780: return () unless (ref($roles) eq 'ARRAY');
5781: my $now = time;
5782: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5783: my %domroles;
5784: foreach my $server (keys(%dompersonnel)) {
5785: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5786: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5787: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5788: }
5789: }
5790: return %domroles;
5791: }
5792:
5793: # ----------------------------------------------------------- Interval timing
5794:
5795: {
5796: # Caches needed for speedup of navmaps
5797: # We don't want to cache this for very long at all (5 seconds at most)
5798: #
5799: # The user for whom we cache
5800: my $cachedkey='';
5801: # The cached times for this user
5802: my %cachedtimes=();
5803: # When this was last done
5804: my $cachedtime='';
5805:
5806: sub load_all_first_access {
5807: my ($uname,$udom,$ignorecache)=@_;
5808: if (($cachedkey eq $uname.':'.$udom) &&
5809: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
5810: (!$ignorecache)) {
5811: return;
5812: }
5813: $cachedtime=time;
5814: $cachedkey=$uname.':'.$udom;
5815: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
5816: }
5817:
5818: sub get_first_access {
5819: my ($type,$argsymb,$argmap,$ignorecache)=@_;
5820: my ($symb,$courseid,$udom,$uname)=&whichuser();
5821: if ($argsymb) { $symb=$argsymb; }
5822: my ($map,$id,$res)=&decode_symb($symb);
5823: if ($argmap) { $map = $argmap; }
5824: if ($type eq 'course') {
5825: $res='course';
5826: } elsif ($type eq 'map') {
5827: $res=&symbread($map);
5828: } else {
5829: $res=$symb;
5830: }
5831: &load_all_first_access($uname,$udom,$ignorecache);
5832: return $cachedtimes{"$courseid\0$res"};
5833: }
5834:
5835: sub set_first_access {
5836: my ($type,$interval)=@_;
5837: my ($symb,$courseid,$udom,$uname)=&whichuser();
5838: my ($map,$id,$res)=&decode_symb($symb);
5839: if ($type eq 'course') {
5840: $res='course';
5841: } elsif ($type eq 'map') {
5842: $res=&symbread($map);
5843: } else {
5844: $res=$symb;
5845: }
5846: $cachedkey='';
5847: my $firstaccess=&get_first_access($type,$symb,$map);
5848: if ($firstaccess) {
5849: &logthis("First access time already set ($firstaccess) when attempting ".
5850: "to set new value (type: $type, extent: $res) for $uname:$udom ".
5851: "in $courseid");
5852: return 'already_set';
5853: } else {
5854: my $start = time;
5855: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5856: $udom,$uname);
5857: if ($putres eq 'ok') {
5858: &put('timerinterval',{"$courseid\0$res"=>$interval},
5859: $udom,$uname);
5860: &appenv(
5861: {
5862: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5863: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5864: }
5865: );
5866: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
5867: $cachedtimes{"$courseid\0$res"} = $start;
5868: }
5869: } elsif ($putres ne 'refused') {
5870: &logthis("Result: $putres when attempting to set first access time ".
5871: "(type: $type, extent: $res) for $uname:$udom in $courseid");
5872: }
5873: return $putres;
5874: }
5875: return 'already_set';
5876: }
5877: }
5878:
5879: # --------------------------------------------- Set Expire Date for Spreadsheet
5880:
5881: sub expirespread {
5882: my ($uname,$udom,$stype,$usymb)=@_;
5883: my $cid=$env{'request.course.id'};
5884: if ($cid) {
5885: my $now=time;
5886: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
5887: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5888: $env{'course.'.$cid.'.num'}.
5889: ':nohist_expirationdates:'.
5890: &escape($key).'='.$now,
5891: $env{'course.'.$cid.'.home'})
5892: }
5893: return 'ok';
5894: }
5895:
5896: # ----------------------------------------------------- Devalidate Spreadsheets
5897:
5898: sub devalidate {
5899: my ($symb,$uname,$udom)=@_;
5900: my $cid=$env{'request.course.id'};
5901: if ($cid) {
5902: # delete the stored spreadsheets for
5903: # - the student level sheet of this user in course's homespace
5904: # - the assessment level sheet for this resource
5905: # for this user in user's homespace
5906: # - current conditional state info
5907: my $key=$uname.':'.$udom.':';
5908: my $status=
5909: &del('nohist_calculatedsheets',
5910: [$key.'studentcalc:'],
5911: $env{'course.'.$cid.'.domain'},
5912: $env{'course.'.$cid.'.num'})
5913: .' '.
5914: &del('nohist_calculatedsheets_'.$cid,
5915: [$key.'assesscalc:'.$symb],$udom,$uname);
5916: unless ($status eq 'ok ok') {
5917: &logthis('Could not devalidate spreadsheet '.
5918: $uname.' at '.$udom.' for '.
5919: $symb.': '.$status);
5920: }
5921: &delenv('user.state.'.$cid);
5922: }
5923: }
5924:
5925: sub get_scalar {
5926: my ($string,$end) = @_;
5927: my $value;
5928: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5929: $value = $1;
5930: } elsif ($$string =~ s/^([^&]*?)&//) {
5931: $value = $1;
5932: }
5933: return &unescape($value);
5934: }
5935:
5936: sub array2str {
5937: my (@array) = @_;
5938: my $result=&arrayref2str(\@array);
5939: $result=~s/^__ARRAY_REF__//;
5940: $result=~s/__END_ARRAY_REF__$//;
5941: return $result;
5942: }
5943:
5944: sub arrayref2str {
5945: my ($arrayref) = @_;
5946: my $result='__ARRAY_REF__';
5947: foreach my $elem (@$arrayref) {
5948: if(ref($elem) eq 'ARRAY') {
5949: $result.=&arrayref2str($elem).'&';
5950: } elsif(ref($elem) eq 'HASH') {
5951: $result.=&hashref2str($elem).'&';
5952: } elsif(ref($elem)) {
5953: #print("Got a ref of ".(ref($elem))." skipping.");
5954: } else {
5955: $result.=&escape($elem).'&';
5956: }
5957: }
5958: $result=~s/\&$//;
5959: $result .= '__END_ARRAY_REF__';
5960: return $result;
5961: }
5962:
5963: sub hash2str {
5964: my (%hash) = @_;
5965: my $result=&hashref2str(\%hash);
5966: $result=~s/^__HASH_REF__//;
5967: $result=~s/__END_HASH_REF__$//;
5968: return $result;
5969: }
5970:
5971: sub hashref2str {
5972: my ($hashref)=@_;
5973: my $result='__HASH_REF__';
5974: foreach my $key (sort(keys(%$hashref))) {
5975: if (ref($key) eq 'ARRAY') {
5976: $result.=&arrayref2str($key).'=';
5977: } elsif (ref($key) eq 'HASH') {
5978: $result.=&hashref2str($key).'=';
5979: } elsif (ref($key)) {
5980: $result.='=';
5981: #print("Got a ref of ".(ref($key))." skipping.");
5982: } else {
5983: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
5984: }
5985:
5986: if(ref($hashref->{$key}) eq 'ARRAY') {
5987: $result.=&arrayref2str($hashref->{$key}).'&';
5988: } elsif(ref($hashref->{$key}) eq 'HASH') {
5989: $result.=&hashref2str($hashref->{$key}).'&';
5990: } elsif(ref($hashref->{$key})) {
5991: $result.='&';
5992: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
5993: } else {
5994: $result.=&escape($hashref->{$key}).'&';
5995: }
5996: }
5997: $result=~s/\&$//;
5998: $result .= '__END_HASH_REF__';
5999: return $result;
6000: }
6001:
6002: sub str2hash {
6003: my ($string)=@_;
6004: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
6005: return %$hash;
6006: }
6007:
6008: sub str2hashref {
6009: my ($string) = @_;
6010:
6011: my %hash;
6012:
6013: if($string !~ /^__HASH_REF__/) {
6014: if (! ($string eq '' || !defined($string))) {
6015: $hash{'error'}='Not hash reference';
6016: }
6017: return (\%hash, $string);
6018: }
6019:
6020: $string =~ s/^__HASH_REF__//;
6021:
6022: while($string !~ /^__END_HASH_REF__/) {
6023: #key
6024: my $key='';
6025: if($string =~ /^__HASH_REF__/) {
6026: ($key, $string)=&str2hashref($string);
6027: if(defined($key->{'error'})) {
6028: $hash{'error'}='Bad data';
6029: return (\%hash, $string);
6030: }
6031: } elsif($string =~ /^__ARRAY_REF__/) {
6032: ($key, $string)=&str2arrayref($string);
6033: if($key->[0] eq 'Array reference error') {
6034: $hash{'error'}='Bad data';
6035: return (\%hash, $string);
6036: }
6037: } else {
6038: $string =~ s/^(.*?)=//;
6039: $key=&unescape($1);
6040: }
6041: $string =~ s/^=//;
6042:
6043: #value
6044: my $value='';
6045: if($string =~ /^__HASH_REF__/) {
6046: ($value, $string)=&str2hashref($string);
6047: if(defined($value->{'error'})) {
6048: $hash{'error'}='Bad data';
6049: return (\%hash, $string);
6050: }
6051: } elsif($string =~ /^__ARRAY_REF__/) {
6052: ($value, $string)=&str2arrayref($string);
6053: if($value->[0] eq 'Array reference error') {
6054: $hash{'error'}='Bad data';
6055: return (\%hash, $string);
6056: }
6057: } else {
6058: $value=&get_scalar(\$string,'__END_HASH_REF__');
6059: }
6060: $string =~ s/^&//;
6061:
6062: $hash{$key}=$value;
6063: }
6064:
6065: $string =~ s/^__END_HASH_REF__//;
6066:
6067: return (\%hash, $string);
6068: }
6069:
6070: sub str2array {
6071: my ($string)=@_;
6072: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
6073: return @$array;
6074: }
6075:
6076: sub str2arrayref {
6077: my ($string) = @_;
6078: my @array;
6079:
6080: if($string !~ /^__ARRAY_REF__/) {
6081: if (! ($string eq '' || !defined($string))) {
6082: $array[0]='Array reference error';
6083: }
6084: return (\@array, $string);
6085: }
6086:
6087: $string =~ s/^__ARRAY_REF__//;
6088:
6089: while($string !~ /^__END_ARRAY_REF__/) {
6090: my $value='';
6091: if($string =~ /^__HASH_REF__/) {
6092: ($value, $string)=&str2hashref($string);
6093: if(defined($value->{'error'})) {
6094: $array[0] ='Array reference error';
6095: return (\@array, $string);
6096: }
6097: } elsif($string =~ /^__ARRAY_REF__/) {
6098: ($value, $string)=&str2arrayref($string);
6099: if($value->[0] eq 'Array reference error') {
6100: $array[0] ='Array reference error';
6101: return (\@array, $string);
6102: }
6103: } else {
6104: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
6105: }
6106: $string =~ s/^&//;
6107:
6108: push(@array, $value);
6109: }
6110:
6111: $string =~ s/^__END_ARRAY_REF__//;
6112:
6113: return (\@array, $string);
6114: }
6115:
6116: # -------------------------------------------------------------------Temp Store
6117:
6118: sub tmpreset {
6119: my ($symb,$namespace,$domain,$stuname) = @_;
6120: if (!$symb) {
6121: $symb=&symbread();
6122: if (!$symb) { $symb= $env{'request.url'}; }
6123: }
6124: $symb=escape($symb);
6125:
6126: if (!$namespace) { $namespace=$env{'request.state'}; }
6127: $namespace=~s/\//\_/g;
6128: $namespace=~s/\W//g;
6129:
6130: if (!$domain) { $domain=$env{'user.domain'}; }
6131: if (!$stuname) { $stuname=$env{'user.name'}; }
6132: if ($domain eq 'public' && $stuname eq 'public') {
6133: $stuname=&get_requestor_ip();
6134: }
6135: my $path=LONCAPA::tempdir();
6136: my %hash;
6137: if (tie(%hash,'GDBM_File',
6138: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
6139: &GDBM_WRCREAT(),0640)) {
6140: foreach my $key (keys(%hash)) {
6141: if ($key=~ /:$symb/) {
6142: delete($hash{$key});
6143: }
6144: }
6145: }
6146: }
6147:
6148: sub tmpstore {
6149: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
6150:
6151: if (!$symb) {
6152: $symb=&symbread();
6153: if (!$symb) { $symb= $env{'request.url'}; }
6154: }
6155: $symb=escape($symb);
6156:
6157: if (!$namespace) {
6158: # I don't think we would ever want to store this for a course.
6159: # it seems this will only be used if we don't have a course.
6160: #$namespace=$env{'request.course.id'};
6161: #if (!$namespace) {
6162: $namespace=$env{'request.state'};
6163: #}
6164: }
6165: $namespace=~s/\//\_/g;
6166: $namespace=~s/\W//g;
6167: if (!$domain) { $domain=$env{'user.domain'}; }
6168: if (!$stuname) { $stuname=$env{'user.name'}; }
6169: if ($domain eq 'public' && $stuname eq 'public') {
6170: $stuname=&get_requestor_ip();
6171: }
6172: my $now=time;
6173: my %hash;
6174: my $path=LONCAPA::tempdir();
6175: if (tie(%hash,'GDBM_File',
6176: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
6177: &GDBM_WRCREAT(),0640)) {
6178: $hash{"version:$symb"}++;
6179: my $version=$hash{"version:$symb"};
6180: my $allkeys='';
6181: foreach my $key (keys(%$storehash)) {
6182: $allkeys.=$key.':';
6183: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
6184: }
6185: $hash{"$version:$symb:timestamp"}=$now;
6186: $allkeys.='timestamp';
6187: $hash{"$version:keys:$symb"}=$allkeys;
6188: if (untie(%hash)) {
6189: return 'ok';
6190: } else {
6191: return "error:$!";
6192: }
6193: } else {
6194: return "error:$!";
6195: }
6196: }
6197:
6198: # -----------------------------------------------------------------Temp Restore
6199:
6200: sub tmprestore {
6201: my ($symb,$namespace,$domain,$stuname) = @_;
6202:
6203: if (!$symb) {
6204: $symb=&symbread();
6205: if (!$symb) { $symb= $env{'request.url'}; }
6206: }
6207: $symb=escape($symb);
6208:
6209: if (!$namespace) { $namespace=$env{'request.state'}; }
6210:
6211: if (!$domain) { $domain=$env{'user.domain'}; }
6212: if (!$stuname) { $stuname=$env{'user.name'}; }
6213: if ($domain eq 'public' && $stuname eq 'public') {
6214: $stuname=&get_requestor_ip();
6215: }
6216: my %returnhash;
6217: $namespace=~s/\//\_/g;
6218: $namespace=~s/\W//g;
6219: my %hash;
6220: my $path=LONCAPA::tempdir();
6221: if (tie(%hash,'GDBM_File',
6222: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
6223: &GDBM_READER(),0640)) {
6224: my $version=$hash{"version:$symb"};
6225: $returnhash{'version'}=$version;
6226: my $scope;
6227: for ($scope=1;$scope<=$version;$scope++) {
6228: my $vkeys=$hash{"$scope:keys:$symb"};
6229: my @keys=split(/:/,$vkeys);
6230: my $key;
6231: $returnhash{"$scope:keys"}=$vkeys;
6232: foreach $key (@keys) {
6233: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
6234: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
6235: }
6236: }
6237: if (!(untie(%hash))) {
6238: return "error:$!";
6239: }
6240: } else {
6241: return "error:$!";
6242: }
6243: return %returnhash;
6244: }
6245:
6246: # ----------------------------------------------------------------------- Store
6247:
6248: sub store {
6249: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
6250: my $home='';
6251:
6252: if ($stuname) { $home=&homeserver($stuname,$domain); }
6253:
6254: $symb=&symbclean($symb);
6255: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
6256:
6257: if (!$domain) { $domain=$env{'user.domain'}; }
6258: if (!$stuname) { $stuname=$env{'user.name'}; }
6259:
6260: &devalidate($symb,$stuname,$domain);
6261:
6262: $symb=escape($symb);
6263: if (!$namespace) {
6264: unless ($namespace=$env{'request.course.id'}) {
6265: return '';
6266: }
6267: }
6268: if (!$home) { $home=$env{'user.home'}; }
6269:
6270: $$storehash{'ip'}=&get_requestor_ip();
6271: $$storehash{'host'}=$perlvar{'lonHostID'};
6272:
6273: my $namevalue='';
6274: foreach my $key (keys(%$storehash)) {
6275: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6276: }
6277: $namevalue=~s/\&$//;
6278: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
6279: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
6280: }
6281:
6282: # -------------------------------------------------------------- Critical Store
6283:
6284: sub cstore {
6285: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
6286: my $home='';
6287:
6288: if ($stuname) { $home=&homeserver($stuname,$domain); }
6289:
6290: $symb=&symbclean($symb);
6291: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
6292:
6293: if (!$domain) { $domain=$env{'user.domain'}; }
6294: if (!$stuname) { $stuname=$env{'user.name'}; }
6295:
6296: &devalidate($symb,$stuname,$domain);
6297:
6298: $symb=escape($symb);
6299: if (!$namespace) {
6300: unless ($namespace=$env{'request.course.id'}) {
6301: return '';
6302: }
6303: }
6304: if (!$home) { $home=$env{'user.home'}; }
6305:
6306: $$storehash{'ip'}=&get_requestor_ip();
6307: $$storehash{'host'}=$perlvar{'lonHostID'};
6308:
6309: my $namevalue='';
6310: foreach my $key (keys(%$storehash)) {
6311: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6312: }
6313: $namevalue=~s/\&$//;
6314: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
6315: return critical
6316: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
6317: }
6318:
6319: # --------------------------------------------------------------------- Restore
6320:
6321: sub restore {
6322: my ($symb,$namespace,$domain,$stuname) = @_;
6323: my $home='';
6324:
6325: if ($stuname) { $home=&homeserver($stuname,$domain); }
6326:
6327: if (!$symb) {
6328: return if ($namespace eq 'courserequests');
6329: unless ($symb=escape(&symbread())) { return ''; }
6330: } else {
6331: unless ($namespace eq 'courserequests') {
6332: $symb=&escape(&symbclean($symb));
6333: }
6334: }
6335: if (!$namespace) {
6336: unless ($namespace=$env{'request.course.id'}) {
6337: return '';
6338: }
6339: }
6340: if (!$domain) { $domain=$env{'user.domain'}; }
6341: if (!$stuname) { $stuname=$env{'user.name'}; }
6342: if (!$home) { $home=$env{'user.home'}; }
6343: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6344:
6345: my %returnhash=();
6346: foreach my $line (split(/\&/,$answer)) {
6347: my ($name,$value)=split(/\=/,$line);
6348: $returnhash{&unescape($name)}=&thaw_unescape($value);
6349: }
6350: my $version;
6351: for ($version=1;$version<=$returnhash{'version'};$version++) {
6352: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6353: $returnhash{$item}=$returnhash{$version.':'.$item};
6354: }
6355: }
6356: return %returnhash;
6357: }
6358:
6359: # ---------------------------------------------------------- Course Description
6360: #
6361: #
6362:
6363: sub coursedescription {
6364: my ($courseid,$args)=@_;
6365: $courseid=~s/^\///;
6366: $courseid=~s/\_/\//g;
6367: my ($cdomain,$cnum)=split(/\//,$courseid);
6368: my $chome=&homeserver($cnum,$cdomain);
6369: my $normalid=$cdomain.'_'.$cnum;
6370: # need to always cache even if we get errors otherwise we keep
6371: # trying and trying and trying to get the course description.
6372: my %envhash=();
6373: my %returnhash=();
6374:
6375: my $expiretime=600;
6376: if ($env{'request.course.id'} eq $normalid) {
6377: $expiretime=120;
6378: }
6379:
6380: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6381: if (!$args->{'freshen_cache'}
6382: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6383: foreach my $key (keys(%env)) {
6384: next if ($key !~ /^\Q$prefix\E(.*)/);
6385: my ($setting) = $1;
6386: $returnhash{$setting} = $env{$key};
6387: }
6388: return %returnhash;
6389: }
6390:
6391: # get the data again
6392:
6393: if (!$args->{'one_time'}) {
6394: $envhash{'course.'.$normalid.'.last_cache'}=time;
6395: }
6396:
6397: if ($chome ne 'no_host') {
6398: %returnhash=&dump('environment',$cdomain,$cnum);
6399: if (!exists($returnhash{'con_lost'})) {
6400: my $username = $env{'user.name'}; # Defult username
6401: if(defined $args->{'user'}) {
6402: $username = $args->{'user'};
6403: }
6404: $returnhash{'home'}= $chome;
6405: $returnhash{'domain'} = $cdomain;
6406: $returnhash{'num'} = $cnum;
6407: if (!defined($returnhash{'type'})) {
6408: $returnhash{'type'} = 'Course';
6409: }
6410: while (my ($name,$value) = each %returnhash) {
6411: $envhash{'course.'.$normalid.'.'.$name}=$value;
6412: }
6413: $returnhash{'url'}=&clutter($returnhash{'url'});
6414: $returnhash{'fn'}=LONCAPA::tempdir() .
6415: $username.'_'.$cdomain.'_'.$cnum;
6416: $envhash{'course.'.$normalid.'.home'}=$chome;
6417: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6418: $envhash{'course.'.$normalid.'.num'}=$cnum;
6419: }
6420: }
6421: if (!$args->{'one_time'}) {
6422: &appenv(\%envhash);
6423: }
6424: return %returnhash;
6425: }
6426:
6427: sub update_released_required {
6428: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6429: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6430: $cid = $env{'request.course.id'};
6431: $cdom = $env{'course.'.$cid.'.domain'};
6432: $cnum = $env{'course.'.$cid.'.num'};
6433: $chome = $env{'course.'.$cid.'.home'};
6434: }
6435: if ($needsrelease) {
6436: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6437: my $needsupdate;
6438: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6439: $needsupdate = 1;
6440: } else {
6441: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6442: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6443: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6444: $needsupdate = 1;
6445: }
6446: }
6447: if ($needsupdate) {
6448: my %needshash = (
6449: 'internal.releaserequired' => $needsrelease,
6450: );
6451: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6452: if ($putresult eq 'ok') {
6453: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6454: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6455: if (ref($crsinfo{$cid}) eq 'HASH') {
6456: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6457: &courseidput($cdom,\%crsinfo,$chome,'notime');
6458: }
6459: }
6460: }
6461: }
6462: return;
6463: }
6464:
6465: # -------------------------------------------------See if a user is privileged
6466:
6467: sub privileged {
6468: my ($username,$domain,$possdomains,$possroles)=@_;
6469: my $now = time;
6470: my $roles;
6471: if (ref($possroles) eq 'ARRAY') {
6472: $roles = $possroles;
6473: } else {
6474: $roles = ['dc','su'];
6475: }
6476: if (ref($possdomains) eq 'ARRAY') {
6477: my %privileged = &privileged_by_domain($possdomains,$roles);
6478: foreach my $dom (@{$possdomains}) {
6479: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6480: (ref($privileged{$dom}) eq 'HASH')) {
6481: foreach my $role (@{$roles}) {
6482: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6483: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6484: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6485: return 1 unless (($end && $end < $now) ||
6486: ($start && $start > $now));
6487: }
6488: }
6489: }
6490: }
6491: }
6492: } else {
6493: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6494: my $now = time;
6495:
6496: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
6497: my ($trole, $tend, $tstart) = split(/_/, $role);
6498: if (grep(/^\Q$trole\E$/,@{$roles})) {
6499: return 1 unless ($tend && $tend < $now)
6500: or ($tstart && $tstart > $now);
6501: }
6502: }
6503: }
6504: return 0;
6505: }
6506:
6507: sub privileged_by_domain {
6508: my ($domains,$roles) = @_;
6509: my %privileged = ();
6510: my $cachetime = 60*60*24;
6511: my $now = time;
6512: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6513: return %privileged;
6514: }
6515: foreach my $dom (@{$domains}) {
6516: next if (ref($privileged{$dom}) eq 'HASH');
6517: my $needroles;
6518: foreach my $role (@{$roles}) {
6519: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6520: if (defined($cached)) {
6521: if (ref($result) eq 'HASH') {
6522: $privileged{$dom}{$role} = $result;
6523: }
6524: } else {
6525: $needroles = 1;
6526: }
6527: }
6528: if ($needroles) {
6529: my %dompersonnel = &get_domain_roles($dom,$roles);
6530: $privileged{$dom} = {};
6531: foreach my $server (keys(%dompersonnel)) {
6532: if (ref($dompersonnel{$server}) eq 'HASH') {
6533: foreach my $item (keys(%{$dompersonnel{$server}})) {
6534: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6535: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6536: next if ($end && $end < $now);
6537: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6538: $dompersonnel{$server}{$item};
6539: }
6540: }
6541: }
6542: if (ref($privileged{$dom}) eq 'HASH') {
6543: foreach my $role (@{$roles}) {
6544: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6545: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6546: } else {
6547: my %hash = ();
6548: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6549: }
6550: }
6551: }
6552: }
6553: }
6554: return %privileged;
6555: }
6556:
6557: # -------------------------------------------------------- Get user privileges
6558:
6559: sub rolesinit {
6560: my ($domain, $username) = @_;
6561: my %userroles = ('user.login.time' => time);
6562: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6563:
6564: # firstaccess and timerinterval are related to timed maps/resources.
6565: # also, blocking can be triggered by an activating timer
6566: # it's saved in the user's %env.
6567: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6568: my %timerinterval = &dump('timerinterval', $domain, $username);
6569: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
6570: %timerintchk, %timerintenv);
6571:
6572: foreach my $key (keys(%firstaccess)) {
6573: my ($cid, $rest) = split(/\0/, $key);
6574: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6575: }
6576:
6577: foreach my $key (keys(%timerinterval)) {
6578: my ($cid,$rest) = split(/\0/,$key);
6579: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6580: }
6581:
6582: my %allroles=();
6583: my %allgroups=();
6584:
6585: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
6586: my $role = $rolesdump{$area};
6587: $area =~ s/\_\w\w$//;
6588:
6589: my ($trole, $tend, $tstart, $group_privs);
6590:
6591: if ($role =~ /^cr/) {
6592: # Custom role, defined by a user
6593: # e.g., user.role.cr/msu/smith/mynewrole
6594: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6595: $trole = $1;
6596: ($tend, $tstart) = split('_', $2);
6597: } else {
6598: $trole = $role;
6599: }
6600: } elsif ($role =~ m|^gr/|) {
6601: # Role of member in a group, defined within a course/community
6602: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6603: ($trole, $tend, $tstart) = split(/_/, $role);
6604: next if $tstart eq '-1';
6605: ($trole, $group_privs) = split(/\//, $trole);
6606: $group_privs = &unescape($group_privs);
6607: } else {
6608: # Just a normal role, defined in roles.tab
6609: ($trole, $tend, $tstart) = split(/_/,$role);
6610: }
6611:
6612: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6613: $username);
6614: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6615:
6616: # role expired or not available yet?
6617: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6618: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6619:
6620: next if $area eq '' or $trole eq '';
6621:
6622: my $spec = "$trole.$area";
6623: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6624:
6625: if ($trole =~ /^cr\//) {
6626: # Custom role, defined by a user
6627: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6628: } elsif ($trole eq 'gr') {
6629: # Role of a member in a group, defined within a course/community
6630: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6631: next;
6632: } else {
6633: # Normal role, defined in roles.tab
6634: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6635: }
6636:
6637: my $cid = $tdomain.'_'.$trest;
6638: unless ($firstaccchk{$cid}) {
6639: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6640: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6641: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6642: $coursetimerstarts{$cid}{$item};
6643: }
6644: }
6645: $firstaccchk{$cid} = 1;
6646: }
6647: unless ($timerintchk{$cid}) {
6648: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6649: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6650: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6651: $coursetimerintervals{$cid}{$item};
6652: }
6653: }
6654: $timerintchk{$cid} = 1;
6655: }
6656: }
6657:
6658: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6659: \%allroles, \%allgroups);
6660: $env{'user.adv'} = $userroles{'user.adv'};
6661: $env{'user.rar'} = $userroles{'user.rar'};
6662:
6663: return (\%userroles,\%firstaccenv,\%timerintenv);
6664: }
6665:
6666: sub set_arearole {
6667: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6668: unless ($nolog) {
6669: # log the associated role with the area
6670: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6671: }
6672: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
6673: }
6674:
6675: sub custom_roleprivs {
6676: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6677: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
6678: my $homsvr = &homeserver($rauthor,$rdomain);
6679: if (&hostname($homsvr) ne '') {
6680: my ($rdummy,$roledef)=
6681: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6682: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6683: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6684: if (defined($syspriv)) {
6685: if ($trest =~ /^$match_community$/) {
6686: $syspriv =~ s/bre\&S//;
6687: }
6688: $$allroles{'cm./'}.=':'.$syspriv;
6689: $$allroles{$spec.'./'}.=':'.$syspriv;
6690: }
6691: if ($tdomain ne '') {
6692: if (defined($dompriv)) {
6693: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6694: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6695: }
6696: if (($trest ne '') && (defined($coursepriv))) {
6697: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6698: my $rolename = $1;
6699: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6700: }
6701: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6702: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6703: }
6704: }
6705: }
6706: }
6707: }
6708:
6709: sub course_adhocrole_privs {
6710: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6711: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6712: if ($overrides{"internal.adhocpriv.$rolename"}) {
6713: my (%currprivs,%storeprivs);
6714: foreach my $item (split(/:/,$coursepriv)) {
6715: my ($priv,$restrict) = split(/\&/,$item);
6716: $currprivs{$priv} = $restrict;
6717: }
6718: my (%possadd,%possremove,%full);
6719: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6720: my ($priv,$restrict)=split(/\&/,$item);
6721: $full{$priv} = $restrict;
6722: }
6723: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6724: next if ($item eq '');
6725: my ($rule,$rest) = split(/=/,$item);
6726: next unless (($rule eq 'off') || ($rule eq 'on'));
6727: foreach my $priv (split(/:/,$rest)) {
6728: if ($priv ne '') {
6729: if ($rule eq 'off') {
6730: $possremove{$priv} = 1;
6731: } else {
6732: $possadd{$priv} = 1;
6733: }
6734: }
6735: }
6736: }
6737: foreach my $priv (sort(keys(%full))) {
6738: if (exists($currprivs{$priv})) {
6739: unless (exists($possremove{$priv})) {
6740: $storeprivs{$priv} = $currprivs{$priv};
6741: }
6742: } elsif (exists($possadd{$priv})) {
6743: $storeprivs{$priv} = $full{$priv};
6744: }
6745: }
6746: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6747: }
6748: return $coursepriv;
6749: }
6750:
6751: sub group_roleprivs {
6752: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6753: my $access = 1;
6754: my $now = time;
6755: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6756: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6757: if ($access) {
6758: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
6759: $$allgroups{$course}{$group} .=':'.$group_privs;
6760: }
6761: }
6762:
6763: sub standard_roleprivs {
6764: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6765: if (defined($pr{$trole.':s'})) {
6766: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6767: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6768: }
6769: if ($tdomain ne '') {
6770: if (defined($pr{$trole.':d'})) {
6771: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6772: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6773: }
6774: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6775: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6776: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6777: }
6778: }
6779: }
6780:
6781: sub set_userprivs {
6782: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
6783: my $author=0;
6784: my $adv=0;
6785: my $rar=0;
6786: my %grouproles = ();
6787: if (keys(%{$allgroups}) > 0) {
6788: my @groupkeys;
6789: foreach my $role (keys(%{$allroles})) {
6790: push(@groupkeys,$role);
6791: }
6792: if (ref($groups_roles) eq 'HASH') {
6793: foreach my $key (keys(%{$groups_roles})) {
6794: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6795: push(@groupkeys,$key);
6796: }
6797: }
6798: }
6799: if (@groupkeys > 0) {
6800: foreach my $role (@groupkeys) {
6801: my ($trole,$area,$sec,$extendedarea);
6802: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6803: $trole = $1;
6804: $area = $2;
6805: $sec = $3;
6806: $extendedarea = $area.$sec;
6807: if (exists($$allgroups{$area})) {
6808: foreach my $group (keys(%{$$allgroups{$area}})) {
6809: my $spec = $trole.'.'.$extendedarea;
6810: $grouproles{$spec.'.'.$area.'/'.$group} =
6811: $$allgroups{$area}{$group};
6812: }
6813: }
6814: }
6815: }
6816: }
6817: }
6818: foreach my $group (keys(%grouproles)) {
6819: $$allroles{$group} = $grouproles{$group};
6820: }
6821: foreach my $role (keys(%{$allroles})) {
6822: my %thesepriv;
6823: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
6824: foreach my $item (split(/:/,$$allroles{$role})) {
6825: if ($item ne '') {
6826: my ($privilege,$restrictions)=split(/&/,$item);
6827: if ($restrictions eq '') {
6828: $thesepriv{$privilege}='F';
6829: } elsif ($thesepriv{$privilege} ne 'F') {
6830: $thesepriv{$privilege}.=$restrictions;
6831: }
6832: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
6833: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
6834: }
6835: }
6836: my $thesestr='';
6837: foreach my $priv (sort(keys(%thesepriv))) {
6838: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6839: }
6840: $userroles->{'user.priv.'.$role} = $thesestr;
6841: }
6842: return ($author,$adv,$rar);
6843: }
6844:
6845: sub role_status {
6846: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
6847: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
6848: my ($one,$two) = split(m{\./},$rolekey,2);
6849: (undef,undef,$$role) = split(/\./,$one,3);
6850: unless (!defined($$role) || $$role eq '') {
6851: $$where = '/'.$two;
6852: $$trolecode=$$role.'.'.$$where;
6853: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6854: $$tstatus='is';
6855: if ($$tstart && $$tstart>$update) {
6856: $$tstatus='future';
6857: if ($$tstart<$now) {
6858: if ($$tstart && $$tstart>$refresh) {
6859: if (($$where ne '') && ($$role ne '')) {
6860: my (%allroles,%allgroups,$group_privs,
6861: %groups_roles,@rolecodes);
6862: my %userroles = (
6863: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6864: );
6865: @rolecodes = ('cm');
6866: my $spec=$$role.'.'.$$where;
6867: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6868: if ($$role =~ /^cr\//) {
6869: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
6870: push(@rolecodes,'cr');
6871: } elsif ($$role eq 'gr') {
6872: push(@rolecodes,$$role);
6873: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6874: $env{'user.name'});
6875: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
6876: (undef,my $group_privs) = split(/\//,$trole);
6877: $group_privs = &unescape($group_privs);
6878: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
6879: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
6880: &get_groups_roles($tdomain,$trest,
6881: \%course_roles,\@rolecodes,
6882: \%groups_roles);
6883: } else {
6884: push(@rolecodes,$$role);
6885: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6886: }
6887: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6888: \%groups_roles);
6889: &appenv(\%userroles,\@rolecodes);
6890: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
6891: }
6892: }
6893: $$tstatus = 'is';
6894: }
6895: }
6896: if ($$tend) {
6897: if ($$tend<$update) {
6898: $$tstatus='expired';
6899: } elsif ($$tend<$now) {
6900: $$tstatus='will_not';
6901: }
6902: }
6903: }
6904: }
6905: }
6906:
6907: sub get_groups_roles {
6908: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6909: return unless((ref($cdom_courseroles) eq 'HASH') &&
6910: (ref($rolecodes) eq 'ARRAY') &&
6911: (ref($groups_roles) eq 'HASH'));
6912: if (keys(%{$cdom_courseroles}) > 0) {
6913: my ($cnum) = ($rest =~ /^($match_courseid)/);
6914: if ($cdom ne '' && $cnum ne '') {
6915: foreach my $key (keys(%{$cdom_courseroles})) {
6916: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6917: my $crsrole = $1;
6918: my $crssec = $2;
6919: if ($crsrole =~ /^cr/) {
6920: unless (grep(/^cr$/,@{$rolecodes})) {
6921: push(@{$rolecodes},'cr');
6922: }
6923: } else {
6924: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6925: push(@{$rolecodes},$crsrole);
6926: }
6927: }
6928: my $rolekey = "$crsrole./$cdom/$cnum";
6929: if ($crssec ne '') {
6930: $rolekey .= "/$crssec";
6931: }
6932: $rolekey .= './';
6933: $groups_roles->{$rolekey} = $rolecodes;
6934: }
6935: }
6936: }
6937: }
6938: return;
6939: }
6940:
6941: sub delete_env_groupprivs {
6942: my ($where,$courseroles,$possroles) = @_;
6943: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6944: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6945: unless (ref($courseroles->{$udom}) eq 'HASH') {
6946: %{$courseroles->{$udom}} =
6947: &get_my_roles('','','userroles',['active'],
6948: $possroles,[$udom],1);
6949: }
6950: if (ref($courseroles->{$udom}) eq 'HASH') {
6951: foreach my $item (keys(%{$courseroles->{$udom}})) {
6952: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6953: my $area = '/'.$cdom.'/'.$cnum;
6954: my $privkey = "user.priv.$crsrole.$area";
6955: if ($crssec ne '') {
6956: $privkey .= '/'.$crssec;
6957: }
6958: $privkey .= ".$area/$group";
6959: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6960: }
6961: }
6962: return;
6963: }
6964:
6965: sub check_adhoc_privs {
6966: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
6967: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
6968: if ($sec) {
6969: $cckey .= '/'.$sec;
6970: }
6971: my $setprivs;
6972: if ($env{$cckey}) {
6973: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
6974: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
6975: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
6976: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
6977: $setprivs = 1;
6978: }
6979: } else {
6980: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
6981: $setprivs = 1;
6982: }
6983: return $setprivs;
6984: }
6985:
6986: sub set_adhoc_privileges {
6987: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
6988: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
6989: my $area = '/'.$dcdom.'/'.$pickedcourse;
6990: if ($sec ne '') {
6991: $area .= '/'.$sec;
6992: }
6993: my $spec = $role.'.'.$area;
6994: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
6995: $env{'user.name'},1);
6996: my %rolehash = ();
6997: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6998: my $rolename = $1;
6999: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
7000: my %domdef = &get_domain_defaults($dcdom);
7001: if (ref($domdef{'adhocroles'}) eq 'HASH') {
7002: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
7003: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
7004: }
7005: }
7006: } else {
7007: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
7008: }
7009: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
7010: &appenv(\%userroles,[$role,'cm']);
7011: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
7012: unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
7013: ($caller eq 'tiny')) {
7014: &appenv( {'request.role' => $spec,
7015: 'request.role.domain' => $dcdom,
7016: 'request.course.sec' => $sec,
7017: }
7018: );
7019: my $tadv=0;
7020: if (&allowed('adv') eq 'F') { $tadv=1; }
7021: &appenv({'request.role.adv' => $tadv});
7022: }
7023: }
7024:
7025: # --------------------------------------------------------------- get interface
7026:
7027: sub get {
7028: my ($namespace,$storearr,$udomain,$uname)=@_;
7029: my $items='';
7030: foreach my $item (@$storearr) {
7031: $items.=&escape($item).'&';
7032: }
7033: $items=~s/\&$//;
7034: if (!$udomain) { $udomain=$env{'user.domain'}; }
7035: if (!$uname) { $uname=$env{'user.name'}; }
7036: my $uhome=&homeserver($uname,$udomain);
7037:
7038: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
7039: my @pairs=split(/\&/,$rep);
7040: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
7041: return @pairs;
7042: }
7043: my %returnhash=();
7044: my $i=0;
7045: foreach my $item (@$storearr) {
7046: $returnhash{$item}=&thaw_unescape($pairs[$i]);
7047: $i++;
7048: }
7049: return %returnhash;
7050: }
7051:
7052: # --------------------------------------------------------------- del interface
7053:
7054: sub del {
7055: my ($namespace,$storearr,$udomain,$uname)=@_;
7056: my $items='';
7057: foreach my $item (@$storearr) {
7058: $items.=&escape($item).'&';
7059: }
7060:
7061: $items=~s/\&$//;
7062: if (!$udomain) { $udomain=$env{'user.domain'}; }
7063: if (!$uname) { $uname=$env{'user.name'}; }
7064: my $uhome=&homeserver($uname,$udomain);
7065: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
7066: }
7067:
7068: # -------------------------------------------------------------- dump interface
7069:
7070: sub unserialize {
7071: my ($rep, $escapedkeys) = @_;
7072:
7073: return {} if $rep =~ /^error/;
7074:
7075: my %returnhash=();
7076: foreach my $item (split(/\&/,$rep)) {
7077: my ($key, $value) = split(/=/, $item, 2);
7078: $key = unescape($key) unless $escapedkeys;
7079: next if $key =~ /^error: 2 /;
7080: $returnhash{$key} = &thaw_unescape($value);
7081: }
7082: #return %returnhash;
7083: return \%returnhash;
7084: }
7085:
7086: # see Lond::dump_with_regexp
7087: # if $escapedkeys hash keys won't get unescaped.
7088: sub dump {
7089: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
7090: if (!$udomain) { $udomain=$env{'user.domain'}; }
7091: if (!$uname) { $uname=$env{'user.name'}; }
7092: my $uhome=&homeserver($uname,$udomain);
7093:
7094: if ($regexp) {
7095: $regexp=&escape($regexp);
7096: } else {
7097: $regexp='.';
7098: }
7099: if (grep { $_ eq $uhome } current_machine_ids()) {
7100: # user is hosted on this machine
7101: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
7102: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
7103: return %{unserialize($reply, $escapedkeys)};
7104: }
7105: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
7106: my @pairs=split(/\&/,$rep);
7107: my %returnhash=();
7108: if (!($rep =~ /^error/ )) {
7109: foreach my $item (@pairs) {
7110: my ($key,$value)=split(/=/,$item,2);
7111: $key = unescape($key) unless $escapedkeys;
7112: #$key = &unescape($key);
7113: next if ($key =~ /^error: 2 /);
7114: $returnhash{$key}=&thaw_unescape($value);
7115: }
7116: }
7117: return %returnhash;
7118: }
7119:
7120:
7121: # --------------------------------------------------------- dumpstore interface
7122:
7123: sub dumpstore {
7124: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
7125: # same as dump but keys must be escaped. They may contain colon separated
7126: # lists of values that may themself contain colons (e.g. symbs).
7127: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
7128: }
7129:
7130: # -------------------------------------------------------------- keys interface
7131:
7132: sub getkeys {
7133: my ($namespace,$udomain,$uname)=@_;
7134: if (!$udomain) { $udomain=$env{'user.domain'}; }
7135: if (!$uname) { $uname=$env{'user.name'}; }
7136: my $uhome=&homeserver($uname,$udomain);
7137: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
7138: my @keyarray=();
7139: foreach my $key (split(/\&/,$rep)) {
7140: next if ($key =~ /^error: 2 /);
7141: push(@keyarray,&unescape($key));
7142: }
7143: return @keyarray;
7144: }
7145:
7146: # --------------------------------------------------------------- currentdump
7147: sub currentdump {
7148: my ($courseid,$sdom,$sname)=@_;
7149: $courseid = $env{'request.course.id'} if (! defined($courseid));
7150: $sdom = $env{'user.domain'} if (! defined($sdom));
7151: $sname = $env{'user.name'} if (! defined($sname));
7152: my $uhome = &homeserver($sname,$sdom);
7153: my $rep;
7154:
7155: if (grep { $_ eq $uhome } current_machine_ids()) {
7156: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
7157: $courseid)));
7158: } else {
7159: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
7160: }
7161:
7162: return if ($rep =~ /^(error:|no_such_host)/);
7163: #
7164: my %returnhash=();
7165: #
7166: if ($rep eq 'unknown_cmd') {
7167: # an old lond will not know currentdump
7168: # Do a dump and make it look like a currentdump
7169: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
7170: return if ($tmp[0] =~ /^(error:|no_such_host)/);
7171: my %hash = @tmp;
7172: @tmp=();
7173: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
7174: } else {
7175: my @pairs=split(/\&/,$rep);
7176: foreach my $pair (@pairs) {
7177: my ($key,$value)=split(/=/,$pair,2);
7178: my ($symb,$param) = split(/:/,$key);
7179: $returnhash{&unescape($symb)}->{&unescape($param)} =
7180: &thaw_unescape($value);
7181: }
7182: }
7183: return %returnhash;
7184: }
7185:
7186: sub convert_dump_to_currentdump{
7187: my %hash = %{shift()};
7188: my %returnhash;
7189: # Code ripped from lond, essentially. The only difference
7190: # here is the unescaping done by lonnet::dump(). Conceivably
7191: # we might run in to problems with parameter names =~ /^v\./
7192: while (my ($key,$value) = each(%hash)) {
7193: my ($v,$symb,$param) = split(/:/,$key);
7194: $symb = &unescape($symb);
7195: $param = &unescape($param);
7196: next if ($v eq 'version' || $symb eq 'keys');
7197: next if (exists($returnhash{$symb}) &&
7198: exists($returnhash{$symb}->{$param}) &&
7199: $returnhash{$symb}->{'v.'.$param} > $v);
7200: $returnhash{$symb}->{$param}=$value;
7201: $returnhash{$symb}->{'v.'.$param}=$v;
7202: }
7203: #
7204: # Remove all of the keys in the hashes which keep track of
7205: # the version of the parameter.
7206: while (my ($symb,$param_hash) = each(%returnhash)) {
7207: # use a foreach because we are going to delete from the hash.
7208: foreach my $key (keys(%$param_hash)) {
7209: delete($param_hash->{$key}) if ($key =~ /^v\./);
7210: }
7211: }
7212: return \%returnhash;
7213: }
7214:
7215: # ------------------------------------------------------ critical inc interface
7216:
7217: sub cinc {
7218: return &inc(@_,'critical');
7219: }
7220:
7221: # --------------------------------------------------------------- inc interface
7222:
7223: sub inc {
7224: my ($namespace,$store,$udomain,$uname,$critical) = @_;
7225: if (!$udomain) { $udomain=$env{'user.domain'}; }
7226: if (!$uname) { $uname=$env{'user.name'}; }
7227: my $uhome=&homeserver($uname,$udomain);
7228: my $items='';
7229: if (! ref($store)) {
7230: # got a single value, so use that instead
7231: $items = &escape($store).'=&';
7232: } elsif (ref($store) eq 'SCALAR') {
7233: $items = &escape($$store).'=&';
7234: } elsif (ref($store) eq 'ARRAY') {
7235: $items = join('=&',map {&escape($_);} @{$store});
7236: } elsif (ref($store) eq 'HASH') {
7237: while (my($key,$value) = each(%{$store})) {
7238: $items.= &escape($key).'='.&escape($value).'&';
7239: }
7240: }
7241: $items=~s/\&$//;
7242: if ($critical) {
7243: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
7244: } else {
7245: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
7246: }
7247: }
7248:
7249: # --------------------------------------------------------------- put interface
7250:
7251: sub put {
7252: my ($namespace,$storehash,$udomain,$uname)=@_;
7253: if (!$udomain) { $udomain=$env{'user.domain'}; }
7254: if (!$uname) { $uname=$env{'user.name'}; }
7255: my $uhome=&homeserver($uname,$udomain);
7256: my $items='';
7257: foreach my $item (keys(%$storehash)) {
7258: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
7259: }
7260: $items=~s/\&$//;
7261: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
7262: }
7263:
7264: # ------------------------------------------------------------ newput interface
7265:
7266: sub newput {
7267: my ($namespace,$storehash,$udomain,$uname)=@_;
7268: if (!$udomain) { $udomain=$env{'user.domain'}; }
7269: if (!$uname) { $uname=$env{'user.name'}; }
7270: my $uhome=&homeserver($uname,$udomain);
7271: my $items='';
7272: foreach my $key (keys(%$storehash)) {
7273: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7274: }
7275: $items=~s/\&$//;
7276: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
7277: }
7278:
7279: # --------------------------------------------------------- putstore interface
7280:
7281: sub putstore {
7282: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
7283: if (!$udomain) { $udomain=$env{'user.domain'}; }
7284: if (!$uname) { $uname=$env{'user.name'}; }
7285: my $uhome=&homeserver($uname,$udomain);
7286: my $items='';
7287: foreach my $key (keys(%$storehash)) {
7288: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7289: }
7290: $items=~s/\&$//;
7291: my $esc_symb=&escape($symb);
7292: my $esc_v=&escape($version);
7293: my $reply =
7294: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
7295: $uhome);
7296: if (($tolog) && ($reply eq 'ok')) {
7297: my $namevalue='';
7298: foreach my $key (keys(%{$storehash})) {
7299: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7300: }
7301: my $ip = &get_requestor_ip();
7302: $namevalue .= 'ip='.&escape($ip).
7303: '&host='.&escape($perlvar{'lonHostID'}).
7304: '&version='.$esc_v.
7305: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
7306: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
7307: }
7308: if ($reply eq 'unknown_cmd') {
7309: # gfall back to way things use to be done
7310: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7311: $uname);
7312: }
7313: return $reply;
7314: }
7315:
7316: sub old_putstore {
7317: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
7318: if (!$udomain) { $udomain=$env{'user.domain'}; }
7319: if (!$uname) { $uname=$env{'user.name'}; }
7320: my $uhome=&homeserver($uname,$udomain);
7321: my %newstorehash;
7322: foreach my $item (keys(%$storehash)) {
7323: my $key = $version.':'.&escape($symb).':'.$item;
7324: $newstorehash{$key} = $storehash->{$item};
7325: }
7326: my $items='';
7327: my %allitems = ();
7328: foreach my $item (keys(%newstorehash)) {
7329: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
7330: my $key = $1.':keys:'.$2;
7331: $allitems{$key} .= $3.':';
7332: }
7333: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
7334: }
7335: foreach my $item (keys(%allitems)) {
7336: $allitems{$item} =~ s/\:$//;
7337: $items.= $item.'='.$allitems{$item}.'&';
7338: }
7339: $items=~s/\&$//;
7340: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
7341: }
7342:
7343: # ------------------------------------------------------ critical put interface
7344:
7345: sub cput {
7346: my ($namespace,$storehash,$udomain,$uname)=@_;
7347: if (!$udomain) { $udomain=$env{'user.domain'}; }
7348: if (!$uname) { $uname=$env{'user.name'}; }
7349: my $uhome=&homeserver($uname,$udomain);
7350: my $items='';
7351: foreach my $item (keys(%$storehash)) {
7352: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
7353: }
7354: $items=~s/\&$//;
7355: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
7356: }
7357:
7358: # -------------------------------------------------------------- eget interface
7359:
7360: sub eget {
7361: my ($namespace,$storearr,$udomain,$uname)=@_;
7362: my $items='';
7363: foreach my $item (@$storearr) {
7364: $items.=&escape($item).'&';
7365: }
7366: $items=~s/\&$//;
7367: if (!$udomain) { $udomain=$env{'user.domain'}; }
7368: if (!$uname) { $uname=$env{'user.name'}; }
7369: my $uhome=&homeserver($uname,$udomain);
7370: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
7371: my @pairs=split(/\&/,$rep);
7372: my %returnhash=();
7373: my $i=0;
7374: foreach my $item (@$storearr) {
7375: $returnhash{$item}=&thaw_unescape($pairs[$i]);
7376: $i++;
7377: }
7378: return %returnhash;
7379: }
7380:
7381: # ------------------------------------------------------------ tmpput interface
7382: sub tmpput {
7383: my ($storehash,$server,$context)=@_;
7384: my $items='';
7385: foreach my $item (keys(%$storehash)) {
7386: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
7387: }
7388: $items=~s/\&$//;
7389: if (defined($context)) {
7390: $items .= ':'.&escape($context);
7391: }
7392: return &reply("tmpput:$items",$server);
7393: }
7394:
7395: # ------------------------------------------------------------ tmpget interface
7396: sub tmpget {
7397: my ($token,$server)=@_;
7398: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7399: my $rep=&reply("tmpget:$token",$server);
7400: my %returnhash;
7401: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7402: return %returnhash;
7403: }
7404: foreach my $item (split(/\&/,$rep)) {
7405: my ($key,$value)=split(/=/,$item);
7406: $returnhash{&unescape($key)}=&thaw_unescape($value);
7407: }
7408: return %returnhash;
7409: }
7410:
7411: # ------------------------------------------------------------ tmpdel interface
7412: sub tmpdel {
7413: my ($token,$server)=@_;
7414: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7415: return &reply("tmpdel:$token",$server);
7416: }
7417:
7418: # ------------------------------------------------------------ get_timebased_id
7419:
7420: sub get_timebased_id {
7421: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7422: $maxtries) = @_;
7423: my ($newid,$error,$dellock);
7424: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7425: return ('','ok','invalid call to get suffix');
7426: }
7427:
7428: # set defaults for any optional args for which values were not supplied
7429: if ($who eq '') {
7430: $who = $env{'user.name'}.':'.$env{'user.domain'};
7431: }
7432: if (!$locktries) {
7433: $locktries = 3;
7434: }
7435: if (!$maxtries) {
7436: $maxtries = 10;
7437: }
7438:
7439: if (($cdom eq '') || ($cnum eq '')) {
7440: if ($env{'request.course.id'}) {
7441: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7442: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7443: }
7444: if (($cdom eq '') || ($cnum eq '')) {
7445: return ('','ok','call to get suffix not in course context');
7446: }
7447: }
7448:
7449: # construct locking item
7450: my $lockhash = {
7451: $prefix."\0".'locked_'.$keyid => $who,
7452: };
7453: my $tries = 0;
7454:
7455: # attempt to get lock on nohist_$namespace file
7456: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7457: while (($gotlock ne 'ok') && $tries <$locktries) {
7458: $tries ++;
7459: sleep 1;
7460: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7461: }
7462:
7463: # attempt to get unique identifier, based on current timestamp
7464: if ($gotlock eq 'ok') {
7465: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
7466: my $id = time;
7467: $newid = $id;
7468: if ($idtype eq 'addcode') {
7469: $newid .= &sixnum_code();
7470: }
7471: my $idtries = 0;
7472: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7473: if ($idtype eq 'concat') {
7474: $newid = $id.$idtries;
7475: } elsif ($idtype eq 'addcode') {
7476: $newid = $newid.&sixnum_code();
7477: } else {
7478: $newid ++;
7479: }
7480: $idtries ++;
7481: }
7482: if (!exists($inuse{$prefix."\0".$newid})) {
7483: my %new_item = (
7484: $prefix."\0".$newid => $who,
7485: );
7486: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
7487: $cdom,$cnum);
7488: if ($putresult ne 'ok') {
7489: undef($newid);
7490: $error = 'error saving new item: '.$putresult;
7491: }
7492: } else {
7493: undef($newid);
7494: $error = ('error: no unique suffix available for the new item ');
7495: }
7496: # remove lock
7497: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7498: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7499: } else {
7500: $error = "error: could not obtain lockfile\n";
7501: $dellock = 'ok';
7502: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7503: $dellock = 'nolock';
7504: }
7505: }
7506: return ($newid,$dellock,$error);
7507: }
7508:
7509: sub sixnum_code {
7510: my $code;
7511: for (0..6) {
7512: $code .= int( rand(9) );
7513: }
7514: return $code;
7515: }
7516:
7517: # -------------------------------------------------- portfolio access checking
7518:
7519: sub portfolio_access {
7520: my ($requrl,$clientip) = @_;
7521: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
7522: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
7523: if ($result) {
7524: my %setters;
7525: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7526: my ($startblock,$endblock) =
7527: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
7528: if ($startblock && $endblock) {
7529: return 'B';
7530: }
7531: } else {
7532: my ($startblock,$endblock) =
7533: &Apache::loncommon::blockcheck(\%setters,'port');
7534: if ($startblock && $endblock) {
7535: return 'B';
7536: }
7537: }
7538: }
7539: if ($result eq 'ok') {
7540: return 'F';
7541: } elsif ($result =~ /^[^:]+:guest_/) {
7542: return 'A';
7543: }
7544: return '';
7545: }
7546:
7547: sub get_portfolio_access {
7548: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
7549:
7550: if (!ref($access_hash)) {
7551: my $current_perms = &get_portfile_permissions($udom,$unum);
7552: my %access_controls = &get_access_controls($current_perms,$group,
7553: $file_name);
7554: $access_hash = $access_controls{$file_name};
7555: }
7556:
7557: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
7558: my $now = time;
7559: if (ref($access_hash) eq 'HASH') {
7560: foreach my $key (keys(%{$access_hash})) {
7561: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7562: if ($start > $now) {
7563: next;
7564: }
7565: if ($end && $end<$now) {
7566: next;
7567: }
7568: if ($scope eq 'public') {
7569: $public = $key;
7570: last;
7571: } elsif ($scope eq 'guest') {
7572: $guest = $key;
7573: } elsif ($scope eq 'domains') {
7574: push(@domains,$key);
7575: } elsif ($scope eq 'users') {
7576: push(@users,$key);
7577: } elsif ($scope eq 'course') {
7578: push(@courses,$key);
7579: } elsif ($scope eq 'group') {
7580: push(@groups,$key);
7581: } elsif ($scope eq 'ip') {
7582: push(@ips,$key);
7583: }
7584: }
7585: if ($public) {
7586: return 'ok';
7587: } elsif (@ips > 0) {
7588: my $allowed;
7589: foreach my $ipkey (@ips) {
7590: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7591: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7592: $allowed = 1;
7593: last;
7594: }
7595: }
7596: }
7597: if ($allowed) {
7598: return 'ok';
7599: }
7600: }
7601: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7602: if ($guest) {
7603: return $guest;
7604: }
7605: } else {
7606: if (@domains > 0) {
7607: foreach my $domkey (@domains) {
7608: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7609: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7610: return 'ok';
7611: }
7612: }
7613: }
7614: }
7615: if (@users > 0) {
7616: foreach my $userkey (@users) {
7617: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7618: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7619: if (ref($item) eq 'HASH') {
7620: if (($item->{'uname'} eq $env{'user.name'}) &&
7621: ($item->{'udom'} eq $env{'user.domain'})) {
7622: return 'ok';
7623: }
7624: }
7625: }
7626: }
7627: }
7628: }
7629: my %roleshash;
7630: my @courses_and_groups = @courses;
7631: push(@courses_and_groups,@groups);
7632: if (@courses_and_groups > 0) {
7633: my (%allgroups,%allroles);
7634: my ($start,$end,$role,$sec,$group);
7635: foreach my $envkey (%env) {
7636: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
7637: my $cid = $2.'_'.$3;
7638: if ($1 eq 'gr') {
7639: $group = $4;
7640: $allgroups{$cid}{$group} = $env{$envkey};
7641: } else {
7642: if ($4 eq '') {
7643: $sec = 'none';
7644: } else {
7645: $sec = $4;
7646: }
7647: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7648: }
7649: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
7650: my $cid = $2.'_'.$3;
7651: if ($4 eq '') {
7652: $sec = 'none';
7653: } else {
7654: $sec = $4;
7655: }
7656: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7657: }
7658: }
7659: if (keys(%allroles) == 0) {
7660: return;
7661: }
7662: foreach my $key (@courses_and_groups) {
7663: my %content = %{$$access_hash{$key}};
7664: my $cnum = $content{'number'};
7665: my $cdom = $content{'domain'};
7666: my $cid = $cdom.'_'.$cnum;
7667: if (!exists($allroles{$cid})) {
7668: next;
7669: }
7670: foreach my $role_id (keys(%{$content{'roles'}})) {
7671: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7672: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7673: my @status = @{$content{'roles'}{$role_id}{'access'}};
7674: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7675: foreach my $role (keys(%{$allroles{$cid}})) {
7676: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7677: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7678: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7679: if (grep/^all$/,@sections) {
7680: return 'ok';
7681: } else {
7682: if (grep/^$sec$/,@sections) {
7683: return 'ok';
7684: }
7685: }
7686: }
7687: }
7688: if (keys(%{$allgroups{$cid}}) == 0) {
7689: if (grep/^none$/,@groups) {
7690: return 'ok';
7691: }
7692: } else {
7693: if (grep/^all$/,@groups) {
7694: return 'ok';
7695: }
7696: foreach my $group (keys(%{$allgroups{$cid}})) {
7697: if (grep/^$group$/,@groups) {
7698: return 'ok';
7699: }
7700: }
7701: }
7702: }
7703: }
7704: }
7705: }
7706: }
7707: if ($guest) {
7708: return $guest;
7709: }
7710: }
7711: }
7712: return;
7713: }
7714:
7715: sub course_group_datechecker {
7716: my ($dates,$now,$status) = @_;
7717: my ($start,$end) = split(/\./,$dates);
7718: if (!$start && !$end) {
7719: return 'ok';
7720: }
7721: if (grep/^active$/,@{$status}) {
7722: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7723: return 'ok';
7724: }
7725: }
7726: if (grep/^previous$/,@{$status}) {
7727: if ($end > $now ) {
7728: return 'ok';
7729: }
7730: }
7731: if (grep/^future$/,@{$status}) {
7732: if ($start > $now) {
7733: return 'ok';
7734: }
7735: }
7736: return;
7737: }
7738:
7739: sub parse_portfolio_url {
7740: my ($url) = @_;
7741:
7742: my ($type,$udom,$unum,$group,$file_name);
7743:
7744: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
7745: $type = 1;
7746: $udom = $1;
7747: $unum = $2;
7748: $file_name = $3;
7749: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
7750: $type = 2;
7751: $udom = $1;
7752: $unum = $2;
7753: $group = $3;
7754: $file_name = $3.'/'.$4;
7755: }
7756: if (wantarray) {
7757: return ($type,$udom,$unum,$file_name,$group);
7758: }
7759: return $type;
7760: }
7761:
7762: sub is_portfolio_url {
7763: my ($url) = @_;
7764: return scalar(&parse_portfolio_url($url));
7765: }
7766:
7767: sub is_portfolio_file {
7768: my ($file) = @_;
7769: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
7770: return 1;
7771: }
7772: return;
7773: }
7774:
7775: sub usertools_access {
7776: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
7777: my ($access,%tools);
7778: if ($context eq '') {
7779: $context = 'tools';
7780: }
7781: if ($context eq 'requestcourses') {
7782: %tools = (
7783: official => 1,
7784: unofficial => 1,
7785: community => 1,
7786: textbook => 1,
7787: placement => 1,
7788: lti => 1,
7789: );
7790: } elsif ($context eq 'requestauthor') {
7791: %tools = (
7792: requestauthor => 1,
7793: );
7794: } else {
7795: %tools = (
7796: aboutme => 1,
7797: blog => 1,
7798: webdav => 1,
7799: portfolio => 1,
7800: );
7801: }
7802: return if (!defined($tools{$tool}));
7803:
7804: if (($udom eq '') || ($uname eq '')) {
7805: $udom = $env{'user.domain'};
7806: $uname = $env{'user.name'};
7807: }
7808:
7809: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7810: if ($action ne 'reload') {
7811: if ($context eq 'requestcourses') {
7812: return $env{'environment.canrequest.'.$tool};
7813: } elsif ($context eq 'requestauthor') {
7814: return $env{'environment.canrequest.author'};
7815: } else {
7816: return $env{'environment.availabletools.'.$tool};
7817: }
7818: }
7819: }
7820:
7821: my ($toolstatus,$inststatus,$envkey);
7822: if ($context eq 'requestauthor') {
7823: $envkey = $context;
7824: } else {
7825: $envkey = $context.'.'.$tool;
7826: }
7827:
7828: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7829: ($action ne 'reload')) {
7830: $toolstatus = $env{'environment.'.$envkey};
7831: $inststatus = $env{'environment.inststatus'};
7832: } else {
7833: if (ref($userenvref) eq 'HASH') {
7834: $toolstatus = $userenvref->{$envkey};
7835: $inststatus = $userenvref->{'inststatus'};
7836: } else {
7837: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7838: $toolstatus = $userenv{$envkey};
7839: $inststatus = $userenv{'inststatus'};
7840: }
7841: }
7842:
7843: if ($toolstatus ne '') {
7844: if ($toolstatus) {
7845: $access = 1;
7846: } else {
7847: $access = 0;
7848: }
7849: return $access;
7850: }
7851:
7852: my ($is_adv,%domdef);
7853: if (ref($is_advref) eq 'HASH') {
7854: $is_adv = $is_advref->{'is_adv'};
7855: } else {
7856: $is_adv = &is_advanced_user($udom,$uname);
7857: }
7858: if (ref($domdefref) eq 'HASH') {
7859: %domdef = %{$domdefref};
7860: } else {
7861: %domdef = &get_domain_defaults($udom);
7862: }
7863: if (ref($domdef{$tool}) eq 'HASH') {
7864: if ($is_adv) {
7865: if ($domdef{$tool}{'_LC_adv'} ne '') {
7866: if ($domdef{$tool}{'_LC_adv'}) {
7867: $access = 1;
7868: } else {
7869: $access = 0;
7870: }
7871: return $access;
7872: }
7873: }
7874: if ($inststatus ne '') {
7875: my ($hasaccess,$hasnoaccess);
7876: foreach my $affiliation (split(/:/,$inststatus)) {
7877: if ($domdef{$tool}{$affiliation} ne '') {
7878: if ($domdef{$tool}{$affiliation}) {
7879: $hasaccess = 1;
7880: } else {
7881: $hasnoaccess = 1;
7882: }
7883: }
7884: }
7885: if ($hasaccess || $hasnoaccess) {
7886: if ($hasaccess) {
7887: $access = 1;
7888: } elsif ($hasnoaccess) {
7889: $access = 0;
7890: }
7891: return $access;
7892: }
7893: } else {
7894: if ($domdef{$tool}{'default'} ne '') {
7895: if ($domdef{$tool}{'default'}) {
7896: $access = 1;
7897: } elsif ($domdef{$tool}{'default'} == 0) {
7898: $access = 0;
7899: }
7900: return $access;
7901: }
7902: }
7903: } else {
7904: if (($context eq 'tools') && ($tool ne 'webdav')) {
7905: $access = 1;
7906: } else {
7907: $access = 0;
7908: }
7909: return $access;
7910: }
7911: }
7912:
7913: sub is_course_owner {
7914: my ($cdom,$cnum,$udom,$uname) = @_;
7915: if (($udom eq '') || ($uname eq '')) {
7916: $udom = $env{'user.domain'};
7917: $uname = $env{'user.name'};
7918: }
7919: unless (($udom eq '') || ($uname eq '')) {
7920: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7921: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7922: return 1;
7923: } else {
7924: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7925: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7926: return 1;
7927: }
7928: }
7929: }
7930: }
7931: return;
7932: }
7933:
7934: sub is_advanced_user {
7935: my ($udom,$uname) = @_;
7936: if ($udom ne '' && $uname ne '') {
7937: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7938: if (wantarray) {
7939: return ($env{'user.adv'},$env{'user.author'});
7940: } else {
7941: return $env{'user.adv'};
7942: }
7943: }
7944: }
7945: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7946: my %allroles;
7947: my ($is_adv,$is_author);
7948: foreach my $role (keys(%roleshash)) {
7949: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7950: my $area = '/'.$tdomain.'/'.$trest;
7951: if ($sec ne '') {
7952: $area .= '/'.$sec;
7953: }
7954: if (($area ne '') && ($trole ne '')) {
7955: my $spec=$trole.'.'.$area;
7956: if ($trole =~ /^cr\//) {
7957: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7958: } elsif ($trole ne 'gr') {
7959: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7960: }
7961: if ($trole eq 'au') {
7962: $is_author = 1;
7963: }
7964: }
7965: }
7966: foreach my $role (keys(%allroles)) {
7967: last if ($is_adv);
7968: foreach my $item (split(/:/,$allroles{$role})) {
7969: if ($item ne '') {
7970: my ($privilege,$restrictions)=split(/&/,$item);
7971: if ($privilege eq 'adv') {
7972: $is_adv = 1;
7973: last;
7974: }
7975: }
7976: }
7977: }
7978: if (wantarray) {
7979: return ($is_adv,$is_author);
7980: }
7981: return $is_adv;
7982: }
7983:
7984: sub check_can_request {
7985: my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
7986: my $canreq = 0;
7987: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7988: $uname = $env{'user.name'};
7989: $udom = $env{'user.domain'};
7990: }
7991: my ($types,$typename) = &Apache::loncommon::course_types();
7992: my @options = ('approval','validate','autolimit');
7993: my $optregex = join('|',@options);
7994: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7995: foreach my $type (@{$types}) {
7996: if (&usertools_access($uname,$udom,$type,undef,
7997: 'requestcourses')) {
7998: $canreq ++;
7999: if (ref($request_domains) eq 'HASH') {
8000: push(@{$request_domains->{$type}},$udom);
8001: }
8002: if ($dom eq $udom) {
8003: $can_request->{$type} = 1;
8004: }
8005: }
8006: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
8007: ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
8008: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
8009: if (@curr > 0) {
8010: foreach my $item (@curr) {
8011: if (ref($request_domains) eq 'HASH') {
8012: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
8013: if ($otherdom ne '') {
8014: if (ref($request_domains->{$type}) eq 'ARRAY') {
8015: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
8016: push(@{$request_domains->{$type}},$otherdom);
8017: }
8018: } else {
8019: push(@{$request_domains->{$type}},$otherdom);
8020: }
8021: }
8022: }
8023: }
8024: unless ($dom eq $env{'user.domain'}) {
8025: $canreq ++;
8026: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
8027: $can_request->{$type} = 1;
8028: }
8029: }
8030: }
8031: }
8032: }
8033: }
8034: return $canreq;
8035: }
8036:
8037: # ---------------------------------------------- Custom access rule evaluation
8038:
8039: sub customaccess {
8040: my ($priv,$uri)=@_;
8041: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
8042: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
8043: $udom = &LONCAPA::clean_domain($udom);
8044: $ucrs = &LONCAPA::clean_username($ucrs);
8045: my $access=0;
8046: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
8047: my ($effect,$realm,$role,$type)=split(/\:/,$right);
8048: if ($type eq 'user') {
8049: foreach my $scope (split(/\s*\,\s*/,$realm)) {
8050: my ($tdom,$tuname)=split(m{/},$scope);
8051: if ($tdom) {
8052: if ($tdom ne $env{'user.domain'}) { next; }
8053: }
8054: if ($tuname) {
8055: if ($tuname ne $env{'user.name'}) { next; }
8056: }
8057: $access=($effect eq 'allow');
8058: last;
8059: }
8060: } else {
8061: if ($role) {
8062: if ($role ne $urole) { next; }
8063: }
8064: foreach my $scope (split(/\s*\,\s*/,$realm)) {
8065: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
8066: if ($tdom) {
8067: if ($tdom ne $udom) { next; }
8068: }
8069: if ($tcrs) {
8070: if ($tcrs ne $ucrs) { next; }
8071: }
8072: if ($tsec) {
8073: if ($tsec ne $usec) { next; }
8074: }
8075: $access=($effect eq 'allow');
8076: last;
8077: }
8078: if ($realm eq '' && $role eq '') {
8079: $access=($effect eq 'allow');
8080: }
8081: }
8082: }
8083: return $access;
8084: }
8085:
8086: # ------------------------------------------------- Check for a user privilege
8087:
8088: sub allowed {
8089: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
8090: my $ver_orguri=$uri;
8091: $uri=&deversion($uri);
8092: my $orguri=$uri;
8093: $uri=&declutter($uri);
8094:
8095: if ($priv eq 'evb') {
8096: # Evade communication block restrictions for specified role in a course
8097: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
8098: return $1;
8099: } else {
8100: return;
8101: }
8102: }
8103:
8104: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
8105: # Free bre access to adm and meta resources
8106: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$}))
8107: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
8108: && ($priv eq 'bre')) {
8109: return 'F';
8110: }
8111:
8112: # Free bre access to user's own portfolio contents
8113: my ($space,$domain,$name,@dir)=split('/',$uri);
8114: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
8115: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
8116: my %setters;
8117: my ($startblock,$endblock) =
8118: &Apache::loncommon::blockcheck(\%setters,'port');
8119: if ($startblock && $endblock) {
8120: return 'B';
8121: } else {
8122: return 'F';
8123: }
8124: }
8125:
8126: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
8127: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
8128: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
8129: if (exists($env{'request.course.id'})) {
8130: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8131: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8132: if (($domain eq $cdom) && ($name eq $cnum)) {
8133: my $courseprivid=$env{'request.course.id'};
8134: $courseprivid=~s/\_/\//;
8135: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
8136: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
8137: return $1;
8138: } else {
8139: if ($env{'request.course.sec'}) {
8140: $courseprivid.='/'.$env{'request.course.sec'};
8141: }
8142: if ($env{'user.priv.'.$env{'request.role'}.'./'.
8143: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
8144: return $2;
8145: }
8146: }
8147: }
8148: }
8149: }
8150:
8151: # Free bre to public access
8152:
8153: if ($priv eq 'bre') {
8154: my $copyright;
8155: unless ($uri =~ /ext\.tool/) {
8156: $copyright=&metadata($uri,'copyright');
8157: }
8158: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
8159: return 'F';
8160: }
8161: if ($copyright eq 'priv') {
8162: $uri=~/([^\/]+)\/([^\/]+)\//;
8163: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
8164: return '';
8165: }
8166: }
8167: if ($copyright eq 'domain') {
8168: $uri=~/([^\/]+)\/([^\/]+)\//;
8169: unless (($env{'user.domain'} eq $1) ||
8170: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
8171: return '';
8172: }
8173: }
8174: if ($env{'request.role'}=~ /li\.\//) {
8175: # Library role, so allow browsing of resources in this domain.
8176: return 'F';
8177: }
8178: if ($copyright eq 'custom') {
8179: unless (&customaccess($priv,$uri)) { return ''; }
8180: }
8181: }
8182: # Domain coordinator is trying to create a course
8183: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
8184: # uri is the requested domain in this case.
8185: # comparison to 'request.role.domain' shows if the user has selected
8186: # a role of dc for the domain in question.
8187: return 'F' if ($uri eq $env{'request.role.domain'});
8188: }
8189:
8190: my $thisallowed='';
8191: my $statecond=0;
8192: my $courseprivid='';
8193:
8194: my $ownaccess;
8195: # Community Coordinator or Assistant Co-author browsing resource space.
8196: if (($priv eq 'bro') && ($env{'user.author'})) {
8197: if ($uri eq '') {
8198: $ownaccess = 1;
8199: } else {
8200: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
8201: my $udom = $env{'user.domain'};
8202: my $uname = $env{'user.name'};
8203: if ($uri =~ m{^\Q$udom\E/?$}) {
8204: $ownaccess = 1;
8205: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
8206: unless ($uri =~ m{\.\./}) {
8207: $ownaccess = 1;
8208: }
8209: } elsif (($udom ne 'public') && ($uname ne 'public')) {
8210: my $now = time;
8211: if ($uri =~ m{^([^/]+)/?$}) {
8212: my $adom = $1;
8213: foreach my $key (keys(%env)) {
8214: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
8215: my ($start,$end) = split('.',$env{$key});
8216: if (($now >= $start) && (!$end || $end < $now)) {
8217: $ownaccess = 1;
8218: last;
8219: }
8220: }
8221: }
8222: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
8223: my $adom = $1;
8224: my $aname = $2;
8225: foreach my $role ('ca','aa') {
8226: if ($env{"user.role.$role./$adom/$aname"}) {
8227: my ($start,$end) =
8228: split('.',$env{"user.role.$role./$adom/$aname"});
8229: if (($now >= $start) && (!$end || $end < $now)) {
8230: $ownaccess = 1;
8231: last;
8232: }
8233: }
8234: }
8235: }
8236: }
8237: }
8238: }
8239: }
8240:
8241: # Course
8242:
8243: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
8244: unless (($priv eq 'bro') && (!$ownaccess)) {
8245: $thisallowed.=$1;
8246: }
8247: }
8248:
8249: # Domain
8250:
8251: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
8252: =~/\Q$priv\E\&([^\:]*)/) {
8253: unless (($priv eq 'bro') && (!$ownaccess)) {
8254: $thisallowed.=$1;
8255: }
8256: }
8257:
8258: # User who is not author or co-author might still be able to edit
8259: # resource of an author in the domain (e.g., if Domain Coordinator).
8260: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
8261: (&allowed('mdc',$env{'request.course.id'}))) {
8262: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
8263: $thisallowed.=$1;
8264: }
8265: }
8266:
8267: # Course: uri itself is a course
8268: my $courseuri=$uri;
8269: $courseuri=~s/\_(\d)/\/$1/;
8270: $courseuri=~s/^([^\/])/\/$1/;
8271:
8272: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
8273: =~/\Q$priv\E\&([^\:]*)/) {
8274: if ($priv eq 'mip') {
8275: my $rem = $1;
8276: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
8277: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
8278: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8279: if ($cdom ne '') {
8280: my %passwdconf = &get_passwdconf($cdom);
8281: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
8282: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
8283: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
8284: my @inststatuses = split(':',$env{'environment.inststatus'});
8285: unless (@inststatuses) {
8286: @inststatuses = ('default');
8287: }
8288: foreach my $status (@inststatuses) {
8289: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
8290: $thisallowed.=$rem;
8291: }
8292: }
8293: }
8294: }
8295: }
8296: }
8297: }
8298: } else {
8299: unless (($priv eq 'bro') && (!$ownaccess)) {
8300: $thisallowed.=$1;
8301: }
8302: }
8303: }
8304:
8305: # URI is an uploaded document for this course, default permissions don't matter
8306: # not allowing 'edit' access (editupload) to uploaded course docs
8307: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
8308: $thisallowed='';
8309: my ($match)=&is_on_map($uri);
8310: if ($match) {
8311: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8312: =~/\Q$priv\E\&([^\:]*)/) {
8313: my $value = $1;
8314: my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
8315: if ($deeplinkblock) {
8316: $thisallowed='D';
8317: } elsif ($noblockcheck) {
8318: $thisallowed.=$value;
8319: } else {
8320: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
8321: if (@blockers > 0) {
8322: $thisallowed = 'B';
8323: } else {
8324: $thisallowed.=$value;
8325: }
8326: }
8327: }
8328: } else {
8329: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
8330: if ($refuri) {
8331: if ($refuri =~ m|^/adm/|) {
8332: $thisallowed='F';
8333: } else {
8334: $refuri=&declutter($refuri);
8335: my ($match) = &is_on_map($refuri);
8336: if ($match) {
8337: my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8338: if ($deeplinkblock) {
8339: $thisallowed='D';
8340: } elsif ($noblockcheck) {
8341: $thisallowed='F';
8342: } else {
8343: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
8344: if (@blockers > 0) {
8345: $thisallowed = 'B';
8346: } else {
8347: $thisallowed='F';
8348: }
8349: }
8350: }
8351: }
8352: }
8353: }
8354: }
8355:
8356: if ($priv eq 'bre'
8357: && $thisallowed ne 'F'
8358: && $thisallowed ne '2'
8359: && &is_portfolio_url($uri)) {
8360: $thisallowed = &portfolio_access($uri,$clientip);
8361: }
8362:
8363: # Full access at system, domain or course-wide level? Exit.
8364: if ($thisallowed=~/F/) {
8365: return 'F';
8366: }
8367:
8368: # If this is generating or modifying users, exit with special codes
8369:
8370: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
8371: if (($priv eq 'cca') || ($priv eq 'caa')) {
8372: my ($audom,$auname)=split('/',$uri);
8373: # no author name given, so this just checks on the general right to make a co-author in this domain
8374: unless ($auname) { return $thisallowed; }
8375: # an author name is given, so we are about to actually make a co-author for a certain account
8376: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8377: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8378: ($audom ne $env{'request.role.domain'}))) { return ''; }
8379: }
8380: return $thisallowed;
8381: }
8382: #
8383: # Gathered so far: system, domain and course wide privileges
8384: #
8385: # Course: See if uri or referer is an individual resource that is part of
8386: # the course
8387:
8388: if ($env{'request.course.id'}) {
8389:
8390: # If this is modifying password (internal auth) domains must match for user and user's role.
8391:
8392: if ($priv eq 'mip') {
8393: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
8394: return $thisallowed;
8395: } else {
8396: return '';
8397: }
8398: }
8399:
8400: $courseprivid=$env{'request.course.id'};
8401: if ($env{'request.course.sec'}) {
8402: $courseprivid.='/'.$env{'request.course.sec'};
8403: }
8404: $courseprivid=~s/\_/\//;
8405: my $checkreferer=1;
8406: my ($match,$cond)=&is_on_map($uri);
8407: if ($match) {
8408: $statecond=$cond;
8409: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
8410: =~/\Q$priv\E\&([^\:]*)/) {
8411: my $value = $1;
8412: if ($priv eq 'bre') {
8413: if ($noblockcheck) {
8414: $thisallowed.=$value;
8415: } else {
8416: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
8417: if (@blockers > 0) {
8418: $thisallowed = 'B';
8419: } else {
8420: $thisallowed.=$value;
8421: }
8422: }
8423: } else {
8424: $thisallowed.=$value;
8425: }
8426: $checkreferer=0;
8427: }
8428: }
8429:
8430: if ($checkreferer) {
8431: my $refuri=$env{'httpref.'.$orguri};
8432: unless ($refuri) {
8433: foreach my $key (keys(%env)) {
8434: if ($key=~/^httpref\..*\*/) {
8435: my $pattern=$key;
8436: $pattern=~s/^httpref\.\/res\///;
8437: $pattern=~s/\*/\[\^\/\]\+/g;
8438: $pattern=~s/\//\\\//g;
8439: if ($orguri=~/$pattern/) {
8440: $refuri=$env{$key};
8441: }
8442: }
8443: }
8444: }
8445:
8446: if ($refuri) {
8447: $refuri=&declutter($refuri);
8448: my ($match,$cond)=&is_on_map($refuri);
8449: if ($match) {
8450: my $refstatecond=$cond;
8451: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
8452: =~/\Q$priv\E\&([^\:]*)/) {
8453: my $value = $1;
8454: if ($priv eq 'bre') {
8455: my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8456: if ($deeplinkblock) {
8457: $thisallowed = 'D';
8458: } elsif ($noblockcheck) {
8459: $thisallowed.=$value;
8460: } else {
8461: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
8462: if (@blockers > 0) {
8463: $thisallowed = 'B';
8464: } else {
8465: $thisallowed.=$value;
8466: }
8467: }
8468: } else {
8469: $thisallowed.=$value;
8470: }
8471: $uri=$refuri;
8472: $statecond=$refstatecond;
8473: }
8474: }
8475: }
8476: }
8477: }
8478:
8479: #
8480: # Gathered now: all privileges that could apply, and condition number
8481: #
8482: #
8483: # Full or no access?
8484: #
8485:
8486: if ($thisallowed=~/F/) {
8487: return 'F';
8488: }
8489:
8490: unless ($thisallowed) {
8491: return '';
8492: }
8493:
8494: # Restrictions exist, deal with them
8495: #
8496: # C:according to course preferences
8497: # R:according to resource settings
8498: # L:unless locked
8499: # X:according to user session state
8500: #
8501:
8502: # Possibly locked functionality, check all courses
8503: # Locks might take effect only after 10 minutes cache expiration for other
8504: # courses, and 2 minutes for current course
8505:
8506: my $envkey;
8507: if ($thisallowed=~/L/) {
8508: foreach $envkey (keys(%env)) {
8509: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8510: my $courseid=$2;
8511: my $roleid=$1.'.'.$2;
8512: $courseid=~s/^\///;
8513: my $expiretime=600;
8514: if ($env{'request.role'} eq $roleid) {
8515: $expiretime=120;
8516: }
8517: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8518: my $prefix='course.'.$cdom.'_'.$cnum.'.';
8519: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
8520: &coursedescription($courseid,{'freshen_cache' => 1});
8521: }
8522: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8523: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8524: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8525: &log($env{'user.domain'},$env{'user.name'},
8526: $env{'user.home'},
8527: 'Locked by res: '.$priv.' for '.$uri.' due to '.
8528: $cdom.'/'.$cnum.'/'.$csec.' expire '.
8529: $env{$prefix.'priv.'.$priv.'.lock.expire'});
8530: return '';
8531: }
8532: }
8533: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8534: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
8535: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
8536: &log($env{'user.domain'},$env{'user.name'},
8537: $env{'user.home'},
8538: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
8539: $cdom.'/'.$cnum.'/'.$csec.' expire '.
8540: $env{$prefix.'priv.'.$priv.'.lock.expire'});
8541: return '';
8542: }
8543: }
8544: }
8545: }
8546: }
8547:
8548: #
8549: # Rest of the restrictions depend on selected course
8550: #
8551:
8552: unless ($env{'request.course.id'}) {
8553: if ($thisallowed eq 'A') {
8554: return 'A';
8555: } elsif ($thisallowed eq 'B') {
8556: return 'B';
8557: } else {
8558: return '1';
8559: }
8560: }
8561:
8562: #
8563: # Now user is definitely in a course
8564: #
8565:
8566:
8567: # Course preferences
8568:
8569: if ($thisallowed=~/C/) {
8570: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8571: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8572: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
8573: =~/\Q$rolecode\E/) {
8574: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
8575: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8576: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8577: $env{'request.course.id'});
8578: }
8579: return '';
8580: }
8581:
8582: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
8583: =~/\Q$unamedom\E/) {
8584: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
8585: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8586: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8587: $env{'request.course.id'});
8588: }
8589: return '';
8590: }
8591: }
8592:
8593: # Resource preferences
8594:
8595: if ($thisallowed=~/R/) {
8596: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8597: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
8598: if (($priv ne 'pch') && ($priv ne 'plc')) {
8599: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8600: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8601: }
8602: return '';
8603: }
8604: }
8605:
8606: # Restricted by state or randomout?
8607:
8608: if ($thisallowed=~/X/) {
8609: if ($env{'acc.randomout'}) {
8610: if (!$symb) { $symb=&symbread($uri,1); }
8611: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
8612: return '';
8613: }
8614: }
8615: if (&condval($statecond)) {
8616: return '2';
8617: } else {
8618: return '';
8619: }
8620: }
8621:
8622: if ($thisallowed eq 'A') {
8623: return 'A';
8624: } elsif ($thisallowed eq 'B') {
8625: return 'B';
8626: } elsif ($thisallowed eq 'D') {
8627: return 'D';
8628: }
8629: return 'F';
8630: }
8631:
8632: # ------------------------------------------- Check construction space access
8633:
8634: sub constructaccess {
8635: my ($url,$setpriv)=@_;
8636:
8637: # We do not allow editing of previous versions of files
8638: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8639:
8640: # Get username and domain from URL
8641: my ($ownername,$ownerdomain,$ownerhome);
8642:
8643: ($ownerdomain,$ownername) =
8644: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
8645:
8646: # The URL does not really point to any authorspace, forget it
8647: unless (($ownername) && ($ownerdomain)) { return ''; }
8648:
8649: # Now we need to see if the user has access to the authorspace of
8650: # $ownername at $ownerdomain
8651:
8652: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8653: # Real author for this?
8654: $ownerhome = $env{'user.home'};
8655: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8656: return ($ownername,$ownerdomain,$ownerhome);
8657: }
8658: } else {
8659: # Co-author for this?
8660: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
8661: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
8662: $ownerhome = &homeserver($ownername,$ownerdomain);
8663: return ($ownername,$ownerdomain,$ownerhome);
8664: }
8665: if ($env{'request.course.id'}) {
8666: if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
8667: ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
8668: if (&allowed('mdc',$env{'request.course.id'})) {
8669: $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
8670: return ($ownername,$ownerdomain,$ownerhome);
8671: }
8672: }
8673: }
8674: }
8675:
8676: # We don't have any access right now. If we are not possibly going to do anything about this,
8677: # we might as well leave
8678: unless ($setpriv) { return ''; }
8679:
8680: # Backdoor access?
8681: my $allowed=&allowed('eco',$ownerdomain);
8682: # Nope
8683: unless ($allowed) { return ''; }
8684: # Looks like we may have access, but could be locked by the owner of the construction space
8685: if ($allowed eq 'U') {
8686: my %blocked=&get('environment',['domcoord.author'],
8687: $ownerdomain,$ownername);
8688: # Is blocked by owner
8689: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
8690: }
8691: if (($allowed eq 'F') || ($allowed eq 'U')) {
8692: # Grant temporary access
8693: my $then=$env{'user.login.time'};
8694: my $update=$env{'user.update.time'};
8695: if (!$update) { $update = $then; }
8696: my $refresh=$env{'user.refresh.time'};
8697: if (!$refresh) { $refresh = $update; }
8698: my $now = time;
8699: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
8700: $now,'ca','constructaccess');
8701: $ownerhome = &homeserver($ownername,$ownerdomain);
8702: return($ownername,$ownerdomain,$ownerhome);
8703: }
8704: # No business here
8705: return '';
8706: }
8707:
8708: # ----------------------------------------------------------- Content Blocking
8709:
8710: {
8711: # Caches for faster Course Contents display where content blocking
8712: # is in operation (i.e., interval param set) for timed quiz.
8713: #
8714: # User for whom data are being temporarily cached.
8715: my $cacheduser='';
8716: # Course for which data are being temporarily cached.
8717: my $cachedcid='';
8718: # Cached blockers for this user (a hash of blocking items).
8719: my %cachedblockers=();
8720: # When the data were last cached.
8721: my $cachedlast='';
8722:
8723: sub load_all_blockers {
8724: my ($uname,$udom)=@_;
8725: if (($uname ne '') && ($udom ne '')) {
8726: if (($cacheduser eq $uname.':'.$udom) &&
8727: ($cachedcid eq $env{'request.course.id'}) &&
8728: (abs($cachedlast-time)<5)) {
8729: return;
8730: }
8731: }
8732: $cachedlast=time;
8733: $cacheduser=$uname.':'.$udom;
8734: $cachedcid=$env{'request.course.id'};
8735: %cachedblockers = &get_commblock_resources();
8736: return;
8737: }
8738:
8739: sub get_comm_blocks {
8740: my ($cdom,$cnum) = @_;
8741: if ($cdom eq '' || $cnum eq '') {
8742: return unless ($env{'request.course.id'});
8743: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8744: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8745: }
8746: my %commblocks;
8747: my $hashid=$cdom.'_'.$cnum;
8748: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8749: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8750: %commblocks = %{$blocksref};
8751: } else {
8752: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8753: my $cachetime = 600;
8754: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8755: }
8756: return %commblocks;
8757: }
8758:
8759: sub get_commblock_resources {
8760: my ($blocks) = @_;
8761: my %blockers = ();
8762: return %blockers unless ($env{'request.course.id'});
8763: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
8764: my %commblocks;
8765: if (ref($blocks) eq 'HASH') {
8766: %commblocks = %{$blocks};
8767: } else {
8768: %commblocks = &get_comm_blocks();
8769: }
8770: return %blockers unless (keys(%commblocks) > 0);
8771: my $navmap = Apache::lonnavmaps::navmap->new();
8772: return %blockers unless (ref($navmap));
8773: my $now = time;
8774: foreach my $block (keys(%commblocks)) {
8775: if ($block =~ /^(\d+)____(\d+)$/) {
8776: my ($start,$end) = ($1,$2);
8777: if ($start <= $now && $end >= $now) {
8778: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8779: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8780: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8781: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8782: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8783: }
8784: }
8785: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8786: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8787: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
8788: }
8789: }
8790: }
8791: }
8792: }
8793: } elsif ($block =~ /^firstaccess____(.+)$/) {
8794: my $item = $1;
8795: my @to_test;
8796: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8797: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8798: my @interval;
8799: my $type = 'map';
8800: if ($item eq 'course') {
8801: $type = 'course';
8802: @interval=&EXT("resource.0.interval");
8803: } else {
8804: if ($item =~ /___\d+___/) {
8805: $type = 'resource';
8806: @interval=&EXT("resource.0.interval",$item);
8807: if (ref($navmap)) {
8808: my $res = $navmap->getBySymb($item);
8809: push(@to_test,$res);
8810: }
8811: } else {
8812: my $mapsymb = &symbread($item,1);
8813: if ($mapsymb) {
8814: if (ref($navmap)) {
8815: my $mapres = $navmap->getBySymb($mapsymb);
8816: if (ref($mapres)) {
8817: my $first = $mapres->map_start();
8818: my $finish = $mapres->map_finish();
8819: my $it = $navmap->getIterator($first,$finish,undef,0,0);
8820: if (ref($it)) {
8821: my $res;
8822: while ($res = $it->next(undef,1)) {
8823: next unless (ref($res));
8824: my $symb = $res->symb();
8825: next if (($symb eq $mapsymb) || ($symb eq ''));
8826: @interval=&EXT("resource.0.interval",$symb);
8827: if ($interval[1] eq 'map') {
8828: if ($res->answerable()) {
8829: push(@to_test,$res);
8830: last;
8831: }
8832: }
8833: }
8834: }
8835: }
8836: }
8837: }
8838: }
8839: }
8840: if ($interval[0] =~ /^(\d+)/) {
8841: my $timelimit = $1;
8842: my $first_access;
8843: if ($type eq 'resource') {
8844: $first_access=&get_first_access($interval[1],$item);
8845: } elsif ($type eq 'map') {
8846: $first_access=&get_first_access($interval[1],undef,$item);
8847: } else {
8848: $first_access=&get_first_access($interval[1]);
8849: }
8850: if ($first_access) {
8851: my $timesup = $first_access+$timelimit;
8852: if ($timesup > $now) {
8853: my $activeblock;
8854: foreach my $res (@to_test) {
8855: if ($res->answerable()) {
8856: $activeblock = 1;
8857: last;
8858: }
8859: }
8860: if ($activeblock) {
8861: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8862: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8863: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8864: }
8865: }
8866: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8867: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8868: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
8869: }
8870: }
8871: }
8872: }
8873: }
8874: }
8875: }
8876: }
8877: }
8878: }
8879: return %blockers;
8880: }
8881:
8882: sub has_comm_blocking {
8883: my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
8884: my @blockers;
8885: return unless ($env{'request.course.id'});
8886: return unless ($priv eq 'bre');
8887: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
8888: return if ($env{'request.state'} eq 'construct');
8889: my %blockinfo;
8890: if (ref($blocks) eq 'HASH') {
8891: %blockinfo = &get_commblock_resources($blocks);
8892: } else {
8893: &load_all_blockers($env{'user.name'},$env{'user.domain'});
8894: %blockinfo = %cachedblockers;
8895: }
8896: return unless (keys(%blockinfo) > 0);
8897: my (%possibles,@symbs);
8898: if (!$symb) {
8899: $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
8900: }
8901: if ($symb) {
8902: @symbs = ($symb);
8903: } elsif (keys(%possibles)) {
8904: @symbs = keys(%possibles);
8905: }
8906: my $noblock;
8907: foreach my $symb (@symbs) {
8908: last if ($noblock);
8909: my ($map,$resid,$resurl)=&decode_symb($symb);
8910: foreach my $block (keys(%blockinfo)) {
8911: if ($block =~ /^firstaccess____(.+)$/) {
8912: my $item = $1;
8913: unless ($blocked) {
8914: if (($item eq $map) || ($item eq $symb)) {
8915: $noblock = 1;
8916: last;
8917: }
8918: }
8919: }
8920: if (ref($blockinfo{$block}) eq 'HASH') {
8921: if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
8922: if ($blockinfo{$block}{'resources'}{$symb}) {
8923: unless (grep(/^\Q$block\E$/,@blockers)) {
8924: push(@blockers,$block);
8925: }
8926: }
8927: }
8928: if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
8929: if ($blockinfo{$block}{'maps'}{$map}) {
8930: unless (grep(/^\Q$block\E$/,@blockers)) {
8931: push(@blockers,$block);
8932: }
8933: }
8934: }
8935: }
8936: }
8937: }
8938: unless ($noblock) {
8939: return @blockers;
8940: }
8941: return;
8942: }
8943: }
8944:
8945: sub deeplink_check {
8946: my ($priv,$symb,$uri) = @_;
8947: return unless ($env{'request.course.id'});
8948: return unless ($priv eq 'bre');
8949: return if ($env{'request.state'} eq 'construct');
8950: return if ($env{'request.role.adv'});
8951: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8952: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8953: my (%possibles,@symbs);
8954: if (!$symb) {
8955: $symb = &symbread($uri,1,1,1,\%possibles);
8956: }
8957: if ($symb) {
8958: @symbs = ($symb);
8959: } elsif (keys(%possibles)) {
8960: @symbs = keys(%possibles);
8961: }
8962:
8963: my ($login,$switchrole,$allow);
8964: if ($env{'request.deeplink.login'} =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
8965: my $key = $1;
8966: my $tinyurl;
8967: my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
8968: if (defined($cached)) {
8969: $tinyurl = $result;
8970: } else {
8971: my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
8972: my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
8973: if ($currtiny{$key} ne '') {
8974: $tinyurl = $currtiny{$key};
8975: &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
8976: }
8977: }
8978: if ($tinyurl ne '') {
8979: my ($cnumreq,$posslogin) = split(/\&/,$tinyurl);
8980: if ($cnumreq eq $cnum) {
8981: $login = $posslogin;
8982: } else {
8983: $switchrole = 1;
8984: }
8985: }
8986: }
8987: foreach my $symb (@symbs) {
8988: last if ($allow);
8989: my $deeplink = &EXT("resource.0.deeplink",$symb);
8990: if ($deeplink eq '') {
8991: $allow = 1;
8992: } else {
8993: my ($listed,$scope,$access) = split(/,/,$deeplink);
8994: if ($access eq 'any') {
8995: $allow = 1;
8996: } elsif ($login) {
8997: if ($access eq 'only') {
8998: if ($scope eq 'res') {
8999: if ($symb eq $login) {
9000: $allow = 1;
9001: }
9002: } elsif ($scope eq 'map') {
9003: #FIXME Compare map for $env{'request.deeplink.login'} with map for $symb
9004: } elsif ($scope eq 'rec') {
9005: #FIXME Recurse up for $env{'request.deeplink.login'} with map for $symb
9006: }
9007: } else {
9008: my ($acctype,$item) = split(/:/,$access);
9009: if (($acctype eq 'lti') && ($env{'user.linkprotector'})) {
9010: if (grep(/^\Q$item\E$/,split(/,/,$env{'user.linkprotector'}))) {
9011: my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
9012: if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.linkproturis'}))) {
9013: $allow = 1;
9014: }
9015: }
9016: } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
9017: if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
9018: my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
9019: if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.keyedlinkuri'}))) {
9020: $allow = 1;
9021: }
9022: }
9023: }
9024: }
9025: }
9026: }
9027: }
9028: return if ($allow);
9029: return 1;
9030: }
9031:
9032: # -------------------------------- Deversion and split uri into path an filename
9033:
9034: #
9035: # Removes the version from a URI and
9036: # splits it in to its filename and path to the filename.
9037: # Seems like File::Basename could have done this more clearly.
9038: # Parameters:
9039: # $uri - input URI
9040: # Returns:
9041: # Two element list consisting of
9042: # $pathname - the URI up to and excluding the trailing /
9043: # $filename - The part of the URI following the last /
9044: # NOTE:
9045: # Another realization of this is simply:
9046: # use File::Basename;
9047: # ...
9048: # $uri = shift;
9049: # $filename = basename($uri);
9050: # $path = dirname($uri);
9051: # return ($filename, $path);
9052: #
9053: # The implementation below is probably faster however.
9054: #
9055: sub split_uri_for_cond {
9056: my $uri=&deversion(&declutter(shift));
9057: my @uriparts=split(/\//,$uri);
9058: my $filename=pop(@uriparts);
9059: my $pathname=join('/',@uriparts);
9060: return ($pathname,$filename);
9061: }
9062: # --------------------------------------------------- Is a resource on the map?
9063:
9064: sub is_on_map {
9065: my ($pathname,$filename) = &split_uri_for_cond(shift);
9066: #Trying to find the conditional for the file
9067: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
9068: /\&\Q$filename\E\:([\d\|]+)\&/);
9069: if ($match) {
9070: return (1,$1);
9071: } else {
9072: return (0,0);
9073: }
9074: }
9075:
9076: # --------------------------------------------------------- Get symb from alias
9077:
9078: sub get_symb_from_alias {
9079: my $symb=shift;
9080: my ($map,$resid,$url)=&decode_symb($symb);
9081: # Already is a symb
9082: if ($url) { return $symb; }
9083: # Must be an alias
9084: my $aliassymb='';
9085: my %bighash;
9086: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9087: &GDBM_READER(),0640)) {
9088: my $rid=$bighash{'mapalias_'.$symb};
9089: if ($rid) {
9090: my ($mapid,$resid)=split(/\./,$rid);
9091: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
9092: $resid,$bighash{'src_'.$rid});
9093: }
9094: untie %bighash;
9095: }
9096: return $aliassymb;
9097: }
9098:
9099: # ----------------------------------------------------------------- Define Role
9100:
9101: sub definerole {
9102: if (allowed('mcr','/')) {
9103: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
9104: foreach my $role (split(':',$sysrole)) {
9105: my ($crole,$cqual)=split(/\&/,$role);
9106: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
9107: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
9108: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
9109: return "refused:s:$crole&$cqual";
9110: }
9111: }
9112: }
9113: foreach my $role (split(':',$domrole)) {
9114: my ($crole,$cqual)=split(/\&/,$role);
9115: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
9116: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
9117: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
9118: return "refused:d:$crole&$cqual";
9119: }
9120: }
9121: }
9122: foreach my $role (split(':',$courole)) {
9123: my ($crole,$cqual)=split(/\&/,$role);
9124: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
9125: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
9126: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
9127: return "refused:c:$crole&$cqual";
9128: }
9129: }
9130: }
9131: my $uhome;
9132: if (($uname ne '') && ($udom ne '')) {
9133: $uhome = &homeserver($uname,$udom);
9134: return $uhome if ($uhome eq 'no_host');
9135: } else {
9136: $uname = $env{'user.name'};
9137: $udom = $env{'user.domain'};
9138: $uhome = $env{'user.home'};
9139: }
9140: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
9141: "$udom:$uname:rolesdef_$rolename=".
9142: escape($sysrole.'_'.$domrole.'_'.$courole);
9143: return reply($command,$uhome);
9144: } else {
9145: return 'refused';
9146: }
9147: }
9148:
9149: # ---------------- Make a metadata query against the network of library servers
9150:
9151: sub metadata_query {
9152: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
9153: my %rhash;
9154: my %libserv = &all_library();
9155: my @server_list = (defined($server_array) ? @$server_array
9156: : keys(%libserv) );
9157: for my $server (@server_list) {
9158: my $domains = '';
9159: if (ref($domains_hash) eq 'HASH') {
9160: $domains = $domains_hash->{$server};
9161: }
9162: unless ($custom or $customshow) {
9163: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
9164: $rhash{$server}=$reply;
9165: }
9166: else {
9167: my $reply=&reply("querysend:".&escape($query).':'.
9168: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
9169: $server);
9170: $rhash{$server}=$reply;
9171: }
9172: }
9173: return \%rhash;
9174: }
9175:
9176: # ----------------------------------------- Send log queries and wait for reply
9177:
9178: sub log_query {
9179: my ($uname,$udom,$query,%filters)=@_;
9180: my $uhome=&homeserver($uname,$udom);
9181: if ($uhome eq 'no_host') { return 'error: no_host'; }
9182: my $uhost=&hostname($uhome);
9183: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
9184: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
9185: $uhome);
9186: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
9187: return get_query_reply($queryid);
9188: }
9189:
9190: # -------------------------- Update MySQL table for portfolio file
9191:
9192: sub update_portfolio_table {
9193: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
9194: if ($group ne '') {
9195: $file_name =~s /^\Q$group\E//;
9196: }
9197: my $homeserver = &homeserver($uname,$udom);
9198: my $queryid=
9199: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
9200: ':'.&escape($file_name).':'.$action,$homeserver);
9201: my $reply = &get_query_reply($queryid);
9202: return $reply;
9203: }
9204:
9205: # -------------------------- Update MySQL allusers table
9206:
9207: sub update_allusers_table {
9208: my ($uname,$udom,$names) = @_;
9209: my $homeserver = &homeserver($uname,$udom);
9210: my $queryid=
9211: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
9212: 'lastname='.&escape($names->{'lastname'}).'%%'.
9213: 'firstname='.&escape($names->{'firstname'}).'%%'.
9214: 'middlename='.&escape($names->{'middlename'}).'%%'.
9215: 'generation='.&escape($names->{'generation'}).'%%'.
9216: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
9217: 'id='.&escape($names->{'id'}),$homeserver);
9218: return;
9219: }
9220:
9221: # ------- Request retrieval of institutional classlists for course(s)
9222:
9223: sub fetch_enrollment_query {
9224: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
9225: my ($homeserver,$sleep,$loopmax);
9226: my $maxtries = 1;
9227: if ($context eq 'automated') {
9228: $homeserver = $perlvar{'lonHostID'};
9229: $sleep = 2;
9230: $loopmax = 100;
9231: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
9232: } else {
9233: $homeserver = &homeserver($cnum,$dom);
9234: }
9235: my $host=&hostname($homeserver);
9236: my $cmd = '';
9237: foreach my $affiliate (keys(%{$affiliatesref})) {
9238: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
9239: }
9240: $cmd =~ s/%%$//;
9241: $cmd = &escape($cmd);
9242: my $query = 'fetchenrollment';
9243: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
9244: unless ($queryid=~/^\Q$host\E\_/) {
9245: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
9246: return 'error: '.$queryid;
9247: }
9248: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
9249: my $tries = 1;
9250: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9251: $reply = &get_query_reply($queryid,$sleep,$loopmax);
9252: $tries ++;
9253: }
9254: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9255: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9256: } else {
9257: my @responses = split(/:/,$reply);
9258: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
9259: foreach my $line (@responses) {
9260: my ($key,$value) = split(/=/,$line,2);
9261: $$replyref{$key} = $value;
9262: }
9263: } else {
9264: my $pathname = LONCAPA::tempdir();
9265: foreach my $line (@responses) {
9266: my ($key,$value) = split(/=/,$line);
9267: $$replyref{$key} = $value;
9268: if ($value > 0) {
9269: foreach my $item (@{$$affiliatesref{$key}}) {
9270: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
9271: my $destname = $pathname.'/'.$filename;
9272: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
9273: if ($xml_classlist =~ /^error/) {
9274: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
9275: } else {
9276: if ( open(FILE,">",$destname) ) {
9277: print FILE &unescape($xml_classlist);
9278: close(FILE);
9279: } else {
9280: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
9281: }
9282: }
9283: }
9284: }
9285: }
9286: }
9287: return 'ok';
9288: }
9289: return 'error';
9290: }
9291:
9292: sub get_query_reply {
9293: my ($queryid,$sleep,$loopmax) = @_;;
9294: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
9295: $sleep = 0.2;
9296: }
9297: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
9298: $loopmax = 100;
9299: }
9300: my $replyfile=LONCAPA::tempdir().$queryid;
9301: my $reply='';
9302: for (1..$loopmax) {
9303: sleep($sleep);
9304: if (-e $replyfile.'.end') {
9305: if (open(my $fh,"<",$replyfile)) {
9306: $reply = join('',<$fh>);
9307: close($fh);
9308: } else { return 'error: reply_file_error'; }
9309: return &unescape($reply);
9310: }
9311: }
9312: return 'timeout:'.$queryid;
9313: }
9314:
9315: sub courselog_query {
9316: #
9317: # possible filters:
9318: # url: url or symb
9319: # username
9320: # domain
9321: # action: view, submit, grade
9322: # start: timestamp
9323: # end: timestamp
9324: #
9325: my (%filters)=@_;
9326: unless ($env{'request.course.id'}) { return 'no_course'; }
9327: if ($filters{'url'}) {
9328: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
9329: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
9330: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
9331: }
9332: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
9333: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
9334: return &log_query($cname,$cdom,'courselog',%filters);
9335: }
9336:
9337: sub userlog_query {
9338: #
9339: # possible filters:
9340: # action: log check role
9341: # start: timestamp
9342: # end: timestamp
9343: #
9344: my ($uname,$udom,%filters)=@_;
9345: return &log_query($uname,$udom,'userlog',%filters);
9346: }
9347:
9348: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
9349:
9350: sub auto_run {
9351: my ($cnum,$cdom) = @_;
9352: my $response = 0;
9353: my $settings;
9354: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
9355: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
9356: $settings = $domconfig{'autoenroll'};
9357: if ($settings->{'run'} eq '1') {
9358: $response = 1;
9359: }
9360: } else {
9361: my $homeserver;
9362: if (&is_course($cdom,$cnum)) {
9363: $homeserver = &homeserver($cnum,$cdom);
9364: } else {
9365: $homeserver = &domain($cdom,'primary');
9366: }
9367: if ($homeserver ne 'no_host') {
9368: $response = &reply('autorun:'.$cdom,$homeserver);
9369: }
9370: }
9371: return $response;
9372: }
9373:
9374: sub auto_get_sections {
9375: my ($cnum,$cdom,$inst_coursecode) = @_;
9376: my $homeserver;
9377: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9378: $homeserver = &homeserver($cnum,$cdom);
9379: }
9380: if (!defined($homeserver)) {
9381: if ($cdom =~ /^$match_domain$/) {
9382: $homeserver = &domain($cdom,'primary');
9383: }
9384: }
9385: my @secs;
9386: if (defined($homeserver)) {
9387: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
9388: unless ($response eq 'refused') {
9389: @secs = split(/:/,$response);
9390: }
9391: }
9392: return @secs;
9393: }
9394:
9395: sub auto_new_course {
9396: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
9397: my $homeserver = &homeserver($cnum,$cdom);
9398: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
9399: return $response;
9400: }
9401:
9402: sub auto_validate_courseID {
9403: my ($cnum,$cdom,$inst_course_id) = @_;
9404: my $homeserver = &homeserver($cnum,$cdom);
9405: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
9406: return $response;
9407: }
9408:
9409: sub auto_validate_instcode {
9410: my ($cnum,$cdom,$instcode,$owner) = @_;
9411: my ($homeserver,$response);
9412: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9413: $homeserver = &homeserver($cnum,$cdom);
9414: }
9415: if (!defined($homeserver)) {
9416: if ($cdom =~ /^$match_domain$/) {
9417: $homeserver = &domain($cdom,'primary');
9418: }
9419: }
9420: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
9421: &escape($instcode).':'.&escape($owner),$homeserver));
9422: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
9423: return ($outcome,$description,$defaultcredits);
9424: }
9425:
9426: sub auto_create_password {
9427: my ($cnum,$cdom,$authparam,$udom) = @_;
9428: my ($homeserver,$response);
9429: my $create_passwd = 0;
9430: my $authchk = '';
9431: if ($udom =~ /^$match_domain$/) {
9432: $homeserver = &domain($udom,'primary');
9433: }
9434: if ($homeserver eq '') {
9435: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9436: $homeserver = &homeserver($cnum,$cdom);
9437: }
9438: }
9439: if ($homeserver eq '') {
9440: $authchk = 'nodomain';
9441: } else {
9442: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
9443: if ($response eq 'refused') {
9444: $authchk = 'refused';
9445: } else {
9446: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
9447: }
9448: }
9449: return ($authparam,$create_passwd,$authchk);
9450: }
9451:
9452: sub auto_photo_permission {
9453: my ($cnum,$cdom,$students) = @_;
9454: my $homeserver = &homeserver($cnum,$cdom);
9455: my ($outcome,$perm_reqd,$conditions) =
9456: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
9457: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9458: return (undef,undef);
9459: }
9460: return ($outcome,$perm_reqd,$conditions);
9461: }
9462:
9463: sub auto_checkphotos {
9464: my ($uname,$udom,$pid) = @_;
9465: my $homeserver = &homeserver($uname,$udom);
9466: my ($result,$resulttype);
9467: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
9468: &escape($uname).':'.&escape($pid),
9469: $homeserver));
9470: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9471: return (undef,undef);
9472: }
9473: if ($outcome) {
9474: ($result,$resulttype) = split(/:/,$outcome);
9475: }
9476: return ($result,$resulttype);
9477: }
9478:
9479: sub auto_photochoice {
9480: my ($cnum,$cdom) = @_;
9481: my $homeserver = &homeserver($cnum,$cdom);
9482: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
9483: &escape($cdom),
9484: $homeserver)));
9485: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9486: return (undef,undef);
9487: }
9488: return ($update,$comment);
9489: }
9490:
9491: sub auto_photoupdate {
9492: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9493: my $homeserver = &homeserver($cnum,$dom);
9494: my $host=&hostname($homeserver);
9495: my $cmd = '';
9496: my $maxtries = 1;
9497: foreach my $affiliate (keys(%{$affiliatesref})) {
9498: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
9499: }
9500: $cmd =~ s/%%$//;
9501: $cmd = &escape($cmd);
9502: my $query = 'institutionalphotos';
9503: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9504: unless ($queryid=~/^\Q$host\E\_/) {
9505: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9506: return 'error: '.$queryid;
9507: }
9508: my $reply = &get_query_reply($queryid);
9509: my $tries = 1;
9510: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9511: $reply = &get_query_reply($queryid);
9512: $tries ++;
9513: }
9514: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9515: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9516: } else {
9517: my @responses = split(/:/,$reply);
9518: my $outcome = shift(@responses);
9519: foreach my $item (@responses) {
9520: my ($key,$value) = split(/=/,$item);
9521: $$photo{$key} = $value;
9522: }
9523: return $outcome;
9524: }
9525: return 'error';
9526: }
9527:
9528: sub auto_instcode_format {
9529: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9530: $cat_order) = @_;
9531: my $courses = '';
9532: my @homeservers;
9533: if ($caller eq 'global') {
9534: my %servers = &get_servers($codedom,'library');
9535: foreach my $tryserver (keys(%servers)) {
9536: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9537: push(@homeservers,$tryserver);
9538: }
9539: }
9540: } elsif ($caller eq 'requests') {
9541: if ($codedom =~ /^$match_domain$/) {
9542: my $chome = &domain($codedom,'primary');
9543: unless ($chome eq 'no_host') {
9544: push(@homeservers,$chome);
9545: }
9546: }
9547: } else {
9548: push(@homeservers,&homeserver($caller,$codedom));
9549: }
9550: foreach my $code (keys(%{$instcodes})) {
9551: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
9552: }
9553: chop($courses);
9554: my $ok_response = 0;
9555: my $response;
9556: while (@homeservers > 0 && $ok_response == 0) {
9557: my $server = shift(@homeservers);
9558: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9559: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9560: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
9561: split(/:/,$response);
9562: %{$codes} = (%{$codes},&str2hash($codes_str));
9563: push(@{$codetitles},&str2array($codetitles_str));
9564: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9565: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9566: $ok_response = 1;
9567: }
9568: }
9569: if ($ok_response) {
9570: return 'ok';
9571: } else {
9572: return $response;
9573: }
9574: }
9575:
9576: sub auto_instcode_defaults {
9577: my ($domain,$returnhash,$code_order) = @_;
9578: my @homeservers;
9579:
9580: my %servers = &get_servers($domain,'library');
9581: foreach my $tryserver (keys(%servers)) {
9582: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9583: push(@homeservers,$tryserver);
9584: }
9585: }
9586:
9587: my $response;
9588: foreach my $server (@homeservers) {
9589: $response=&reply('autoinstcodedefaults:'.$domain,$server);
9590: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9591:
9592: foreach my $pair (split(/\&/,$response)) {
9593: my ($name,$value)=split(/\=/,$pair);
9594: if ($name eq 'code_order') {
9595: @{$code_order} = split(/\&/,&unescape($value));
9596: } else {
9597: $returnhash->{&unescape($name)}=&unescape($value);
9598: }
9599: }
9600: return 'ok';
9601: }
9602:
9603: return $response;
9604: }
9605:
9606: sub auto_possible_instcodes {
9607: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9608: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9609: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9610: return;
9611: }
9612: my (@homeservers,$uhome);
9613: if (defined(&domain($domain,'primary'))) {
9614: $uhome=&domain($domain,'primary');
9615: push(@homeservers,&domain($domain,'primary'));
9616: } else {
9617: my %servers = &get_servers($domain,'library');
9618: foreach my $tryserver (keys(%servers)) {
9619: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9620: push(@homeservers,$tryserver);
9621: }
9622: }
9623: }
9624: my $response;
9625: foreach my $server (@homeservers) {
9626: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9627: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9628: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9629: split(':',$response);
9630: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9631: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
9632: foreach my $item (split('&',$cat_title)) {
9633: my ($name,$value)=split('=',$item);
9634: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
9635: }
9636: foreach my $item (split('&',$cat_order)) {
9637: my ($name,$value)=split('=',$item);
9638: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
9639: }
9640: return 'ok';
9641: }
9642: return $response;
9643: }
9644:
9645: sub auto_courserequest_checks {
9646: my ($dom) = @_;
9647: my ($homeserver,%validations);
9648: if ($dom =~ /^$match_domain$/) {
9649: $homeserver = &domain($dom,'primary');
9650: }
9651: unless ($homeserver eq 'no_host') {
9652: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9653: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9654: my @items = split(/&/,$response);
9655: foreach my $item (@items) {
9656: my ($key,$value) = split('=',$item);
9657: $validations{&unescape($key)} = &thaw_unescape($value);
9658: }
9659: }
9660: }
9661: return %validations;
9662: }
9663:
9664: sub auto_courserequest_validation {
9665: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
9666: my ($homeserver,$response);
9667: if ($dom =~ /^$match_domain$/) {
9668: $homeserver = &domain($dom,'primary');
9669: }
9670: unless ($homeserver eq 'no_host') {
9671: my $customdata;
9672: if (ref($custominfo) eq 'HASH') {
9673: $customdata = &freeze_escape($custominfo);
9674: }
9675: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
9676: ':'.&escape($crstype).':'.&escape($inststatuslist).
9677: ':'.&escape($instcode).':'.&escape($instseclist).':'.
9678: $customdata,$homeserver));
9679: }
9680: return $response;
9681: }
9682:
9683: sub auto_validate_class_sec {
9684: my ($cdom,$cnum,$owners,$inst_class) = @_;
9685: my $homeserver = &homeserver($cnum,$cdom);
9686: my $ownerlist;
9687: if (ref($owners) eq 'ARRAY') {
9688: $ownerlist = join(',',@{$owners});
9689: } else {
9690: $ownerlist = $owners;
9691: }
9692: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
9693: &escape($ownerlist).':'.$cdom,$homeserver);
9694: return $response;
9695: }
9696:
9697: sub auto_validate_instclasses {
9698: my ($cdom,$cnum,$owners,$classesref) = @_;
9699: my ($homeserver,%validations);
9700: $homeserver = &homeserver($cnum,$cdom);
9701: unless ($homeserver eq 'no_host') {
9702: my $ownerlist;
9703: if (ref($owners) eq 'ARRAY') {
9704: $ownerlist = join(',',@{$owners});
9705: } else {
9706: $ownerlist = $owners;
9707: }
9708: if (ref($classesref) eq 'HASH') {
9709: my $classes = &freeze_escape($classesref);
9710: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
9711: ':'.$cdom.':'.$classes,$homeserver);
9712: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9713: my @items = split(/&/,$response);
9714: foreach my $item (@items) {
9715: my ($key,$value) = split('=',$item);
9716: $validations{&unescape($key)} = &thaw_unescape($value);
9717: }
9718: }
9719: }
9720: }
9721: return %validations;
9722: }
9723:
9724: sub auto_crsreq_update {
9725: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
9726: $code,$accessstart,$accessend,$inbound) = @_;
9727: my ($homeserver,%crsreqresponse);
9728: if ($cdom =~ /^$match_domain$/) {
9729: $homeserver = &domain($cdom,'primary');
9730: }
9731: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9732: my $info;
9733: if (ref($inbound) eq 'HASH') {
9734: $info = &freeze_escape($inbound);
9735: }
9736: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
9737: ':'.&escape($action).':'.&escape($ownername).':'.
9738: &escape($ownerdomain).':'.&escape($fullname).':'.
9739: &escape($title).':'.&escape($code).':'.
9740: &escape($accessstart).':'.&escape($accessend).':'.$info,
9741: $homeserver);
9742: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9743: my @items = split(/&/,$response);
9744: foreach my $item (@items) {
9745: my ($key,$value) = split('=',$item);
9746: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
9747: }
9748: }
9749: }
9750: return \%crsreqresponse;
9751: }
9752:
9753: sub auto_export_grades {
9754: my ($cdom,$cnum,$inforef,$gradesref) = @_;
9755: my ($homeserver,%exportresponse);
9756: if ($cdom =~ /^$match_domain$/) {
9757: $homeserver = &domain($cdom,'primary');
9758: }
9759: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9760: my $info;
9761: if (ref($inforef) eq 'HASH') {
9762: $info = &freeze_escape($inforef);
9763: }
9764: if (ref($gradesref) eq 'HASH') {
9765: my $grades = &freeze_escape($gradesref);
9766: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
9767: $info.':'.$grades,$homeserver);
9768: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
9769: my @items = split(/&/,$response);
9770: foreach my $item (@items) {
9771: my ($key,$value) = split('=',$item);
9772: $exportresponse{&unescape($key)} = &thaw_unescape($value);
9773: }
9774: }
9775: }
9776: }
9777: return \%exportresponse;
9778: }
9779:
9780: sub check_instcode_cloning {
9781: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
9782: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9783: return;
9784: }
9785: my $canclone;
9786: if (@{$code_order} > 0) {
9787: my $instcoderegexp ='^';
9788: my @clonecodes = split(/\&/,$cloner);
9789: foreach my $item (@{$code_order}) {
9790: if (grep(/^\Q$item\E=/,@clonecodes)) {
9791: foreach my $pair (@clonecodes) {
9792: my ($key,$val) = split(/\=/,$pair,2);
9793: $val = &unescape($val);
9794: if ($key eq $item) {
9795: $instcoderegexp .= '('.$val.')';
9796: last;
9797: }
9798: }
9799: } else {
9800: $instcoderegexp .= $codedefaults->{$item};
9801: }
9802: }
9803: $instcoderegexp .= '$';
9804: my (@from,@to);
9805: eval {
9806: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9807: (@to) = ($clonetocode =~ /$instcoderegexp/);
9808: };
9809: if ((@from > 0) && (@to > 0)) {
9810: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9811: if (!@diffs) {
9812: $canclone = 1;
9813: }
9814: }
9815: }
9816: return $canclone;
9817: }
9818:
9819: sub default_instcode_cloning {
9820: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
9821: my (%codedefaults,@code_order,$canclone);
9822: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
9823: %codedefaults = %{$codedefaultsref};
9824: @code_order = @{$codeorderref};
9825: } elsif ($clonedom) {
9826: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
9827: }
9828: if (($domdefclone) && (@code_order)) {
9829: my @clonecodes = split(/\+/,$domdefclone);
9830: my $instcoderegexp ='^';
9831: foreach my $item (@code_order) {
9832: if (grep(/^\Q$item\E$/,@clonecodes)) {
9833: $instcoderegexp .= '('.$codedefaults{$item}.')';
9834: } else {
9835: $instcoderegexp .= $codedefaults{$item};
9836: }
9837: }
9838: $instcoderegexp .= '$';
9839: my (@from,@to);
9840: eval {
9841: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9842: (@to) = ($clonetocode =~ /$instcoderegexp/);
9843: };
9844: if ((@from > 0) && (@to > 0)) {
9845: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9846: if (!@diffs) {
9847: $canclone = 1;
9848: }
9849: }
9850: }
9851: return $canclone;
9852: }
9853:
9854: # ------------------------------------------------------- Course Group routines
9855:
9856: sub get_coursegroups {
9857: my ($cdom,$cnum,$group,$namespace) = @_;
9858: return(&dump($namespace,$cdom,$cnum,$group));
9859: }
9860:
9861: sub modify_coursegroup {
9862: my ($cdom,$cnum,$groupsettings) = @_;
9863: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
9864: }
9865:
9866: sub toggle_coursegroup_status {
9867: my ($cdom,$cnum,$group,$action) = @_;
9868: my ($from_namespace,$to_namespace);
9869: if ($action eq 'delete') {
9870: $from_namespace = 'coursegroups';
9871: $to_namespace = 'deleted_groups';
9872: } else {
9873: $from_namespace = 'deleted_groups';
9874: $to_namespace = 'coursegroups';
9875: }
9876: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
9877: if (my $tmp = &error(%curr_group)) {
9878: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
9879: return ('read error',$tmp);
9880: } else {
9881: my %savedsettings = %curr_group;
9882: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
9883: my $deloutcome;
9884: if ($result eq 'ok') {
9885: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
9886: } else {
9887: return ('write error',$result);
9888: }
9889: if ($deloutcome eq 'ok') {
9890: return 'ok';
9891: } else {
9892: return ('delete error',$deloutcome);
9893: }
9894: }
9895: }
9896:
9897: sub modify_group_roles {
9898: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
9899: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
9900: my $role = 'gr/'.&escape($userprivs);
9901: my ($uname,$udom) = split(/:/,$user);
9902: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
9903: if ($result eq 'ok') {
9904: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
9905: }
9906: return $result;
9907: }
9908:
9909: sub modify_coursegroup_membership {
9910: my ($cdom,$cnum,$membership) = @_;
9911: my $result = &put('groupmembership',$membership,$cdom,$cnum);
9912: return $result;
9913: }
9914:
9915: sub get_active_groups {
9916: my ($udom,$uname,$cdom,$cnum) = @_;
9917: my $now = time;
9918: my %groups = ();
9919: foreach my $key (keys(%env)) {
9920: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
9921: my ($start,$end) = split(/\./,$env{$key});
9922: if (($end!=0) && ($end<$now)) { next; }
9923: if (($start!=0) && ($start>$now)) { next; }
9924: if ($1 eq $cdom && $2 eq $cnum) {
9925: $groups{$3} = $env{$key} ;
9926: }
9927: }
9928: }
9929: return %groups;
9930: }
9931:
9932: sub get_group_membership {
9933: my ($cdom,$cnum,$group) = @_;
9934: return(&dump('groupmembership',$cdom,$cnum,$group));
9935: }
9936:
9937: sub get_users_groups {
9938: my ($udom,$uname,$courseid) = @_;
9939: my @usersgroups;
9940: my $cachetime=1800;
9941:
9942: my $hashid="$udom:$uname:$courseid";
9943: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
9944: if (defined($cached)) {
9945: @usersgroups = split(/:/,$grouplist);
9946: } else {
9947: $grouplist = '';
9948: my $courseurl = &courseid_to_courseurl($courseid);
9949: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
9950: my $access_end = $env{'course.'.$courseid.
9951: '.default_enrollment_end_date'};
9952: my $now = time;
9953: foreach my $key (keys(%roleshash)) {
9954: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
9955: my $group = $1;
9956: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
9957: my $start = $2;
9958: my $end = $1;
9959: if ($start == -1) { next; } # deleted from group
9960: if (($start!=0) && ($start>$now)) { next; }
9961: if (($end!=0) && ($end<$now)) {
9962: if ($access_end && $access_end < $now) {
9963: if ($access_end - $end < 86400) {
9964: push(@usersgroups,$group);
9965: }
9966: }
9967: next;
9968: }
9969: push(@usersgroups,$group);
9970: }
9971: }
9972: }
9973: @usersgroups = &sort_course_groups($courseid,@usersgroups);
9974: $grouplist = join(':',@usersgroups);
9975: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
9976: }
9977: return @usersgroups;
9978: }
9979:
9980: sub devalidate_getgroups_cache {
9981: my ($udom,$uname,$cdom,$cnum)=@_;
9982: my $courseid = $cdom.'_'.$cnum;
9983:
9984: my $hashid="$udom:$uname:$courseid";
9985: &devalidate_cache_new('getgroups',$hashid);
9986: }
9987:
9988: # ------------------------------------------------------------------ Plain Text
9989:
9990: sub plaintext {
9991: my ($short,$type,$cid,$forcedefault) = @_;
9992: if ($short =~ m{^cr/}) {
9993: return (split('/',$short))[-1];
9994: }
9995: if (!defined($cid)) {
9996: $cid = $env{'request.course.id'};
9997: }
9998: my %rolenames = (
9999: Course => 'std',
10000: Community => 'alt1',
10001: Placement => 'std',
10002: );
10003: if ($cid ne '') {
10004: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10005: unless ($forcedefault) {
10006: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
10007: &Apache::lonlocal::mt_escape(\$roletext);
10008: return &Apache::lonlocal::mt($roletext);
10009: }
10010: }
10011: }
10012: if ((defined($type)) && (defined($rolenames{$type})) &&
10013: (defined($rolenames{$type})) &&
10014: (defined($prp{$short}{$rolenames{$type}}))) {
10015: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
10016: } elsif ($cid ne '') {
10017: my $crstype = $env{'course.'.$cid.'.type'};
10018: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10019: (defined($prp{$short}{$rolenames{$crstype}}))) {
10020: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10021: }
10022: }
10023: return &Apache::lonlocal::mt($prp{$short}{'std'});
10024: }
10025:
10026: # ----------------------------------------------------------------- Assign Role
10027:
10028: sub assignrole {
10029: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10030: $context)=@_;
10031: my $mrole;
10032: if ($role =~ /^cr\//) {
10033: my $cwosec=$url;
10034: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10035: unless (&allowed('ccr',$cwosec)) {
10036: my $refused = 1;
10037: if ($context eq 'requestcourses') {
10038: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10039: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10040: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10041: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10042: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10043: if ($crsenv{'internal.courseowner'} eq
10044: $env{'user.name'}.':'.$env{'user.domain'}) {
10045: $refused = '';
10046: }
10047: }
10048: }
10049: }
10050: }
10051: if ($refused) {
10052: &logthis('Refused custom assignrole: '.
10053: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10054: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10055: return 'refused';
10056: }
10057: }
10058: $mrole='cr';
10059: } elsif ($role =~ /^gr\//) {
10060: my $cwogrp=$url;
10061: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
10062: unless (&allowed('mdg',$cwogrp)) {
10063: &logthis('Refused group assignrole: '.
10064: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10065: $env{'user.name'}.' at '.$env{'user.domain'});
10066: return 'refused';
10067: }
10068: $mrole='gr';
10069: } else {
10070: my $cwosec=$url;
10071: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10072: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10073: my $refused;
10074: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
10075: if (!(&allowed('c'.$role,$url))) {
10076: $refused = 1;
10077: }
10078: } else {
10079: $refused = 1;
10080: }
10081: if ($refused) {
10082: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10083: if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
10084: my %crsenv;
10085: if ($role eq 'cc' || $role eq 'co') {
10086: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10087: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10088: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10089: if ($crsenv{'internal.courseowner'} eq
10090: $env{'user.name'}.':'.$env{'user.domain'}) {
10091: $refused = '';
10092: }
10093: }
10094: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
10095: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10096: if ($crsenv{'internal.courseowner'} eq
10097: $env{'user.name'}.':'.$env{'user.domain'}) {
10098: $refused = '';
10099: }
10100: }
10101: }
10102: }
10103: } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10104: if ($role eq 'st') {
10105: $refused = '';
10106: } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10107: $refused = '';
10108: }
10109: } elsif ($context eq 'requestcourses') {
10110: my @possroles = ('st','ta','ep','in','cc','co');
10111: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
10112: my $wrongcc;
10113: if ($cnum =~ /^$match_community$/) {
10114: $wrongcc = 1 if ($role eq 'cc');
10115: } else {
10116: $wrongcc = 1 if ($role eq 'co');
10117: }
10118: unless ($wrongcc) {
10119: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10120: if ($crsenv{'internal.courseowner'} eq
10121: $env{'user.name'}.':'.$env{'user.domain'}) {
10122: $refused = '';
10123: }
10124: }
10125: }
10126: } elsif ($context eq 'requestauthor') {
10127: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
10128: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10129: if ($env{'environment.requestauthor'} eq 'automatic') {
10130: $refused = '';
10131: } else {
10132: my %domdefaults = &get_domain_defaults($udom);
10133: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10134: my $checkbystatus;
10135: if ($env{'user.adv'}) {
10136: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10137: if ($disposition eq 'automatic') {
10138: $refused = '';
10139: } elsif ($disposition eq '') {
10140: $checkbystatus = 1;
10141: }
10142: } else {
10143: $checkbystatus = 1;
10144: }
10145: if ($checkbystatus) {
10146: if ($env{'environment.inststatus'}) {
10147: my @inststatuses = split(/,/,$env{'environment.inststatus'});
10148: foreach my $type (@inststatuses) {
10149: if (($type ne '') &&
10150: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10151: $refused = '';
10152: }
10153: }
10154: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10155: $refused = '';
10156: }
10157: }
10158: }
10159: }
10160: }
10161: }
10162: if ($refused) {
10163: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10164: ' '.$role.' '.$end.' '.$start.' by '.
10165: $env{'user.name'}.' at '.$env{'user.domain'});
10166: return 'refused';
10167: }
10168: }
10169: } elsif ($role eq 'au') {
10170: if ($url ne '/'.$udom.'/') {
10171: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10172: ' to assign author role for '.$uname.':'.$udom.
10173: ' in domain: '.$url.' refused (wrong domain).');
10174: return 'refused';
10175: }
10176: }
10177: $mrole=$role;
10178: }
10179: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
10180: "$udom:$uname:$url".'_'."$mrole=$role";
10181: if ($end) { $command.='_'.$end; }
10182: if ($start) {
10183: if ($end) {
10184: $command.='_'.$start;
10185: } else {
10186: $command.='_0_'.$start;
10187: }
10188: }
10189: my $origstart = $start;
10190: my $origend = $end;
10191: my $delflag;
10192: # actually delete
10193: if ($deleteflag) {
10194: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
10195: # modify command to delete the role
10196: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
10197: "$udom:$uname:$url".'_'."$mrole";
10198: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
10199: # set start and finish to negative values for userrolelog
10200: $start=-1;
10201: $end=-1;
10202: $delflag = 1;
10203: }
10204: }
10205: # send command
10206: my $answer=&reply($command,&homeserver($uname,$udom));
10207: # log new user role if status is ok
10208: if ($answer eq 'ok') {
10209: &userrolelog($role,$uname,$udom,$url,$start,$end);
10210: if (($role eq 'cc') || ($role eq 'in') ||
10211: ($role eq 'ep') || ($role eq 'ad') ||
10212: ($role eq 'ta') || ($role eq 'st') ||
10213: ($role=~/^cr/) || ($role eq 'gr') ||
10214: ($role eq 'co')) {
10215: # for course roles, perform group memberships changes triggered by role change.
10216: unless ($role =~ /^gr/) {
10217: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10218: $origstart,$selfenroll,$context);
10219: }
10220: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10221: $selfenroll,$context);
10222: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10223: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10224: ($role eq 'da')) {
10225: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10226: $context);
10227: } elsif (($role eq 'ca') || ($role eq 'aa')) {
10228: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10229: $context);
10230: }
10231: if ($role eq 'cc') {
10232: &autoupdate_coowners($url,$end,$start,$uname,$udom);
10233: }
10234: }
10235: return $answer;
10236: }
10237:
10238: sub autoupdate_coowners {
10239: my ($url,$end,$start,$uname,$udom) = @_;
10240: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10241: if (($cdom ne '') && ($cnum ne '')) {
10242: my $now = time;
10243: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10244: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10245: my %coursehash = &coursedescription($cdom.'_'.$cnum);
10246: my $instcode = $coursehash{'internal.coursecode'};
10247: if ($instcode ne '') {
10248: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10249: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10250: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10251: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10252: if ($result eq 'valid') {
10253: if ($coursehash{'internal.co-owners'}) {
10254: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10255: push(@newcoowners,$coowner);
10256: }
10257: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10258: push(@newcoowners,$uname.':'.$udom);
10259: }
10260: @newcoowners = sort(@newcoowners);
10261: } else {
10262: push(@newcoowners,$uname.':'.$udom);
10263: }
10264: } else {
10265: if ($coursehash{'internal.co-owners'}) {
10266: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10267: unless ($coowner eq $uname.':'.$udom) {
10268: push(@newcoowners,$coowner);
10269: }
10270: }
10271: unless (@newcoowners > 0) {
10272: $delcoowners = 1;
10273: $coowners = '';
10274: }
10275: }
10276: }
10277: if (@newcoowners || $delcoowners) {
10278: &store_coowners($cdom,$cnum,$coursehash{'home'},
10279: $delcoowners,@newcoowners);
10280: }
10281: }
10282: }
10283: }
10284: }
10285: }
10286: }
10287:
10288: sub store_coowners {
10289: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10290: my $cid = $cdom.'_'.$cnum;
10291: my ($coowners,$delresult,$putresult);
10292: if (@newcoowners) {
10293: $coowners = join(',',@newcoowners);
10294: my %coownershash = (
10295: 'internal.co-owners' => $coowners,
10296: );
10297: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10298: if ($putresult eq 'ok') {
10299: if ($env{'course.'.$cid.'.num'} eq $cnum) {
10300: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10301: }
10302: }
10303: }
10304: if ($delcoowners) {
10305: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10306: if ($delresult eq 'ok') {
10307: if ($env{'course.'.$cid.'.internal.co-owners'}) {
10308: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10309: }
10310: }
10311: }
10312: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10313: my %crsinfo =
10314: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10315: if (ref($crsinfo{$cid}) eq 'HASH') {
10316: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10317: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10318: }
10319: }
10320: }
10321:
10322: # -------------------------------------------------- Modify user authentication
10323: # Overrides without validation
10324:
10325: sub modifyuserauth {
10326: my ($udom,$uname,$umode,$upass)=@_;
10327: my $uhome=&homeserver($uname,$udom);
10328: my $allowed;
10329: if (&allowed('mau',$udom)) {
10330: $allowed = 1;
10331: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10332: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10333: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10334: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10335: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10336: if (($cdom ne '') && ($cnum ne '')) {
10337: my $is_owner = &is_course_owner($cdom,$cnum);
10338: if ($is_owner) {
10339: $allowed = 1;
10340: }
10341: }
10342: }
10343: unless ($allowed) { return 'refused'; }
10344: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
10345: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10346: ' in domain '.$env{'request.role.domain'});
10347: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10348: &escape($upass),$uhome);
10349: my $ip = &get_requestor_ip();
10350: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
10351: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10352: '(Remote '.$ip.'): '.$reply);
10353: &log($udom,,$uname,$uhome,
10354: 'Authentication changed by '.$env{'user.domain'}.', '.
10355: $env{'user.name'}.', '.$umode.
10356: '(Remote '.$ip.'): '.$reply);
10357: unless ($reply eq 'ok') {
10358: &logthis('Authentication mode error: '.$reply);
10359: return 'error: '.$reply;
10360: }
10361: return 'ok';
10362: }
10363:
10364: # --------------------------------------------------------------- Modify a user
10365:
10366: sub modifyuser {
10367: my ($udom, $uname, $uid,
10368: $umode, $upass, $first,
10369: $middle, $last, $gene,
10370: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10371: $udom= &LONCAPA::clean_domain($udom);
10372: $uname=&LONCAPA::clean_username($uname);
10373: my $showcandelete = 'none';
10374: if (ref($candelete) eq 'ARRAY') {
10375: if (@{$candelete} > 0) {
10376: $showcandelete = join(', ',@{$candelete});
10377: }
10378: }
10379: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10380: $umode.', '.$first.', '.$middle.', '.
10381: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10382: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10383: ' desiredhome not specified').
10384: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10385: ' in domain '.$env{'request.role.domain'});
10386: my $uhome=&homeserver($uname,$udom,'true');
10387: my $newuser;
10388: if ($uhome eq 'no_host') {
10389: $newuser = 1;
10390: unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10391: ($umode eq 'lti')) {
10392: return 'error: more information needed to create new user';
10393: }
10394: }
10395: # ----------------------------------------------------------------- Create User
10396: if (($uhome eq 'no_host') &&
10397: (($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
10398: my $unhome='';
10399: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
10400: $unhome = $desiredhome;
10401: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10402: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10403: } else { # load balancing routine for determining $unhome
10404: my $loadm=10000000;
10405: my %servers = &get_servers($udom,'library');
10406: foreach my $tryserver (keys(%servers)) {
10407: my $answer=reply('load',$tryserver);
10408: if (($answer=~/\d+/) && ($answer<$loadm)) {
10409: $loadm=$answer;
10410: $unhome=$tryserver;
10411: }
10412: }
10413: }
10414: if (($unhome eq '') || ($unhome eq 'no_host')) {
10415: return 'error: unable to find a home server for '.$uname.
10416: ' in domain '.$udom;
10417: }
10418: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10419: &escape($upass),$unhome);
10420: unless ($reply eq 'ok') {
10421: return 'error: '.$reply;
10422: }
10423: $uhome=&homeserver($uname,$udom,'true');
10424: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10425: return 'error: unable verify users home machine.';
10426: }
10427: } # End of creation of new user
10428: # ---------------------------------------------------------------------- Add ID
10429: if ($uid) {
10430: $uid=~tr/A-Z/a-z/;
10431: my %uidhash=&idrget($udom,$uname);
10432: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
10433: && (!$forceid)) {
10434: unless ($uid eq $uidhash{$uname}) {
10435: return 'error: user id "'.$uid.'" does not match '.
10436: 'current user id "'.$uidhash{$uname}.'".';
10437: }
10438: } else {
10439: &idput($udom,{$uname => $uid},$uhome,'ids');
10440: }
10441: }
10442: # -------------------------------------------------------------- Add names, etc
10443: my @tmp=&get('environment',
10444: ['firstname','middlename','lastname','generation','id',
10445: 'permanentemail','inststatus'],
10446: $udom,$uname);
10447: my (%names,%oldnames);
10448: if ($tmp[0] =~ m/^error:.*/) {
10449: %names=();
10450: } else {
10451: %names = @tmp;
10452: %oldnames = %names;
10453: }
10454: #
10455: # If name, email and/or uid are blank (e.g., because an uploaded file
10456: # of users did not contain them), do not overwrite existing values
10457: # unless field is in $candelete array ref.
10458: #
10459:
10460: my @fields = ('firstname','middlename','lastname','generation',
10461: 'permanentemail','id');
10462: my %newvalues;
10463: if (ref($candelete) eq 'ARRAY') {
10464: foreach my $field (@fields) {
10465: if (grep(/^\Q$field\E$/,@{$candelete})) {
10466: if ($field eq 'firstname') {
10467: $names{$field} = $first;
10468: } elsif ($field eq 'middlename') {
10469: $names{$field} = $middle;
10470: } elsif ($field eq 'lastname') {
10471: $names{$field} = $last;
10472: } elsif ($field eq 'generation') {
10473: $names{$field} = $gene;
10474: } elsif ($field eq 'permanentemail') {
10475: $names{$field} = $email;
10476: } elsif ($field eq 'id') {
10477: $names{$field} = $uid;
10478: }
10479: }
10480: }
10481: }
10482: if ($first) { $names{'firstname'} = $first; }
10483: if (defined($middle)) { $names{'middlename'} = $middle; }
10484: if ($last) { $names{'lastname'} = $last; }
10485: if (defined($gene)) { $names{'generation'} = $gene; }
10486: if ($email) {
10487: $email=~s/[^\w\@\.\-\,]//gs;
10488: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10489: }
10490: if ($uid) { $names{'id'} = $uid; }
10491: if (defined($inststatus)) {
10492: $names{'inststatus'} = '';
10493: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10494: if (ref($usertypes) eq 'HASH') {
10495: my @okstatuses;
10496: foreach my $item (split(/:/,$inststatus)) {
10497: if (defined($usertypes->{$item})) {
10498: push(@okstatuses,$item);
10499: }
10500: }
10501: if (@okstatuses) {
10502: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10503: }
10504: }
10505: }
10506: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10507: $umode.', '.$first.', '.$middle.', '.
10508: $last.', '.$gene.', '.$email.', '.$inststatus;
10509: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10510: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10511: } else {
10512: $logmsg .= ' during self creation';
10513: }
10514: my $changed;
10515: if ($newuser) {
10516: $changed = 1;
10517: } else {
10518: foreach my $field (@fields) {
10519: if ($names{$field} ne $oldnames{$field}) {
10520: $changed = 1;
10521: last;
10522: }
10523: }
10524: }
10525: unless ($changed) {
10526: $logmsg = 'No changes in user information needed for: '.$logmsg;
10527: &logthis($logmsg);
10528: return 'ok';
10529: }
10530: my $reply = &put('environment', \%names, $udom,$uname);
10531: if ($reply ne 'ok') {
10532: return 'error: '.$reply;
10533: }
10534: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10535: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10536: }
10537: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10538: &devalidate_cache_new('namescache',$uname.':'.$udom);
10539: $logmsg = 'Success modifying user '.$logmsg;
10540: &logthis($logmsg);
10541: return 'ok';
10542: }
10543:
10544: # -------------------------------------------------------------- Modify student
10545:
10546: sub modifystudent {
10547: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10548: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10549: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10550: if (!$cid) {
10551: unless ($cid=$env{'request.course.id'}) {
10552: return 'not_in_class';
10553: }
10554: }
10555: # --------------------------------------------------------------- Make the user
10556: my $reply=&modifyuser
10557: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10558: $desiredhome,$email,$inststatus);
10559: unless ($reply eq 'ok') { return $reply; }
10560: # This will cause &modify_student_enrollment to get the uid from the
10561: # student's environment
10562: $uid = undef if (!$forceid);
10563: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10564: $gene,$usec,$end,$start,$type,$locktype,
10565: $cid,$selfenroll,$context,$credits,$instsec);
10566: return $reply;
10567: }
10568:
10569: sub modify_student_enrollment {
10570: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10571: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10572: my ($cdom,$cnum,$chome);
10573: if (!$cid) {
10574: unless ($cid=$env{'request.course.id'}) {
10575: return 'not_in_class';
10576: }
10577: $cdom=$env{'course.'.$cid.'.domain'};
10578: $cnum=$env{'course.'.$cid.'.num'};
10579: } else {
10580: ($cdom,$cnum)=split(/_/,$cid);
10581: }
10582: $chome=$env{'course.'.$cid.'.home'};
10583: if (!$chome) {
10584: $chome=&homeserver($cnum,$cdom);
10585: }
10586: if (!$chome) { return 'unknown_course'; }
10587: # Make sure the user exists
10588: my $uhome=&homeserver($uname,$udom);
10589: if (($uhome eq '') || ($uhome eq 'no_host')) {
10590: return 'error: no such user';
10591: }
10592: # Get student data if we were not given enough information
10593: if (!defined($first) || $first eq '' ||
10594: !defined($last) || $last eq '' ||
10595: !defined($uid) || $uid eq '' ||
10596: !defined($middle) || $middle eq '' ||
10597: !defined($gene) || $gene eq '') {
10598: # They did not supply us with enough data to enroll the student, so
10599: # we need to pick up more information.
10600: my %tmp = &get('environment',
10601: ['firstname','middlename','lastname', 'generation','id']
10602: ,$udom,$uname);
10603:
10604: #foreach my $key (keys(%tmp)) {
10605: # &logthis("key $key = ".$tmp{$key});
10606: #}
10607: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10608: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10609: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
10610: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
10611: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10612: }
10613: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10614: my $user = "$uname:$udom";
10615: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10616: my $reply=cput('classlist',
10617: {$user =>
10618: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10619: $cdom,$cnum);
10620: if (($reply eq 'ok') || ($reply eq 'delayed')) {
10621: &devalidate_getsection_cache($udom,$uname,$cid);
10622: } else {
10623: return 'error: '.$reply;
10624: }
10625: # Add student role to user
10626: my $uurl='/'.$cid;
10627: $uurl=~s/\_/\//g;
10628: if ($usec) {
10629: $uurl.='/'.$usec;
10630: }
10631: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10632: $selfenroll,$context);
10633: if ($result ne 'ok') {
10634: if ($old_entry{$user} ne '') {
10635: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10636: } else {
10637: $reply = &del('classlist',[$user],$cdom,$cnum);
10638: }
10639: }
10640: return $result;
10641: }
10642:
10643: sub format_name {
10644: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10645: my $name;
10646: if ($first ne 'lastname') {
10647: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10648: } else {
10649: if ($lastname=~/\S/) {
10650: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10651: $name=~s/\s+,/,/;
10652: } else {
10653: $name.= $firstname.' '.$middlename.' '.$generation;
10654: }
10655: }
10656: $name=~s/^\s+//;
10657: $name=~s/\s+$//;
10658: $name=~s/\s+/ /g;
10659: return $name;
10660: }
10661:
10662: # ------------------------------------------------- Write to course preferences
10663:
10664: sub writecoursepref {
10665: my ($courseid,%prefs)=@_;
10666: $courseid=~s/^\///;
10667: $courseid=~s/\_/\//g;
10668: my ($cdomain,$cnum)=split(/\//,$courseid);
10669: my $chome=homeserver($cnum,$cdomain);
10670: if (($chome eq '') || ($chome eq 'no_host')) {
10671: return 'error: no such course';
10672: }
10673: my $cstring='';
10674: foreach my $pref (keys(%prefs)) {
10675: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10676: }
10677: $cstring=~s/\&$//;
10678: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10679: }
10680:
10681: # ---------------------------------------------------------- Make/modify course
10682:
10683: sub createcourse {
10684: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10685: $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
10686: $url=&declutter($url);
10687: my $cid='';
10688: if ($context eq 'requestcourses') {
10689: my $can_create = 0;
10690: my ($ownername,$ownerdom) = split(':',$course_owner);
10691: if ($udom eq $ownerdom) {
10692: my $reload;
10693: if (($callercontext eq 'auto') &&
10694: ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
10695: $reload = 'reload';
10696: }
10697: if (&usertools_access($ownername,$ownerdom,$category,$reload,
10698: $context)) {
10699: $can_create = 1;
10700: }
10701: } else {
10702: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10703: $category);
10704: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10705: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10706: if (@curr > 0) {
10707: my @options = qw(approval validate autolimit);
10708: my $optregex = join('|',@options);
10709: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10710: $can_create = 1;
10711: }
10712: }
10713: }
10714: }
10715: if ($can_create) {
10716: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10717: unless (&allowed('ccc',$udom)) {
10718: return 'refused';
10719: }
10720: }
10721: } else {
10722: return 'refused';
10723: }
10724: } elsif (!&allowed('ccc',$udom)) {
10725: return 'refused';
10726: }
10727: # --------------------------------------------------------------- Get Unique ID
10728: my $uname;
10729: if ($cnum =~ /^$match_courseid$/) {
10730: my $chome=&homeserver($cnum,$udom,'true');
10731: if (($chome eq '') || ($chome eq 'no_host')) {
10732: $uname = $cnum;
10733: } else {
10734: $uname = &generate_coursenum($udom,$crstype);
10735: }
10736: } else {
10737: $uname = &generate_coursenum($udom,$crstype);
10738: }
10739: return $uname if ($uname =~ /^error/);
10740: # -------------------------------------------------- Check supplied server name
10741: if (!defined($course_server)) {
10742: if (defined(&domain($udom,'primary'))) {
10743: $course_server = &domain($udom,'primary');
10744: } else {
10745: $course_server = $env{'user.home'};
10746: }
10747: }
10748: my %host_servers =
10749: &Apache::lonnet::get_servers($udom,'library');
10750: unless ($host_servers{$course_server}) {
10751: return 'error: invalid home server for course: '.$course_server;
10752: }
10753: # ------------------------------------------------------------- Make the course
10754: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10755: $course_server);
10756: unless ($reply eq 'ok') { return 'error: '.$reply; }
10757: my $uhome=&homeserver($uname,$udom,'true');
10758: if (($uhome eq '') || ($uhome eq 'no_host')) {
10759: return 'error: no such course';
10760: }
10761: # ----------------------------------------------------------------- Course made
10762: # log existence
10763: my $now = time;
10764: my $newcourse = {
10765: $udom.'_'.$uname => {
10766: description => $description,
10767: inst_code => $inst_code,
10768: owner => $course_owner,
10769: type => $crstype,
10770: creator => $env{'user.name'}.':'.
10771: $env{'user.domain'},
10772: created => $now,
10773: context => $context,
10774: },
10775: };
10776: &courseidput($udom,$newcourse,$uhome,'notime');
10777: # set toplevel url
10778: my $topurl=$url;
10779: unless ($nonstandard) {
10780: # ------------------------------------------ For standard courses, make top url
10781: my $mapurl=&clutter($url);
10782: if ($mapurl eq '/res/') { $mapurl=''; }
10783: $env{'form.initmap'}=(<<ENDINITMAP);
10784: <map>
10785: <resource id="1" type="start"></resource>
10786: <resource id="2" src="$mapurl"></resource>
10787: <resource id="3" type="finish"></resource>
10788: <link index="1" from="1" to="2"></link>
10789: <link index="2" from="2" to="3"></link>
10790: </map>
10791: ENDINITMAP
10792: $topurl=&declutter(
10793: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10794: );
10795: }
10796: # ----------------------------------------------------------- Write preferences
10797: &writecoursepref($udom.'_'.$uname,
10798: ('description' => $description,
10799: 'url' => $topurl,
10800: 'internal.creator' => $env{'user.name'}.':'.
10801: $env{'user.domain'},
10802: 'internal.created' => $now,
10803: 'internal.creationcontext' => $context)
10804: );
10805: return '/'.$udom.'/'.$uname;
10806: }
10807:
10808: # ------------------------------------------------------------------- Create ID
10809: sub generate_coursenum {
10810: my ($udom,$crstype) = @_;
10811: my $domdesc = &domain($udom);
10812: return 'error: invalid domain' if ($domdesc eq '');
10813: my $first;
10814: if ($crstype eq 'Community') {
10815: $first = '0';
10816: } else {
10817: $first = int(1+rand(9));
10818: }
10819: my $uname=$first.
10820: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10821: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10822: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10823: # ----------------------------------------------- Make sure that does not exist
10824: my $uhome=&homeserver($uname,$udom,'true');
10825: unless (($uhome eq '') || ($uhome eq 'no_host')) {
10826: if ($crstype eq 'Community') {
10827: $first = '0';
10828: } else {
10829: $first = int(1+rand(9));
10830: }
10831: $uname=$first.
10832: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10833: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10834: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10835: $uhome=&homeserver($uname,$udom,'true');
10836: unless (($uhome eq '') || ($uhome eq 'no_host')) {
10837: return 'error: unable to generate unique course-ID';
10838: }
10839: }
10840: return $uname;
10841: }
10842:
10843: sub is_course {
10844: my ($cdom, $cnum) = scalar(@_) == 1 ?
10845: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
10846:
10847: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10848: my $uhome=&homeserver($cnum,$cdom);
10849: my $iscourse;
10850: if (grep { $_ eq $uhome } current_machine_ids()) {
10851: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10852: } else {
10853: my $hashid = $cdom.':'.$cnum;
10854: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10855: unless (defined($cached)) {
10856: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10857: $cnum,undef,undef,'.');
10858: $iscourse = 0;
10859: if (exists($courses{$cdom.'_'.$cnum})) {
10860: $iscourse = 1;
10861: }
10862: &do_cache_new('iscourse',$hashid,$iscourse,3600);
10863: }
10864: }
10865: return unless ($iscourse);
10866: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10867: }
10868:
10869: sub store_userdata {
10870: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10871: my $result;
10872: if ($datakey ne '') {
10873: if (ref($storehash) eq 'HASH') {
10874: if ($udom eq '' || $uname eq '') {
10875: $udom = $env{'user.domain'};
10876: $uname = $env{'user.name'};
10877: }
10878: my $uhome=&homeserver($uname,$udom);
10879: if (($uhome eq '') || ($uhome eq 'no_host')) {
10880: $result = 'error: no_host';
10881: } else {
10882: $storehash->{'ip'} = &get_requestor_ip();
10883: $storehash->{'host'} = $perlvar{'lonHostID'};
10884:
10885: my $namevalue='';
10886: foreach my $key (keys(%{$storehash})) {
10887: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10888: }
10889: $namevalue=~s/\&$//;
10890: unless ($namespace eq 'courserequests') {
10891: $datakey = &escape($datakey);
10892: }
10893: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
10894: $namevalue,$uhome);
10895: }
10896: } else {
10897: $result = 'error: data to store was not a hash reference';
10898: }
10899: } else {
10900: $result= 'error: invalid requestkey';
10901: }
10902: return $result;
10903: }
10904:
10905: # ---------------------------------------------------------- Assign Custom Role
10906:
10907: sub assigncustomrole {
10908: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10909: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10910: $end,$start,$deleteflag,$selfenroll,$context);
10911: }
10912:
10913: # ----------------------------------------------------------------- Revoke Role
10914:
10915: sub revokerole {
10916: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10917: my $now=time;
10918: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10919: }
10920:
10921: # ---------------------------------------------------------- Revoke Custom Role
10922:
10923: sub revokecustomrole {
10924: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10925: my $now=time;
10926: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10927: $deleteflag,$selfenroll,$context);
10928: }
10929:
10930: # ------------------------------------------------------------ Disk usage
10931: sub diskusage {
10932: my ($udom,$uname,$directorypath,$getpropath)=@_;
10933: $directorypath =~ s/\/$//;
10934: my $listing=&reply('du2:'.&escape($directorypath).':'
10935: .&escape($getpropath).':'.&escape($uname).':'
10936: .&escape($udom),homeserver($uname,$udom));
10937: if ($listing eq 'unknown_cmd') {
10938: if ($getpropath) {
10939: $directorypath = &propath($udom,$uname).'/'.$directorypath;
10940: }
10941: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10942: }
10943: return $listing;
10944: }
10945:
10946: sub is_locked {
10947: my ($file_name, $domain, $user, $which) = @_;
10948: my @check;
10949: my $is_locked;
10950: push (@check,$file_name);
10951: my %locked = &get('file_permissions',\@check,
10952: $env{'user.domain'},$env{'user.name'});
10953: my ($tmp)=keys(%locked);
10954: if ($tmp=~/^error:/) { undef(%locked); }
10955:
10956: if (ref($locked{$file_name}) eq 'ARRAY') {
10957: $is_locked = 'false';
10958: foreach my $entry (@{$locked{$file_name}}) {
10959: if (ref($entry) eq 'ARRAY') {
10960: $is_locked = 'true';
10961: if (ref($which) eq 'ARRAY') {
10962: push(@{$which},$entry);
10963: } else {
10964: last;
10965: }
10966: }
10967: }
10968: } else {
10969: $is_locked = 'false';
10970: }
10971: return $is_locked;
10972: }
10973:
10974: sub declutter_portfile {
10975: my ($file) = @_;
10976: $file =~ s{^(/portfolio/|portfolio/)}{/};
10977: return $file;
10978: }
10979:
10980: # ------------------------------------------------------------- Mark as Read Only
10981:
10982: sub mark_as_readonly {
10983: my ($domain,$user,$files,$what) = @_;
10984: my %current_permissions = &dump('file_permissions',$domain,$user);
10985: my ($tmp)=keys(%current_permissions);
10986: if ($tmp=~/^error:/) { undef(%current_permissions); }
10987: foreach my $file (@{$files}) {
10988: $file = &declutter_portfile($file);
10989: push(@{$current_permissions{$file}},$what);
10990: }
10991: &put('file_permissions',\%current_permissions,$domain,$user);
10992: return;
10993: }
10994:
10995: # ------------------------------------------------------------Save Selected Files
10996:
10997: sub save_selected_files {
10998: my ($user, $path, @files) = @_;
10999: my $filename = $user."savedfiles";
11000: my @other_files = &files_not_in_path($user, $path);
11001: open (OUT,'>',LONCAPA::tempdir().$filename);
11002: foreach my $file (@files) {
11003: print (OUT $env{'form.currentpath'}.$file."\n");
11004: }
11005: foreach my $file (@other_files) {
11006: print (OUT $file."\n");
11007: }
11008: close (OUT);
11009: return 'ok';
11010: }
11011:
11012: sub clear_selected_files {
11013: my ($user) = @_;
11014: my $filename = $user."savedfiles";
11015: open (OUT,'>',LONCAPA::tempdir().$filename);
11016: print (OUT undef);
11017: close (OUT);
11018: return ("ok");
11019: }
11020:
11021: sub files_in_path {
11022: my ($user, $path) = @_;
11023: my $filename = $user."savedfiles";
11024: my %return_files;
11025: open (IN,'<',LONCAPA::tempdir().$filename);
11026: while (my $line_in = <IN>) {
11027: chomp ($line_in);
11028: my @paths_and_file = split (m!/!, $line_in);
11029: my $file_part = pop (@paths_and_file);
11030: my $path_part = join ('/', @paths_and_file);
11031: $path_part.='/';
11032: my $path_and_file = $path_part.$file_part;
11033: if ($path_part eq $path) {
11034: $return_files{$file_part}= 'selected';
11035: }
11036: }
11037: close (IN);
11038: return (\%return_files);
11039: }
11040:
11041: # called in portfolio select mode, to show files selected NOT in current directory
11042: sub files_not_in_path {
11043: my ($user, $path) = @_;
11044: my $filename = $user."savedfiles";
11045: my @return_files;
11046: my $path_part;
11047: open(IN, '<',LONCAPA::tempdir().$filename);
11048: while (my $line = <IN>) {
11049: #ok, I know it's clunky, but I want it to work
11050: my @paths_and_file = split(m|/|, $line);
11051: my $file_part = pop(@paths_and_file);
11052: chomp($file_part);
11053: my $path_part = join('/', @paths_and_file);
11054: $path_part .= '/';
11055: my $path_and_file = $path_part.$file_part;
11056: if ($path_part ne $path) {
11057: push(@return_files, ($path_and_file));
11058: }
11059: }
11060: close(OUT);
11061: return (@return_files);
11062: }
11063:
11064: #------------------------------Submitted/Handedback Portfolio Files Versioning
11065:
11066: sub portfiles_versioning {
11067: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11068: my $portfolio_root = '/userfiles/portfolio';
11069: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11070: foreach my $file (@{$portfiles}) {
11071: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11072: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11073: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11074: my $getpropath = 1;
11075: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11076: $stu_name,$getpropath);
11077: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11078: my $new_answer =
11079: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11080: if ($new_answer ne 'problem getting file') {
11081: push(@{$versioned_portfiles}, $directory.$new_answer);
11082: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11083: [$symb,$env{'request.course.id'},'graded']);
11084: }
11085: }
11086: }
11087:
11088: sub get_next_version {
11089: my ($answer_name, $answer_ext, $dir_list) = @_;
11090: my $version;
11091: if (ref($dir_list) eq 'ARRAY') {
11092: foreach my $row (@{$dir_list}) {
11093: my ($file) = split(/\&/,$row,2);
11094: my ($file_name,$file_version,$file_ext) =
11095: &file_name_version_ext($file);
11096: if (($file_name eq $answer_name) &&
11097: ($file_ext eq $answer_ext)) {
11098: # gets here if filename and extension match,
11099: # regardless of version
11100: if ($file_version ne '') {
11101: # a versioned file is found so save it for later
11102: if ($file_version > $version) {
11103: $version = $file_version;
11104: }
11105: }
11106: }
11107: }
11108: }
11109: $version ++;
11110: return($version);
11111: }
11112:
11113: sub version_selected_portfile {
11114: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11115: my ($answer_name,$answer_ver,$answer_ext) =
11116: &file_name_version_ext($file_name);
11117: my $new_answer;
11118: $env{'form.copy'} =
11119: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11120: if($env{'form.copy'} eq '-1') {
11121: $new_answer = 'problem getting file';
11122: } else {
11123: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11124: my $copy_result =
11125: &finishuserfileupload($stu_name,$domain,'copy',
11126: '/portfolio'.$directory.$new_answer);
11127: }
11128: undef($env{'form.copy'});
11129: return ($new_answer);
11130: }
11131:
11132: sub file_name_version_ext {
11133: my ($file)=@_;
11134: my @file_parts = split(/\./, $file);
11135: my ($name,$version,$ext);
11136: if (@file_parts > 1) {
11137: $ext=pop(@file_parts);
11138: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11139: $version=pop(@file_parts);
11140: }
11141: $name=join('.',@file_parts);
11142: } else {
11143: $name=join('.',@file_parts);
11144: }
11145: return($name,$version,$ext);
11146: }
11147:
11148: #----------------------------------------------Get portfolio file permissions
11149:
11150: sub get_portfile_permissions {
11151: my ($domain,$user) = @_;
11152: my %current_permissions = &dump('file_permissions',$domain,$user);
11153: my ($tmp)=keys(%current_permissions);
11154: if ($tmp=~/^error:/) { undef(%current_permissions); }
11155: return \%current_permissions;
11156: }
11157:
11158: #---------------------------------------------Get portfolio file access controls
11159:
11160: sub get_access_controls {
11161: my ($current_permissions,$group,$file) = @_;
11162: my %access;
11163: my $real_file = $file;
11164: $file =~ s/\.meta$//;
11165: if (defined($file)) {
11166: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11167: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
11168: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
11169: }
11170: }
11171: } else {
11172: foreach my $key (keys(%{$current_permissions})) {
11173: if ($key =~ /\0accesscontrol$/) {
11174: if (defined($group)) {
11175: if ($key !~ m-^\Q$group\E/-) {
11176: next;
11177: }
11178: }
11179: my ($fullpath) = split(/\0/,$key);
11180: if (ref($$current_permissions{$key}) eq 'HASH') {
11181: foreach my $control (keys(%{$$current_permissions{$key}})) {
11182: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11183: }
11184: }
11185: }
11186: }
11187: }
11188: return %access;
11189: }
11190:
11191: sub modify_access_controls {
11192: my ($file_name,$changes,$domain,$user)=@_;
11193: my ($outcome,$deloutcome);
11194: my %store_permissions;
11195: my %new_values;
11196: my %new_control;
11197: my %translation;
11198: my @deletions = ();
11199: my $now = time;
11200: if (exists($$changes{'activate'})) {
11201: if (ref($$changes{'activate'}) eq 'HASH') {
11202: my @newitems = sort(keys(%{$$changes{'activate'}}));
11203: my $numnew = scalar(@newitems);
11204: for (my $i=0; $i<$numnew; $i++) {
11205: my $newkey = $newitems[$i];
11206: my $newid = &Apache::loncommon::get_cgi_id();
11207: if ($newkey =~ /^\d+:/) {
11208: $newkey =~ s/^(\d+)/$newid/;
11209: $translation{$1} = $newid;
11210: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11211: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11212: $translation{$1} = $newid;
11213: }
11214: $new_values{$file_name."\0".$newkey} =
11215: $$changes{'activate'}{$newitems[$i]};
11216: $new_control{$newkey} = $now;
11217: }
11218: }
11219: }
11220: my %todelete;
11221: my %changed_items;
11222: foreach my $action ('delete','update') {
11223: if (exists($$changes{$action})) {
11224: if (ref($$changes{$action}) eq 'HASH') {
11225: foreach my $key (keys(%{$$changes{$action}})) {
11226: my ($itemnum) = ($key =~ /^([^:]+):/);
11227: if ($action eq 'delete') {
11228: $todelete{$itemnum} = 1;
11229: } else {
11230: $changed_items{$itemnum} = $key;
11231: }
11232: }
11233: }
11234: }
11235: }
11236: # get lock on access controls for file.
11237: my $lockhash = {
11238: $file_name."\0".'locked_access_records' => $env{'user.name'}.
11239: ':'.$env{'user.domain'},
11240: };
11241: my $tries = 0;
11242: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11243:
11244: while (($gotlock ne 'ok') && $tries < 10) {
11245: $tries ++;
11246: sleep(0.1);
11247: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11248: }
11249: if ($gotlock eq 'ok') {
11250: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11251: my ($tmp)=keys(%curr_permissions);
11252: if ($tmp=~/^error:/) { undef(%curr_permissions); }
11253: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11254: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11255: if (ref($curr_controls) eq 'HASH') {
11256: foreach my $control_item (keys(%{$curr_controls})) {
11257: my ($itemnum) = ($control_item =~ /^([^:]+):/);
11258: if (defined($todelete{$itemnum})) {
11259: push(@deletions,$file_name."\0".$control_item);
11260: } else {
11261: if (defined($changed_items{$itemnum})) {
11262: $new_control{$changed_items{$itemnum}} = $now;
11263: push(@deletions,$file_name."\0".$control_item);
11264: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11265: } else {
11266: $new_control{$control_item} = $$curr_controls{$control_item};
11267: }
11268: }
11269: }
11270: }
11271: }
11272: my ($group);
11273: if (&is_course($domain,$user)) {
11274: ($group,my $file) = split(/\//,$file_name,2);
11275: }
11276: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11277: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11278: $outcome = &put('file_permissions',\%new_values,$domain,$user);
11279: # remove lock
11280: my @del_lock = ($file_name."\0".'locked_access_records');
11281: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
11282: my $sqlresult =
11283: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
11284: $group);
11285: } else {
11286: $outcome = "error: could not obtain lockfile\n";
11287: }
11288: return ($outcome,$deloutcome,\%new_values,\%translation);
11289: }
11290:
11291: sub make_public_indefinitely {
11292: my (@requrl) = @_;
11293: return &automated_portfile_access('public',\@requrl);
11294: }
11295:
11296: sub automated_portfile_access {
11297: my ($accesstype,$addsref,$delsref,$info) = @_;
11298: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11299: return 'invalid';
11300: }
11301: my %urls;
11302: if (ref($addsref) eq 'ARRAY') {
11303: foreach my $requrl (@{$addsref}) {
11304: if (&is_portfolio_url($requrl)) {
11305: unless (exists($urls{$requrl})) {
11306: $urls{$requrl} = 'add';
11307: }
11308: }
11309: }
11310: }
11311: if (ref($delsref) eq 'ARRAY') {
11312: foreach my $requrl (@{$delsref}) {
11313: if (&is_portfolio_url($requrl)) {
11314: unless (exists($urls{$requrl})) {
11315: $urls{$requrl} = 'delete';
11316: }
11317: }
11318: }
11319: }
11320: unless (keys(%urls)) {
11321: return 'invalid';
11322: }
11323: my $ip;
11324: if ($accesstype eq 'ip') {
11325: if (ref($info) eq 'HASH') {
11326: if ($info->{'ip'} ne '') {
11327: $ip = $info->{'ip'};
11328: }
11329: }
11330: if ($ip eq '') {
11331: return 'invalid';
11332: }
11333: }
11334: my $errors;
11335: my $now = time;
11336: my %current_perms;
11337: foreach my $requrl (sort(keys(%urls))) {
11338: my $action;
11339: if ($urls{$requrl} eq 'add') {
11340: $action = 'activate';
11341: } else {
11342: $action = 'none';
11343: }
11344: my $aclnum = 0;
11345: my (undef,$udom,$unum,$file_name,$group) =
11346: &parse_portfolio_url($requrl);
11347: unless (exists($current_perms{$unum.':'.$udom})) {
11348: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11349: }
11350: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
11351: $group,$file_name);
11352: foreach my $key (keys(%{$access_controls{$file_name}})) {
11353: my ($num,$scope,$end,$start) =
11354: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11355: if ($scope eq $accesstype) {
11356: if (($start <= $now) && ($end == 0)) {
11357: if ($accesstype eq 'ip') {
11358: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11359: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11360: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11361: if ($urls{$requrl} eq 'add') {
11362: $action = 'none';
11363: last;
11364: } else {
11365: $action = 'delete';
11366: $aclnum = $num;
11367: last;
11368: }
11369: }
11370: }
11371: }
11372: } elsif ($accesstype eq 'public') {
11373: if ($urls{$requrl} eq 'add') {
11374: $action = 'none';
11375: last;
11376: } else {
11377: $action = 'delete';
11378: $aclnum = $num;
11379: last;
11380: }
11381: }
11382: } elsif ($accesstype eq 'public') {
11383: $action = 'update';
11384: $aclnum = $num;
11385: last;
11386: }
11387: }
11388: }
11389: if ($action eq 'none') {
11390: next;
11391: } else {
11392: my %changes;
11393: my $newend = 0;
11394: my $newstart = $now;
11395: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
11396: $changes{$action}{$newkey} = {
11397: type => $accesstype,
11398: time => {
11399: start => $newstart,
11400: end => $newend,
11401: },
11402: };
11403: if ($accesstype eq 'ip') {
11404: $changes{$action}{$newkey}{'ip'} = [$ip];
11405: }
11406: my ($outcome,$deloutcome,$new_values,$translation) =
11407: &modify_access_controls($file_name,\%changes,$udom,$unum);
11408: unless ($outcome eq 'ok') {
11409: $errors .= $outcome.' ';
11410: }
11411: }
11412: }
11413: if ($errors) {
11414: $errors =~ s/\s$//;
11415: return $errors;
11416: } else {
11417: return 'ok';
11418: }
11419: }
11420:
11421: #------------------------------------------------------Get Marked as Read Only
11422:
11423: sub get_marked_as_readonly {
11424: my ($domain,$user,$what,$group) = @_;
11425: my $current_permissions = &get_portfile_permissions($domain,$user);
11426: my @readonly_files;
11427: my $cmp1=$what;
11428: if (ref($what)) { $cmp1=join('',@{$what}) };
11429: while (my ($file_name,$value) = each(%{$current_permissions})) {
11430: if (defined($group)) {
11431: if ($file_name !~ m-^\Q$group\E/-) {
11432: next;
11433: }
11434: }
11435: if (ref($value) eq "ARRAY"){
11436: foreach my $stored_what (@{$value}) {
11437: my $cmp2=$stored_what;
11438: if (ref($stored_what) eq 'ARRAY') {
11439: $cmp2=join('',@{$stored_what});
11440: }
11441: if ($cmp1 eq $cmp2) {
11442: push(@readonly_files, $file_name);
11443: last;
11444: } elsif (!defined($what)) {
11445: push(@readonly_files, $file_name);
11446: last;
11447: }
11448: }
11449: }
11450: }
11451: return @readonly_files;
11452: }
11453: #-----------------------------------------------------------Get Marked as Read Only Hash
11454:
11455: sub get_marked_as_readonly_hash {
11456: my ($current_permissions,$group,$what) = @_;
11457: my %readonly_files;
11458: while (my ($file_name,$value) = each(%{$current_permissions})) {
11459: if (defined($group)) {
11460: if ($file_name !~ m-^\Q$group\E/-) {
11461: next;
11462: }
11463: }
11464: if (ref($value) eq "ARRAY"){
11465: foreach my $stored_what (@{$value}) {
11466: if (ref($stored_what) eq 'ARRAY') {
11467: foreach my $lock_descriptor(@{$stored_what}) {
11468: if ($lock_descriptor eq 'graded') {
11469: $readonly_files{$file_name} = 'graded';
11470: } elsif ($lock_descriptor eq 'handback') {
11471: $readonly_files{$file_name} = 'handback';
11472: } else {
11473: if (!exists($readonly_files{$file_name})) {
11474: $readonly_files{$file_name} = 'locked';
11475: }
11476: }
11477: }
11478: }
11479: }
11480: }
11481: }
11482: return %readonly_files;
11483: }
11484: # ------------------------------------------------------------ Unmark as Read Only
11485:
11486: sub unmark_as_readonly {
11487: # unmarks $file_name (if $file_name is defined), or all files locked by $what
11488: # for portfolio submissions, $what contains [$symb,$crsid]
11489: my ($domain,$user,$what,$file_name,$group) = @_;
11490: $file_name = &declutter_portfile($file_name);
11491: my $symb_crs = $what;
11492: if (ref($what)) { $symb_crs=join('',@$what); }
11493: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
11494: my ($tmp)=keys(%current_permissions);
11495: if ($tmp=~/^error:/) { undef(%current_permissions); }
11496: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
11497: foreach my $file (@readonly_files) {
11498: my $clean_file = &declutter_portfile($file);
11499: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
11500: my $current_locks = $current_permissions{$file};
11501: my @new_locks;
11502: my @del_keys;
11503: if (ref($current_locks) eq "ARRAY"){
11504: foreach my $locker (@{$current_locks}) {
11505: my $compare=$locker;
11506: if (ref($locker) eq 'ARRAY') {
11507: $compare=join('',@{$locker});
11508: if ($compare ne $symb_crs) {
11509: push(@new_locks, $locker);
11510: }
11511: }
11512: }
11513: if (scalar(@new_locks) > 0) {
11514: $current_permissions{$file} = \@new_locks;
11515: } else {
11516: push(@del_keys, $file);
11517: &del('file_permissions',\@del_keys, $domain, $user);
11518: delete($current_permissions{$file});
11519: }
11520: }
11521: }
11522: &put('file_permissions',\%current_permissions,$domain,$user);
11523: return;
11524: }
11525:
11526: # ------------------------------------------------------------ Directory lister
11527:
11528: sub dirlist {
11529: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
11530: $uri=~s/^\///;
11531: $uri=~s/\/$//;
11532: my ($udom, $uname);
11533: if ($getuserdir) {
11534: $udom = $userdomain;
11535: $uname = $username;
11536: } else {
11537: (undef,$udom,$uname)=split(/\//,$uri);
11538: if(defined($userdomain)) {
11539: $udom = $userdomain;
11540: }
11541: if(defined($username)) {
11542: $uname = $username;
11543: }
11544: }
11545: my ($dirRoot,$listing,@listing_results);
11546:
11547: $dirRoot = $perlvar{'lonDocRoot'};
11548: if (defined($getpropath)) {
11549: $dirRoot = &propath($udom,$uname);
11550: $dirRoot =~ s/\/$//;
11551: } elsif (defined($getuserdir)) {
11552: my $subdir=$uname.'__';
11553: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11554: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11555: ."/$udom/$subdir/$uname";
11556: } elsif (defined($alternateRoot)) {
11557: $dirRoot = $alternateRoot;
11558: }
11559:
11560: if($udom) {
11561: if($uname) {
11562: my $uhome = &homeserver($uname,$udom);
11563: if ($uhome eq 'no_host') {
11564: return ([],'no_host');
11565: }
11566: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11567: .$getuserdir.':'.&escape($dirRoot)
11568: .':'.&escape($uname).':'.&escape($udom),$uhome);
11569: if ($listing eq 'unknown_cmd') {
11570: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11571: } else {
11572: @listing_results = map { &unescape($_); } split(/:/,$listing);
11573: }
11574: if ($listing eq 'unknown_cmd') {
11575: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11576: @listing_results = split(/:/,$listing);
11577: } else {
11578: @listing_results = map { &unescape($_); } split(/:/,$listing);
11579: }
11580: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11581: ($listing eq 'rejected') || ($listing eq 'refused') ||
11582: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11583: return ([],$listing);
11584: } else {
11585: return (\@listing_results);
11586: }
11587: } elsif(!$alternateRoot) {
11588: my (%allusers,%listerror);
11589: my %servers = &get_servers($udom,'library');
11590: foreach my $tryserver (keys(%servers)) {
11591: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11592: &escape($udom),$tryserver);
11593: if ($listing eq 'unknown_cmd') {
11594: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11595: $udom, $tryserver);
11596: } else {
11597: @listing_results = map { &unescape($_); } split(/:/,$listing);
11598: }
11599: if ($listing eq 'unknown_cmd') {
11600: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11601: $udom, $tryserver);
11602: @listing_results = split(/:/,$listing);
11603: } else {
11604: @listing_results =
11605: map { &unescape($_); } split(/:/,$listing);
11606: }
11607: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11608: ($listing eq 'rejected') || ($listing eq 'refused') ||
11609: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11610: $listerror{$tryserver} = $listing;
11611: } else {
11612: foreach my $line (@listing_results) {
11613: my ($entry) = split(/&/,$line,2);
11614: $allusers{$entry} = 1;
11615: }
11616: }
11617: }
11618: my @alluserslist=();
11619: foreach my $user (sort(keys(%allusers))) {
11620: push(@alluserslist,$user.'&user');
11621: }
11622:
11623: if (!%listerror) {
11624: # no errors
11625: return (\@alluserslist);
11626: } elsif (scalar(keys(%servers)) == 1) {
11627: # one library server, one error
11628: my ($key) = keys(%listerror);
11629: return (\@alluserslist, $listerror{$key});
11630: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11631: # con_lost indicates that we might miss data from at least one
11632: # library server
11633: return (\@alluserslist, 'con_lost');
11634: } else {
11635: # multiple library servers and no con_lost -> data should be
11636: # complete.
11637: return (\@alluserslist);
11638: }
11639:
11640: } else {
11641: return ([],'missing username');
11642: }
11643: } elsif(!defined($getpropath)) {
11644: my $path = $perlvar{'lonDocRoot'}.'/res/';
11645: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11646: return (\@all_domains);
11647: } else {
11648: return ([],'missing domain');
11649: }
11650: }
11651:
11652: # --------------------------------------------- GetFileTimestamp
11653: # This function utilizes dirlist and returns the date stamp for
11654: # when it was last modified. It will also return an error of -1
11655: # if an error occurs
11656:
11657: sub GetFileTimestamp {
11658: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11659: $studentDomain = &LONCAPA::clean_domain($studentDomain);
11660: $studentName = &LONCAPA::clean_username($studentName);
11661: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11662: undef,$getuserdir);
11663: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11664: return -1;
11665: }
11666: if (ref($fileref) eq 'ARRAY') {
11667: my @stats = split('&',$fileref->[0]);
11668: # @stats contains first the filename, then the stat output
11669: return $stats[10]; # so this is 10 instead of 9.
11670: } else {
11671: return -1;
11672: }
11673: }
11674:
11675: sub stat_file {
11676: my ($uri) = @_;
11677: $uri = &clutter_with_no_wrapper($uri);
11678:
11679: my ($udom,$uname,$file);
11680: if ($uri =~ m-^/(uploaded|editupload)/-) {
11681: ($udom,$uname,$file) =
11682: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11683: $file = 'userfiles/'.$file;
11684: }
11685: if ($uri =~ m-^/res/-) {
11686: ($udom,$uname) =
11687: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11688: $file = $uri;
11689: }
11690:
11691: if (!$udom || !$uname || !$file) {
11692: # unable to handle the uri
11693: return ();
11694: }
11695: my $getpropath;
11696: if ($file =~ /^userfiles\//) {
11697: $getpropath = 1;
11698: }
11699: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11700: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11701: return ();
11702: } else {
11703: if (ref($listref) eq 'ARRAY') {
11704: my @stats = split('&',$listref->[0]);
11705: shift(@stats); #filename is first
11706: return @stats;
11707: }
11708: }
11709: return ();
11710: }
11711:
11712: # --------------------------------------------------------- recursedirs
11713: # Recursive function to traverse either a specific user's Authoring Space
11714: # or corresponding Published Resource Space, and populate the hash ref:
11715: # $dirhashref with URLs of all directories, and if $filehashref hash
11716: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11717: # or .rights files in resource space, and .meta, .save, .log, and .bak
11718: # files in Authoring Space.
11719: #
11720: # Inputs:
11721: #
11722: # $is_home - true if current server is home server for user's space
11723: # $context - either: priv, or res respectively for Authoring or Resource Space.
11724: # $docroot - Document root (i.e., /home/httpd/html
11725: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11726: # $relpath - Current path (relative to top level).
11727: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11728: # $filehashref - reference to hash to populate with URLs of files (Optional)
11729: #
11730: # Returns: nothing
11731: #
11732: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11733: #
11734: # Currently used by interface/londocs.pm to create linked select boxes for
11735: # directory and filename to import a Course "Author" resource into a course, and
11736: # also to create linked select boxes for Authoring Space and Directory to choose
11737: # save location for creation of a new "standard" problem from the Course Editor.
11738: #
11739:
11740: sub recursedirs {
11741: my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11742: return unless (ref($dirhashref) eq 'HASH');
11743: my $currpath = $docroot.$toppath;
11744: if ($relpath) {
11745: $currpath .= "/$relpath";
11746: }
11747: my $savefile;
11748: if (ref($filehashref)) {
11749: $savefile = 1;
11750: }
11751: if ($is_home) {
11752: if (opendir(my $dirh,$currpath)) {
11753: foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11754: next if ($item eq '');
11755: if (-d "$currpath/$item") {
11756: my $newpath;
11757: if ($relpath) {
11758: $newpath = "$relpath/$item";
11759: } else {
11760: $newpath = $item;
11761: }
11762: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11763: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11764: } elsif ($savefile) {
11765: if ($context eq 'priv') {
11766: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11767: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11768: }
11769: } else {
11770: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11771: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11772: }
11773: }
11774: }
11775: }
11776: closedir($dirh);
11777: }
11778: } else {
11779: my ($dirlistref,$listerror) =
11780: &dirlist($toppath.$relpath);
11781: my @dir_lines;
11782: my $dirptr=16384;
11783: if (ref($dirlistref) eq 'ARRAY') {
11784: foreach my $dir_line (sort
11785: {
11786: my ($afile)=split('&',$a,2);
11787: my ($bfile)=split('&',$b,2);
11788: return (lc($afile) cmp lc($bfile));
11789: } (@{$dirlistref})) {
11790: my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11791: split(/\&/,$dir_line,16);
11792: $item =~ s/\s+$//;
11793: next if (($item =~ /^\.\.?$/) || ($obs));
11794: if ($dirptr&$testdir) {
11795: my $newpath;
11796: if ($relpath) {
11797: $newpath = "$relpath/$item";
11798: } else {
11799: $relpath = '/';
11800: $newpath = $item;
11801: }
11802: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11803: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11804: } elsif ($savefile) {
11805: if ($context eq 'priv') {
11806: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11807: $filehashref->{$relpath}{$item} = 1;
11808: }
11809: } else {
11810: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11811: $filehashref->{$relpath}{$item} = 1;
11812: }
11813: }
11814: }
11815: }
11816: }
11817: }
11818: return;
11819: }
11820:
11821: # -------------------------------------------------------- Value of a Condition
11822:
11823: # gets the value of a specific preevaluated condition
11824: # stored in the string $env{user.state.<cid>}
11825: # or looks up a condition reference in the bighash and if if hasn't
11826: # already been evaluated recurses into docondval to get the value of
11827: # the condition, then memoizing it to
11828: # $env{user.state.<cid>.<condition>}
11829: sub directcondval {
11830: my $number=shift;
11831: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11832: &Apache::lonuserstate::evalstate();
11833: }
11834: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11835: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11836: } elsif ($number =~ /^_/) {
11837: my $sub_condition;
11838: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11839: &GDBM_READER(),0640)) {
11840: $sub_condition=$bighash{'conditions'.$number};
11841: untie(%bighash);
11842: }
11843: my $value = &docondval($sub_condition);
11844: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11845: return $value;
11846: }
11847: if ($env{'user.state.'.$env{'request.course.id'}}) {
11848: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11849: } else {
11850: return 2;
11851: }
11852: }
11853:
11854: # get the collection of conditions for this resource
11855: sub condval {
11856: my $condidx=shift;
11857: my $allpathcond='';
11858: foreach my $cond (split(/\|/,$condidx)) {
11859: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11860: $allpathcond.=
11861: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11862: }
11863: }
11864: $allpathcond=~s/\|$//;
11865: return &docondval($allpathcond);
11866: }
11867:
11868: #evaluates an expression of conditions
11869: sub docondval {
11870: my ($allpathcond) = @_;
11871: my $result=0;
11872: if ($env{'request.course.id'}
11873: && defined($allpathcond)) {
11874: my $operand='|';
11875: my @stack;
11876: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11877: if ($chunk eq '(') {
11878: push @stack,($operand,$result);
11879: } elsif ($chunk eq ')') {
11880: my $before=pop @stack;
11881: if (pop @stack eq '&') {
11882: $result=$result>$before?$before:$result;
11883: } else {
11884: $result=$result>$before?$result:$before;
11885: }
11886: } elsif (($chunk eq '&') || ($chunk eq '|')) {
11887: $operand=$chunk;
11888: } else {
11889: my $new=directcondval($chunk);
11890: if ($operand eq '&') {
11891: $result=$result>$new?$new:$result;
11892: } else {
11893: $result=$result>$new?$result:$new;
11894: }
11895: }
11896: }
11897: }
11898: return $result;
11899: }
11900:
11901: # ---------------------------------------------------- Devalidate courseresdata
11902:
11903: sub devalidatecourseresdata {
11904: my ($coursenum,$coursedomain)=@_;
11905: my $hashid=$coursenum.':'.$coursedomain;
11906: &devalidate_cache_new('courseres',$hashid);
11907: }
11908:
11909:
11910: # --------------------------------------------------- Course Resourcedata Query
11911: #
11912: # Parameters:
11913: # $coursenum - Number of the course.
11914: # $coursedomain - Domain at which the course was created.
11915: # Returns:
11916: # A hash of the course parameters along (I think) with timestamps
11917: # and version info.
11918:
11919: sub get_courseresdata {
11920: my ($coursenum,$coursedomain)=@_;
11921: my $coursehom=&homeserver($coursenum,$coursedomain);
11922: my $hashid=$coursenum.':'.$coursedomain;
11923: my ($result,$cached)=&is_cached_new('courseres',$hashid);
11924: my %dumpreply;
11925: unless (defined($cached)) {
11926: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11927: $result=\%dumpreply;
11928: my ($tmp) = keys(%dumpreply);
11929: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11930: &do_cache_new('courseres',$hashid,$result,600);
11931: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11932: return $tmp;
11933: } elsif ($tmp =~ /^(error)/) {
11934: $result=undef;
11935: &do_cache_new('courseres',$hashid,$result,600);
11936: }
11937: }
11938: return $result;
11939: }
11940:
11941: sub devalidateuserresdata {
11942: my ($uname,$udom)=@_;
11943: my $hashid="$udom:$uname";
11944: &devalidate_cache_new('userres',$hashid);
11945: }
11946:
11947: sub get_userresdata {
11948: my ($uname,$udom)=@_;
11949: #most student don\'t have any data set, check if there is some data
11950: if (&EXT_cache_status($udom,$uname)) { return undef; }
11951:
11952: my $hashid="$udom:$uname";
11953: my ($result,$cached)=&is_cached_new('userres',$hashid);
11954: if (!defined($cached)) {
11955: my %resourcedata=&dump('resourcedata',$udom,$uname);
11956: $result=\%resourcedata;
11957: &do_cache_new('userres',$hashid,$result,600);
11958: }
11959: my ($tmp)=keys(%$result);
11960: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11961: return $result;
11962: }
11963: #error 2 occurs when the .db doesn't exist
11964: if ($tmp!~/error: 2 /) {
11965: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11966: &logthis("<font color=\"blue\">WARNING:".
11967: " Trying to get resource data for ".
11968: $uname." at ".$udom.": ".
11969: $tmp."</font>");
11970: }
11971: } elsif ($tmp=~/error: 2 /) {
11972: #&EXT_cache_set($udom,$uname);
11973: &do_cache_new('userres',$hashid,undef,600);
11974: undef($tmp); # not really an error so don't send it back
11975: }
11976: return $tmp;
11977: }
11978: #----------------------------------------------- resdata - return resource data
11979: # Purpose:
11980: # Return resource data for either users or for a course.
11981: # Parameters:
11982: # $name - Course/user name.
11983: # $domain - Name of the domain the user/course is registered on.
11984: # $type - Type of thing $name is (must be 'course' or 'user')
11985: # $mapp - decluttered URL of enclosing map
11986: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
11987: # $recurseup - Ref to array of map URLs, starting with map containing
11988: # $mapp up through hierarchy of nested maps to top level map.
11989: # $courseid - CourseID (first part of param identifier).
11990: # $modifier - Middle part of param identifier.
11991: # $what - Last part of param identifier.
11992: # @which - Array of names of resources desired.
11993: # Returns:
11994: # The value of the first reasource in @which that is found in the
11995: # resource hash.
11996: # Exceptional Conditions:
11997: # If the $type passed in is not valid (not the string 'course' or
11998: # 'user', an undefined reference is returned.
11999: # If none of the resources are found, an undef is returned
12000: sub resdata {
12001: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12002: $modifier,$what,@which)=@_;
12003: my $result;
12004: if ($type eq 'course') {
12005: $result=&get_courseresdata($name,$domain);
12006: } elsif ($type eq 'user') {
12007: $result=&get_userresdata($name,$domain);
12008: }
12009: if (!ref($result)) { return $result; }
12010: foreach my $item (@which) {
12011: if ($item->[1] eq 'course') {
12012: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12013: unless ($$recursed) {
12014: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
12015: $$recursed = 1;
12016: }
12017: foreach my $item (@${recurseup}) {
12018: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12019: last if (defined($result->{$norecursechk}));
12020: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12021: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12022: }
12023: }
12024: }
12025: if (defined($result->{$item->[0]})) {
12026: return [$result->{$item->[0]},$item->[1]];
12027: }
12028: }
12029: return undef;
12030: }
12031:
12032: sub get_domain_lti {
12033: my ($cdom,$context) = @_;
12034: my ($name,%lti);
12035: if ($context eq 'consumer') {
12036: $name = 'ltitools';
12037: } elsif ($context eq 'provider') {
12038: $name = 'lti';
12039: } else {
12040: return %lti;
12041: }
12042: my ($result,$cached)=&is_cached_new($name,$cdom);
12043: if (defined($cached)) {
12044: if (ref($result) eq 'HASH') {
12045: %lti = %{$result};
12046: }
12047: } else {
12048: my %domconfig = &get_dom('configuration',[$name],$cdom);
12049: if (ref($domconfig{$name}) eq 'HASH') {
12050: %lti = %{$domconfig{$name}};
12051: my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
12052: if (ref($encdomconfig{$name}) eq 'HASH') {
12053: foreach my $id (keys(%lti)) {
12054: if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
12055: foreach my $item ('key','secret') {
12056: $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
12057: }
12058: }
12059: }
12060: }
12061: }
12062: my $cachetime = 24*60*60;
12063: &do_cache_new($name,$cdom,\%lti,$cachetime);
12064: }
12065: return %lti;
12066: }
12067:
12068: sub get_numsuppfiles {
12069: my ($cnum,$cdom,$ignorecache)=@_;
12070: my $hashid=$cnum.':'.$cdom;
12071: my ($suppcount,$cached);
12072: unless ($ignorecache) {
12073: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
12074: }
12075: unless (defined($cached)) {
12076: my $chome=&homeserver($cnum,$cdom);
12077: unless ($chome eq 'no_host') {
12078: ($suppcount,my $supptools,my $errors) = (0,0,0);
12079: my $suppmap = 'supplemental.sequence';
12080: ($suppcount,$supptools,$errors) =
12081: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
12082: $supptools,$errors);
12083: }
12084: &do_cache_new('suppcount',$hashid,$suppcount,600);
12085: }
12086: return $suppcount;
12087: }
12088:
12089: #
12090: # EXT resource caching routines
12091: #
12092:
12093: {
12094: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12095: #
12096: # The course for which we cache
12097: my $cachedmapkey='';
12098: # The cached recursive maps for this course
12099: my %cachedmaps=();
12100: # When this was last done
12101: my $cachedmaptime='';
12102:
12103: sub clear_EXT_cache_status {
12104: &delenv('cache.EXT.');
12105: }
12106:
12107: sub EXT_cache_status {
12108: my ($target_domain,$target_user) = @_;
12109: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12110: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
12111: # We know already the user has no data
12112: return 1;
12113: } else {
12114: return 0;
12115: }
12116: }
12117:
12118: sub EXT_cache_set {
12119: my ($target_domain,$target_user) = @_;
12120: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12121: #&appenv({$cachename => time});
12122: }
12123:
12124: # --------------------------------------------------------- Value of a Variable
12125: sub EXT {
12126:
12127: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
12128: unless ($varname) { return ''; }
12129: #get real user name/domain, courseid and symb
12130: my $courseid;
12131: my $publicuser;
12132: if ($symbparm) {
12133: $symbparm=&get_symb_from_alias($symbparm);
12134: }
12135: if (!($uname && $udom)) {
12136: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
12137: if (!$symbparm) { $symbparm=$cursymb; }
12138: } else {
12139: $courseid=$env{'request.course.id'};
12140: }
12141: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12142: my $rest;
12143: if (defined($therest[0])) {
12144: $rest=join('.',@therest);
12145: } else {
12146: $rest='';
12147: }
12148:
12149: my $qualifierrest=$qualifier;
12150: if ($rest) { $qualifierrest.='.'.$rest; }
12151: my $spacequalifierrest=$space;
12152: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
12153: if ($realm eq 'user') {
12154: # --------------------------------------------------------------- user.resource
12155: if ($space eq 'resource') {
12156: if ( (defined($Apache::lonhomework::parsing_a_problem)
12157: || defined($Apache::lonhomework::parsing_a_task))
12158: &&
12159: ($symbparm eq &symbread()) ) {
12160: # if we are in the middle of processing the resource the
12161: # get the value we are planning on committing
12162: if (defined($Apache::lonhomework::results{$qualifierrest})) {
12163: return $Apache::lonhomework::results{$qualifierrest};
12164: } else {
12165: return $Apache::lonhomework::history{$qualifierrest};
12166: }
12167: } else {
12168: my %restored;
12169: if ($publicuser || $env{'request.state'} eq 'construct') {
12170: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12171: } else {
12172: %restored=&restore($symbparm,$courseid,$udom,$uname);
12173: }
12174: return $restored{$qualifierrest};
12175: }
12176: # ----------------------------------------------------------------- user.access
12177: } elsif ($space eq 'access') {
12178: # FIXME - not supporting calls for a specific user
12179: return &allowed($qualifier,$rest);
12180: # ------------------------------------------ user.preferences, user.environment
12181: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
12182: if (($uname eq $env{'user.name'}) &&
12183: ($udom eq $env{'user.domain'})) {
12184: return $env{join('.',('environment',$qualifierrest))};
12185: } else {
12186: my %returnhash;
12187: if (!$publicuser) {
12188: %returnhash=&userenvironment($udom,$uname,
12189: $qualifierrest);
12190: }
12191: return $returnhash{$qualifierrest};
12192: }
12193: # ----------------------------------------------------------------- user.course
12194: } elsif ($space eq 'course') {
12195: # FIXME - not supporting calls for a specific user
12196: return $env{join('.',('request.course',$qualifier))};
12197: # ------------------------------------------------------------------- user.role
12198: } elsif ($space eq 'role') {
12199: # FIXME - not supporting calls for a specific user
12200: my ($role,$where)=split(/\./,$env{'request.role'});
12201: if ($qualifier eq 'value') {
12202: return $role;
12203: } elsif ($qualifier eq 'extent') {
12204: return $where;
12205: }
12206: # ----------------------------------------------------------------- user.domain
12207: } elsif ($space eq 'domain') {
12208: return $udom;
12209: # ------------------------------------------------------------------- user.name
12210: } elsif ($space eq 'name') {
12211: return $uname;
12212: # ---------------------------------------------------- Any other user namespace
12213: } else {
12214: my %reply;
12215: if (!$publicuser) {
12216: %reply=&get($space,[$qualifierrest],$udom,$uname);
12217: }
12218: return $reply{$qualifierrest};
12219: }
12220: } elsif ($realm eq 'query') {
12221: # ---------------------------------------------- pull stuff out of query string
12222: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12223: [$spacequalifierrest]);
12224: return $env{'form.'.$spacequalifierrest};
12225: } elsif ($realm eq 'request') {
12226: # ------------------------------------------------------------- request.browser
12227: if ($space eq 'browser') {
12228: return $env{'browser.'.$qualifier};
12229: # ------------------------------------------------------------ request.filename
12230: } else {
12231: return $env{'request.'.$spacequalifierrest};
12232: }
12233: } elsif ($realm eq 'course') {
12234: # ---------------------------------------------------------- course.description
12235: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
12236: } elsif ($realm eq 'resource') {
12237:
12238: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
12239: if (!$symbparm) { $symbparm=&symbread(); }
12240: }
12241:
12242: if ($qualifier eq '') {
12243: if ($space eq 'title') {
12244: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12245: return &gettitle($symbparm);
12246: }
12247:
12248: if ($space eq 'map') {
12249: my ($map) = &decode_symb($symbparm);
12250: return &symbread($map);
12251: }
12252: if ($space eq 'maptitle') {
12253: my ($map) = &decode_symb($symbparm);
12254: return &gettitle($map);
12255: }
12256: if ($space eq 'filename') {
12257: if ($symbparm) {
12258: return &clutter((&decode_symb($symbparm))[2]);
12259: }
12260: return &hreflocation('',$env{'request.filename'});
12261: }
12262:
12263: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12264: if ($space eq 'visibleparts') {
12265: my $navmap = Apache::lonnavmaps::navmap->new();
12266: my $item;
12267: if (ref($navmap)) {
12268: my $res = $navmap->getBySymb($symbparm);
12269: my $parts = $res->parts();
12270: if (ref($parts) eq 'ARRAY') {
12271: $item = join(',',@{$parts});
12272: }
12273: undef($navmap);
12274: }
12275: return $item;
12276: }
12277: }
12278: }
12279:
12280: my ($section, $group, @groups, @recurseup, $recursed);
12281: my ($courselevelm,$courseleveli,$courselevel,$mapp);
12282: if (($courseid eq '') && ($cid)) {
12283: $courseid = $cid;
12284: }
12285: if (($symbparm && $courseid) &&
12286: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
12287:
12288: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
12289:
12290: # ----------------------------------------------------- Cascading lookup scheme
12291: my $symbp=$symbparm;
12292: $mapp=&deversion((&decode_symb($symbp))[0]);
12293: my $symbparm=$symbp.'.'.$spacequalifierrest;
12294: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
12295: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
12296: if (($env{'user.name'} eq $uname) &&
12297: ($env{'user.domain'} eq $udom)) {
12298: $section=$env{'request.course.sec'};
12299: @groups = split(/:/,$env{'request.course.groups'});
12300: @groups=&sort_course_groups($courseid,@groups);
12301: } else {
12302: if (! defined($usection)) {
12303: $section=&getsection($udom,$uname,$courseid);
12304: } else {
12305: $section = $usection;
12306: }
12307: @groups = &get_users_groups($udom,$uname,$courseid);
12308: }
12309:
12310: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12311: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
12312: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
12313: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12314:
12315: $courselevel=$courseid.'.'.$spacequalifierrest;
12316: my $courselevelr=$courseid.'.'.$symbparm;
12317: $courseleveli=$courseid.'.'.$recurseparm;
12318: $courselevelm=$courseid.'.'.$mapparm;
12319:
12320: # ----------------------------------------------------------- first, check user
12321:
12322: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12323: \@recurseup,$courseid,'.',$spacequalifierrest,
12324: ([$courselevelr,'resource'],
12325: [$courselevelm,'map' ],
12326: [$courseleveli,'map' ],
12327: [$courselevel, 'course' ]));
12328: if (defined($userreply)) { return &get_reply($userreply); }
12329:
12330: # ------------------------------------------------ second, check some of course
12331: my $coursereply;
12332: if (@groups > 0) {
12333: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
12334: $recurseparm,$mapparm,$spacequalifierrest,
12335: $mapp,\$recursed,\@recurseup);
12336: if (defined($coursereply)) { return &get_reply($coursereply); }
12337: }
12338:
12339: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12340: $env{'course.'.$courseid.'.domain'},
12341: 'course',$mapp,\$recursed,\@recurseup,
12342: $courseid,'.['.$section.'].',$spacequalifierrest,
12343: ([$seclevelr, 'resource'],
12344: [$seclevelm, 'map' ],
12345: [$secleveli, 'map' ],
12346: [$seclevel, 'course' ],
12347: [$courselevelr,'resource']));
12348: if (defined($coursereply)) { return &get_reply($coursereply); }
12349:
12350: # ------------------------------------------------------ third, check map parms
12351: my %parmhash=();
12352: my $thisparm='';
12353: if (tie(%parmhash,'GDBM_File',
12354: $env{'request.course.fn'}.'_parms.db',
12355: &GDBM_READER(),0640)) {
12356: $thisparm=$parmhash{$symbparm};
12357: untie(%parmhash);
12358: }
12359: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
12360: }
12361: # ------------------------------------------ fourth, look in resource metadata
12362:
12363: my $what = $spacequalifierrest;
12364: $what=~s/\./\_/;
12365: my $filename;
12366: if (!$symbparm) { $symbparm=&symbread(); }
12367: if ($symbparm) {
12368: $filename=(&decode_symb($symbparm))[2];
12369: } else {
12370: $filename=$env{'request.filename'};
12371: }
12372: my $toolsymb;
12373: if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12374: $toolsymb = $symbparm;
12375: }
12376: my $metadata=&metadata($filename,$what,$toolsymb);
12377: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12378: $metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
12379: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12380:
12381: # ----------------------------------------------- fifth, look in rest of course
12382: if ($symbparm && defined($courseid) &&
12383: $courseid eq $env{'request.course.id'}) {
12384: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12385: $env{'course.'.$courseid.'.domain'},
12386: 'course',$mapp,\$recursed,\@recurseup,
12387: $courseid,'.',$spacequalifierrest,
12388: ([$courselevelm,'map' ],
12389: [$courseleveli,'map' ],
12390: [$courselevel, 'course']));
12391: if (defined($coursereply)) { return &get_reply($coursereply); }
12392: }
12393: # ------------------------------------------------------------------ Cascade up
12394: unless ($space eq '0') {
12395: my @parts=split(/_/,$space);
12396: my $id=pop(@parts);
12397: my $part=join('_',@parts);
12398: if ($part eq '') { $part='0'; }
12399: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
12400: $symbparm,$udom,$uname,$section,1);
12401: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
12402: }
12403: if ($recurse) { return undef; }
12404: my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
12405: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
12406: # ---------------------------------------------------- Any other user namespace
12407: } elsif ($realm eq 'environment') {
12408: # ----------------------------------------------------------------- environment
12409: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12410: return $env{'environment.'.$spacequalifierrest};
12411: } else {
12412: if ($uname eq 'anonymous' && $udom eq '') {
12413: return '';
12414: }
12415: my %returnhash=&userenvironment($udom,$uname,
12416: $spacequalifierrest);
12417: return $returnhash{$spacequalifierrest};
12418: }
12419: } elsif ($realm eq 'system') {
12420: # ----------------------------------------------------------------- system.time
12421: if ($space eq 'time') {
12422: return time;
12423: }
12424: } elsif ($realm eq 'server') {
12425: # ----------------------------------------------------------------- system.time
12426: if ($space eq 'name') {
12427: return $ENV{'SERVER_NAME'};
12428: }
12429: } elsif ($realm eq 'client') {
12430: if ($space eq 'remote_addr') {
12431: return &get_requestor_ip();
12432: }
12433: }
12434: return '';
12435: }
12436:
12437: sub get_reply {
12438: my ($reply_value) = @_;
12439: if (ref($reply_value) eq 'ARRAY') {
12440: if (wantarray) {
12441: return @$reply_value;
12442: }
12443: return $reply_value->[0];
12444: } else {
12445: return $reply_value;
12446: }
12447: }
12448:
12449: sub check_group_parms {
12450: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12451: $recursed,$recurseupref) = @_;
12452: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12453: [$what,'course']);
12454: my $coursereply;
12455: foreach my $group (@{$groups}) {
12456: my @groupitems = ();
12457: foreach my $level (@levels) {
12458: my $item = $courseid.'.['.$group.'].'.$level->[0];
12459: push(@groupitems,[$item,$level->[1]]);
12460: }
12461: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12462: $env{'course.'.$courseid.'.domain'},
12463: 'course',$mapp,$recursed,$recurseupref,
12464: $courseid,'.['.$group.'].',$what,
12465: @groupitems);
12466: last if (defined($coursereply));
12467: }
12468: return $coursereply;
12469: }
12470:
12471: sub get_map_hierarchy {
12472: my ($mapname,$courseid) = @_;
12473: my @recurseup = ();
12474: if ($mapname) {
12475: if (($cachedmapkey eq $courseid) &&
12476: (abs($cachedmaptime-time)<5)) {
12477: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12478: return @{$cachedmaps{$mapname}};
12479: }
12480: }
12481: my $navmap = Apache::lonnavmaps::navmap->new();
12482: if (ref($navmap)) {
12483: @recurseup = $navmap->recurseup_maps($mapname);
12484: undef($navmap);
12485: $cachedmaps{$mapname} = \@recurseup;
12486: $cachedmaptime=time;
12487: $cachedmapkey=$courseid;
12488: }
12489: }
12490: return @recurseup;
12491: }
12492:
12493: }
12494:
12495: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
12496: my ($courseid,@groups) = @_;
12497: @groups = sort(@groups);
12498: return @groups;
12499: }
12500:
12501: sub packages_tab_default {
12502: my ($uri,$varname,$toolsymb)=@_;
12503: my (undef,$part,$name)=split(/\./,$varname);
12504:
12505: my (@extension,@specifics,$do_default);
12506: foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
12507: my ($pack_type,$pack_part)=split(/_/,$package,2);
12508: if ($pack_type eq 'default') {
12509: $do_default=1;
12510: } elsif ($pack_type eq 'extension') {
12511: push(@extension,[$package,$pack_type,$pack_part]);
12512: } elsif ($pack_part eq $part || $pack_type eq 'part') {
12513: # only look at packages defaults for packages that this id is
12514: push(@specifics,[$package,$pack_type,$pack_part]);
12515: }
12516: }
12517: # first look for a package that matches the requested part id
12518: foreach my $package (@specifics) {
12519: my (undef,$pack_type,$pack_part)=@{$package};
12520: next if ($pack_part ne $part);
12521: if (defined($packagetab{"$pack_type&$name&default"})) {
12522: return $packagetab{"$pack_type&$name&default"};
12523: }
12524: }
12525: # look for any possible matching non extension_ package
12526: foreach my $package (@specifics) {
12527: my (undef,$pack_type,$pack_part)=@{$package};
12528: if (defined($packagetab{"$pack_type&$name&default"})) {
12529: return $packagetab{"$pack_type&$name&default"};
12530: }
12531: if ($pack_type eq 'part') { $pack_part='0'; }
12532: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12533: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
12534: }
12535: }
12536: # look for any posible extension_ match
12537: foreach my $package (@extension) {
12538: my ($package,$pack_type)=@{$package};
12539: if (defined($packagetab{"$pack_type&$name&default"})) {
12540: return $packagetab{"$pack_type&$name&default"};
12541: }
12542: if (defined($packagetab{$package."&$name&default"})) {
12543: return $packagetab{$package."&$name&default"};
12544: }
12545: }
12546: # look for a global default setting
12547: if ($do_default && defined($packagetab{"default&$name&default"})) {
12548: return $packagetab{"default&$name&default"};
12549: }
12550: return undef;
12551: }
12552:
12553: sub add_prefix_and_part {
12554: my ($prefix,$part)=@_;
12555: my $keyroot;
12556: if (defined($prefix) && $prefix !~ /^__/) {
12557: # prefix that has a part already
12558: $keyroot=$prefix;
12559: } elsif (defined($prefix)) {
12560: # prefix that is missing a part
12561: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12562: } else {
12563: # no prefix at all
12564: if (defined($part)) { $keyroot='_'.$part; }
12565: }
12566: return $keyroot;
12567: }
12568:
12569: # ---------------------------------------------------------------- Get metadata
12570:
12571: my %metaentry;
12572: my %importedpartids;
12573: my %importedrespids;
12574: sub metadata {
12575: my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
12576: $uri=&declutter($uri);
12577: # if it is a non metadata possible uri return quickly
12578: if (($uri eq '') ||
12579: (($uri =~ m|^/*adm/|) &&
12580: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
12581: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
12582: return undef;
12583: }
12584: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
12585: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
12586: return undef;
12587: }
12588: my $filename=$uri;
12589: $uri=~s/\.meta$//;
12590: #
12591: # Is the metadata already cached?
12592: # Look at timestamp of caching
12593: # Everything is cached by the main uri, libraries are never directly cached
12594: #
12595: if (!defined($liburi)) {
12596: my ($result,$cached)=&is_cached_new('meta',$uri);
12597: if (defined($cached)) { return $result->{':'.$what}; }
12598: }
12599:
12600: #
12601: # If the uri is for an external tool the file from
12602: # which metadata should be retrieved depends on whether
12603: # the tool had been configured to be gradable (set in the Course
12604: # Editor or Resource Editor).
12605: #
12606: # If a valid symb has been included as the third arg in the call
12607: # to &metadata() that can be used to retrieve the value of
12608: # parameter_0_gradable set for the resource, and included in the
12609: # uploaded map containing the tool. The value is retrieved via
12610: # &EXT(), if a valid symb is available. Otherwise the value of
12611: # gradable in the exttool_$marker.db file for the tool instance
12612: # is retrieved via &get().
12613: #
12614: # When lonuserstate::traceroute() calls lonnet::EXT() for
12615: # hiddenresource and encrypturl (during course initialization)
12616: # the map-level parameter for resource.0.gradable included in the
12617: # uploaded map containing the tool will not yet have been stored
12618: # in the user_course_parms.db file for the user's session, so in
12619: # this case fall back to retrieving gradable status from the
12620: # exttool_$marker.db file.
12621: #
12622: # In order to avoid an infinite loop, &metadata() will return
12623: # before a call to &EXT(), if the uri is for an external tool
12624: # and the $what for which metadata is being requested is
12625: # parameter_0_gradable or 0_gradable.
12626: #
12627:
12628: if ($uri =~ /ext\.tool$/) {
12629: if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12630: return;
12631: } else {
12632: my ($checked,$use_passback);
12633: if ($toolsymb ne '') {
12634: (undef,undef,my $tooluri) = &decode_symb($toolsymb);
12635: if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
12636: $checked = 1;
12637: if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12638: $use_passback = 1;
12639: }
12640: }
12641: }
12642: unless ($checked) {
12643: my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12644: $marker=~s/\D//g;
12645: if ($marker) {
12646: my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12647: $use_passback = $toolsettings{'gradable'};
12648: }
12649: }
12650: if ($use_passback) {
12651: $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12652: } else {
12653: $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12654: }
12655: }
12656: }
12657:
12658: {
12659: # Imported parts would go here
12660: my @origfiletagids=();
12661: my $importedparts=0;
12662:
12663: # Imported responseids would go here
12664: my $importedresponses=0;
12665: #
12666: # Is this a recursive call for a library?
12667: #
12668: # if (! exists($metacache{$uri})) {
12669: # $metacache{$uri}={};
12670: # }
12671: my $cachetime = 60*60;
12672: if ($liburi) {
12673: $liburi=&declutter($liburi);
12674: $filename=$liburi;
12675: } else {
12676: &devalidate_cache_new('meta',$uri);
12677: undef(%metaentry);
12678: }
12679: my %metathesekeys=();
12680: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
12681: my $metastring;
12682: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
12683: my $which = &hreflocation('','/'.($liburi || $uri));
12684: $metastring =
12685: &Apache::lonnet::ssi_body($which,
12686: ('grade_target' => 'meta'));
12687: $cachetime = 1; # only want this cached in the child not long term
12688: } elsif (($uri !~ m -^(editupload)/-) &&
12689: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
12690: my $file=&filelocation('',&clutter($filename));
12691: #push(@{$metaentry{$uri.'.file'}},$file);
12692: $metastring=&getfile($file);
12693: }
12694: my $parser=HTML::LCParser->new(\$metastring);
12695: my $token;
12696: undef %metathesekeys;
12697: while ($token=$parser->get_token) {
12698: if ($token->[0] eq 'S') {
12699: if (defined($token->[2]->{'package'})) {
12700: #
12701: # This is a package - get package info
12702: #
12703: my $package=$token->[2]->{'package'};
12704: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12705: if (defined($token->[2]->{'id'})) {
12706: $keyroot.='_'.$token->[2]->{'id'};
12707: }
12708: if ($metaentry{':packages'}) {
12709: $metaentry{':packages'}.=','.$package.$keyroot;
12710: } else {
12711: $metaentry{':packages'}=$package.$keyroot;
12712: }
12713: foreach my $pack_entry (keys(%packagetab)) {
12714: my $part=$keyroot;
12715: $part=~s/^\_//;
12716: if ($pack_entry=~/^\Q$package\E\&/ ||
12717: $pack_entry=~/^\Q$package\E_0\&/) {
12718: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
12719: # ignore package.tab specified default values
12720: # here &package_tab_default() will fetch those
12721: if ($subp eq 'default') { next; }
12722: my $value=$packagetab{$pack_entry};
12723: my $unikey;
12724: if ($pack =~ /_0$/) {
12725: $unikey='parameter_0_'.$name;
12726: $part=0;
12727: } else {
12728: $unikey='parameter'.$keyroot.'_'.$name;
12729: }
12730: if ($subp eq 'display') {
12731: $value.=' [Part: '.$part.']';
12732: }
12733: $metaentry{':'.$unikey.'.part'}=$part;
12734: $metathesekeys{$unikey}=1;
12735: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12736: $metaentry{':'.$unikey.'.'.$subp}=$value;
12737: }
12738: if (defined($metaentry{':'.$unikey.'.default'})) {
12739: $metaentry{':'.$unikey}=
12740: $metaentry{':'.$unikey.'.default'};
12741: }
12742: }
12743: }
12744: } else {
12745: #
12746: # This is not a package - some other kind of start tag
12747: #
12748: my $entry=$token->[1];
12749: my $unikey='';
12750:
12751: if ($entry eq 'import') {
12752: #
12753: # Importing a library here
12754: #
12755: my $location=$parser->get_text('/import');
12756: my $dir=$filename;
12757: $dir=~s|[^/]*$||;
12758: $location=&filelocation($dir,$location);
12759:
12760: my $importid=$token->[2]->{'id'};
12761: my $importmode=$token->[2]->{'importmode'};
12762: #
12763: # Check metadata for imported file to
12764: # see if it contained response items
12765: #
12766: my ($origfile,@libfilekeys);
12767: my %currmetaentry = %metaentry;
12768: @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12769: $depthcount+1));
12770: if (grep(/^responseorder$/,@libfilekeys)) {
12771: my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12772: undef,$depthcount+1);
12773: if ($libresponseorder ne '') {
12774: if ($#origfiletagids<0) {
12775: undef(%importedrespids);
12776: undef(%importedpartids);
12777: }
12778: my @respids = split(/\s*,\s*/,$libresponseorder);
12779: if (@respids) {
12780: $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12781: }
12782: if ($importedrespids{$importid} ne '') {
12783: $importedresponses = 1;
12784: # We need to get the original file and the imported file to get the response order correct
12785: # Load and inspect original file
12786: if ($#origfiletagids<0) {
12787: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12788: $origfile=&getfile($origfilelocation);
12789: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12790: }
12791: }
12792: }
12793: }
12794: # Do not overwrite contents of %metaentry hash for resource itself with
12795: # hash populated for imported library file
12796: %metaentry = %currmetaentry;
12797: undef(%currmetaentry);
12798: if ($importmode eq 'part') {
12799: # Import as part(s)
12800: $importedparts=1;
12801: # We need to get the original file and the imported file to get the part order correct
12802: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
12803: # Load and inspect original file if we didn't do that already
12804: if ($#origfiletagids<0) {
12805: undef(%importedrespids);
12806: undef(%importedpartids);
12807: if ($origfile eq '') {
12808: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12809: $origfile=&getfile($origfilelocation);
12810: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12811: }
12812: }
12813: my @impfilepartids;
12814: # If <partorder> tag is included in metadata for the imported file
12815: # get the parts in the imported file from that.
12816: if (grep(/^partorder$/,@libfilekeys)) {
12817: %currmetaentry = %metaentry;
12818: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12819: $depthcount+1);
12820: %metaentry = %currmetaentry;
12821: undef(%currmetaentry);
12822: if ($libpartorder ne '') {
12823: @impfilepartids=split(/\s*,\s*/,$libpartorder);
12824: }
12825: } else {
12826: # If no <partorder> tag available, load and inspect imported file
12827: my $impfile=&getfile($location);
12828: @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12829: }
12830: if ($#impfilepartids>=0) {
12831: # This problem had parts
12832: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12833: } else {
12834: # Importing by turning a single problem into a problem part
12835: # It gets the import-tags ID as part-ID
12836: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12837: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12838: }
12839: } else {
12840: # Import as problem or as normal import
12841: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12842: unless ($importmode eq 'problem') {
12843: # Normal import
12844: if (defined($token->[2]->{'id'})) {
12845: $unikey.='_'.$token->[2]->{'id'};
12846: }
12847: }
12848: # Check metadata for imported file to
12849: # see if it contained parts
12850: if (grep(/^partorder$/,@libfilekeys)) {
12851: %currmetaentry = %metaentry;
12852: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12853: $depthcount+1);
12854: %metaentry = %currmetaentry;
12855: undef(%currmetaentry);
12856: if ($libpartorder ne '') {
12857: $importedparts = 1;
12858: $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12859: }
12860: }
12861: }
12862: if ($depthcount<20) {
12863: my $metadata =
12864: &metadata($uri,'keys',$toolsymb,$location,$unikey,
12865: $depthcount+1);
12866: foreach my $meta (split(',',$metadata)) {
12867: $metaentry{':'.$meta}=$metaentry{':'.$meta};
12868: $metathesekeys{$meta}=1;
12869: }
12870: }
12871: } else {
12872: #
12873: # Not importing, some other kind of non-package, non-library start tag
12874: #
12875: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12876: if (defined($token->[2]->{'id'})) {
12877: $unikey.='_'.$token->[2]->{'id'};
12878: }
12879: if (defined($token->[2]->{'name'})) {
12880: $unikey.='_'.$token->[2]->{'name'};
12881: }
12882: $metathesekeys{$unikey}=1;
12883: foreach my $param (@{$token->[3]}) {
12884: $metaentry{':'.$unikey.'.'.$param} =
12885: $token->[2]->{$param};
12886: }
12887: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12888: my $default=$metaentry{':'.$unikey.'.default'};
12889: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12890: # only ws inside the tag, and not in default, so use default
12891: # as value
12892: $metaentry{':'.$unikey}=$default;
12893: } elsif ( $internaltext =~ /\S/ ) {
12894: # something interesting inside the tag
12895: $metaentry{':'.$unikey}=$internaltext;
12896: } else {
12897: # no interesting values, don't set a default
12898: }
12899: # end of not-a-package not-a-library import
12900: }
12901: # end of not-a-package start tag
12902: }
12903: # the next is the end of "start tag"
12904: }
12905: }
12906: my ($extension) = ($uri =~ /\.(\w+)$/);
12907: $extension = lc($extension);
12908: if ($extension eq 'htm') { $extension='html'; }
12909:
12910: foreach my $key (keys(%packagetab)) {
12911: #no specific packages #how's our extension
12912: if ($key!~/^extension_\Q$extension\E&/) { next; }
12913: &metadata_create_package_def($uri,$key,'extension_'.$extension,
12914: \%metathesekeys);
12915: }
12916:
12917: if (!exists($metaentry{':packages'})
12918: || $packagetab{"import_defaults&extension_$extension"}) {
12919: foreach my $key (keys(%packagetab)) {
12920: #no specific packages well let's get default then
12921: if ($key!~/^default&/) { next; }
12922: &metadata_create_package_def($uri,$key,'default',
12923: \%metathesekeys);
12924: }
12925: }
12926: # are there custom rights to evaluate
12927: if ($metaentry{':copyright'} eq 'custom') {
12928:
12929: #
12930: # Importing a rights file here
12931: #
12932: unless ($depthcount) {
12933: my $location=$metaentry{':customdistributionfile'};
12934: my $dir=$filename;
12935: $dir=~s|[^/]*$||;
12936: $location=&filelocation($dir,$location);
12937: my $rights_metadata =
12938: &metadata($uri,'keys',$toolsymb,$location,'_rights',
12939: $depthcount+1);
12940: foreach my $rights (split(',',$rights_metadata)) {
12941: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12942: $metathesekeys{$rights}=1;
12943: }
12944: }
12945: }
12946: # uniqifiy package listing
12947: my %seen;
12948: my @uniq_packages =
12949: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12950: $metaentry{':packages'} = join(',',@uniq_packages);
12951:
12952: if (($importedresponses) || ($importedparts)) {
12953: if ($importedparts) {
12954: # We had imported parts and need to rebuild partorder
12955: $metaentry{':partorder'}='';
12956: $metathesekeys{'partorder'}=1;
12957: }
12958: if ($importedresponses) {
12959: # We had imported responses and need to rebuil responseorder
12960: $metaentry{':responseorder'}='';
12961: $metathesekeys{'responseorder'}=1;
12962: }
12963: for (my $index=0;$index<$#origfiletagids;$index+=2) {
12964: my $origid = $origfiletagids[$index+1];
12965: if ($origfiletagids[$index] eq 'part') {
12966: # Original part, part of the problem
12967: if ($importedparts) {
12968: $metaentry{':partorder'}.=','.$origid;
12969: }
12970: } elsif ($origfiletagids[$index] eq 'import') {
12971: if ($importedparts) {
12972: # We have imported parts at this position
12973: if ($importedpartids{$origid} ne '') {
12974: $metaentry{':partorder'}.=','.$importedpartids{$origid};
12975: }
12976: }
12977: if ($importedresponses) {
12978: # We have imported responses at this position
12979: if ($importedrespids{$origid} ne '') {
12980: $metaentry{':responseorder'}.=','.$importedrespids{$origid};
12981: }
12982: }
12983: } else {
12984: # Original response item, part of the problem
12985: if ($importedresponses) {
12986: $metaentry{':responseorder'}.=','.$origid;
12987: }
12988: }
12989: }
12990: if ($importedparts) {
12991: $metaentry{':partorder'}=~s/^\,//;
12992: }
12993: if ($importedresponses) {
12994: $metaentry{':responseorder'}=~s/^\,//;
12995: }
12996: }
12997: $metaentry{':keys'} = join(',',keys(%metathesekeys));
12998: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12999: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
13000: unless ($liburi) {
13001: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
13002: }
13003: # this is the end of "was not already recently cached
13004: }
13005: return $metaentry{':'.$what};
13006: }
13007:
13008: sub metadata_create_package_def {
13009: my ($uri,$key,$package,$metathesekeys)=@_;
13010: my ($pack,$name,$subp)=split(/\&/,$key);
13011: if ($subp eq 'default') { next; }
13012:
13013: if (defined($metaentry{':packages'})) {
13014: $metaentry{':packages'}.=','.$package;
13015: } else {
13016: $metaentry{':packages'}=$package;
13017: }
13018: my $value=$packagetab{$key};
13019: my $unikey;
13020: $unikey='parameter_0_'.$name;
13021: $metaentry{':'.$unikey.'.part'}=0;
13022: $$metathesekeys{$unikey}=1;
13023: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13024: $metaentry{':'.$unikey.'.'.$subp}=$value;
13025: }
13026: if (defined($metaentry{':'.$unikey.'.default'})) {
13027: $metaentry{':'.$unikey}=
13028: $metaentry{':'.$unikey.'.default'};
13029: }
13030: }
13031:
13032: sub metadata_generate_part0 {
13033: my ($metadata,$metacache,$uri) = @_;
13034: my %allnames;
13035: foreach my $metakey (keys(%$metadata)) {
13036: if ($metakey=~/^parameter\_(.*)/) {
13037: my $part=$$metacache{':'.$metakey.'.part'};
13038: my $name=$$metacache{':'.$metakey.'.name'};
13039: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
13040: $allnames{$name}=$part;
13041: }
13042: }
13043: }
13044: foreach my $name (keys(%allnames)) {
13045: $$metadata{"parameter_0_$name"}=1;
13046: my $key=":parameter_0_$name";
13047: $$metacache{"$key.part"}='0';
13048: $$metacache{"$key.name"}=$name;
13049: $$metacache{"$key.type"}=$$metacache{':parameter_'.
13050: $allnames{$name}.'_'.$name.
13051: '.type'};
13052: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
13053: '.display'};
13054: my $expr='[Part: '.$allnames{$name}.']';
13055: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
13056: $$metacache{"$key.display"}=$olddis;
13057: }
13058: }
13059:
13060: # ------------------------------------------------------ Devalidate title cache
13061:
13062: sub devalidate_title_cache {
13063: my ($url)=@_;
13064: if (!$env{'request.course.id'}) { return; }
13065: my $symb=&symbread($url);
13066: if (!$symb) { return; }
13067: my $key=$env{'request.course.id'}."\0".$symb;
13068: &devalidate_cache_new('title',$key);
13069: }
13070:
13071: # ------------------------------------------------- Get the title of a course
13072:
13073: sub current_course_title {
13074: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
13075: }
13076: # ------------------------------------------------- Get the title of a resource
13077:
13078: sub gettitle {
13079: my $urlsymb=shift;
13080: my $symb=&symbread($urlsymb);
13081: if ($symb) {
13082: my $key=$env{'request.course.id'}."\0".$symb;
13083: my ($result,$cached)=&is_cached_new('title',$key);
13084: if (defined($cached)) {
13085: return $result;
13086: }
13087: my ($map,$resid,$url)=&decode_symb($symb);
13088: my $title='';
13089: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13090: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13091: } else {
13092: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13093: &GDBM_READER(),0640)) {
13094: my $mapid=$bighash{'map_pc_'.&clutter($map)};
13095: $title=$bighash{'title_'.$mapid.'.'.$resid};
13096: untie(%bighash);
13097: }
13098: }
13099: $title=~s/\&colon\;/\:/gs;
13100: if ($title) {
13101: # Remember both $symb and $title for dynamic metadata
13102: $accesshash{$symb.'___crstitle'}=$title;
13103: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
13104: # Cache this title and then return it
13105: return &do_cache_new('title',$key,$title,600);
13106: }
13107: $urlsymb=$url;
13108: }
13109: my $title=&metadata($urlsymb,'title');
13110: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
13111: return $title;
13112: }
13113:
13114: sub get_slot {
13115: my ($which,$cnum,$cdom)=@_;
13116: if (!$cnum || !$cdom) {
13117: (undef,my $courseid)=&whichuser();
13118: $cdom=$env{'course.'.$courseid.'.domain'};
13119: $cnum=$env{'course.'.$courseid.'.num'};
13120: }
13121: my $key=join("\0",'slots',$cdom,$cnum,$which);
13122: my %slotinfo;
13123: if (exists($remembered{$key})) {
13124: $slotinfo{$which} = $remembered{$key};
13125: } else {
13126: %slotinfo=&get('slots',[$which],$cdom,$cnum);
13127: &Apache::lonhomework::showhash(%slotinfo);
13128: my ($tmp)=keys(%slotinfo);
13129: if ($tmp=~/^error:/) { return (); }
13130: $remembered{$key} = $slotinfo{$which};
13131: }
13132: if (ref($slotinfo{$which}) eq 'HASH') {
13133: return %{$slotinfo{$which}};
13134: }
13135: return $slotinfo{$which};
13136: }
13137:
13138: sub get_reservable_slots {
13139: my ($cnum,$cdom,$uname,$udom) = @_;
13140: my $now = time;
13141: my $reservable_info;
13142: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13143: if (exists($remembered{$key})) {
13144: $reservable_info = $remembered{$key};
13145: } else {
13146: my %resv;
13147: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13148: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13149: $reservable_info = \%resv;
13150: $remembered{$key} = $reservable_info;
13151: }
13152: return $reservable_info;
13153: }
13154:
13155: sub get_course_slots {
13156: my ($cnum,$cdom) = @_;
13157: my $hashid=$cnum.':'.$cdom;
13158: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
13159: if (defined($cached)) {
13160: if (ref($result) eq 'HASH') {
13161: return %{$result};
13162: }
13163: } else {
13164: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
13165: my ($tmp) = keys(%slots);
13166: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
13167: &do_cache_new('allslots',$hashid,\%slots,600);
13168: return %slots;
13169: }
13170: }
13171: return;
13172: }
13173:
13174: sub devalidate_slots_cache {
13175: my ($cnum,$cdom)=@_;
13176: my $hashid=$cnum.':'.$cdom;
13177: &devalidate_cache_new('allslots',$hashid);
13178: }
13179:
13180: sub get_coursechange {
13181: my ($cdom,$cnum) = @_;
13182: if ($cdom eq '' || $cnum eq '') {
13183: return unless ($env{'request.course.id'});
13184: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13185: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13186: }
13187: my $hashid=$cdom.'_'.$cnum;
13188: my ($change,$cached)=&is_cached_new('crschange',$hashid);
13189: if ((defined($cached)) && ($change ne '')) {
13190: return $change;
13191: } else {
13192: my %crshash;
13193: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13194: if ($crshash{'internal.contentchange'} eq '') {
13195: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13196: if ($change eq '') {
13197: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13198: $change = $crshash{'internal.created'};
13199: }
13200: } else {
13201: $change = $crshash{'internal.contentchange'};
13202: }
13203: my $cachetime = 600;
13204: &do_cache_new('crschange',$hashid,$change,$cachetime);
13205: }
13206: return $change;
13207: }
13208:
13209: sub devalidate_coursechange_cache {
13210: my ($cnum,$cdom)=@_;
13211: my $hashid=$cnum.':'.$cdom;
13212: &devalidate_cache_new('crschange',$hashid);
13213: }
13214:
13215: # ------------------------------------------------- Update symbolic store links
13216:
13217: sub symblist {
13218: my ($mapname,%newhash)=@_;
13219: $mapname=&deversion(&declutter($mapname));
13220: my %hash;
13221: if (($env{'request.course.fn'}) && (%newhash)) {
13222: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13223: &GDBM_WRCREAT(),0640)) {
13224: foreach my $url (keys(%newhash)) {
13225: next if ($url eq 'last_known'
13226: && $env{'form.no_update_last_known'});
13227: $hash{declutter($url)}=&encode_symb($mapname,
13228: $newhash{$url}->[1],
13229: $newhash{$url}->[0]);
13230: }
13231: if (untie(%hash)) {
13232: return 'ok';
13233: }
13234: }
13235: }
13236: return 'error';
13237: }
13238:
13239: # --------------------------------------------------------------- Verify a symb
13240:
13241: sub symbverify {
13242: my ($symb,$thisurl,$encstate)=@_;
13243: my $thisfn=$thisurl;
13244: $thisfn=&declutter($thisfn);
13245: # direct jump to resource in page or to a sequence - will construct own symbs
13246: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13247: # check URL part
13248: my ($map,$resid,$url)=&decode_symb($symb);
13249:
13250: unless ($url eq $thisfn) { return 0; }
13251:
13252: $symb=&symbclean($symb);
13253: $thisurl=&deversion($thisurl);
13254: $thisfn=&deversion($thisfn);
13255:
13256: my %bighash;
13257: my $okay=0;
13258:
13259: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13260: &GDBM_READER(),0640)) {
13261: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13262: $thisurl =~ s/\?.+$//;
13263: if ($map =~ m{^uploaded/.+\.page$}) {
13264: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13265: $thisurl =~ s{^\Qhttp://https://\E}{https://};
13266: }
13267: }
13268: my $ids;
13269: if ($map =~ m{^uploaded/.+\.page$}) {
13270: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
13271: } else {
13272: $ids=$bighash{'ids_'.&clutter($thisurl)};
13273: }
13274: unless ($ids) {
13275: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
13276: $ids=$bighash{$idkey};
13277: }
13278: if ($ids) {
13279: # ------------------------------------------------------------------- Has ID(s)
13280: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
13281: $symb =~ s/\?.+$//;
13282: }
13283: foreach my $id (split(/\,/,$ids)) {
13284: my ($mapid,$resid)=split(/\./,$id);
13285: if (
13286: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
13287: eq $symb) {
13288: if (ref($encstate)) {
13289: $$encstate = $bighash{'encrypted_'.$id};
13290: }
13291: if (($env{'request.role.adv'}) ||
13292: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13293: ($thisurl eq '/adm/navmaps')) {
13294: $okay=1;
13295: last;
13296: }
13297: }
13298: }
13299: }
13300: untie(%bighash);
13301: }
13302: return $okay;
13303: }
13304:
13305: # --------------------------------------------------------------- Clean-up symb
13306:
13307: sub symbclean {
13308: my $symb=shift;
13309: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13310: # remove version from map
13311: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
13312:
13313: # remove version from URL
13314: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
13315:
13316: # remove wrapper
13317:
13318: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
13319: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
13320: return $symb;
13321: }
13322:
13323: # ---------------------------------------------- Split symb to find map and url
13324:
13325: sub encode_symb {
13326: my ($map,$resid,$url)=@_;
13327: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13328: }
13329:
13330: sub decode_symb {
13331: my $symb=shift;
13332: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13333: my ($map,$resid,$url)=split(/___/,$symb);
13334: return (&fixversion($map),$resid,&fixversion($url));
13335: }
13336:
13337: sub fixversion {
13338: my $fn=shift;
13339: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
13340: my %bighash;
13341: my $uri=&clutter($fn);
13342: my $key=$env{'request.course.id'}.'_'.$uri;
13343: # is this cached?
13344: my ($result,$cached)=&is_cached_new('courseresversion',$key);
13345: if (defined($cached)) { return $result; }
13346: # unfortunately not cached, or expired
13347: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13348: &GDBM_READER(),0640)) {
13349: if ($bighash{'version_'.$uri}) {
13350: my $version=$bighash{'version_'.$uri};
13351: unless (($version eq 'mostrecent') ||
13352: ($version==&getversion($uri))) {
13353: $uri=~s/\.(\w+)$/\.$version\.$1/;
13354: }
13355: }
13356: untie %bighash;
13357: }
13358: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
13359: }
13360:
13361: sub deversion {
13362: my $url=shift;
13363: $url=~s/\.\d+\.(\w+)$/\.$1/;
13364: return $url;
13365: }
13366:
13367: # ------------------------------------------------------ Return symb list entry
13368:
13369: sub symbread {
13370: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
13371: $ignoresymbdb,$noenccheck)=@_;
13372: my $cache_str='request.symbread.cached.'.$thisfn;
13373: if (defined($env{$cache_str})) {
13374: unless (ref($possibles) eq 'HASH') {
13375: if ($ignorecachednull) {
13376: return $env{$cache_str} unless ($env{$cache_str} eq '');
13377: } else {
13378: return $env{$cache_str};
13379: }
13380: }
13381: }
13382: # no filename provided? try from environment
13383: unless ($thisfn) {
13384: if ($env{'request.symb'}) {
13385: return $env{$cache_str}=&symbclean($env{'request.symb'});
13386: }
13387: $thisfn=$env{'request.filename'};
13388: }
13389: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13390: # is that filename actually a symb? Verify, clean, and return
13391: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
13392: if (&symbverify($thisfn,$1)) {
13393: return $env{$cache_str}=&symbclean($thisfn);
13394: }
13395: }
13396: $thisfn=declutter($thisfn);
13397: my %hash;
13398: my %bighash;
13399: my $syval='';
13400: if (($env{'request.course.fn'}) && ($thisfn)) {
13401: my $targetfn = $thisfn;
13402: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
13403: $targetfn = 'adm/wrapper/'.$thisfn;
13404: }
13405: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
13406: $targetfn=$1;
13407: }
13408: unless ($ignoresymbdb) {
13409: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13410: &GDBM_READER(),0640)) {
13411: $syval=$hash{$targetfn};
13412: untie(%hash);
13413: }
13414: if ($syval && $checkforblock) {
13415: my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
13416: if (@blockers) {
13417: $syval='';
13418: }
13419: }
13420: }
13421: # ---------------------------------------------------------- There was an entry
13422: if ($syval) {
13423: #unless ($syval=~/\_\d+$/) {
13424: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
13425: #&appenv({'request.ambiguous' => $thisfn});
13426: #return $env{$cache_str}='';
13427: #}
13428: #$syval.=$1;
13429: #}
13430: } else {
13431: # ------------------------------------------------------- Was not in symb table
13432: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13433: &GDBM_READER(),0640)) {
13434: # ---------------------------------------------- Get ID(s) for current resource
13435: my $ids=$bighash{'ids_'.&clutter($thisfn)};
13436: unless ($ids) {
13437: $ids=$bighash{'ids_/'.$thisfn};
13438: }
13439: unless ($ids) {
13440: # alias?
13441: $ids=$bighash{'mapalias_'.$thisfn};
13442: }
13443: if ($ids) {
13444: # ------------------------------------------------------------------- Has ID(s)
13445: my @possibilities=split(/\,/,$ids);
13446: if ($#possibilities==0) {
13447: # ----------------------------------------------- There is only one possibility
13448: my ($mapid,$resid)=split(/\./,$ids);
13449: $syval=&encode_symb($bighash{'map_id_'.$mapid},
13450: $resid,$thisfn);
13451: if (ref($possibles) eq 'HASH') {
13452: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13453: $possibles->{$syval} = 1;
13454: }
13455: }
13456: if ($checkforblock) {
13457: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13458: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
13459: if (@blockers) {
13460: $syval = '';
13461: untie(%bighash);
13462: return $env{$cache_str}='';
13463: }
13464: }
13465: }
13466: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13467: # ------------------------------------------ There is more than one possibility
13468: my $realpossible=0;
13469: foreach my $id (@possibilities) {
13470: my $file=$bighash{'src_'.$id};
13471: my $canaccess;
13472: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13473: $canaccess = 1;
13474: } else {
13475: $canaccess = &allowed('bre',$file);
13476: }
13477: if ($canaccess) {
13478: my ($mapid,$resid)=split(/\./,$id);
13479: if ($bighash{'map_type_'.$mapid} ne 'page') {
13480: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13481: $resid,$thisfn);
13482: next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
13483: next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
13484: if ($checkforblock) {
13485: my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
13486: if (@blockers > 0) {
13487: $syval = '';
13488: } else {
13489: $syval = $poss_syval;
13490: $realpossible++;
13491: }
13492: } else {
13493: $syval = $poss_syval;
13494: $realpossible++;
13495: }
13496: if ($syval) {
13497: if (ref($possibles) eq 'HASH') {
13498: $possibles->{$syval} = 1;
13499: }
13500: }
13501: }
13502: }
13503: }
13504: if ($realpossible!=1) { $syval=''; }
13505: } else {
13506: $syval='';
13507: }
13508: }
13509: untie(%bighash);
13510: }
13511: }
13512: if ($syval) {
13513: return $env{$cache_str}=$syval;
13514: }
13515: }
13516: &appenv({'request.ambiguous' => $thisfn});
13517: return $env{$cache_str}='';
13518: }
13519:
13520: # ---------------------------------------------------------- Return random seed
13521:
13522: sub numval {
13523: my $txt=shift;
13524: $txt=~tr/A-J/0-9/;
13525: $txt=~tr/a-j/0-9/;
13526: $txt=~tr/K-T/0-9/;
13527: $txt=~tr/k-t/0-9/;
13528: $txt=~tr/U-Z/0-5/;
13529: $txt=~tr/u-z/0-5/;
13530: $txt=~s/\D//g;
13531: if ($_64bit) { if ($txt > 2**32) { return -1; } }
13532: return int($txt);
13533: }
13534:
13535: sub numval2 {
13536: my $txt=shift;
13537: $txt=~tr/A-J/0-9/;
13538: $txt=~tr/a-j/0-9/;
13539: $txt=~tr/K-T/0-9/;
13540: $txt=~tr/k-t/0-9/;
13541: $txt=~tr/U-Z/0-5/;
13542: $txt=~tr/u-z/0-5/;
13543: $txt=~s/\D//g;
13544: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13545: my $total;
13546: foreach my $val (@txts) { $total+=$val; }
13547: if ($_64bit) { if ($total > 2**32) { return -1; } }
13548: return int($total);
13549: }
13550:
13551: sub numval3 {
13552: use integer;
13553: my $txt=shift;
13554: $txt=~tr/A-J/0-9/;
13555: $txt=~tr/a-j/0-9/;
13556: $txt=~tr/K-T/0-9/;
13557: $txt=~tr/k-t/0-9/;
13558: $txt=~tr/U-Z/0-5/;
13559: $txt=~tr/u-z/0-5/;
13560: $txt=~s/\D//g;
13561: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13562: my $total;
13563: foreach my $val (@txts) { $total+=$val; }
13564: if ($_64bit) { $total=(($total<<32)>>32); }
13565: return $total;
13566: }
13567:
13568: sub digest {
13569: my ($data)=@_;
13570: my $digest=&Digest::MD5::md5($data);
13571: my ($a,$b,$c,$d)=unpack("iiii",$digest);
13572: my ($e,$f);
13573: {
13574: use integer;
13575: $e=($a+$b);
13576: $f=($c+$d);
13577: if ($_64bit) {
13578: $e=(($e<<32)>>32);
13579: $f=(($f<<32)>>32);
13580: }
13581: }
13582: if (wantarray) {
13583: return ($e,$f);
13584: } else {
13585: my $g;
13586: {
13587: use integer;
13588: $g=($e+$f);
13589: if ($_64bit) {
13590: $g=(($g<<32)>>32);
13591: }
13592: }
13593: return $g;
13594: }
13595: }
13596:
13597: sub latest_rnd_algorithm_id {
13598: return '64bit5';
13599: }
13600:
13601: sub get_rand_alg {
13602: my ($courseid)=@_;
13603: if (!$courseid) { $courseid=(&whichuser())[1]; }
13604: if ($courseid) {
13605: return $env{"course.$courseid.rndseed"};
13606: }
13607: return &latest_rnd_algorithm_id();
13608: }
13609:
13610: sub validCODE {
13611: my ($CODE)=@_;
13612: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13613: return 0;
13614: }
13615:
13616: sub getCODE {
13617: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
13618: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13619: defined($Apache::lonhomework::parsing_a_task) ) &&
13620: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
13621: return $Apache::lonhomework::history{'resource.CODE'};
13622: }
13623: return undef;
13624: }
13625: #
13626: # Determines the random seed for a specific context:
13627: #
13628: # parameters:
13629: # symb - in course context the symb for the seed.
13630: # course_id - The course id of the form domain_coursenum.
13631: # domain - Domain for the user.
13632: # course - Course for the user.
13633: # cenv - environment of the course.
13634: #
13635: # NOTE:
13636: # All parameters are picked out of the environment if missing
13637: # or not defined.
13638: # If a symb cannot be determined the current time is used instead.
13639: #
13640: # For a given well defined symb, courside, domain, username,
13641: # and course environment, the seed is reproducible.
13642: #
13643: sub rndseed {
13644: my ($symb,$courseid,$domain,$username, $cenv)=@_;
13645: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
13646: if (!defined($symb)) {
13647: unless ($symb=$wsymb) { return time; }
13648: }
13649: if (!defined $courseid) {
13650: $courseid=$wcourseid;
13651: }
13652: if (!defined $domain) { $domain=$wdomain; }
13653: if (!defined $username) { $username=$wusername }
13654:
13655: my $which;
13656: if (defined($cenv->{'rndseed'})) {
13657: $which = $cenv->{'rndseed'};
13658: } else {
13659: $which =&get_rand_alg($courseid);
13660: }
13661: if (defined(&getCODE())) {
13662:
13663: if ($which eq '64bit5') {
13664: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
13665: } elsif ($which eq '64bit4') {
13666: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
13667: } else {
13668: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
13669: }
13670: } elsif ($which eq '64bit5') {
13671: return &rndseed_64bit5($symb,$courseid,$domain,$username);
13672: } elsif ($which eq '64bit4') {
13673: return &rndseed_64bit4($symb,$courseid,$domain,$username);
13674: } elsif ($which eq '64bit3') {
13675: return &rndseed_64bit3($symb,$courseid,$domain,$username);
13676: } elsif ($which eq '64bit2') {
13677: return &rndseed_64bit2($symb,$courseid,$domain,$username);
13678: } elsif ($which eq '64bit') {
13679: return &rndseed_64bit($symb,$courseid,$domain,$username);
13680: }
13681: return &rndseed_32bit($symb,$courseid,$domain,$username);
13682: }
13683:
13684: sub rndseed_32bit {
13685: my ($symb,$courseid,$domain,$username)=@_;
13686: {
13687: use integer;
13688: my $symbchck=unpack("%32C*",$symb) << 27;
13689: my $symbseed=numval($symb) << 22;
13690: my $namechck=unpack("%32C*",$username) << 17;
13691: my $nameseed=numval($username) << 12;
13692: my $domainseed=unpack("%32C*",$domain) << 7;
13693: my $courseseed=unpack("%32C*",$courseid);
13694: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
13695: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13696: #&logthis("rndseed :$num:$symb");
13697: if ($_64bit) { $num=(($num<<32)>>32); }
13698: return $num;
13699: }
13700: }
13701:
13702: sub rndseed_64bit {
13703: my ($symb,$courseid,$domain,$username)=@_;
13704: {
13705: use integer;
13706: my $symbchck=unpack("%32S*",$symb) << 21;
13707: my $symbseed=numval($symb) << 10;
13708: my $namechck=unpack("%32S*",$username);
13709:
13710: my $nameseed=numval($username) << 21;
13711: my $domainseed=unpack("%32S*",$domain) << 10;
13712: my $courseseed=unpack("%32S*",$courseid);
13713:
13714: my $num1=$symbchck+$symbseed+$namechck;
13715: my $num2=$nameseed+$domainseed+$courseseed;
13716: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13717: #&logthis("rndseed :$num:$symb");
13718: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13719: return "$num1,$num2";
13720: }
13721: }
13722:
13723: sub rndseed_64bit2 {
13724: my ($symb,$courseid,$domain,$username)=@_;
13725: {
13726: use integer;
13727: # strings need to be an even # of cahracters long, it it is odd the
13728: # last characters gets thrown away
13729: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13730: my $symbseed=numval($symb) << 10;
13731: my $namechck=unpack("%32S*",$username.' ');
13732:
13733: my $nameseed=numval($username) << 21;
13734: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13735: my $courseseed=unpack("%32S*",$courseid.' ');
13736:
13737: my $num1=$symbchck+$symbseed+$namechck;
13738: my $num2=$nameseed+$domainseed+$courseseed;
13739: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13740: #&logthis("rndseed :$num:$symb");
13741: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13742: return "$num1,$num2";
13743: }
13744: }
13745:
13746: sub rndseed_64bit3 {
13747: my ($symb,$courseid,$domain,$username)=@_;
13748: {
13749: use integer;
13750: # strings need to be an even # of cahracters long, it it is odd the
13751: # last characters gets thrown away
13752: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13753: my $symbseed=numval2($symb) << 10;
13754: my $namechck=unpack("%32S*",$username.' ');
13755:
13756: my $nameseed=numval2($username) << 21;
13757: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13758: my $courseseed=unpack("%32S*",$courseid.' ');
13759:
13760: my $num1=$symbchck+$symbseed+$namechck;
13761: my $num2=$nameseed+$domainseed+$courseseed;
13762: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13763: #&logthis("rndseed :$num1:$num2:$_64bit");
13764: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13765:
13766: return "$num1:$num2";
13767: }
13768: }
13769:
13770: sub rndseed_64bit4 {
13771: my ($symb,$courseid,$domain,$username)=@_;
13772: {
13773: use integer;
13774: # strings need to be an even # of cahracters long, it it is odd the
13775: # last characters gets thrown away
13776: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13777: my $symbseed=numval3($symb) << 10;
13778: my $namechck=unpack("%32S*",$username.' ');
13779:
13780: my $nameseed=numval3($username) << 21;
13781: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13782: my $courseseed=unpack("%32S*",$courseid.' ');
13783:
13784: my $num1=$symbchck+$symbseed+$namechck;
13785: my $num2=$nameseed+$domainseed+$courseseed;
13786: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13787: #&logthis("rndseed :$num1:$num2:$_64bit");
13788: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13789:
13790: return "$num1:$num2";
13791: }
13792: }
13793:
13794: sub rndseed_64bit5 {
13795: my ($symb,$courseid,$domain,$username)=@_;
13796: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13797: return "$num1:$num2";
13798: }
13799:
13800: sub rndseed_CODE_64bit {
13801: my ($symb,$courseid,$domain,$username)=@_;
13802: {
13803: use integer;
13804: my $symbchck=unpack("%32S*",$symb.' ') << 16;
13805: my $symbseed=numval2($symb);
13806: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13807: my $CODEseed=numval(&getCODE());
13808: my $courseseed=unpack("%32S*",$courseid.' ');
13809: my $num1=$symbseed+$CODEchck;
13810: my $num2=$CODEseed+$courseseed+$symbchck;
13811: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13812: #&logthis("rndseed :$num1:$num2:$symb");
13813: if ($_64bit) { $num1=(($num1<<32)>>32); }
13814: if ($_64bit) { $num2=(($num2<<32)>>32); }
13815: return "$num1:$num2";
13816: }
13817: }
13818:
13819: sub rndseed_CODE_64bit4 {
13820: my ($symb,$courseid,$domain,$username)=@_;
13821: {
13822: use integer;
13823: my $symbchck=unpack("%32S*",$symb.' ') << 16;
13824: my $symbseed=numval3($symb);
13825: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13826: my $CODEseed=numval3(&getCODE());
13827: my $courseseed=unpack("%32S*",$courseid.' ');
13828: my $num1=$symbseed+$CODEchck;
13829: my $num2=$CODEseed+$courseseed+$symbchck;
13830: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13831: #&logthis("rndseed :$num1:$num2:$symb");
13832: if ($_64bit) { $num1=(($num1<<32)>>32); }
13833: if ($_64bit) { $num2=(($num2<<32)>>32); }
13834: return "$num1:$num2";
13835: }
13836: }
13837:
13838: sub rndseed_CODE_64bit5 {
13839: my ($symb,$courseid,$domain,$username)=@_;
13840: my $code = &getCODE();
13841: my ($num1,$num2)=&digest("$symb,$courseid,$code");
13842: return "$num1:$num2";
13843: }
13844:
13845: sub setup_random_from_rndseed {
13846: my ($rndseed)=@_;
13847: if ($rndseed =~/([,:])/) {
13848: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13849: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13850: &Math::Random::random_set_seed_from_phrase($rndseed);
13851: } else {
13852: &Math::Random::random_set_seed($num1,$num2);
13853: }
13854: } else {
13855: &Math::Random::random_set_seed_from_phrase($rndseed);
13856: }
13857: }
13858:
13859: sub latest_receipt_algorithm_id {
13860: return 'receipt3';
13861: }
13862:
13863: sub recunique {
13864: my $fucourseid=shift;
13865: my $unique;
13866: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13867: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13868: $unique=$env{"course.$fucourseid.internal.encseed"};
13869: } else {
13870: $unique=$perlvar{'lonReceipt'};
13871: }
13872: return unpack("%32C*",$unique);
13873: }
13874:
13875: sub recprefix {
13876: my $fucourseid=shift;
13877: my $prefix;
13878: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13879: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13880: $prefix=$env{"course.$fucourseid.internal.encpref"};
13881: } else {
13882: $prefix=$perlvar{'lonHostID'};
13883: }
13884: return unpack("%32C*",$prefix);
13885: }
13886:
13887: sub ireceipt {
13888: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13889:
13890: my $return =&recprefix($fucourseid).'-';
13891:
13892: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13893: $env{'request.state'} eq 'construct') {
13894: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13895: return $return;
13896: }
13897:
13898: my $cuname=unpack("%32C*",$funame);
13899: my $cudom=unpack("%32C*",$fudom);
13900: my $cucourseid=unpack("%32C*",$fucourseid);
13901: my $cusymb=unpack("%32C*",$fusymb);
13902: my $cunique=&recunique($fucourseid);
13903: my $cpart=unpack("%32S*",$part);
13904: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13905:
13906: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
13907:
13908: $return.= ($cunique%$cuname+
13909: $cunique%$cudom+
13910: $cusymb%$cuname+
13911: $cusymb%$cudom+
13912: $cucourseid%$cuname+
13913: $cucourseid%$cudom+
13914: $cpart%$cuname+
13915: $cpart%$cudom);
13916: } else {
13917: $return.= ($cunique%$cuname+
13918: $cunique%$cudom+
13919: $cusymb%$cuname+
13920: $cusymb%$cudom+
13921: $cucourseid%$cuname+
13922: $cucourseid%$cudom);
13923: }
13924: return $return;
13925: }
13926:
13927: sub receipt {
13928: my ($part)=@_;
13929: my ($symb,$courseid,$domain,$name) = &whichuser();
13930: return &ireceipt($name,$domain,$courseid,$symb,$part);
13931: }
13932:
13933: sub whichuser {
13934: my ($passedsymb)=@_;
13935: my ($symb,$courseid,$domain,$name,$publicuser);
13936: if (defined($env{'form.grade_symb'})) {
13937: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13938: my $allowed=&allowed('vgr',$tmp_courseid);
13939: if (!$allowed &&
13940: exists($env{'request.course.sec'}) &&
13941: $env{'request.course.sec'} !~ /^\s*$/) {
13942: $allowed=&allowed('vgr',$tmp_courseid.
13943: '/'.$env{'request.course.sec'});
13944: }
13945: if ($allowed) {
13946: ($symb)=&get_env_multiple('form.grade_symb');
13947: $courseid=$tmp_courseid;
13948: ($domain)=&get_env_multiple('form.grade_domain');
13949: ($name)=&get_env_multiple('form.grade_username');
13950: return ($symb,$courseid,$domain,$name,$publicuser);
13951: }
13952: }
13953: if (!$passedsymb) {
13954: $symb=&symbread();
13955: } else {
13956: $symb=$passedsymb;
13957: }
13958: $courseid=$env{'request.course.id'};
13959: $domain=$env{'user.domain'};
13960: $name=$env{'user.name'};
13961: if ($name eq 'public' && $domain eq 'public') {
13962: if (!defined($env{'form.username'})) {
13963: $env{'form.username'}.=time.rand(10000000);
13964: }
13965: $name.=$env{'form.username'};
13966: }
13967: return ($symb,$courseid,$domain,$name,$publicuser);
13968:
13969: }
13970:
13971: # ------------------------------------------------------------ Serves up a file
13972: # returns either the contents of the file or
13973: # -1 if the file doesn't exist
13974: #
13975: # if the target is a file that was uploaded via DOCS,
13976: # a check will be made to see if a current copy exists on the local server,
13977: # if it does this will be served, otherwise a copy will be retrieved from
13978: # the home server for the course and stored in /home/httpd/html/userfiles on
13979: # the local server.
13980:
13981: sub getfile {
13982: my ($file) = @_;
13983: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13984: &repcopy($file);
13985: return &readfile($file);
13986: }
13987:
13988: sub repcopy_userfile {
13989: my ($file)=@_;
13990: my $londocroot = $perlvar{'lonDocRoot'};
13991: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13992: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13993: my ($cdom,$cnum,$filename) =
13994: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13995: my $uri="/uploaded/$cdom/$cnum/$filename";
13996: if (-e "$file") {
13997: # we already have a local copy, check it out
13998: my @fileinfo = stat($file);
13999: my $rtncode;
14000: my $info;
14001: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
14002: if ($lwpresp ne 'ok') {
14003: # there is no such file anymore, even though we had a local copy
14004: if ($rtncode eq '404') {
14005: unlink($file);
14006: }
14007: return -1;
14008: }
14009: if ($info < $fileinfo[9]) {
14010: # nice, the file we have is up-to-date, just say okay
14011: return 'ok';
14012: } else {
14013: # the file is outdated, get rid of it
14014: unlink($file);
14015: }
14016: }
14017: # one way or the other, at this point, we don't have the file
14018: # construct the correct path for the file
14019: my @parts = ($cdom,$cnum);
14020: if ($filename =~ m|^(.+)/[^/]+$|) {
14021: push @parts, split(/\//,$1);
14022: }
14023: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
14024: foreach my $part (@parts) {
14025: $path .= '/'.$part;
14026: if (!-e $path) {
14027: mkdir($path,0770);
14028: }
14029: }
14030: # now the path exists for sure
14031: # get a user agent
14032: my $transferfile=$file.'.in.transfer';
14033: # FIXME: this should flock
14034: if (-e $transferfile) { return 'ok'; }
14035: my $request;
14036: $uri=~s/^\///;
14037: my $homeserver = &homeserver($cnum,$cdom);
14038: my $hostname = &hostname($homeserver);
14039: my $protocol = $protocol{$homeserver};
14040: $protocol = 'http' if ($protocol ne 'https');
14041: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
14042: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
14043: # did it work?
14044: if ($response->is_error()) {
14045: unlink($transferfile);
14046: &logthis("Userfile repcopy failed for $uri");
14047: return -1;
14048: }
14049: # worked, rename the transfer file
14050: rename($transferfile,$file);
14051: return 'ok';
14052: }
14053:
14054: sub tokenwrapper {
14055: my $uri=shift;
14056: $uri=~s|^https?\://([^/]+)||;
14057: $uri=~s|^/||;
14058: $env{'user.environment'}=~/\/([^\/]+)\.id/;
14059: my $token=$1;
14060: my (undef,$udom,$uname,$file)=split('/',$uri,4);
14061: if ($udom && $uname && $file) {
14062: $file=~s|(\?\.*)*$||;
14063: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
14064: my $homeserver = &homeserver($uname,$udom);
14065: my $hostname = &hostname($homeserver);
14066: my $protocol = $protocol{$homeserver};
14067: $protocol = 'http' if ($protocol ne 'https');
14068: return $protocol.'://'.$hostname.'/'.$uri.
14069: (($uri=~/\?/)?'&':'?').'token='.$token.
14070: '&tokenissued='.$perlvar{'lonHostID'};
14071: } else {
14072: return '/adm/notfound.html';
14073: }
14074: }
14075:
14076: # call with reqtype HEAD: get last modification time
14077: # call with reqtype GET: get the file contents
14078: # Do not call this with reqtype GET for large files! It loads everything into memory
14079: #
14080: sub getuploaded {
14081: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
14082: $uri=~s/^\///;
14083: my $homeserver = &homeserver($cnum,$cdom);
14084: my $hostname = &hostname($homeserver);
14085: my $protocol = $protocol{$homeserver};
14086: $protocol = 'http' if ($protocol ne 'https');
14087: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
14088: my $request=new HTTP::Request($reqtype,$uri);
14089: my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
14090: $$rtncode = $response->code;
14091: if (! $response->is_success()) {
14092: return 'failed';
14093: }
14094: if ($reqtype eq 'HEAD') {
14095: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
14096: } elsif ($reqtype eq 'GET') {
14097: $$info = $response->content;
14098: }
14099: return 'ok';
14100: }
14101:
14102: sub readfile {
14103: my $file = shift;
14104: if ( (! -e $file ) || ($file eq '') ) { return -1; };
14105: my $fh;
14106: open($fh,"<",$file);
14107: my $a='';
14108: while (my $line = <$fh>) { $a .= $line; }
14109: return $a;
14110: }
14111:
14112: sub filelocation {
14113: my ($dir,$file) = @_;
14114: my $location;
14115: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
14116:
14117: if ($file =~ m-^/adm/-) {
14118: $file=~s-^/adm/wrapper/-/-;
14119: $file=~s-^/adm/coursedocs/showdoc/-/-;
14120: }
14121:
14122: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
14123: $location = $file;
14124: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
14125: my ($udom,$uname,$filename)=
14126: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
14127: my $home=&homeserver($uname,$udom);
14128: my $is_me=0;
14129: my @ids=¤t_machine_ids();
14130: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
14131: if ($is_me) {
14132: $location=propath($udom,$uname).'/userfiles/'.$filename;
14133: } else {
14134: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14135: $udom.'/'.$uname.'/'.$filename;
14136: }
14137: } elsif ($file =~ m-^/adm/-) {
14138: $location = $perlvar{'lonDocRoot'}.'/'.$file;
14139: } else {
14140: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
14141: $file=~s:^/(res|priv)/:/:;
14142: my $space=$1;
14143: if ( !( $file =~ m:^/:) ) {
14144: $location = $dir. '/'.$file;
14145: } else {
14146: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
14147: }
14148: }
14149: $location=~s://+:/:g; # remove duplicate /
14150: while ($location=~m{/\.\./}) {
14151: if ($location =~ m{/[^/]+/\.\./}) {
14152: $location=~ s{/[^/]+/\.\./}{/}g;
14153: } else {
14154: $location=~ s{/\.\./}{/}g;
14155: }
14156: } #remove dir/..
14157: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14158: return $location;
14159: }
14160:
14161: sub hreflocation {
14162: my ($dir,$file)=@_;
14163: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
14164: $file=filelocation($dir,$file);
14165: } elsif ($file=~m-^/adm/-) {
14166: $file=~s-^/adm/wrapper/-/-;
14167: $file=~s-^/adm/coursedocs/showdoc/-/-;
14168: }
14169: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14170: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14171: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
14172: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14173: {/uploaded/$1/$2/}x;
14174: }
14175: if ($file=~ m{^/userfiles/}) {
14176: $file =~ s{^/userfiles/}{/uploaded/};
14177: }
14178: return $file;
14179: }
14180:
14181:
14182:
14183:
14184:
14185: sub current_machine_domains {
14186: return &machine_domains(&hostname($perlvar{'lonHostID'}));
14187: }
14188:
14189: sub machine_domains {
14190: my ($hostname) = @_;
14191: my @domains;
14192: my %hostname = &all_hostnames();
14193: while( my($id, $name) = each(%hostname)) {
14194: # &logthis("-$id-$name-$hostname-");
14195: if ($hostname eq $name) {
14196: push(@domains,&host_domain($id));
14197: }
14198: }
14199: return @domains;
14200: }
14201:
14202: sub current_machine_ids {
14203: return &machine_ids(&hostname($perlvar{'lonHostID'}));
14204: }
14205:
14206: sub machine_ids {
14207: my ($hostname) = @_;
14208: $hostname ||= &hostname($perlvar{'lonHostID'});
14209: my @ids;
14210: my %name_to_host = &all_names();
14211: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14212: return @{ $name_to_host{$hostname} };
14213: }
14214: return;
14215: }
14216:
14217: sub additional_machine_domains {
14218: my @domains;
14219: open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
14220: while( my $line = <$fh>) {
14221: $line =~ s/\s//g;
14222: push(@domains,$line);
14223: }
14224: return @domains;
14225: }
14226:
14227: sub default_login_domain {
14228: my $domain = $perlvar{'lonDefDomain'};
14229: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14230: foreach my $posdom (¤t_machine_domains(),
14231: &additional_machine_domains()) {
14232: if (lc($posdom) eq lc($testdomain)) {
14233: $domain=$posdom;
14234: last;
14235: }
14236: }
14237: return $domain;
14238: }
14239:
14240: sub shared_institution {
14241: my ($dom,$lonhost) = @_;
14242: if ($lonhost eq '') {
14243: $lonhost = $perlvar{'lonHostID'};
14244: }
14245: my $same_intdom;
14246: my $hostintdom = &internet_dom($lonhost);
14247: if ($hostintdom ne '') {
14248: my %iphost = &get_iphost();
14249: my $primary_id = &domain($dom,'primary');
14250: my $primary_ip = &get_host_ip($primary_id);
14251: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14252: foreach my $id (@{$iphost{$primary_ip}}) {
14253: my $intdom = &internet_dom($id);
14254: if ($intdom eq $hostintdom) {
14255: $same_intdom = 1;
14256: last;
14257: }
14258: }
14259: }
14260: }
14261: return $same_intdom;
14262: }
14263:
14264: sub uses_sts {
14265: my ($ignore_cache) = @_;
14266: my $lonhost = $perlvar{'lonHostID'};
14267: my $hostname = &hostname($lonhost);
14268: my $sts_on;
14269: if ($protocol{$lonhost} eq 'https') {
14270: my $cachetime = 12*3600;
14271: if (!$ignore_cache) {
14272: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14273: if (defined($cached)) {
14274: return $sts_on;
14275: }
14276: }
14277: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14278: my $request=new HTTP::Request('HEAD',$url);
14279: my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14280: if ($response->is_success) {
14281: my $has_sts = $response->header('Strict-Transport-Security');
14282: if ($has_sts eq '') {
14283: $sts_on = 0;
14284: } else {
14285: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14286: my $maxage = $1;
14287: if ($maxage) {
14288: $sts_on = 1;
14289: } else {
14290: $sts_on = 0;
14291: }
14292: } else {
14293: $sts_on = 0;
14294: }
14295: }
14296: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14297: }
14298: }
14299: return;
14300: }
14301:
14302: sub get_requestor_ip {
14303: my ($r,$nolookup,$noproxy) = @_;
14304: my $from_ip;
14305: if (ref($r)) {
14306: $from_ip = $r->get_remote_host($nolookup);
14307: } else {
14308: $from_ip = $ENV{'REMOTE_ADDR'};
14309: }
14310: return $from_ip if ($noproxy);
14311: # Who controls proxy settings for server
14312: my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
14313: my $proxyinfo = &get_proxy_settings($dom_in_use);
14314: if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
14315: if ($proxyinfo->{'vpnint'}) {
14316: if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
14317: return $from_ip;
14318: }
14319: }
14320: if ($proxyinfo->{'trusted'}) {
14321: if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
14322: my $ipheader = $proxyinfo->{'ipheader'};
14323: my ($ip,$xfor);
14324: if (ref($r)) {
14325: if ($ipheader) {
14326: $ip = $r->headers_in->{$ipheader};
14327: }
14328: $xfor = $r->headers_in->{'X-Forwarded-For'};
14329: } else {
14330: if ($ipheader) {
14331: $ip = $ENV{'HTTP_'.uc($ipheader)};
14332: }
14333: $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
14334: }
14335: if (($ip eq '') && ($xfor ne '')) {
14336: foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
14337: unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
14338: $ip = $poss_ip;
14339: last;
14340: }
14341: }
14342: }
14343: if ($ip ne '') {
14344: return $ip;
14345: }
14346: }
14347: }
14348: }
14349: return $from_ip;
14350: }
14351:
14352: sub get_proxy_settings {
14353: my ($dom_in_use) = @_;
14354: my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
14355: my $proxyinfo = {
14356: ipheader => $domdefaults{'waf_ipheader'},
14357: trusted => $domdefaults{'waf_trusted'},
14358: vpnint => $domdefaults{'waf_vpnint'},
14359: vpnext => $domdefaults{'waf_vpnext'},
14360: };
14361: return $proxyinfo;
14362: }
14363:
14364: sub ip_match {
14365: my ($ip,$pattern_str) = @_;
14366: $ip=Net::CIDR::cidrvalidate($ip);
14367: if ($ip) {
14368: return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
14369: }
14370: return;
14371: }
14372:
14373: sub get_proxy_alias {
14374: my $lonhost = $perlvar{'lonHostID'};
14375: if ($lonhost ne '') {
14376: my ($alias,$cached) = &is_cached_new('proxyalias',$lonhost);
14377: if ($cached) {
14378: return $alias;
14379: }
14380: my $dom = &Apache::lonnet::host_domain($lonhost);
14381: if ($dom ne '') {
14382: my $cachetime = 60*60*24;
14383: my %domconfig =
14384: &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
14385: my $alias;
14386: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14387: if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
14388: $alias = $domconfig{'wafproxy'}{'alias'}{$lonhost};
14389: }
14390: }
14391: return &do_cache_new('proxyalias',$lonhost,$alias,$cachetime);
14392: }
14393: }
14394: return;
14395: }
14396:
14397: # ------------------------------------------------------------- Declutters URLs
14398:
14399: sub declutter {
14400: my $thisfn=shift;
14401: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14402: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
14403: $thisfn=~s{^/home/httpd/html}{};
14404: }
14405: $thisfn=~s/^\///;
14406: $thisfn=~s|^adm/wrapper/||;
14407: $thisfn=~s|^adm/coursedocs/showdoc/||;
14408: $thisfn=~s/^res\///;
14409: $thisfn=~s/^priv\///;
14410: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
14411: $thisfn=~s/\?.+$//;
14412: }
14413: return $thisfn;
14414: }
14415:
14416: # ------------------------------------------------------------- Clutter up URLs
14417:
14418: sub clutter {
14419: my $thisfn='/'.&declutter(shift);
14420: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
14421: || $thisfn =~ m{^/adm/(includes|pages)} ) {
14422: $thisfn='/res'.$thisfn;
14423: }
14424: if ($thisfn !~m|^/adm|) {
14425: if ($thisfn =~ m|^/ext/|) {
14426: $thisfn='/adm/wrapper'.$thisfn;
14427: } else {
14428: my ($ext) = ($thisfn =~ /\.(\w+)$/);
14429: my $embstyle=&Apache::loncommon::fileembstyle($ext);
14430: if ($embstyle eq 'ssi'
14431: || ($embstyle eq 'hdn')
14432: || ($embstyle eq 'rat')
14433: || ($embstyle eq 'prv')
14434: || ($embstyle eq 'ign')) {
14435: #do nothing with these
14436: } elsif (($embstyle eq 'img')
14437: || ($embstyle eq 'emb')
14438: || ($embstyle eq 'wrp')) {
14439: $thisfn='/adm/wrapper'.$thisfn;
14440: } elsif ($embstyle eq 'unk'
14441: && $thisfn!~/\.(sequence|page)$/) {
14442: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
14443: } else {
14444: # &logthis("Got a blank emb style");
14445: }
14446: }
14447: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
14448: $thisfn='/adm/wrapper'.$thisfn;
14449: }
14450: return $thisfn;
14451: }
14452:
14453: sub clutter_with_no_wrapper {
14454: my $uri = &clutter(shift);
14455: if ($uri =~ m-^/adm/-) {
14456: $uri =~ s-^/adm/wrapper/-/-;
14457: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
14458: }
14459: return $uri;
14460: }
14461:
14462: sub freeze_escape {
14463: my ($value)=@_;
14464: if (ref($value)) {
14465: $value=&nfreeze($value);
14466: return '__FROZEN__'.&escape($value);
14467: }
14468: return &escape($value);
14469: }
14470:
14471:
14472: sub thaw_unescape {
14473: my ($value)=@_;
14474: if ($value =~ /^__FROZEN__/) {
14475: substr($value,0,10,undef);
14476: $value=&unescape($value);
14477: return &thaw($value);
14478: }
14479: return &unescape($value);
14480: }
14481:
14482: sub correct_line_ends {
14483: my ($result)=@_;
14484: $$result =~s/\r\n/\n/mg;
14485: $$result =~s/\r/\n/mg;
14486: }
14487: # ================================================================ Main Program
14488:
14489: sub goodbye {
14490: &logthis("Starting Shut down");
14491: #not converted to using infrastruture and probably shouldn't be
14492: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
14493: #converted
14494: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
14495: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14496: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14497: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
14498: #1.1 only
14499: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14500: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14501: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14502: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14503: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
14504: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14505: &logthis(sprintf("%-20s is %s",'hits',$hits));
14506: &flushcourselogs();
14507: &logthis("Shutting down");
14508: }
14509:
14510: sub get_dns {
14511: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
14512: if (!$ignore_cache) {
14513: my ($content,$cached)=
14514: &Apache::lonnet::is_cached_new('dns',$url);
14515: if ($cached) {
14516: &$func($content,$hashref);
14517: return;
14518: }
14519: }
14520:
14521: my %alldns;
14522: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
14523: foreach my $dns (<$config>) {
14524: next if ($dns !~ /^\^(\S*)/x);
14525: my $line = $1;
14526: my ($host,$protocol) = split(/:/,$line);
14527: if ($protocol ne 'https') {
14528: $protocol = 'http';
14529: }
14530: $alldns{$host} = $protocol;
14531: }
14532: close($config);
14533: }
14534: while (%alldns) {
14535: my ($dns) = sort { $b cmp $a } keys(%alldns);
14536: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
14537: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
14538: delete($alldns{$dns});
14539: next if ($response->is_error());
14540: if ($url eq '/adm/dns/loncapaCRL') {
14541: return &$func($response);
14542: } else {
14543: my @content = split("\n",$response->content);
14544: unless ($nocache) {
14545: &do_cache_new('dns',$url,\@content,30*24*60*60);
14546: }
14547: &$func(\@content,$hashref);
14548: return;
14549: }
14550: }
14551: my $which = (split('/',$url,4))[3];
14552: if ($which eq 'loncapaCRL') {
14553: my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14554: if (-e $diskfile) {
14555: &logthis("unable to contact DNS, on disk file $diskfile not updated");
14556: } else {
14557: &logthis("unable to contact DNS, no on disk file $diskfile available");
14558: }
14559: } else {
14560: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
14561: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14562: my @content = <$config>;
14563: close($config);
14564: &$func(\@content,$hashref);
14565: }
14566: }
14567: return;
14568: }
14569:
14570: # ------------------------------------------------------Get DNS checksums file
14571: sub parse_dns_checksums_tab {
14572: my ($lines,$hashref) = @_;
14573: my $lonhost = $perlvar{'lonHostID'};
14574: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
14575: my $loncaparev = &get_server_loncaparev($machine_dom);
14576: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14577: my $webconfdir = '/etc/httpd/conf';
14578: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14579: $webconfdir = '/etc/apache2';
14580: } elsif ($distro =~ /^sles(\d+)$/) {
14581: if ($1 >= 10) {
14582: $webconfdir = '/etc/apache2';
14583: }
14584: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14585: if ($1 >= 10.0) {
14586: $webconfdir = '/etc/apache2';
14587: }
14588: }
14589: my ($release,$timestamp) = split(/\-/,$loncaparev);
14590: my (%chksum,%revnum);
14591: if (ref($lines) eq 'ARRAY') {
14592: chomp(@{$lines});
14593: my $version = shift(@{$lines});
14594: if ($version eq $release) {
14595: foreach my $line (@{$lines}) {
14596: my ($file,$version,$shasum) = split(/,/,$line);
14597: if ($file =~ m{^/etc/httpd/conf}) {
14598: if ($webconfdir eq '/etc/apache2') {
14599: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14600: }
14601: }
14602: $chksum{$file} = $shasum;
14603: $revnum{$file} = $version;
14604: }
14605: if (ref($hashref) eq 'HASH') {
14606: %{$hashref} = (
14607: sums => \%chksum,
14608: versions => \%revnum,
14609: );
14610: }
14611: }
14612: }
14613: return;
14614: }
14615:
14616: sub fetch_dns_checksums {
14617: my %checksums;
14618: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
14619: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
14620: my ($release,$timestamp) = split(/\-/,$loncaparev);
14621: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
14622: \%checksums);
14623: return \%checksums;
14624: }
14625:
14626: sub fetch_crl_pemfile {
14627: return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
14628: }
14629:
14630: sub save_crl_pem {
14631: my ($response) = @_;
14632: my ($msg,$hadchanges);
14633: if (ref($response)) {
14634: my $now = time;
14635: my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
14636: my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
14637: if (open(my $fh,'>',"$tmpcrl")) {
14638: print $fh $response->content;
14639: close($fh);
14640: if (-e $lonca) {
14641: if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
14642: my $check = <PIPE>;
14643: close(PIPE);
14644: chomp($check);
14645: if ($check eq 'verify OK') {
14646: my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14647: my $backup;
14648: if (-e $dest) {
14649: if (&File::Copy::move($dest,"$dest.bak")) {
14650: $backup = 'ok';
14651: }
14652: }
14653: if (&File::Copy::move($tmpcrl,$dest)) {
14654: $msg = 'ok';
14655: if ($backup) {
14656: my (%oldnums,%newnums);
14657: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
14658: while (<PIPE>) {
14659: $oldnums{(split(/:/))[1]} = 1;
14660: }
14661: close(PIPE);
14662: }
14663: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
14664: while(<PIPE>) {
14665: $newnums{(split(/:/))[1]} = 1;
14666: }
14667: close(PIPE);
14668: }
14669: foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
14670: unless (exists($oldnums{$key})) {
14671: $hadchanges = 1;
14672: last;
14673: }
14674: }
14675: unless ($hadchanges) {
14676: foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
14677: unless (exists($newnums{$key})) {
14678: $hadchanges = 1;
14679: last;
14680: }
14681: }
14682: }
14683: }
14684: }
14685: } else {
14686: unlink($tmpcrl);
14687: }
14688: } else {
14689: unlink($tmpcrl);
14690: }
14691: } else {
14692: unlink($tmpcrl);
14693: }
14694: }
14695: }
14696: return ($msg,$hadchanges);
14697: }
14698:
14699: # ------------------------------------------------------------ Read domain file
14700: {
14701: my $loaded;
14702: my %domain;
14703:
14704: sub parse_domain_tab {
14705: my ($lines) = @_;
14706: foreach my $line (@$lines) {
14707: next if ($line =~ /^(\#|\s*$ )/x);
14708:
14709: chomp($line);
14710: my ($name,@elements) = split(/:/,$line,9);
14711: my %this_domain;
14712: foreach my $field ('description', 'auth_def', 'auth_arg_def',
14713: 'lang_def', 'city', 'longi', 'lati',
14714: 'primary') {
14715: $this_domain{$field} = shift(@elements);
14716: }
14717: $domain{$name} = \%this_domain;
14718: }
14719: }
14720:
14721: sub reset_domain_info {
14722: undef($loaded);
14723: undef(%domain);
14724: }
14725:
14726: sub load_domain_tab {
14727: my ($ignore_cache,$nocache) = @_;
14728: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
14729: my $fh;
14730: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
14731: my @lines = <$fh>;
14732: &parse_domain_tab(\@lines);
14733: }
14734: close($fh);
14735: $loaded = 1;
14736: }
14737:
14738: sub domain {
14739: &load_domain_tab() if (!$loaded);
14740:
14741: my ($name,$what) = @_;
14742: return if ( !exists($domain{$name}) );
14743:
14744: if (!$what) {
14745: return $domain{$name}{'description'};
14746: }
14747: return $domain{$name}{$what};
14748: }
14749:
14750: sub domain_info {
14751: &load_domain_tab() if (!$loaded);
14752: return %domain;
14753: }
14754:
14755: }
14756:
14757:
14758: # ------------------------------------------------------------- Read hosts file
14759: {
14760: my %hostname;
14761: my %hostdom;
14762: my %libserv;
14763: my $loaded;
14764: my %name_to_host;
14765: my %internetdom;
14766: my %LC_dns_serv;
14767:
14768: sub parse_hosts_tab {
14769: my ($file) = @_;
14770: foreach my $configline (@$file) {
14771: next if ($configline =~ /^(\#|\s*$ )/x);
14772: chomp($configline);
14773: if ($configline =~ /^\^/) {
14774: if ($configline =~ /^\^([\w.\-]+)/) {
14775: $LC_dns_serv{$1} = 1;
14776: }
14777: next;
14778: }
14779: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
14780: $name=~s/\s//g;
14781: if ($id && $domain && $role && $name) {
14782: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
14783: my $curr = $hostname{$id};
14784: my $skip;
14785: if (ref($name_to_host{$curr}) eq 'ARRAY') {
14786: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
14787: $skip = 1;
14788: } else {
14789: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
14790: }
14791: }
14792: unless ($skip) {
14793: push(@{$name_to_host{$name}},$id);
14794: }
14795: } else {
14796: push(@{$name_to_host{$name}},$id);
14797: }
14798: $hostname{$id}=$name;
14799: $hostdom{$id}=$domain;
14800: if ($role eq 'library') { $libserv{$id}=$name; }
14801: if (defined($protocol)) {
14802: if ($protocol eq 'https') {
14803: $protocol{$id} = $protocol;
14804: } else {
14805: $protocol{$id} = 'http';
14806: }
14807: } else {
14808: $protocol{$id} = 'http';
14809: }
14810: if (defined($intdom)) {
14811: $internetdom{$id} = $intdom;
14812: }
14813: }
14814: }
14815: }
14816:
14817: sub reset_hosts_info {
14818: &purge_remembered();
14819: &reset_domain_info();
14820: &reset_hosts_ip_info();
14821: undef(%internetdom);
14822: undef(%name_to_host);
14823: undef(%hostname);
14824: undef(%hostdom);
14825: undef(%libserv);
14826: undef($loaded);
14827: }
14828:
14829: sub load_hosts_tab {
14830: my ($ignore_cache,$nocache) = @_;
14831: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
14832: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
14833: my @config = <$config>;
14834: &parse_hosts_tab(\@config);
14835: close($config);
14836: $loaded=1;
14837: }
14838:
14839: sub hostname {
14840: &load_hosts_tab() if (!$loaded);
14841:
14842: my ($lonid) = @_;
14843: return $hostname{$lonid};
14844: }
14845:
14846: sub all_hostnames {
14847: &load_hosts_tab() if (!$loaded);
14848:
14849: return %hostname;
14850: }
14851:
14852: sub all_names {
14853: my ($ignore_cache,$nocache) = @_;
14854: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
14855:
14856: return %name_to_host;
14857: }
14858:
14859: sub all_host_domain {
14860: &load_hosts_tab() if (!$loaded);
14861: return %hostdom;
14862: }
14863:
14864: sub all_host_intdom {
14865: &load_hosts_tab() if (!$loaded);
14866: return %internetdom;
14867: }
14868:
14869: sub is_library {
14870: &load_hosts_tab() if (!$loaded);
14871:
14872: return exists($libserv{$_[0]});
14873: }
14874:
14875: sub all_library {
14876: &load_hosts_tab() if (!$loaded);
14877:
14878: return %libserv;
14879: }
14880:
14881: sub unique_library {
14882: #2x reverse removes all hostnames that appear more than once
14883: my %unique = reverse &all_library();
14884: return reverse %unique;
14885: }
14886:
14887: sub get_servers {
14888: &load_hosts_tab() if (!$loaded);
14889:
14890: my ($domain,$type) = @_;
14891: my %possible_hosts = ($type eq 'library') ? %libserv
14892: : %hostname;
14893: my %result;
14894: if (ref($domain) eq 'ARRAY') {
14895: while ( my ($host,$hostname) = each(%possible_hosts)) {
14896: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
14897: $result{$host} = $hostname;
14898: }
14899: }
14900: } else {
14901: while ( my ($host,$hostname) = each(%possible_hosts)) {
14902: if ($hostdom{$host} eq $domain) {
14903: $result{$host} = $hostname;
14904: }
14905: }
14906: }
14907: return %result;
14908: }
14909:
14910: sub get_unique_servers {
14911: my %unique = reverse &get_servers(@_);
14912: return reverse %unique;
14913: }
14914:
14915: sub host_domain {
14916: &load_hosts_tab() if (!$loaded);
14917:
14918: my ($lonid) = @_;
14919: return $hostdom{$lonid};
14920: }
14921:
14922: sub all_domains {
14923: &load_hosts_tab() if (!$loaded);
14924:
14925: my %seen;
14926: my @uniq = grep(!$seen{$_}++, values(%hostdom));
14927: return @uniq;
14928: }
14929:
14930: sub internet_dom {
14931: &load_hosts_tab() if (!$loaded);
14932:
14933: my ($lonid) = @_;
14934: return $internetdom{$lonid};
14935: }
14936:
14937: sub is_LC_dns {
14938: &load_hosts_tab() if (!$loaded);
14939:
14940: my ($hostname) = @_;
14941: return exists($LC_dns_serv{$hostname});
14942: }
14943:
14944: }
14945:
14946: {
14947: my %iphost;
14948: my %name_to_ip;
14949: my %lonid_to_ip;
14950:
14951: sub get_hosts_from_ip {
14952: my ($ip) = @_;
14953: my %iphosts = &get_iphost();
14954: if (ref($iphosts{$ip})) {
14955: return @{$iphosts{$ip}};
14956: }
14957: return;
14958: }
14959:
14960: sub reset_hosts_ip_info {
14961: undef(%iphost);
14962: undef(%name_to_ip);
14963: undef(%lonid_to_ip);
14964: }
14965:
14966: sub get_host_ip {
14967: my ($lonid) = @_;
14968: if (exists($lonid_to_ip{$lonid})) {
14969: return $lonid_to_ip{$lonid};
14970: }
14971: my $name=&hostname($lonid);
14972: my $ip = gethostbyname($name);
14973: return if (!$ip || length($ip) ne 4);
14974: $ip=inet_ntoa($ip);
14975: $name_to_ip{$name} = $ip;
14976: $lonid_to_ip{$lonid} = $ip;
14977: return $ip;
14978: }
14979:
14980: sub get_iphost {
14981: my ($ignore_cache,$nocache) = @_;
14982:
14983: if (!$ignore_cache) {
14984: if (%iphost) {
14985: return %iphost;
14986: }
14987: my ($ip_info,$cached)=
14988: &Apache::lonnet::is_cached_new('iphost','iphost');
14989: if ($cached) {
14990: %iphost = %{$ip_info->[0]};
14991: %name_to_ip = %{$ip_info->[1]};
14992: %lonid_to_ip = %{$ip_info->[2]};
14993: return %iphost;
14994: }
14995: }
14996:
14997: # get yesterday's info for fallback
14998: my %old_name_to_ip;
14999: my ($ip_info,$cached)=
15000: &Apache::lonnet::is_cached_new('iphost','iphost');
15001: if ($cached) {
15002: %old_name_to_ip = %{$ip_info->[1]};
15003: }
15004:
15005: my %name_to_host = &all_names($ignore_cache,$nocache);
15006: foreach my $name (keys(%name_to_host)) {
15007: my $ip;
15008: if (!exists($name_to_ip{$name})) {
15009: $ip = gethostbyname($name);
15010: if (!$ip || length($ip) ne 4) {
15011: if (defined($old_name_to_ip{$name})) {
15012: $ip = $old_name_to_ip{$name};
15013: &logthis("Can't find $name defaulting to old $ip");
15014: } else {
15015: &logthis("Name $name no IP found");
15016: next;
15017: }
15018: } else {
15019: $ip=inet_ntoa($ip);
15020: }
15021: $name_to_ip{$name} = $ip;
15022: } else {
15023: $ip = $name_to_ip{$name};
15024: }
15025: foreach my $id (@{ $name_to_host{$name} }) {
15026: $lonid_to_ip{$id} = $ip;
15027: }
15028: push(@{$iphost{$ip}},@{$name_to_host{$name}});
15029: }
15030: unless ($nocache) {
15031: &do_cache_new('iphost','iphost',
15032: [\%iphost,\%name_to_ip,\%lonid_to_ip],
15033: 48*60*60);
15034: }
15035:
15036: return %iphost;
15037: }
15038:
15039: #
15040: # Given a DNS returns the loncapa host name for that DNS
15041: #
15042: sub host_from_dns {
15043: my ($dns) = @_;
15044: my @hosts;
15045: my $ip;
15046:
15047: if (exists($name_to_ip{$dns})) {
15048: $ip = $name_to_ip{$dns};
15049: }
15050: if (!$ip) {
15051: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
15052: if (length($ip) == 4) {
15053: $ip = &IO::Socket::inet_ntoa($ip);
15054: }
15055: }
15056: if ($ip) {
15057: @hosts = get_hosts_from_ip($ip);
15058: return $hosts[0];
15059: }
15060: return undef;
15061: }
15062:
15063: sub get_internet_names {
15064: my ($lonid) = @_;
15065: return if ($lonid eq '');
15066: my ($idnref,$cached)=
15067: &Apache::lonnet::is_cached_new('internetnames',$lonid);
15068: if ($cached) {
15069: return $idnref;
15070: }
15071: my $ip = &get_host_ip($lonid);
15072: my @hosts = &get_hosts_from_ip($ip);
15073: my %iphost = &get_iphost();
15074: my (@idns,%seen);
15075: foreach my $id (@hosts) {
15076: my $dom = &host_domain($id);
15077: my $prim_id = &domain($dom,'primary');
15078: my $prim_ip = &get_host_ip($prim_id);
15079: next if ($seen{$prim_ip});
15080: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
15081: foreach my $id (@{$iphost{$prim_ip}}) {
15082: my $intdom = &internet_dom($id);
15083: unless (grep(/^\Q$intdom\E$/,@idns)) {
15084: push(@idns,$intdom);
15085: }
15086: }
15087: }
15088: $seen{$prim_ip} = 1;
15089: }
15090: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
15091: }
15092:
15093: }
15094:
15095: sub all_loncaparevs {
15096: 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);
15097: }
15098:
15099: # ---------------------------------------------------------- Read loncaparev table
15100: {
15101: sub load_loncaparevs {
15102: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
15103: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
15104: while (my $configline=<$config>) {
15105: chomp($configline);
15106: my ($hostid,$loncaparev)=split(/:/,$configline);
15107: $loncaparevs{$hostid}=$loncaparev;
15108: }
15109: close($config);
15110: }
15111: }
15112: }
15113: }
15114:
15115: # ---------------------------------------------------------- Read serverhostID table
15116: {
15117: sub load_serverhomeIDs {
15118: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
15119: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
15120: while (my $configline=<$config>) {
15121: chomp($configline);
15122: my ($name,$id)=split(/:/,$configline);
15123: $serverhomeIDs{$name}=$id;
15124: }
15125: close($config);
15126: }
15127: }
15128: }
15129: }
15130:
15131:
15132: BEGIN {
15133:
15134: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
15135: unless ($readit) {
15136: {
15137: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
15138: %perlvar = (%perlvar,%{$configvars});
15139: }
15140:
15141:
15142: # ------------------------------------------------------ Read spare server file
15143: {
15144: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
15145:
15146: while (my $configline=<$config>) {
15147: chomp($configline);
15148: if ($configline) {
15149: my ($host,$type) = split(':',$configline,2);
15150: if (!defined($type) || $type eq '') { $type = 'default' };
15151: push(@{ $spareid{$type} }, $host);
15152: }
15153: }
15154: close($config);
15155: }
15156: # ------------------------------------------------------------ Read permissions
15157: {
15158: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
15159:
15160: while (my $configline=<$config>) {
15161: chomp($configline);
15162: if ($configline) {
15163: my ($role,$perm)=split(/ /,$configline);
15164: if ($perm ne '') { $pr{$role}=$perm; }
15165: }
15166: }
15167: close($config);
15168: }
15169:
15170: # -------------------------------------------- Read plain texts for permissions
15171: {
15172: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
15173:
15174: while (my $configline=<$config>) {
15175: chomp($configline);
15176: if ($configline) {
15177: my ($short,@plain)=split(/:/,$configline);
15178: %{$prp{$short}} = ();
15179: if (@plain > 0) {
15180: $prp{$short}{'std'} = $plain[0];
15181: for (my $i=1; $i<@plain; $i++) {
15182: $prp{$short}{'alt'.$i} = $plain[$i];
15183: }
15184: }
15185: }
15186: }
15187: close($config);
15188: }
15189:
15190: # ---------------------------------------------------------- Read package table
15191: {
15192: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
15193:
15194: while (my $configline=<$config>) {
15195: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
15196: chomp($configline);
15197: my ($short,$plain)=split(/:/,$configline);
15198: my ($pack,$name)=split(/\&/,$short);
15199: if ($plain ne '') {
15200: $packagetab{$pack.'&'.$name.'&name'}=$name;
15201: $packagetab{$short}=$plain;
15202: }
15203: }
15204: close($config);
15205: }
15206:
15207: # ---------------------------------------------------------- Read loncaparev table
15208:
15209: &load_loncaparevs();
15210:
15211: # ---------------------------------------------------------- Read serverhostID table
15212:
15213: &load_serverhomeIDs();
15214:
15215: # ---------------------------------------------------------- Read releaseslist XML
15216: {
15217: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
15218: if (-e $file) {
15219: my $parser = HTML::LCParser->new($file);
15220: while (my $token = $parser->get_token()) {
15221: if ($token->[0] eq 'S') {
15222: my $item = $token->[1];
15223: my $name = $token->[2]{'name'};
15224: my $value = $token->[2]{'value'};
15225: my $valuematch = $token->[2]{'valuematch'};
15226: my $namematch = $token->[2]{'namematch'};
15227: if ($item eq 'parameter') {
15228: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
15229: my $release = $parser->get_text();
15230: $release =~ s/(^\s*|\s*$ )//gx;
15231: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
15232: }
15233: } elsif ($item ne '' && $name ne '') {
15234: my $release = $parser->get_text();
15235: $release =~ s/(^\s*|\s*$ )//gx;
15236: $needsrelease{$item.':'.$name.':'.$value} = $release;
15237: }
15238: }
15239: }
15240: }
15241: }
15242:
15243: # ---------------------------------------------------------- Read managers table
15244: {
15245: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
15246: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
15247: while (my $configline=<$config>) {
15248: chomp($configline);
15249: next if ($configline =~ /^\#/);
15250: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
15251: $managerstab{$configline} = 1;
15252: }
15253: }
15254: close($config);
15255: }
15256: }
15257: }
15258:
15259: # ------------- set up temporary directory
15260: {
15261: $tmpdir = LONCAPA::tempdir();
15262:
15263: }
15264:
15265: # ------------- set default texengine (domain default overrides this)
15266: {
15267: $deftex = LONCAPA::texengine();
15268: }
15269:
15270: # ------------- set default minimum length for passwords for internal auth users
15271: {
15272: $passwdmin = LONCAPA::passwd_min();
15273: }
15274:
15275: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
15276: 'compress_threshold'=> 20_000,
15277: });
15278:
15279: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
15280: $dumpcount=0;
15281: $locknum=0;
15282:
15283: &logtouch();
15284: &logthis('<font color="yellow">INFO: Read configuration</font>');
15285: $readit=1;
15286: {
15287: use integer;
15288: my $test=(2**32)+1;
15289: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
15290: &logthis(" Detected 64bit platform ($_64bit)");
15291: }
15292: }
15293: }
15294:
15295: 1;
15296: __END__
15297:
15298: =pod
15299:
15300: =head1 NAME
15301:
15302: Apache::lonnet - Subroutines to ask questions about things in the network.
15303:
15304: =head1 SYNOPSIS
15305:
15306: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
15307:
15308: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
15309:
15310: Common parameters:
15311:
15312: =over 4
15313:
15314: =item *
15315:
15316: $uname : an internal username (if $cname expecting a course Id specifically)
15317:
15318: =item *
15319:
15320: $udom : a domain (if $cdom expecting a course's domain specifically)
15321:
15322: =item *
15323:
15324: $symb : a resource instance identifier
15325:
15326: =item *
15327:
15328: $namespace : the name of a .db file that contains the data needed or
15329: being set.
15330:
15331: =back
15332:
15333: =head1 OVERVIEW
15334:
15335: lonnet provides subroutines which interact with the
15336: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
15337: about classes, users, and resources.
15338:
15339: For many of these objects you can also use this to store data about
15340: them or modify them in various ways.
15341:
15342: =head2 Symbs
15343:
15344: To identify a specific instance of a resource, LON-CAPA uses symbols
15345: or "symbs"X<symb>. These identifiers are built from the URL of the
15346: map, the resource number of the resource in the map, and the URL of
15347: the resource itself. The latter is somewhat redundant, but might help
15348: if maps change.
15349:
15350: An example is
15351:
15352: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
15353:
15354: The respective map entry is
15355:
15356: <resource id="19" src="/res/msu/korte/tests/part12.problem"
15357: title="Problem 2">
15358: </resource>
15359:
15360: Symbs are used by the random number generator, as well as to store and
15361: restore data specific to a certain instance of for example a problem.
15362:
15363: =head2 Storing And Retrieving Data
15364:
15365: X<store()>X<cstore()>X<restore()>Three of the most important functions
15366: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
15367: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
15368: is is the non-critical message twin of cstore. These functions are for
15369: handlers to store a perl hash to a user's permanent data space in an
15370: easy manner, and to retrieve it again on another call. It is expected
15371: that a handler would use this once at the beginning to retrieve data,
15372: and then again once at the end to send only the new data back.
15373:
15374: The data is stored in the user's data directory on the user's
15375: homeserver under the ID of the course.
15376:
15377: The hash that is returned by restore will have all of the previous
15378: value for all of the elements of the hash.
15379:
15380: Example:
15381:
15382: #creating a hash
15383: my %hash;
15384: $hash{'foo'}='bar';
15385:
15386: #storing it
15387: &Apache::lonnet::cstore(\%hash);
15388:
15389: #changing a value
15390: $hash{'foo'}='notbar';
15391:
15392: #adding a new value
15393: $hash{'bar'}='foo';
15394: &Apache::lonnet::cstore(\%hash);
15395:
15396: #retrieving the hash
15397: my %history=&Apache::lonnet::restore();
15398:
15399: #print the hash
15400: foreach my $key (sort(keys(%history))) {
15401: print("\%history{$key} = $history{$key}");
15402: }
15403:
15404: Will print out:
15405:
15406: %history{1:foo} = bar
15407: %history{1:keys} = foo:timestamp
15408: %history{1:timestamp} = 990455579
15409: %history{2:bar} = foo
15410: %history{2:foo} = notbar
15411: %history{2:keys} = foo:bar:timestamp
15412: %history{2:timestamp} = 990455580
15413: %history{bar} = foo
15414: %history{foo} = notbar
15415: %history{timestamp} = 990455580
15416: %history{version} = 2
15417:
15418: Note that the special hash entries C<keys>, C<version> and
15419: C<timestamp> were added to the hash. C<version> will be equal to the
15420: total number of versions of the data that have been stored. The
15421: C<timestamp> attribute will be the UNIX time the hash was
15422: stored. C<keys> is available in every historical section to list which
15423: keys were added or changed at a specific historical revision of a
15424: hash.
15425:
15426: B<Warning>: do not store the hash that restore returns directly. This
15427: will cause a mess since it will restore the historical keys as if the
15428: were new keys. I.E. 1:foo will become 1:1:foo etc.
15429:
15430: Calling convention:
15431:
15432: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
15433: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
15434:
15435: For more detailed information, see lonnet specific documentation.
15436:
15437: =head1 RETURN MESSAGES
15438:
15439: =over 4
15440:
15441: =item * B<con_lost>: unable to contact remote host
15442:
15443: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15444: when the connection is brought back up
15445:
15446: =item * B<con_failed>: unable to contact remote host and unable to save message
15447: for later delivery
15448:
15449: =item * B<error:>: an error a occurred, a description of the error follows the :
15450:
15451: =item * B<no_such_host>: unable to fund a host associated with the user/domain
15452: that was requested
15453:
15454: =back
15455:
15456: =head1 PUBLIC SUBROUTINES
15457:
15458: =head2 Session Environment Functions
15459:
15460: =over 4
15461:
15462: =item *
15463: X<appenv()>
15464: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
15465: the user envirnoment file, and will be restored for each access this
15466: user makes during this session, also modifies the %env for the current
15467: process. Optional rolesarrayref - if defined contains a reference to an array
15468: of roles which are exempt from the restriction on modifying user.role entries
15469: in the user's environment.db and in %env.
15470:
15471: =item *
15472: X<delenv()>
15473: B<delenv($delthis,$regexp)>: removes all items from the session
15474: environment file that begin with $delthis. If the
15475: optional second arg - $regexp - is true, $delthis is treated as a
15476: regular expression, otherwise \Q$delthis\E is used.
15477: The values are also deleted from the current processes %env.
15478:
15479: =item * get_env_multiple($name)
15480:
15481: gets $name from the %env hash, it seemlessly handles the cases where multiple
15482: values may be defined and end up as an array ref.
15483:
15484: returns an array of values
15485:
15486: =back
15487:
15488: =head2 User Information
15489:
15490: =over 4
15491:
15492: =item *
15493: X<queryauthenticate()>
15494: B<queryauthenticate($uname,$udom)>: try to determine user's current
15495: authentication scheme
15496:
15497: =item *
15498: X<authenticate()>
15499: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
15500: authenticate user from domain's lib servers (first use the current
15501: one). C<$upass> should be the users password.
15502: $checkdefauth is optional (value is 1 if a check should be made to
15503: authenticate user using default authentication method, and allow
15504: account creation if username does not have account in the domain).
15505: $clientcancheckhost is optional (value is 1 if checking whether the
15506: server can host will occur on the client side in lonauth.pm).
15507:
15508: =item *
15509: X<homeserver()>
15510: B<homeserver($uname,$udom)>: find the server which has
15511: the user's directory and files (there must be only one), this caches
15512: the answer, and also caches if there is a borken connection.
15513:
15514: =item *
15515: X<idget()>
15516: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
15517: a list of student/employee IDs or clicker IDs
15518: (student/employee IDs are a unique resource in a domain, there must be
15519: only 1 ID per username, and only 1 username per ID in a specific domain).
15520: clickerIDs are not necessarily unique, as students might share clickers.
15521: (returns hash: id=>name,id=>name)
15522:
15523: =item *
15524: X<idrget()>
15525: B<idrget($udom,@unames)>: find the IDs behind a list of
15526: usernames (returns hash: name=>id,name=>id)
15527:
15528: =item *
15529: X<idput()>
15530: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
15531: names and associated student/employee IDs or clicker IDs.
15532:
15533: =item *
15534: X<iddel()>
15535: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
15536: student/employee ID or clicker ID username look-ups from domain.
15537: The homeserver ($uhome) and namespace ($namespace) are optional.
15538: If no $uhome is provided, it will be determined usig &homeserver()
15539: for each user. If no $namespace is provided, the default is ids.
15540:
15541: =item *
15542: X<updateclickers()>
15543: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
15544: clicker ID-to-username look-ups in clickers.db on library server.
15545: Permitted actions are add or del (i.e., add or delete). The
15546: clickers.db contains clickerID as keys (escaped), and each corresponding
15547: value is an escaped comma-separated list of usernames (for whom the
15548: library server is the homeserver), who registered that particular ID.
15549: If $critical is true, the update will be sent via &critical, otherwise
15550: &reply() will be used.
15551:
15552: =item *
15553: X<rolesinit()>
15554: B<rolesinit($udom,$username)>: get user privileges.
15555: returns user role, first access and timer interval hashes
15556:
15557: =item *
15558: X<privileged()>
15559: B<privileged($username,$domain)>: returns a true if user has a
15560: privileged and active role (i.e. su or dc), false otherwise.
15561:
15562: =item *
15563: X<getsection()>
15564: B<getsection($udom,$uname,$cname)>: finds the section of student in the
15565: course $cname, return section name/number or '' for "not in course"
15566: and '-1' for "no section"
15567:
15568: =item *
15569: X<userenvironment()>
15570: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
15571: passed in @what from the requested user's environment, returns a hash
15572:
15573: =item *
15574: X<userlog_query()>
15575: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
15576: activity.log file. %filters defines filters applied when parsing the
15577: log file. These can be start or end timestamps, or the type of action
15578: - log to look for Login or Logout events, check for Checkin or
15579: Checkout, role for role selection. The response is in the form
15580: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
15581: escaped strings of the action recorded in the activity.log file.
15582:
15583: =back
15584:
15585: =head2 User Roles
15586:
15587: =over 4
15588:
15589: =item *
15590:
15591: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
15592: returns codes for allowed actions.
15593:
15594: The first argument is required, all others are optional.
15595:
15596: $priv is the privilege being checked.
15597: $uri contains additional information about what is being checked for access (e.g.,
15598: URL, course ID etc.).
15599: $symb is the unique resource instance identifier in a course; if needed,
15600: but not provided, it will be retrieved via a call to &symbread().
15601: $role is the role for which a priv is being checked (only used if priv is evb).
15602: $clientip is the user's IP address (only used when checking for access to portfolio
15603: files).
15604: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
15605: prevents recursive calls to &allowed.
15606:
15607: F: full access
15608: U,I,K: authentication modes (cxx only)
15609: '': forbidden
15610: 1: user needs to choose course
15611: 2: browse allowed
15612: A: passphrase authentication needed
15613: B: access temporarily blocked because of a blocking event in a course.
15614: D: access blocked because access is required via session initiated via deep-link
15615:
15616: =item *
15617:
15618: constructaccess($url,$setpriv) : check for access to construction space URL
15619:
15620: See if the owner domain and name in the URL match those in the
15621: expected environment. If so, return three element list
15622: ($ownername,$ownerdomain,$ownerhome).
15623:
15624: Otherwise return the null string.
15625:
15626: If second argument 'setpriv' is true, it assigns the privileges,
15627: and returns the same three element list, unless the owner has
15628: blocked "ad hoc" Domain Coordinator access to the Author Space,
15629: in which case the null string is returned.
15630:
15631: =item *
15632:
15633: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
15634: define a custom role rolename set privileges in format of lonTabs/roles.tab
15635: for system, domain, and course level. $uname and $udom are optional (current
15636: user's username and domain will be used when either of $uname or $udom are absent.
15637:
15638: =item *
15639:
15640: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
15641: (rolesplain.tab); plain text explanation of a user role term.
15642: $type is Course (default) or Community.
15643: If $forcedefault evaluates to true, text returned will be default
15644: text for $type. Otherwise, if this is a course, the text returned
15645: will be a custom name for the role (if defined in the course's
15646: environment). If no custom name is defined the default is returned.
15647:
15648: =item *
15649:
15650: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
15651: All arguments are optional. Returns a hash of a roles, either for
15652: co-author/assistant author roles for a user's Construction Space
15653: (default), or if $context is 'userroles', roles for the user himself,
15654: In the hash, keys are set to colon-separated $uname,$udom,$role, and
15655: (optionally) if $withsec is true, a fourth colon-separated item - $section.
15656: For each key, value is set to colon-separated start and end times for
15657: the role. If no username and domain are specified, will default to
15658: current user/domain. Types, roles, and roledoms are references to arrays
15659: of role statuses (active, future or previous), roles
15660: (e.g., cc,in, st etc.) and domains of the roles which can be used
15661: to restrict the list of roles reported. If no array ref is
15662: provided for types, will default to return only active roles.
15663:
15664: =item *
15665:
15666: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
15667: user: $uname:$udom has a role in the course: $cdom_$cnum.
15668:
15669: Additional optional arguments are: $type (if role checking is to be restricted
15670: to certain user status types -- previous (expired roles), active (currently
15671: available roles) or future (roles available in the future), and
15672: $hideprivileged -- if true will not report course roles for users who
15673: have active Domain Coordinator role in course's domain or in additional
15674: domains (specified in 'Domains to check for privileged users' in course
15675: environment -- set via: Course Settings -> Classlists and staff listing).
15676:
15677: =item *
15678:
15679: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15680: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15681: $possdomains and $possroles are optional array refs -- to domains to check and
15682: roles to check. If $possdomains is not specified, a dump will be done of the
15683: users' roles.db to check for a dc or su role in any domain. This can be
15684: time consuming if &privileged is called repeatedly (e.g., when displaying a
15685: classlist), so in such cases, supplying a $possdomains array is preferred, as
15686: this then allows &privileged_by_domain() to be used, which caches the identity
15687: of privileged users, eliminating the need for repeated calls to &dump().
15688:
15689: =item *
15690:
15691: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15692: where the outer hash keys are domains specified in the $possdomains array ref,
15693: next inner hash keys are privileged roles specified in the $roles array ref,
15694: and the innermost hash contains key = value pairs for username:domain = end:start
15695: for active or future "privileged" users with that role in that domain. To avoid
15696: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15697: innerhash are cached using priv_$role and $dom as the identifiers.
15698:
15699: =back
15700:
15701: =head2 User Modification
15702:
15703: =over 4
15704:
15705: =item *
15706:
15707: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
15708: user for the level given by URL. Optional start and end dates (leave empty
15709: string or zero for "no date")
15710:
15711: =item *
15712:
15713: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15714: change a users, password, possible return values are: ok,
15715: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15716: refused
15717:
15718: =item *
15719:
15720: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
15721:
15722: =item *
15723:
15724: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
15725: $forceid,$desiredhome,$email,$inststatus,$candelete) :
15726:
15727: will update user information (firstname,middlename,lastname,generation,
15728: permanentemail), and if forceid is true, student/employee ID also.
15729: A user's institutional affiliation(s) can also be updated.
15730: User information fields will not be overwritten with empty entries
15731: unless the field is included in the $candelete array reference.
15732: This array is included when a single user is modified via "Manage Users",
15733: or when Autoupdate.pl is run by cron in a domain.
15734:
15735: =item *
15736:
15737: modifystudent
15738:
15739: modify a student's enrollment and identification information.
15740: The course id is resolved based on the current user's environment.
15741: This means the invoking user must be a course coordinator or otherwise
15742: associated with a course.
15743:
15744: This call is essentially a wrapper for lonnet::modifyuser and
15745: lonnet::modify_student_enrollment
15746:
15747: Inputs:
15748:
15749: =over 4
15750:
15751: =item B<$udom> Student's loncapa domain
15752:
15753: =item B<$uname> Student's loncapa login name
15754:
15755: =item B<$uid> Student/Employee ID
15756:
15757: =item B<$umode> Student's authentication mode
15758:
15759: =item B<$upass> Student's password
15760:
15761: =item B<$first> Student's first name
15762:
15763: =item B<$middle> Student's middle name
15764:
15765: =item B<$last> Student's last name
15766:
15767: =item B<$gene> Student's generation
15768:
15769: =item B<$usec> Student's section in course
15770:
15771: =item B<$end> Unix time of the roles expiration
15772:
15773: =item B<$start> Unix time of the roles start date
15774:
15775: =item B<$forceid> If defined, allow $uid to be changed
15776:
15777: =item B<$desiredhome> server to use as home server for student
15778:
15779: =item B<$email> Student's permanent e-mail address
15780:
15781: =item B<$type> Type of enrollment (auto or manual)
15782:
15783: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
15784:
15785: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
15786:
15787: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
15788:
15789: =item B<$context> role change context (shown in User Management Logs display in a course)
15790:
15791: =item B<$inststatus> institutional status of user - : separated string of escaped status types
15792:
15793: =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.
15794:
15795: =back
15796:
15797: =item *
15798:
15799: modify_student_enrollment
15800:
15801: Change a student's enrollment status in a class. The environment variable
15802: 'role.request.course' must be defined for this function to proceed.
15803:
15804: Inputs:
15805:
15806: =over 4
15807:
15808: =item $udom, student's domain
15809:
15810: =item $uname, student's name
15811:
15812: =item $uid, student's user id
15813:
15814: =item $first, student's first name
15815:
15816: =item $middle
15817:
15818: =item $last
15819:
15820: =item $gene
15821:
15822: =item $usec
15823:
15824: =item $end
15825:
15826: =item $start
15827:
15828: =item $type
15829:
15830: =item $locktype
15831:
15832: =item $cid
15833:
15834: =item $selfenroll
15835:
15836: =item $context
15837:
15838: =item $credits, number of credits student will earn from this class
15839:
15840: =item $instsec, institutional course section code for student
15841:
15842: =back
15843:
15844:
15845: =item *
15846:
15847: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
15848: custom role; give a custom role to a user for the level given by URL. Specify
15849: name and domain of role author, and role name
15850:
15851: =item *
15852:
15853: revokerole($udom,$uname,$url,$role) : revoke a role for url
15854:
15855: =item *
15856:
15857: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
15858:
15859: =back
15860:
15861: =head2 Course Infomation
15862:
15863: =over 4
15864:
15865: =item *
15866:
15867: coursedescription($courseid,$options) : returns a hash of information about the
15868: specified course id, including all environment settings for the
15869: course, the description of the course will be in the hash under the
15870: key 'description'
15871:
15872: $options is an optional parameter that if supplied is a hash reference that controls
15873: what how this function works. It has the following key/values:
15874:
15875: =over 4
15876:
15877: =item freshen_cache
15878:
15879: If defined, and the environment cache for the course is valid, it is
15880: returned in the returned hash.
15881:
15882: =item one_time
15883:
15884: If defined, the last cache time is set to _now_
15885:
15886: =item user
15887:
15888: If defined, the supplied username is used instead of the current user.
15889:
15890:
15891: =back
15892:
15893: =item *
15894:
15895: resdata($name,$domain,$type,@which) : request for current parameter
15896: setting for a specific $type, where $type is either 'course' or 'user',
15897: @what should be a list of parameters to ask about. This routine caches
15898: answers for 10 minutes.
15899:
15900: =item *
15901:
15902: get_courseresdata($courseid, $domain) : dump the entire course resource
15903: data base, returning a hash that is keyed by the resource name and has
15904: values that are the resource value. I believe that the timestamps and
15905: versions are also returned.
15906:
15907: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15908: supplemental content area. This routine caches the number of files for
15909: 10 minutes.
15910:
15911: =back
15912:
15913: =head2 Course Modification
15914:
15915: =over 4
15916:
15917: =item *
15918:
15919: writecoursepref($courseid,%prefs) : write preferences (environment
15920: database) for a course
15921:
15922: =item *
15923:
15924: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15925:
15926: =item *
15927:
15928: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
15929:
15930: =item *
15931:
15932: is_course($courseid), is_course($cdom, $cnum)
15933:
15934: Accepts either a combined $courseid (in the form of domain_courseid) or the
15935: two component version $cdom, $cnum. It checks if the specified course exists.
15936:
15937: Returns:
15938: undef if the course doesn't exist, otherwise
15939: in scalar context the combined courseid.
15940: in list context the two components of the course identifier, domain and
15941: courseid.
15942:
15943: =back
15944:
15945: =head2 Bubblesheet Configuration
15946:
15947: =over 4
15948:
15949: =item *
15950:
15951: get_scantron_config($which)
15952:
15953: $which - the name of the configuration to parse from the file.
15954:
15955: Parses and returns the bubblesheet configuration line selected as a
15956: hash of configuration file fields.
15957:
15958:
15959: Returns:
15960: If the named configuration is not in the file, an empty
15961: hash is returned.
15962:
15963: a hash with the fields
15964: name - internal name for the this configuration setup
15965: description - text to display to operator that describes this config
15966: CODElocation - if 0 or the string 'none'
15967: - no CODE exists for this config
15968: if -1 || the string 'letter'
15969: - a CODE exists for this config and is
15970: a string of letters
15971: Unsupported value (but planned for future support)
15972: if a positive integer
15973: - The CODE exists as the first n items from
15974: the question section of the form
15975: if the string 'number'
15976: - The CODE exists for this config and is
15977: a string of numbers
15978: CODEstart - (only matter if a CODE exists) column in the line where
15979: the CODE starts
15980: CODElength - length of the CODE
15981: IDstart - column where the student/employee ID starts
15982: IDlength - length of the student/employee ID info
15983: Qstart - column where the information from the bubbled
15984: 'questions' start
15985: Qlength - number of columns comprising a single bubble line from
15986: the sheet. (usually either 1 or 10)
15987: Qon - either a single character representing the character used
15988: to signal a bubble was chosen in the positional setup, or
15989: the string 'letter' if the letter of the chosen bubble is
15990: in the final, or 'number' if a number representing the
15991: chosen bubble is in the file (1->A 0->J)
15992: Qoff - the character used to represent that a bubble was
15993: left blank
15994: PaperID - if the scanning process generates a unique number for each
15995: sheet scanned the column that this ID number starts in
15996: PaperIDlength - number of columns that comprise the unique ID number
15997: for the sheet of paper
15998: FirstName - column that the first name starts in
15999: FirstNameLength - number of columns that the first name spans
16000: LastName - column that the last name starts in
16001: LastNameLength - number of columns that the last name spans
16002: BubblesPerRow - number of bubbles available in each row used to
16003: bubble an answer. (If not specified, 10 assumed).
16004:
16005:
16006: =item *
16007:
16008: get_scantronformat_file($cdom)
16009:
16010: $cdom - the course's domain (optional); if not supplied, uses
16011: domain for current $env{'request.course.id'}.
16012:
16013: Returns an array containing lines from the scantron format file for
16014: the domain of the course.
16015:
16016: If a url for a custom.tab file is listed in domain's configuration.db,
16017: lines are from this file.
16018:
16019: Otherwise, if a default.tab has been published in RES space by the
16020: domainconfig user, lines are from this file.
16021:
16022: Otherwise, fall back to getting lines from the legacy file on the
16023: local server: /home/httpd/lonTabs/default_scantronformat.tab
16024:
16025: =back
16026:
16027: =head2 Resource Subroutines
16028:
16029: =over 4
16030:
16031: =item *
16032:
16033: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
16034:
16035: =item *
16036:
16037: repcopy($filename) : subscribes to the requested file, and attempts to
16038: replicate from the owning library server, Might return
16039: 'unavailable', 'not_found', 'forbidden', 'ok', or
16040: 'bad_request', also attempts to grab the metadata for the
16041: resource. Expects the local filesystem pathname
16042: (/home/httpd/html/res/....)
16043:
16044: =back
16045:
16046: =head2 Resource Information
16047:
16048: =over 4
16049:
16050: =item *
16051:
16052: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
16053: and returns the value of a variety of different possible values,
16054: $varname should be a request string, and the other parameters can be
16055: used to specify who and what one is asking about. Ordinarily, $cid
16056: does not need to be specified, as it is retrived from
16057: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
16058: within lonuserstate::loadmap() when initializing a course, before
16059: $env{'request.course.id'} has been set, so it needs to be provided
16060: in that one case.
16061:
16062: Possible values for $varname are environment.lastname (or other item
16063: from the envirnment hash), user.name (or someother aspect about the
16064: user), resource.0.maxtries (or some other part and parameter of a
16065: resource)
16066:
16067: =item *
16068:
16069: directcondval($number) : get current value of a condition; reads from a state
16070: string
16071:
16072: =item *
16073:
16074: condval($condidx) : value of condition index based on state
16075:
16076: =item *
16077:
16078: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
16079: resource's metadata, $what should be either a specific key, or either
16080: 'keys' (to get a list of possible keys) or 'packages' to get a list of
16081: packages that this resource currently uses, the last 3 arguments are
16082: only used internally for recursive metadata.
16083:
16084: the toolsymb is only used where the uri is for an external tool (for which
16085: the uri as well as the symb are guaranteed to be unique).
16086:
16087: this function automatically caches all requests except any made recursively
16088: to retrieve a list of metadata keys for an imported library file ($liburi is
16089: defined).
16090:
16091: =item *
16092:
16093: metadata_query($query,$custom,$customshow) : make a metadata query against the
16094: network of library servers; returns file handle of where SQL and regex results
16095: will be stored for query
16096:
16097: =item *
16098:
16099: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
16100: return symbolic list entry (all arguments optional).
16101:
16102: Args: filename is the filename (including path) for the file for which a symb
16103: is required; donotrecurse, if true will prevent calls to allowed() being made
16104: to check access status if more than one resource was found in the bighash
16105: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
16106: a randompick); ignorecachednull, if true will prevent a symb of '' being
16107: returned if $env{$cache_str} is defined as ''; checkforblock if true will
16108: cause possible symbs to be checked to determine if they are subject to content
16109: blocking, if so they will not be included as possible symbs; possibles is a
16110: ref to a hash, which, as a side effect, will be populated with all possible
16111: symbs (content blocking not tested).
16112:
16113: returns the data handle
16114:
16115: =item *
16116:
16117: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
16118: and is a possible symb for the URL in $thisfn, and if is an encrypted
16119: resource that the user accessed using /enc/ returns a 1 on success, 0
16120: on failure, user must be in a course, as it assumes the existence of
16121: the course initial hash, and uses $env('request.course.id'}. The third
16122: arg is an optional reference to a scalar. If this arg is passed in the
16123: call to symbverify, it will be set to 1 if the symb has been set to be
16124: encrypted; otherwise it will be null.
16125:
16126: =item *
16127:
16128: symbclean($symb) : removes versions numbers from a symb, returns the
16129: cleaned symb
16130:
16131: =item *
16132:
16133: is_on_map($uri) : checks if the $uri is somewhere on the current
16134: course map, user must be in a course for it to work.
16135:
16136: =item *
16137:
16138: numval($salt) : return random seed value (addend for rndseed)
16139:
16140: =item *
16141:
16142: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
16143: a random seed, all arguments are optional, if they aren't sent it uses the
16144: environment to derive them. Note: if symb isn't sent and it can't get one
16145: from &symbread it will use the current time as its return value
16146:
16147: =item *
16148:
16149: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
16150: unfakeable, receipt
16151:
16152: =item *
16153:
16154: receipt() : API to ireceipt working off of env values; given out to users
16155:
16156: =item *
16157:
16158: countacc($url) : count the number of accesses to a given URL
16159:
16160: =item *
16161:
16162: 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
16163:
16164: =item *
16165:
16166: 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)
16167:
16168: =item *
16169:
16170: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
16171:
16172: =item *
16173:
16174: devalidate($symb) : devalidate temporary spreadsheet calculations,
16175: forcing spreadsheet to reevaluate the resource scores next time.
16176:
16177: =item *
16178:
16179: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
16180: when viewing in course context.
16181:
16182: input: six args -- filename (decluttered), course number, course domain,
16183: url, symb (if registered) and group (if this is a
16184: group item -- e.g., bulletin board, group page etc.).
16185:
16186: output: array of five scalars --
16187: $cfile -- url for file editing if editable on current server
16188: $home -- homeserver of resource (i.e., for author if published,
16189: or course if uploaded.).
16190: $switchserver -- 1 if server switch will be needed.
16191: $forceedit -- 1 if icon/link should be to go to edit mode
16192: $forceview -- 1 if icon/link should be to go to view mode
16193:
16194: =item *
16195:
16196: is_course_upload($file,$cnum,$cdom)
16197:
16198: Used in course context to determine if current file was uploaded to
16199: the course (i.e., would be found in /userfiles/docs on the course's
16200: homeserver.
16201:
16202: input: 3 args -- filename (decluttered), course number and course domain.
16203: output: boolean -- 1 if file was uploaded.
16204:
16205: =back
16206:
16207: =head2 Storing/Retreiving Data
16208:
16209: =over 4
16210:
16211: =item *
16212:
16213: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
16214: permanently for this url; hashref needs to be given and should be a \%hashname;
16215: the remaining args aren't required and if they aren't passed or are '' they will
16216: be derived from the env (with the exception of $laststore, which is an
16217: optional arg used when a user's submission is stored in grading).
16218: $laststore is $version=$timestamp, where $version is the most recent version
16219: number retrieved for the corresponding $symb in the $namespace db file, and
16220: $timestamp is the timestamp for that transaction (UNIX time).
16221: $laststore is currently only passed when cstore() is called by
16222: structuretags::finalize_storage().
16223:
16224: =item *
16225:
16226: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
16227: but uses critical subroutine
16228:
16229: =item *
16230:
16231: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
16232: all args are optional
16233:
16234: =item *
16235:
16236: dumpstore($namespace,$udom,$uname,$regexp,$range) :
16237: dumps the complete (or key matching regexp) namespace into a hash
16238: ($udom, $uname, $regexp, $range are optional) for a namespace that is
16239: normally &store()ed into
16240:
16241: $range should be either an integer '100' (give me the first 100
16242: matching records)
16243: or be two integers sperated by a - with no spaces
16244: '30-50' (give me the 30th through the 50th matching
16245: records)
16246:
16247:
16248: =item *
16249:
16250: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
16251: replaces a &store() version of data with a replacement set of data
16252: for a particular resource in a namespace passed in the $storehash hash
16253: reference. If $tolog is true, the transaction is logged in the courselog
16254: with an action=PUTSTORE.
16255:
16256: =item *
16257:
16258: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
16259: works very similar to store/cstore, but all data is stored in a
16260: temporary location and can be reset using tmpreset, $storehash should
16261: be a hash reference, returns nothing on success
16262:
16263: =item *
16264:
16265: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
16266: similar to restore, but all data is stored in a temporary location and
16267: can be reset using tmpreset. Returns a hash of values on success,
16268: error string otherwise.
16269:
16270: =item *
16271:
16272: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
16273: deltes all keys for $symb form the temporary storage hash.
16274:
16275: =item *
16276:
16277: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16278: reference filled in from namesp ($udom and $uname are optional)
16279:
16280: =item *
16281:
16282: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
16283: namesp ($udom and $uname are optional)
16284:
16285: =item *
16286:
16287: dump($namespace,$udom,$uname,$regexp,$range) :
16288: dumps the complete (or key matching regexp) namespace into a hash
16289: ($udom, $uname, $regexp, $range are optional)
16290:
16291: $range should be either an integer '100' (give me the first 100
16292: matching records)
16293: or be two integers sperated by a - with no spaces
16294: '30-50' (give me the 30th through the 50th matching
16295: records)
16296: =item *
16297:
16298: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
16299: $store can be a scalar, an array reference, or if the amount to be
16300: incremented is > 1, a hash reference.
16301:
16302: ($udom and $uname are optional)
16303:
16304: =item *
16305:
16306: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
16307: ($udom and $uname are optional)
16308:
16309: =item *
16310:
16311: cput($namespace,$storehash,$udom,$uname) : critical put
16312: ($udom and $uname are optional)
16313:
16314: =item *
16315:
16316: newput($namespace,$storehash,$udom,$uname) :
16317:
16318: Attempts to store the items in the $storehash, but only if they don't
16319: currently exist, if this succeeds you can be certain that you have
16320: successfully created a new key value pair in the $namespace db.
16321:
16322:
16323: Args:
16324: $namespace: name of database to store values to
16325: $storehash: hashref to store to the db
16326: $udom: (optional) domain of user containing the db
16327: $uname: (optional) name of user caontaining the db
16328:
16329: Returns:
16330: 'ok' -> succeeded in storing all keys of $storehash
16331: 'key_exists: <key>' -> failed to anything out of $storehash, as at
16332: least <key> already existed in the db (other
16333: requested keys may also already exist)
16334: 'error: <msg>' -> unable to tie the DB or other error occurred
16335: 'con_lost' -> unable to contact request server
16336: 'refused' -> action was not allowed by remote machine
16337:
16338:
16339: =item *
16340:
16341: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16342: reference filled in from namesp (encrypts the return communication)
16343: ($udom and $uname are optional)
16344:
16345: =item *
16346:
16347: log($udom,$name,$home,$message) : write to permanent log for user; use
16348: critical subroutine
16349:
16350: =item *
16351:
16352: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
16353: array reference filled in from namespace found in domain level on either
16354: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
16355:
16356: =item *
16357:
16358: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
16359: domain level either on specified domain server ($uhome) or primary domain
16360: server ($udom and $uhome are optional)
16361:
16362: =item *
16363:
16364: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
16365: for: authentication, language, quotas, timezone, date locale, and portal URL in
16366: the target domain.
16367:
16368: May also include additional key => value pairs for the following groups:
16369:
16370: =over
16371:
16372: =item
16373: disk quotas (MB allocated by default to portfolios and authoring spaces).
16374:
16375: =over
16376:
16377: =item defaultquota, authorquota
16378:
16379: =back
16380:
16381: =item
16382: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
16383: portfolio for users).
16384:
16385: =over
16386:
16387: =item
16388: aboutme, blog, webdav, portfolio
16389:
16390: =back
16391:
16392: =item
16393: requestcourses: ability to request courses, and how requests are processed.
16394:
16395: =over
16396:
16397: =item
16398: official, unofficial, community, textbook, placement
16399:
16400: =back
16401:
16402: =item
16403: inststatus: types of institutional affiliation, and order in which they are displayed.
16404:
16405: =over
16406:
16407: =item
16408: inststatustypes, inststatusorder, inststatusguest
16409:
16410: =back
16411:
16412: =item
16413: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
16414: for course's uploaded content.
16415:
16416: =over
16417:
16418: =item
16419: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
16420: communityquota, textbookquota, placementquota
16421:
16422: =back
16423:
16424: =item
16425: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16426: on your servers.
16427:
16428: =over
16429:
16430: =item
16431: remotesessions, hostedsessions
16432:
16433: =back
16434:
16435: =back
16436:
16437: In cases where a domain coordinator has never used the "Set Domain Configuration"
16438: utility to create a configuration.db file on a domain's primary library server
16439: only the following domain defaults: auth_def, auth_arg_def, lang_def
16440: -- corresponding values are authentication type (internal, krb4, krb5,
16441: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
16442: will be available. Values are retrieved from cache (if current), unless the
16443: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16444: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16445:
16446: Typical usage:
16447:
16448: %domdefaults = &get_domain_defaults($target_domain);
16449:
16450: =back
16451:
16452: =head2 Network Status Functions
16453:
16454: =over 4
16455:
16456: =item *
16457:
16458: dirlist() : return directory list based on URI (first arg).
16459:
16460: Inputs: 1 required, 5 optional.
16461:
16462: =over
16463:
16464: =item
16465: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16466:
16467: =item
16468: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
16469:
16470: =item
16471: $username - username of user/course to be listed. Extracted from $uri if absent.
16472:
16473: =item
16474: $getpropath - boolean: 1 if prepend path using &propath().
16475:
16476: =item
16477: $getuserdir - boolean: 1 if prepend path for "userfiles".
16478:
16479: =item
16480: $alternateRoot - path to prepend in place of path from $uri.
16481:
16482: =back
16483:
16484: Returns: Array of up to two items.
16485:
16486: =over
16487:
16488: a reference to an array of files/subdirectories
16489:
16490: =over
16491:
16492: Each element in the array of files/subdirectories is a & separated list of
16493: item name and the result of running stat on the item. If dirlist was requested
16494: for a file instead of a directory, the item name will be ''. For a directory
16495: listing, if the item is a metadata file, the element will end &N&M
16496: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
16497: default copyright set (1).
16498:
16499: =back
16500:
16501: a scalar containing error condition (if encountered).
16502:
16503: =over
16504:
16505: =item
16506: no_host (no homeserver identified for $username:$domain).
16507:
16508: =item
16509: no_such_host (server contacted for listing not identified as valid host).
16510:
16511: =item
16512: con_lost (connection to remote server failed).
16513:
16514: =item
16515: refused (invalid $username:$domain received on lond side).
16516:
16517: =item
16518: no_such_dir (directory at specified path on lond side does not exist).
16519:
16520: =item
16521: empty (directory at specified path on lond side is empty).
16522:
16523: =over
16524:
16525: This is currently not encountered because the &ls3, &ls2,
16526: &ls (_handler) routines on the lond side do not filter out
16527: . and .. from a directory listing.
16528:
16529: =back
16530:
16531: =back
16532:
16533: =back
16534:
16535: =item *
16536:
16537: spareserver() : find server with least workload from spare.tab
16538:
16539:
16540: =item *
16541:
16542: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
16543: if there is no corresponding loncapa host.
16544:
16545: =back
16546:
16547:
16548: =head2 Apache Request
16549:
16550: =over 4
16551:
16552: =item *
16553:
16554: ssi($url,%hash) : server side include, does a complete request cycle on url to
16555: localhost, posts hash
16556:
16557: =back
16558:
16559: =head2 Data to String to Data
16560:
16561: =over 4
16562:
16563: =item *
16564:
16565: hash2str(%hash) : convert a hash into a string complete with escaping and '='
16566: and '&' separators, supports elements that are arrayrefs and hashrefs
16567:
16568: =item *
16569:
16570: hashref2str($hashref) : convert a hashref into a string complete with
16571: escaping and '=' and '&' separators, supports elements that are
16572: arrayrefs and hashrefs
16573:
16574: =item *
16575:
16576: arrayref2str($arrayref) : convert an arrayref into a string complete
16577: with escaping and '&' separators, supports elements that are arrayrefs
16578: and hashrefs
16579:
16580: =item *
16581:
16582: str2hash($string) : convert string to hash using unescaping and
16583: splitting on '=' and '&', supports elements that are arrayrefs and
16584: hashrefs
16585:
16586: =item *
16587:
16588: str2array($string) : convert string to hash using unescaping and
16589: splitting on '&', supports elements that are arrayrefs and hashrefs
16590:
16591: =back
16592:
16593: =head2 Logging Routines
16594:
16595:
16596: These routines allow one to make log messages in the lonnet.log and
16597: lonnet.perm logfiles.
16598:
16599: =over 4
16600:
16601: =item *
16602:
16603: logtouch() : make sure the logfile, lonnet.log, exists
16604:
16605: =item *
16606:
16607: logthis() : append message to the normal lonnet.log file, it gets
16608: preiodically rolled over and deleted.
16609:
16610: =item *
16611:
16612: logperm() : append a permanent message to lonnet.perm.log, this log
16613: file never gets deleted by any automated portion of the system, only
16614: messages of critical importance should go in here.
16615:
16616:
16617: =back
16618:
16619: =head2 General File Helper Routines
16620:
16621: =over 4
16622:
16623: =item *
16624:
16625: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
16626: (a) files in /uploaded
16627: (i) If a local copy of the file exists -
16628: compares modification date of local copy with last-modified date for
16629: definitive version stored on home server for course. If local copy is
16630: stale, requests a new version from the home server and stores it.
16631: If the original has been removed from the home server, then local copy
16632: is unlinked.
16633: (ii) If local copy does not exist -
16634: requests the file from the home server and stores it.
16635:
16636: If $caller is 'uploadrep':
16637: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
16638: for request for files originally uploaded via DOCS.
16639: - returns 'ok' if fresh local copy now available, -1 otherwise.
16640:
16641: Otherwise:
16642: This indicates a call from the content generation phase of the request.
16643: - returns the entire contents of the file or -1.
16644:
16645: (b) files in /res
16646: - returns the entire contents of a file or -1;
16647: it properly subscribes to and replicates the file if neccessary.
16648:
16649:
16650: =item *
16651:
16652: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
16653: reference
16654:
16655: returns either a stat() list of data about the file or an empty list
16656: if the file doesn't exist or couldn't find out about it (connection
16657: problems or user unknown)
16658:
16659: =item *
16660:
16661: filelocation($dir,$file) : returns file system location of a file
16662: based on URI; meant to be "fairly clean" absolute reference, $dir is a
16663: directory that relative $file lookups are to looked in ($dir of /a/dir
16664: and a file of ../bob will become /a/bob)
16665:
16666: =item *
16667:
16668: hreflocation($dir,$file) : returns file system location or a URL; same as
16669: filelocation except for hrefs
16670:
16671: =item *
16672:
16673: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16674: also removes beginning /home/httpd/html unless /priv/ follows it.
16675:
16676: =back
16677:
16678: =head2 Usererfile file routines (/uploaded*)
16679:
16680: =over 4
16681:
16682: =item *
16683:
16684: userfileupload(): main rotine for putting a file in a user or course's
16685: filespace, arguments are,
16686:
16687: formname - required - this is the name of the element in $env where the
16688: filename, and the contents of the file to create/modifed exist
16689: the filename is in $env{'form.'.$formname.'.filename'} and the
16690: contents of the file is located in $env{'form.'.$formname}
16691: context - if coursedoc, store the file in the course of the active role
16692: of the current user;
16693: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16694: if 'canceloverwrite': delete file in tmp/overwrites directory
16695: subdir - required - subdirectory to put the file in under ../userfiles/
16696: if undefined, it will be placed in "unknown"
16697:
16698: (This routine calls clean_filename() to remove any dangerous
16699: characters from the filename, and then calls finuserfileupload() to
16700: complete the transaction)
16701:
16702: returns either the url of the uploaded file (/uploaded/....) if successful
16703: and /adm/notfound.html if unsuccessful
16704:
16705: =item *
16706:
16707: clean_filename(): routine for cleaing a filename up for storage in
16708: userfile space, argument is:
16709:
16710: filename - proposed filename
16711:
16712: returns: the new clean filename
16713:
16714: =item *
16715:
16716: finishuserfileupload(): routine that creates and sends the file to
16717: userspace, probably shouldn't be called directly
16718:
16719: docuname: username or courseid of destination for the file
16720: docudom: domain of user/course of destination for the file
16721: formname: same as for userfileupload()
16722: fname: filename (including subdirectories) for the file
16723: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
16724: if hashref, and context is scantron, will convert csv format to standard format
16725: allfiles: reference to hash used to store objects found by parser
16726: codebase: reference to hash used for codebases of java objects found by parser
16727: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
16728: thumbheight: height (pixels) of thumbnail to be created for uploaded image
16729: resizewidth: width to be used to resize image using resizeImage from ImageMagick
16730: resizeheight: height to be used to resize image using resizeImage from ImageMagick
16731: context: if 'overwrite', will move the uploaded file from its temporary location to
16732: userfiles to facilitate overwriting a previously uploaded file with same name.
16733: mimetype: reference to scalar to accommodate mime type determined
16734: from File::MMagic if $parser = parse.
16735:
16736: returns either the url of the uploaded file (/uploaded/....) if successful
16737: and /adm/notfound.html if unsuccessful (or an error message if context
16738: was 'overwrite').
16739:
16740:
16741: =item *
16742:
16743: renameuserfile(): renames an existing userfile to a new name
16744:
16745: Args:
16746: docuname: username or courseid of destination for the file
16747: docudom: domain of user/course of destination for the file
16748: old: current file name (including any subdirs under userfiles)
16749: new: desired file name (including any subdirs under userfiles)
16750:
16751: =item *
16752:
16753: mkdiruserfile(): creates a directory is a userfiles dir
16754:
16755: Args:
16756: docuname: username or courseid of destination for the file
16757: docudom: domain of user/course of destination for the file
16758: dir: dir to create (including any subdirs under userfiles)
16759:
16760: =item *
16761:
16762: removeuserfile(): removes a file that exists in userfiles
16763:
16764: Args:
16765: docuname: username or courseid of destination for the file
16766: docudom: domain of user/course of destination for the file
16767: fname: filname to delete (including any subdirs under userfiles)
16768:
16769: =item *
16770:
16771: removeuploadedurl(): convience function for removeuserfile()
16772:
16773: Args:
16774: url: a full /uploaded/... url to delete
16775:
16776: =item *
16777:
16778: get_portfile_permissions():
16779: Args:
16780: domain: domain of user or course contain the portfolio files
16781: user: name of user or num of course contain the portfolio files
16782: Returns:
16783: hashref of a dump of the proper file_permissions.db
16784:
16785:
16786: =item *
16787:
16788: get_access_controls():
16789:
16790: Args:
16791: current_permissions: the hash ref returned from get_portfile_permissions()
16792: group: (optional) the group you want the files associated with
16793: file: (optional) the file you want access info on
16794:
16795: Returns:
16796: a hash (keys are file names) of hashes containing
16797: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
16798: values are XML containing access control settings (see below)
16799:
16800: Internal notes:
16801:
16802: access controls are stored in file_permissions.db as key=value pairs.
16803: key -> path to file/file_name\0uniqueID:scope_end_start
16804: where scope -> public,guest,course,group,domains or users.
16805: end -> UNIX time for end of access (0 -> no end date)
16806: start -> UNIX time for start of access
16807:
16808: value -> XML description of access control
16809: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
16810: <start></start>
16811: <end></end>
16812:
16813: <password></password> for scope type = guest
16814:
16815: <domain></domain> for scope type = course or group
16816: <number></number>
16817: <roles id="">
16818: <role></role>
16819: <access></access>
16820: <section></section>
16821: <group></group>
16822: </roles>
16823:
16824: <dom></dom> for scope type = domains
16825:
16826: <users> for scope type = users
16827: <user>
16828: <uname></uname>
16829: <udom></udom>
16830: </user>
16831: </users>
16832: </scope>
16833:
16834: Access data is also aggregated for each file in an additional key=value pair:
16835: key -> path to file/file_name\0accesscontrol
16836: value -> reference to hash
16837: hash contains key = value pairs
16838: where key = uniqueID:scope_end_start
16839: value = UNIX time record was last updated
16840:
16841: Used to improve speed of look-ups of access controls for each file.
16842:
16843: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
16844:
16845: =item *
16846:
16847: modify_access_controls():
16848:
16849: Modifies access controls for a portfolio file
16850: Args
16851: 1. file name
16852: 2. reference to hash of required changes,
16853: 3. domain
16854: 4. username
16855: where domain,username are the domain of the portfolio owner
16856: (either a user or a course)
16857:
16858: Returns:
16859: 1. result of additions or updates ('ok' or 'error', with error message).
16860: 2. result of deletions ('ok' or 'error', with error message).
16861: 3. reference to hash of any new or updated access controls.
16862: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
16863: key = integer (inbound ID)
16864: value = uniqueID
16865:
16866: =item *
16867:
16868: get_timebased_id():
16869:
16870: Attempts to get a unique timestamp-based suffix for use with items added to a
16871: course via the Course Editor (e.g., folders, composite pages,
16872: group bulletin boards).
16873:
16874: Args: (first three required; six others optional)
16875:
16876: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
16877: docssequence, or name of group
16878:
16879: 2. keyid (alphanumeric): name of temporary locking key in hash,
16880: e.g., num, boardids
16881:
16882: 3. namespace: name of gdbm file used to store suffixes already assigned;
16883: file will be named nohist_namespace.db
16884:
16885: 4. cdom: domain of course; default is current course domain from %env
16886:
16887: 5. cnum: course number; default is current course number from %env
16888:
16889: 6. idtype: set to concat if an additional digit is to be appended to the
16890: unix timestamp to form the suffix, if the plain timestamp is already
16891: in use. Default is to not do this, but simply increment the unix
16892: timestamp by 1 until a unique key is obtained.
16893:
16894: 7. who: holder of locking key; defaults to user:domain for user.
16895:
16896: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
16897: retrying); default is 3.
16898:
16899: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
16900:
16901: Returns:
16902:
16903: 1. suffix obtained (numeric)
16904:
16905: 2. result of deleting locking key (ok if deleted, or lock never obtained)
16906:
16907: 3. error: contains (localized) error message if an error occurred.
16908:
16909:
16910: =back
16911:
16912: =head2 HTTP Helper Routines
16913:
16914: =over 4
16915:
16916: =item *
16917:
16918: escape() : unpack non-word characters into CGI-compatible hex codes
16919:
16920: =item *
16921:
16922: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
16923:
16924: =back
16925:
16926: =head1 PRIVATE SUBROUTINES
16927:
16928: =head2 Underlying communication routines (Shouldn't call)
16929:
16930: =over 4
16931:
16932: =item *
16933:
16934: subreply() : tries to pass a message to lonc, returns con_lost if incapable
16935:
16936: =item *
16937:
16938: reply() : uses subreply to send a message to remote machine, logs all failures
16939:
16940: =item *
16941:
16942: critical() : passes a critical message to another server; if cannot
16943: get through then place message in connection buffer directory and
16944: returns con_delayed, if incapable of saving message, returns
16945: con_failed
16946:
16947: =item *
16948:
16949: reconlonc() : tries to reconnect lonc client processes.
16950:
16951: =back
16952:
16953: =head2 Resource Access Logging
16954:
16955: =over 4
16956:
16957: =item *
16958:
16959: flushcourselogs() : flush (save) buffer logs and access logs
16960:
16961: =item *
16962:
16963: courselog($what) : save message for course in hash
16964:
16965: =item *
16966:
16967: courseacclog($what) : save message for course using &courselog(). Perform
16968: special processing for specific resource types (problems, exams, quizzes, etc).
16969:
16970: =item *
16971:
16972: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16973: as a PerlChildExitHandler
16974:
16975: =back
16976:
16977: =head2 Other
16978:
16979: =over 4
16980:
16981: =item *
16982:
16983: symblist($mapname,%newhash) : update symbolic storage links
16984:
16985: =back
16986:
16987: =cut
16988:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>