1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.1473 2021/11/30 15:55:40 raeburn Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28: ###
29:
30: =pod
31:
32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
71: package Apache::lonnet;
72:
73: use strict;
74: use HTTP::Date;
75: use Image::Magick;
76: use CGI::Cookie;
77:
78: use Encode;
79:
80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
81: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
82: %managerstab $passwdmin);
83:
84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
85: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
86: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
87: %courseownerbuf, %coursetypebuf,$locknum);
88:
89: use IO::Socket;
90: use GDBM_File;
91: use HTML::LCParser;
92: use Fcntl qw(:flock);
93: use Storable qw(thaw nfreeze);
94: use Time::HiRes qw( sleep gettimeofday tv_interval );
95: use Cache::Memcached;
96: use Digest::MD5;
97: use Math::Random;
98: use File::MMagic;
99: use Net::CIDR;
100: use Sys::Hostname::FQDN();
101: use LONCAPA qw(:DEFAULT :match);
102: use LONCAPA::Configuration;
103: use LONCAPA::lonmetadata;
104: use LONCAPA::Lond;
105: use LONCAPA::LWPReq;
106: use LONCAPA::transliterate;
107:
108: use File::Copy;
109:
110: my $readit;
111: my $max_connection_retries = 20; # Or some such value.
112:
113: require Exporter;
114:
115: our @ISA = qw (Exporter);
116: our @EXPORT = qw(%env);
117:
118:
119: # ------------------------------------ Logging (parameters, docs, slots, roles)
120: {
121: my $logid;
122: sub write_log {
123: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
124: if ($context eq 'course') {
125: if (($cnum eq '') || ($cdom eq '')) {
126: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
127: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
128: }
129: }
130: $logid ++;
131: my $now = time();
132: my $id=$now.'00000'.$$.'00000'.$logid;
133: my $ip = &get_requestor_ip();
134: my $logentry = {
135: $id => {
136: 'exe_uname' => $env{'user.name'},
137: 'exe_udom' => $env{'user.domain'},
138: 'exe_time' => $now,
139: 'exe_ip' => $ip,
140: 'delflag' => $delflag,
141: 'logentry' => $storehash,
142: 'uname' => $uname,
143: 'udom' => $udom,
144: }
145: };
146: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
147: }
148: }
149:
150: sub logtouch {
151: my $execdir=$perlvar{'lonDaemons'};
152: unless (-e "$execdir/logs/lonnet.log") {
153: open(my $fh,">>","$execdir/logs/lonnet.log");
154: close $fh;
155: }
156: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
157: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
158: }
159:
160: sub logthis {
161: my $message=shift;
162: my $execdir=$perlvar{'lonDaemons'};
163: my $now=time;
164: my $local=localtime($now);
165: if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
166: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
167: print $fh $logstring;
168: close($fh);
169: }
170: return 1;
171: }
172:
173: sub logperm {
174: my $message=shift;
175: my $execdir=$perlvar{'lonDaemons'};
176: my $now=time;
177: my $local=localtime($now);
178: if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
179: print $fh "$now:$message:$local\n";
180: close($fh);
181: }
182: return 1;
183: }
184:
185: sub create_connection {
186: my ($hostname,$lonid) = @_;
187: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
188: Type => SOCK_STREAM,
189: Timeout => 10);
190: return 0 if (!$client);
191: print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
192: my $result = <$client>;
193: chomp($result);
194: return 1 if ($result eq 'done');
195: return 0;
196: }
197:
198: sub get_server_timezone {
199: my ($cnum,$cdom) = @_;
200: my $home=&homeserver($cnum,$cdom);
201: if ($home ne 'no_host') {
202: my $cachetime = 24*3600;
203: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
204: if (defined($cached)) {
205: return $timezone;
206: } else {
207: my $timezone = &reply('servertimezone',$home);
208: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
209: }
210: }
211: }
212:
213: sub get_server_distarch {
214: my ($lonhost,$ignore_cache) = @_;
215: if (defined($lonhost)) {
216: if (!defined(&hostname($lonhost))) {
217: return;
218: }
219: my $cachetime = 12*3600;
220: if (!$ignore_cache) {
221: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
222: if (defined($cached)) {
223: return $distarch;
224: }
225: }
226: my $rep = &reply('serverdistarch',$lonhost);
227: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
228: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
229: $rep eq '') {
230: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
231: }
232: }
233: return;
234: }
235:
236: sub get_servercerts_info {
237: my ($lonhost,$hostname,$context) = @_;
238: return if ($lonhost eq '');
239: if ($hostname eq '') {
240: $hostname = &hostname($lonhost);
241: }
242: return if ($hostname eq '');
243: my ($rep,$uselocal);
244: if ($context eq 'install') {
245: $uselocal = 1;
246: } elsif (grep { $_ eq $lonhost } ¤t_machine_ids()) {
247: $uselocal = 1;
248: }
249: if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
250: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
251: if ($distro eq '') {
252: $uselocal = 0;
253: } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
254: if ($1 < 6) {
255: $uselocal = 0;
256: }
257: } elsif ($distro =~ /^(?:sles)(\d+)$/) {
258: if ($1 < 12) {
259: $uselocal = 0;
260: }
261: }
262: }
263: if ($uselocal) {
264: $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
265: } else {
266: $rep=&reply('servercerts',$lonhost);
267: }
268: my ($result,%returnhash);
269: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
270: ($rep eq 'unknown_cmd')) {
271: $result = $rep;
272: } else {
273: $result = 'ok';
274: my @pairs=split(/\&/,$rep);
275: foreach my $item (@pairs) {
276: my ($key,$value)=split(/=/,$item,2);
277: my $what = &unescape($key);
278: $returnhash{$what}=&thaw_unescape($value);
279: }
280: }
281: return ($result,\%returnhash);
282: }
283:
284: sub get_server_loncaparev {
285: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
286: if (defined($lonhost)) {
287: if (!defined(&hostname($lonhost))) {
288: undef($lonhost);
289: }
290: }
291: if (!defined($lonhost)) {
292: if (defined(&domain($dom,'primary'))) {
293: $lonhost=&domain($dom,'primary');
294: if ($lonhost eq 'no_host') {
295: undef($lonhost);
296: }
297: }
298: }
299: if (defined($lonhost)) {
300: my $cachetime = 12*3600;
301: if (!$ignore_cache) {
302: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
303: if (defined($cached)) {
304: return $loncaparev;
305: }
306: }
307: my ($answer,$loncaparev);
308: my @ids=¤t_machine_ids();
309: if (grep(/^\Q$lonhost\E$/,@ids)) {
310: $answer = $perlvar{'lonVersion'};
311: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
312: $loncaparev = $1;
313: }
314: } else {
315: $answer = &reply('serverloncaparev',$lonhost);
316: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
317: if ($caller eq 'loncron') {
318: my $hostname = &hostname($lonhost);
319: my $protocol = $protocol{$lonhost};
320: $protocol = 'http' if ($protocol ne 'https');
321: my $url = $protocol.'://'.$hostname.'/adm/about.html';
322: my $request=new HTTP::Request('GET',$url);
323: my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
324: unless ($response->is_error()) {
325: my $content = $response->content;
326: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
327: $loncaparev = $1;
328: }
329: }
330: } else {
331: $loncaparev = $loncaparevs{$lonhost};
332: }
333: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
334: $loncaparev = $1;
335: }
336: }
337: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
338: }
339: }
340:
341: sub get_server_homeID {
342: my ($hostname,$ignore_cache,$caller) = @_;
343: unless ($ignore_cache) {
344: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
345: if (defined($cached)) {
346: return $serverhomeID;
347: }
348: }
349: my $cachetime = 12*3600;
350: my $serverhomeID;
351: if ($caller eq 'loncron') {
352: my @machine_ids = &machine_ids($hostname);
353: foreach my $id (@machine_ids) {
354: my $response = &reply('serverhomeID',$id);
355: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
356: $serverhomeID = $response;
357: last;
358: }
359: }
360: if ($serverhomeID eq '') {
361: $serverhomeID = $machine_ids[-1];
362: }
363: } else {
364: $serverhomeID = $serverhomeIDs{$hostname};
365: }
366: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
367: }
368:
369: sub get_remote_globals {
370: my ($lonhost,$whathash,$ignore_cache) = @_;
371: my ($result,%returnhash,%whatneeded);
372: if (ref($whathash) eq 'HASH') {
373: foreach my $what (sort(keys(%{$whathash}))) {
374: my $hashid = $lonhost.'-'.$what;
375: my ($response,$cached);
376: unless ($ignore_cache) {
377: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
378: }
379: if (defined($cached)) {
380: $returnhash{$what} = $response;
381: } else {
382: $whatneeded{$what} = 1;
383: }
384: }
385: if (keys(%whatneeded) == 0) {
386: $result = 'ok';
387: } else {
388: my $requested = &freeze_escape(\%whatneeded);
389: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
390: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
391: ($rep eq 'unknown_cmd')) {
392: $result = $rep;
393: } else {
394: $result = 'ok';
395: my @pairs=split(/\&/,$rep);
396: foreach my $item (@pairs) {
397: my ($key,$value)=split(/=/,$item,2);
398: my $what = &unescape($key);
399: my $hashid = $lonhost.'-'.$what;
400: $returnhash{$what}=&thaw_unescape($value);
401: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
402: }
403: }
404: }
405: }
406: return ($result,\%returnhash);
407: }
408:
409: sub remote_devalidate_cache {
410: my ($lonhost,$cachekeys) = @_;
411: my $items;
412: return unless (ref($cachekeys) eq 'ARRAY');
413: my $cachestr = join('&',@{$cachekeys});
414: my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
415: return $response;
416: }
417:
418: # -------------------------------------------------- Non-critical communication
419: sub subreply {
420: my ($cmd,$server)=@_;
421: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
422: #
423: # With loncnew process trimming, there's a timing hole between lonc server
424: # process exit and the master server picking up the listen on the AF_UNIX
425: # socket. In that time interval, a lock file will exist:
426:
427: my $lockfile=$peerfile.".lock";
428: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
429: sleep(0.1);
430: }
431: # At this point, either a loncnew parent is listening or an old lonc
432: # or loncnew child is listening so we can connect or everything's dead.
433: #
434: # We'll give the connection a few tries before abandoning it. If
435: # connection is not possible, we'll con_lost back to the client.
436: #
437: my $client;
438: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
439: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
440: Type => SOCK_STREAM,
441: Timeout => 10);
442: if ($client) {
443: last; # Connected!
444: } else {
445: &create_connection(&hostname($server),$server);
446: }
447: sleep(0.1); # Try again later if failed connection.
448: }
449: my $answer;
450: if ($client) {
451: print $client "sethost:$server:$cmd\n";
452: $answer=<$client>;
453: if (!$answer) { $answer="con_lost"; }
454: chomp($answer);
455: } else {
456: $answer = 'con_lost'; # Failed connection.
457: }
458: return $answer;
459: }
460:
461: sub reply {
462: my ($cmd,$server)=@_;
463: unless (defined(&hostname($server))) { return 'no_such_host'; }
464: my $answer=subreply($cmd,$server);
465: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
466: my $logged = $cmd;
467: if ($cmd =~ /^encrypt:([^:]+):/) {
468: my $subcmd = $1;
469: if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
470: ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
471: ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades') ||
472: ($subcmd eq 'put')) {
473: (undef,undef,my @rest) = split(/:/,$cmd);
474: if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
475: splice(@rest,2,1,'Hidden');
476: } elsif ($subcmd eq 'passwd') {
477: splice(@rest,2,2,('Hidden','Hidden'));
478: } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
479: ($subcmd eq 'autoexportgrades') || ($subcmd eq 'put')) {
480: splice(@rest,3,1,'Hidden');
481: }
482: $logged = join(':',('encrypt:'.$subcmd,@rest));
483: }
484: }
485: &logthis("<font color=\"blue\">WARNING:".
486: " $logged to $server returned $answer</font>");
487: }
488: return $answer;
489: }
490:
491: # ----------------------------------------------------------- Send USR1 to lonc
492:
493: sub reconlonc {
494: my ($lonid) = @_;
495: if ($lonid) {
496: my $hostname = &hostname($lonid);
497: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
498: if ($hostname && -e $peerfile) {
499: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
500: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
501: Type => SOCK_STREAM,
502: Timeout => 10);
503: if ($client) {
504: print $client ("reset_retries\n");
505: my $answer=<$client>;
506: #reset just this one.
507: }
508: }
509: return;
510: }
511:
512: &logthis("Trying to reconnect lonc");
513: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
514: if (open(my $fh,"<",$loncfile)) {
515: my $loncpid=<$fh>;
516: chomp($loncpid);
517: if (kill 0 => $loncpid) {
518: &logthis("lonc at pid $loncpid responding, sending USR1");
519: kill USR1 => $loncpid;
520: sleep 1;
521: } else {
522: &logthis(
523: "<font color=\"blue\">WARNING:".
524: " lonc at pid $loncpid not responding, giving up</font>");
525: }
526: } else {
527: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
528: }
529: }
530:
531: # ------------------------------------------------------ Critical communication
532:
533: sub critical {
534: my ($cmd,$server)=@_;
535: unless (&hostname($server)) {
536: &logthis("<font color=\"blue\">WARNING:".
537: " Critical message to unknown server ($server)</font>");
538: return 'no_such_host';
539: }
540: my $answer=reply($cmd,$server);
541: if ($answer eq 'con_lost') {
542: &reconlonc($server);
543: my $answer=reply($cmd,$server);
544: if ($answer eq 'con_lost') {
545: my $now=time;
546: my $middlename=$cmd;
547: $middlename=substr($middlename,0,16);
548: $middlename=~s/\W//g;
549: my $dfilename=
550: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
551: $dumpcount++;
552: {
553: my $dfh;
554: if (open($dfh,">",$dfilename)) {
555: print $dfh "$cmd\n";
556: close($dfh);
557: }
558: }
559: sleep 1;
560: my $wcmd='';
561: {
562: my $dfh;
563: if (open($dfh,"<",$dfilename)) {
564: $wcmd=<$dfh>;
565: close($dfh);
566: }
567: }
568: chomp($wcmd);
569: if ($wcmd eq $cmd) {
570: &logthis("<font color=\"blue\">WARNING: ".
571: "Connection buffer $dfilename: $cmd</font>");
572: &logperm("D:$server:$cmd");
573: return 'con_delayed';
574: } else {
575: &logthis("<font color=\"red\">CRITICAL:"
576: ." Critical connection failed: $server $cmd</font>");
577: &logperm("F:$server:$cmd");
578: return 'con_failed';
579: }
580: }
581: }
582: return $answer;
583: }
584:
585: # ------------------------------------------- check if return value is an error
586:
587: sub error {
588: my ($result) = @_;
589: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
590: if ($2 == 2) { return undef; }
591: return $1;
592: }
593: return undef;
594: }
595:
596: sub convert_and_load_session_env {
597: my ($lonidsdir,$handle)=@_;
598: my @profile;
599: {
600: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
601: if (!$opened) {
602: return 0;
603: }
604: flock($idf,LOCK_SH);
605: @profile=<$idf>;
606: close($idf);
607: }
608: my %temp_env;
609: foreach my $line (@profile) {
610: if ($line !~ m/=/) {
611: return 0;
612: }
613: chomp($line);
614: my ($envname,$envvalue)=split(/=/,$line,2);
615: $temp_env{&unescape($envname)} = &unescape($envvalue);
616: }
617: unlink("$lonidsdir/$handle.id");
618: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
619: 0640)) {
620: %disk_env = %temp_env;
621: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
622: untie(%disk_env);
623: }
624: return 1;
625: }
626:
627: # ------------------------------------------- Transfer profile into environment
628: my $env_loaded;
629: sub transfer_profile_to_env {
630: my ($lonidsdir,$handle,$force_transfer) = @_;
631: if (!$force_transfer && $env_loaded) { return; }
632:
633: if (!defined($lonidsdir)) {
634: $lonidsdir = $perlvar{'lonIDsDir'};
635: }
636: if (!defined($handle)) {
637: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
638: }
639:
640: my $convert;
641: {
642: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
643: if (!$opened) {
644: return;
645: }
646: flock($idf,LOCK_SH);
647: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
648: &GDBM_READER(),0640)) {
649: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
650: untie(%disk_env);
651: } else {
652: $convert = 1;
653: }
654: }
655: if ($convert) {
656: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
657: &logthis("Failed to load session, or convert session.");
658: }
659: }
660:
661: my %remove;
662: while ( my $envname = each(%env) ) {
663: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
664: if ($time < time-300) {
665: $remove{$key}++;
666: }
667: }
668: }
669:
670: $env{'user.environment'} = "$lonidsdir/$handle.id";
671: $env_loaded=1;
672: foreach my $expired_key (keys(%remove)) {
673: &delenv($expired_key);
674: }
675: }
676:
677: # ---------------------------------------------------- Check for valid session
678: sub check_for_valid_session {
679: my ($r,$name,$userhashref,$domref) = @_;
680: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
681: my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
682: if ($name eq 'lonDAV') {
683: $lonidsdir=$r->dir_config('lonDAVsessDir');
684: } else {
685: $lonidsdir=$r->dir_config('lonIDsDir');
686: if ($name eq '') {
687: $name = 'lonID';
688: }
689: }
690: if ($name eq 'lonID') {
691: $secure = 'lonSID';
692: $linkname = 'lonLinkID';
693: $pubname = 'lonPubID';
694: if (exists($cookies{$secure})) {
695: $lonid=$cookies{$secure};
696: } elsif (exists($cookies{$name})) {
697: $lonid=$cookies{$name};
698: } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
699: $lonid=$cookies{$linkname};
700: } elsif (exists($cookies{$pubname})) {
701: $lonid=$cookies{$pubname};
702: }
703: } else {
704: $lonid=$cookies{$name};
705: }
706: return undef if (!$lonid);
707:
708: my $handle=&LONCAPA::clean_handle($lonid->value);
709: if (-l "$lonidsdir/$handle.id") {
710: my $link = readlink("$lonidsdir/$handle.id");
711: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
712: $handle = $1;
713: }
714: }
715: if (!-e "$lonidsdir/$handle.id") {
716: if ((ref($domref)) && ($name eq 'lonID') &&
717: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
718: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
719: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
720: $$domref = $possudom;
721: }
722: }
723: return undef;
724: }
725:
726: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
727: return undef if (!$opened);
728:
729: flock($idf,LOCK_SH);
730: my %disk_env;
731: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
732: &GDBM_READER(),0640)) {
733: return undef;
734: }
735:
736: if (!defined($disk_env{'user.name'})
737: || !defined($disk_env{'user.domain'})) {
738: untie(%disk_env);
739: return undef;
740: }
741:
742: if (ref($userhashref) eq 'HASH') {
743: $userhashref->{'name'} = $disk_env{'user.name'};
744: $userhashref->{'domain'} = $disk_env{'user.domain'};
745: if ($disk_env{'request.role'}) {
746: $userhashref->{'role'} = $disk_env{'request.role'};
747: }
748: $userhashref->{'lti'} = $disk_env{'request.lti.login'};
749: if ($userhashref->{'lti'}) {
750: $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
751: $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
752: }
753: }
754: untie(%disk_env);
755:
756: return $handle;
757: }
758:
759: sub timed_flock {
760: my ($file,$lock_type) = @_;
761: my $failed=0;
762: eval {
763: local $SIG{__DIE__}='DEFAULT';
764: local $SIG{ALRM}=sub {
765: $failed=1;
766: die("failed lock");
767: };
768: alarm(13);
769: flock($file,$lock_type);
770: alarm(0);
771: };
772: if ($failed) {
773: return undef;
774: } else {
775: return 1;
776: }
777: }
778:
779: sub get_sessionfile_vars {
780: my ($handle,$lonidsdir,$storearr) = @_;
781: my %returnhash;
782: unless (ref($storearr) eq 'ARRAY') {
783: return %returnhash;
784: }
785: if (-l "$lonidsdir/$handle.id") {
786: my $link = readlink("$lonidsdir/$handle.id");
787: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
788: $handle = $1;
789: }
790: }
791: if ((-e "$lonidsdir/$handle.id") &&
792: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
793: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
794: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
795: if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
796: flock($idf,LOCK_SH);
797: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
798: &GDBM_READER(),0640)) {
799: foreach my $item (@{$storearr}) {
800: $returnhash{$item} = $disk_env{$item};
801: }
802: untie(%disk_env);
803: }
804: }
805: }
806: }
807: return %returnhash;
808: }
809:
810: # ---------------------------------------------------------- Append Environment
811:
812: sub appenv {
813: my ($newenv,$roles) = @_;
814: if (ref($newenv) eq 'HASH') {
815: foreach my $key (keys(%{$newenv})) {
816: my $refused = 0;
817: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
818: $refused = 1;
819: if (ref($roles) eq 'ARRAY') {
820: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
821: if (grep(/^\Q$role\E$/,@{$roles})) {
822: $refused = 0;
823: }
824: }
825: }
826: if ($refused) {
827: &logthis("<font color=\"blue\">WARNING: ".
828: "Attempt to modify environment ".$key." to ".$newenv->{$key}
829: .'</font>');
830: delete($newenv->{$key});
831: } else {
832: $env{$key}=$newenv->{$key};
833: }
834: }
835: my $lonids = $perlvar{'lonIDsDir'};
836: if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
837: my $opened = open(my $env_file,'+<',$env{'user.environment'});
838: if ($opened
839: && &timed_flock($env_file,LOCK_EX)
840: &&
841: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
842: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
843: while (my ($key,$value) = each(%{$newenv})) {
844: $disk_env{$key} = $value;
845: }
846: untie(%disk_env);
847: }
848: }
849: }
850: return 'ok';
851: }
852: # ----------------------------------------------------- Delete from Environment
853:
854: sub delenv {
855: my ($delthis,$regexp,$roles) = @_;
856: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
857: my $refused = 1;
858: if (ref($roles) eq 'ARRAY') {
859: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
860: if (grep(/^\Q$role\E$/,@{$roles})) {
861: $refused = 0;
862: }
863: }
864: if ($refused) {
865: &logthis("<font color=\"blue\">WARNING: ".
866: "Attempt to delete from environment ".$delthis);
867: return 'error';
868: }
869: }
870: my $opened = open(my $env_file,'+<',$env{'user.environment'});
871: if ($opened
872: && &timed_flock($env_file,LOCK_EX)
873: &&
874: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
875: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
876: foreach my $key (keys(%disk_env)) {
877: if ($regexp) {
878: if ($key=~/^$delthis/) {
879: delete($env{$key});
880: delete($disk_env{$key});
881: }
882: } else {
883: if ($key=~/^\Q$delthis\E/) {
884: delete($env{$key});
885: delete($disk_env{$key});
886: }
887: }
888: }
889: untie(%disk_env);
890: }
891: return 'ok';
892: }
893:
894: sub get_env_multiple {
895: my ($name) = @_;
896: my @values;
897: if (defined($env{$name})) {
898: # exists is it an array
899: if (ref($env{$name})) {
900: @values=@{ $env{$name} };
901: } else {
902: $values[0]=$env{$name};
903: }
904: }
905: return(@values);
906: }
907:
908: # ------------------------------------------------------------------- Locking
909:
910: sub set_lock {
911: my ($text)=@_;
912: $locknum++;
913: my $id=$$.'-'.$locknum;
914: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
915: 'session.lock.'.$id => $text});
916: return $id;
917: }
918:
919: sub get_locks {
920: my $num=0;
921: my %texts=();
922: foreach my $lock (split(/\,/,$env{'session.locks'})) {
923: if ($lock=~/\w/) {
924: $num++;
925: $texts{$lock}=$env{'session.lock.'.$lock};
926: }
927: }
928: return ($num,%texts);
929: }
930:
931: sub remove_lock {
932: my ($id)=@_;
933: my $newlocks='';
934: foreach my $lock (split(/\,/,$env{'session.locks'})) {
935: if (($lock=~/\w/) && ($lock ne $id)) {
936: $newlocks.=','.$lock;
937: }
938: }
939: &appenv({'session.locks' => $newlocks});
940: &delenv('session.lock.'.$id);
941: }
942:
943: sub remove_all_locks {
944: my $activelocks=$env{'session.locks'};
945: foreach my $lock (split(/\,/,$env{'session.locks'})) {
946: if ($lock=~/\w/) {
947: &remove_lock($lock);
948: }
949: }
950: }
951:
952:
953: # ------------------------------------------ Find out current server userload
954: sub userload {
955: my $numusers=0;
956: {
957: opendir(LONIDS,$perlvar{'lonIDsDir'});
958: my $filename;
959: my $curtime=time;
960: while ($filename=readdir(LONIDS)) {
961: next if ($filename eq '.' || $filename eq '..');
962: next if ($filename =~ /publicuser_\d+\.id/);
963: next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
964: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
965: if ($curtime-$mtime < 1800) { $numusers++; }
966: }
967: closedir(LONIDS);
968: }
969: my $userloadpercent=0;
970: my $maxuserload=$perlvar{'lonUserLoadLim'};
971: if ($maxuserload) {
972: $userloadpercent=100*$numusers/$maxuserload;
973: }
974: $userloadpercent=sprintf("%.2f",$userloadpercent);
975: return $userloadpercent;
976: }
977:
978: # ------------------------------ Find server with least workload from spare.tab
979:
980: sub spareserver {
981: my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
982: my $spare_server;
983: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
984: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
985: : $userloadpercent;
986: my ($uint_dom,$remotesessions);
987: if (($udom ne '') && (&domain($udom) ne '')) {
988: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
989: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
990: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
991: $remotesessions = $udomdefaults{'remotesessions'};
992: }
993: my $spareshash = &this_host_spares($udom);
994: if (ref($spareshash) eq 'HASH') {
995: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
996: foreach my $try_server (@{ $spareshash->{'primary'} }) {
997: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
998: $try_server));
999: ($spare_server, $lowest_load) =
1000: &compare_server_load($try_server, $spare_server, $lowest_load);
1001: }
1002: }
1003:
1004: my $found_server = ($spare_server ne '' && $lowest_load < 100);
1005:
1006: if (!$found_server) {
1007: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1008: foreach my $try_server (@{ $spareshash->{'default'} }) {
1009: next unless (&spare_can_host($udom,$uint_dom,
1010: $remotesessions,$try_server));
1011: ($spare_server, $lowest_load) =
1012: &compare_server_load($try_server, $spare_server, $lowest_load);
1013: }
1014: }
1015: }
1016: }
1017:
1018: if (!$want_server_name) {
1019: if (defined($spare_server)) {
1020: my $hostname = &hostname($spare_server);
1021: if (defined($hostname)) {
1022: my $protocol = 'http';
1023: if ($protocol{$spare_server} eq 'https') {
1024: $protocol = $protocol{$spare_server};
1025: }
1026: my $alias = &Apache::lonnet::use_proxy_alias($r,$spare_server);
1027: $hostname = $alias if ($alias ne '');
1028: $spare_server = $protocol.'://'.$hostname;
1029: }
1030: }
1031: }
1032: return $spare_server;
1033: }
1034:
1035: sub compare_server_load {
1036: my ($try_server, $spare_server, $lowest_load, $required) = @_;
1037:
1038: if ($required) {
1039: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
1040: my $remoterev = &get_server_loncaparev(undef,$try_server);
1041: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
1042: if (($major eq '' && $minor eq '') ||
1043: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
1044: return ($spare_server,$lowest_load);
1045: }
1046: }
1047:
1048: my $loadans = &reply('load', $try_server);
1049: my $userloadans = &reply('userload',$try_server);
1050:
1051: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1052: return ($spare_server, $lowest_load); #didn't get a number from the server
1053: }
1054:
1055: my $load;
1056: if ($loadans =~ /\d/) {
1057: if ($userloadans =~ /\d/) {
1058: #both are numbers, pick the bigger one
1059: $load = ($loadans > $userloadans) ? $loadans
1060: : $userloadans;
1061: } else {
1062: $load = $loadans;
1063: }
1064: } else {
1065: $load = $userloadans;
1066: }
1067:
1068: if (($load =~ /\d/) && ($load < $lowest_load)) {
1069: $spare_server = $try_server;
1070: $lowest_load = $load;
1071: }
1072: return ($spare_server,$lowest_load);
1073: }
1074:
1075: # --------------------------- ask offload servers if user already has a session
1076: sub find_existing_session {
1077: my ($udom,$uname) = @_;
1078: my $spareshash = &this_host_spares($udom);
1079: if (ref($spareshash) eq 'HASH') {
1080: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
1081: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1082: return $try_server if (&has_user_session($try_server, $udom, $uname));
1083: }
1084: }
1085: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1086: foreach my $try_server (@{ $spareshash->{'default'} }) {
1087: return $try_server if (&has_user_session($try_server, $udom, $uname));
1088: }
1089: }
1090: }
1091: return;
1092: }
1093:
1094: sub delusersession {
1095: my ($lonid,$udom,$uname) = @_;
1096: my $uprimary_id = &domain($udom,'primary');
1097: my $uintdom = &internet_dom($uprimary_id);
1098: my $intdom = &internet_dom($lonid);
1099: my $serverhomedom = &host_domain($lonid);
1100: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1101: return &reply(join(':','delusersession',
1102: map {&escape($_)} ($udom,$uname)),$lonid);
1103: }
1104: return;
1105: }
1106:
1107: # check if user's browser sent load balancer cookie and server still has session
1108: # and is not overloaded.
1109: sub check_for_balancer_cookie {
1110: my ($r,$update_mtime) = @_;
1111: my ($otherserver,$cookie);
1112: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1113: if (exists($cookies{'balanceID'})) {
1114: my $balid = $cookies{'balanceID'};
1115: $cookie=&LONCAPA::clean_handle($balid->value);
1116: my $balancedir=$r->dir_config('lonBalanceDir');
1117: if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
1118: if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
1119: my ($possudom,$possuname) = ($1,$2);
1120: my $has_session = 0;
1121: if ((&domain($possudom) ne '') &&
1122: (&homeserver($possuname,$possudom) ne 'no_host')) {
1123: my $try_server;
1124: my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
1125: if ($opened) {
1126: flock($idf,LOCK_SH);
1127: while (my $line = <$idf>) {
1128: chomp($line);
1129: if (&hostname($line) ne '') {
1130: $try_server = $line;
1131: last;
1132: }
1133: }
1134: close($idf);
1135: if (($try_server) &&
1136: (&has_user_session($try_server,$possudom,$possuname))) {
1137: my $lowest_load = 30000;
1138: ($otherserver,$lowest_load) =
1139: &compare_server_load($try_server,undef,$lowest_load);
1140: if ($otherserver ne '' && $lowest_load < 100) {
1141: $has_session = 1;
1142: } else {
1143: undef($otherserver);
1144: }
1145: }
1146: }
1147: }
1148: if ($has_session) {
1149: if ($update_mtime) {
1150: my $atime = my $mtime = time;
1151: utime($atime,$mtime,"$balancedir/$cookie.id");
1152: }
1153: } else {
1154: unlink("$balancedir/$cookie.id");
1155: }
1156: }
1157: }
1158: }
1159: return ($otherserver,$cookie);
1160: }
1161:
1162: sub updatebalcookie {
1163: my ($cookie,$balancer,$lastentry)=@_;
1164: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1165: my ($udom,$uname) = ($1,$2);
1166: my $uprimary_id = &domain($udom,'primary');
1167: my $uintdom = &internet_dom($uprimary_id);
1168: my $intdom = &internet_dom($balancer);
1169: my $serverhomedom = &host_domain($balancer);
1170: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1171: return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
1172: }
1173: }
1174: return;
1175: }
1176:
1177: sub delbalcookie {
1178: my ($cookie,$balancer) =@_;
1179: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1180: my ($udom,$uname) = ($1,$2);
1181: my $uprimary_id = &domain($udom,'primary');
1182: my $uintdom = &internet_dom($uprimary_id);
1183: my $intdom = &internet_dom($balancer);
1184: my $serverhomedom = &host_domain($balancer);
1185: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1186: return &reply('delbalcookie:'.&escape($cookie),$balancer);
1187: }
1188: }
1189: }
1190:
1191: # -------------------------------- ask if server already has a session for user
1192: sub has_user_session {
1193: my ($lonid,$udom,$uname) = @_;
1194: my $result = &reply(join(':','userhassession',
1195: map {&escape($_)} ($udom,$uname)),$lonid);
1196: return 1 if ($result eq 'ok');
1197:
1198: return 0;
1199: }
1200:
1201: # --------- determine least loaded server in a user's domain which allows login
1202:
1203: sub choose_server {
1204: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1205: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1206: my %servers = &get_servers($udom);
1207: my $lowest_load = 30000;
1208: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1209: if ($skiploadbal) {
1210: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1211: unless (defined($cached)) {
1212: my $cachetime = 60*60*24;
1213: my %domconfig =
1214: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1215: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1216: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1217: $cachetime);
1218: }
1219: }
1220: }
1221: foreach my $lonhost (keys(%servers)) {
1222: if ($skiploadbal) {
1223: if (ref($balancers) eq 'HASH') {
1224: next if (exists($balancers->{$lonhost}));
1225: }
1226: }
1227: my $loginvia;
1228: if ($checkloginvia) {
1229: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1230: if ($loginvia) {
1231: my ($server,$path) = split(/:/,$loginvia);
1232: ($login_host, $lowest_load) =
1233: &compare_server_load($server, $login_host, $lowest_load, $required);
1234: if ($login_host eq $server) {
1235: $portal_path = $path;
1236: $isredirect = 1;
1237: }
1238: } else {
1239: ($login_host, $lowest_load) =
1240: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1241: if ($login_host eq $lonhost) {
1242: $portal_path = '';
1243: $isredirect = '';
1244: }
1245: }
1246: } else {
1247: ($login_host, $lowest_load) =
1248: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1249: }
1250: }
1251: if ($login_host ne '') {
1252: $hostname = &hostname($login_host);
1253: }
1254: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1255: }
1256:
1257: sub get_course_sessions {
1258: my ($cnum,$cdom,$lastactivity) = @_;
1259: my %servers = &internet_dom_servers($cdom);
1260: my %returnhash;
1261: foreach my $server (sort(keys(%servers))) {
1262: my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
1263: my @pairs=split(/\&/,$rep);
1264: unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
1265: foreach my $item (@pairs) {
1266: my ($key,$value)=split(/=/,$item,2);
1267: $key = &unescape($key);
1268: next if ($key =~ /^error: 2 /);
1269: if (exists($returnhash{$key})) {
1270: next if ($value < $returnhash{$key});
1271: }
1272: $returnhash{$key}=$value;
1273: }
1274: }
1275: }
1276: return %returnhash;
1277: }
1278:
1279: # --------------------------------------------- Try to change a user's password
1280:
1281: sub changepass {
1282: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1283: $currentpass = &escape($currentpass);
1284: $newpass = &escape($newpass);
1285: my $lonhost = $perlvar{'lonHostID'};
1286: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1287: $server);
1288: if (! $answer) {
1289: &logthis("No reply on password change request to $server ".
1290: "by $uname in domain $udom.");
1291: } elsif ($answer =~ "^ok") {
1292: &logthis("$uname in $udom successfully changed their password ".
1293: "on $server.");
1294: } elsif ($answer =~ "^pwchange_failure") {
1295: &logthis("$uname in $udom was unable to change their password ".
1296: "on $server. The action was blocked by either lcpasswd ".
1297: "or pwchange");
1298: } elsif ($answer =~ "^non_authorized") {
1299: &logthis("$uname in $udom did not get their password correct when ".
1300: "attempting to change it on $server.");
1301: } elsif ($answer =~ "^auth_mode_error") {
1302: &logthis("$uname in $udom attempted to change their password despite ".
1303: "not being locally or internally authenticated on $server.");
1304: } elsif ($answer =~ "^unknown_user") {
1305: &logthis("$uname in $udom attempted to change their password ".
1306: "on $server but were unable to because $server is not ".
1307: "their home server.");
1308: } elsif ($answer =~ "^refused") {
1309: &logthis("$server refused to change $uname in $udom password because ".
1310: "it was sent an unencrypted request to change the password.");
1311: } elsif ($answer =~ "invalid_client") {
1312: &logthis("$server refused to change $uname in $udom password because ".
1313: "it was a reset by e-mail originating from an invalid server.");
1314: } elsif ($answer =~ "^prioruse") {
1315: &logthis("$server refused to change $uname in $udom password because ".
1316: "the password had been used before");
1317: }
1318: return $answer;
1319: }
1320:
1321: # ----------------------- Try to determine user's current authentication scheme
1322:
1323: sub queryauthenticate {
1324: my ($uname,$udom)=@_;
1325: my $uhome=&homeserver($uname,$udom);
1326: if (!$uhome) {
1327: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1328: return 'no_host';
1329: }
1330: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1331: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1332: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1333: }
1334: return $answer;
1335: }
1336:
1337: # --------- Try to authenticate user from domain's lib servers (first this one)
1338:
1339: sub authenticate {
1340: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1341: $upass=&escape($upass);
1342: $uname= &LONCAPA::clean_username($uname);
1343: my $uhome=&homeserver($uname,$udom,1);
1344: my $newhome;
1345: if ((!$uhome) || ($uhome eq 'no_host')) {
1346: # Maybe the machine was offline and only re-appeared again recently?
1347: &reconlonc();
1348: # One more
1349: $uhome=&homeserver($uname,$udom,1);
1350: if (($uhome eq 'no_host') && $checkdefauth) {
1351: if (defined(&domain($udom,'primary'))) {
1352: $newhome=&domain($udom,'primary');
1353: }
1354: if ($newhome ne '') {
1355: $uhome = $newhome;
1356: }
1357: }
1358: if ((!$uhome) || ($uhome eq 'no_host')) {
1359: &logthis("User $uname at $udom is unknown in authenticate");
1360: return 'no_host';
1361: }
1362: }
1363: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1364: if ($answer eq 'authorized') {
1365: if ($newhome) {
1366: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1367: return 'no_account_on_host';
1368: } else {
1369: &logthis("User $uname at $udom authorized by $uhome");
1370: return $uhome;
1371: }
1372: }
1373: if ($answer eq 'non_authorized') {
1374: &logthis("User $uname at $udom rejected by $uhome");
1375: return 'no_host';
1376: }
1377: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1378: return 'no_host';
1379: }
1380:
1381: sub can_host_session {
1382: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1383: my $canhost = 1;
1384: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1385: if (ref($remotesessions) eq 'HASH') {
1386: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1387: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1388: $canhost = 0;
1389: } else {
1390: $canhost = 1;
1391: }
1392: }
1393: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1394: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1395: $canhost = 1;
1396: } else {
1397: $canhost = 0;
1398: }
1399: }
1400: if ($canhost) {
1401: if ($remotesessions->{'version'} ne '') {
1402: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1403: if ($reqmajor ne '' && $reqminor ne '') {
1404: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1405: my $major = $1;
1406: my $minor = $2;
1407: if (($major < $reqmajor ) ||
1408: (($major == $reqmajor) && ($minor < $reqminor))) {
1409: $canhost = 0;
1410: }
1411: } else {
1412: $canhost = 0;
1413: }
1414: }
1415: }
1416: }
1417: }
1418: if ($canhost) {
1419: if (ref($hostedsessions) eq 'HASH') {
1420: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1421: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1422: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1423: if (($uint_dom ne '') &&
1424: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1425: $canhost = 0;
1426: } else {
1427: $canhost = 1;
1428: }
1429: }
1430: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1431: if (($uint_dom ne '') &&
1432: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1433: $canhost = 1;
1434: } else {
1435: $canhost = 0;
1436: }
1437: }
1438: }
1439: }
1440: return $canhost;
1441: }
1442:
1443: sub spare_can_host {
1444: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1445: my $canhost=1;
1446: my $try_server_hostname = &hostname($try_server);
1447: my $serverhomeID = &get_server_homeID($try_server_hostname);
1448: my $serverhomedom = &host_domain($serverhomeID);
1449: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1450: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1451: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1452: $canhost = 0;
1453: }
1454: }
1455: if ($canhost) {
1456: if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
1457: if ($defdomdefaults{'offloadoth'}{$try_server}) {
1458: unless (&shared_institution($udom,$try_server)) {
1459: $canhost = 0;
1460: }
1461: }
1462: }
1463: }
1464: if (($canhost) && ($uint_dom)) {
1465: my @intdoms;
1466: my $internet_names = &get_internet_names($try_server);
1467: if (ref($internet_names) eq 'ARRAY') {
1468: @intdoms = @{$internet_names};
1469: }
1470: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1471: my $remoterev = &get_server_loncaparev(undef,$try_server);
1472: $canhost = &can_host_session($udom,$try_server,$remoterev,
1473: $remotesessions,
1474: $defdomdefaults{'hostedsessions'});
1475: }
1476: }
1477: return $canhost;
1478: }
1479:
1480: sub this_host_spares {
1481: my ($dom) = @_;
1482: my ($dom_in_use,$lonhost_in_use,$result);
1483: my @hosts = ¤t_machine_ids();
1484: foreach my $lonhost (@hosts) {
1485: if (&host_domain($lonhost) eq $dom) {
1486: $dom_in_use = $dom;
1487: $lonhost_in_use = $lonhost;
1488: last;
1489: }
1490: }
1491: if ($dom_in_use ne '') {
1492: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1493: }
1494: if (ref($result) ne 'HASH') {
1495: $lonhost_in_use = $perlvar{'lonHostID'};
1496: $dom_in_use = &host_domain($lonhost_in_use);
1497: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1498: if (ref($result) ne 'HASH') {
1499: $result = \%spareid;
1500: }
1501: }
1502: return $result;
1503: }
1504:
1505: sub spares_for_offload {
1506: my ($dom_in_use,$lonhost_in_use) = @_;
1507: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1508: if (defined($cached)) {
1509: return $result;
1510: } else {
1511: my $cachetime = 60*60*24;
1512: my %domconfig =
1513: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1514: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1515: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1516: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1517: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1518: }
1519: }
1520: }
1521: }
1522: return;
1523: }
1524:
1525: sub get_lonbalancer_config {
1526: my ($servers) = @_;
1527: my ($currbalancer,$currtargets);
1528: if (ref($servers) eq 'HASH') {
1529: foreach my $server (keys(%{$servers})) {
1530: my %what = (
1531: spareid => 1,
1532: perlvar => 1,
1533: );
1534: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1535: if ($result eq 'ok') {
1536: if (ref($returnhash) eq 'HASH') {
1537: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1538: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1539: $currbalancer = $server;
1540: $currtargets = {};
1541: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1542: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1543: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1544: }
1545: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1546: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1547: }
1548: }
1549: last;
1550: }
1551: }
1552: }
1553: }
1554: }
1555: }
1556: return ($currbalancer,$currtargets);
1557: }
1558:
1559: sub check_loadbalancing {
1560: my ($uname,$udom,$caller) = @_;
1561: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1562: $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1563: my $lonhost = $perlvar{'lonHostID'};
1564: my @hosts = ¤t_machine_ids();
1565: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1566: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1567: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1568: my $serverhomedom = &host_domain($lonhost);
1569: my $domneedscache;
1570: my $cachetime = 60*60*24;
1571:
1572: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1573: $dom_in_use = $udom;
1574: $homeintdom = 1;
1575: } else {
1576: $dom_in_use = $serverhomedom;
1577: }
1578: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1579: unless (defined($cached)) {
1580: my %domconfig =
1581: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1582: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1583: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1584: } else {
1585: $domneedscache = $dom_in_use;
1586: }
1587: }
1588: if (ref($result) eq 'HASH') {
1589: ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1590: &check_balancer_result($result,@hosts);
1591: if ($is_balancer) {
1592: if (ref($currrules) eq 'HASH') {
1593: if ($homeintdom) {
1594: if ($uname ne '') {
1595: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1596: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1597: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1598: $rule_in_effect = $currrules->{'_LC_author'};
1599: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1600: $rule_in_effect = $currrules->{'_LC_adv'}
1601: }
1602: }
1603: if ($rule_in_effect eq '') {
1604: my %userenv = &userenvironment($udom,$uname,'inststatus');
1605: if ($userenv{'inststatus'} ne '') {
1606: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1607: my ($othertitle,$usertypes,$types) =
1608: &Apache::loncommon::sorted_inst_types($udom);
1609: if (ref($types) eq 'ARRAY') {
1610: foreach my $type (@{$types}) {
1611: if (grep(/^\Q$type\E$/,@statuses)) {
1612: if (exists($currrules->{$type})) {
1613: $rule_in_effect = $currrules->{$type};
1614: }
1615: }
1616: }
1617: }
1618: } else {
1619: if (exists($currrules->{'default'})) {
1620: $rule_in_effect = $currrules->{'default'};
1621: }
1622: }
1623: }
1624: } else {
1625: if (exists($currrules->{'default'})) {
1626: $rule_in_effect = $currrules->{'default'};
1627: }
1628: }
1629: } else {
1630: if ($currrules->{'_LC_external'} ne '') {
1631: $rule_in_effect = $currrules->{'_LC_external'};
1632: }
1633: }
1634: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1635: $uname,$udom);
1636: }
1637: }
1638: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1639: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1640: unless (defined($cached)) {
1641: my %domconfig =
1642: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1643: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1644: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1645: } else {
1646: $domneedscache = $serverhomedom;
1647: }
1648: }
1649: if (ref($result) eq 'HASH') {
1650: ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1651: &check_balancer_result($result,@hosts);
1652: if ($is_balancer) {
1653: if (ref($currrules) eq 'HASH') {
1654: if ($currrules->{'_LC_internetdom'} ne '') {
1655: $rule_in_effect = $currrules->{'_LC_internetdom'};
1656: }
1657: }
1658: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1659: $uname,$udom);
1660: }
1661: } else {
1662: if ($perlvar{'lonBalancer'} eq 'yes') {
1663: $is_balancer = 1;
1664: $offloadto = &this_host_spares($dom_in_use);
1665: }
1666: unless (defined($cached)) {
1667: $domneedscache = $serverhomedom;
1668: }
1669: }
1670: } else {
1671: if ($perlvar{'lonBalancer'} eq 'yes') {
1672: $is_balancer = 1;
1673: $offloadto = &this_host_spares($dom_in_use);
1674: }
1675: unless (defined($cached)) {
1676: $domneedscache = $serverhomedom;
1677: }
1678: }
1679: if ($domneedscache) {
1680: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1681: }
1682: if (($is_balancer) && ($caller ne 'switchserver')) {
1683: my $lowest_load = 30000;
1684: if (ref($offloadto) eq 'HASH') {
1685: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1686: foreach my $try_server (@{$offloadto->{'primary'}}) {
1687: ($otherserver,$lowest_load) =
1688: &compare_server_load($try_server,$otherserver,$lowest_load);
1689: }
1690: }
1691: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1692:
1693: if (!$found_server) {
1694: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1695: foreach my $try_server (@{$offloadto->{'default'}}) {
1696: ($otherserver,$lowest_load) =
1697: &compare_server_load($try_server,$otherserver,$lowest_load);
1698: }
1699: }
1700: }
1701: } elsif (ref($offloadto) eq 'ARRAY') {
1702: if (@{$offloadto} == 1) {
1703: $otherserver = $offloadto->[0];
1704: } elsif (@{$offloadto} > 1) {
1705: foreach my $try_server (@{$offloadto}) {
1706: ($otherserver,$lowest_load) =
1707: &compare_server_load($try_server,$otherserver,$lowest_load);
1708: }
1709: }
1710: }
1711: unless ($caller eq 'login') {
1712: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1713: $is_balancer = 0;
1714: if ($uname ne '' && $udom ne '') {
1715: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1716: &appenv({'user.loadbalexempt' => $lonhost,
1717: 'user.loadbalcheck.time' => time});
1718: }
1719: }
1720: }
1721: }
1722: }
1723: if (($is_balancer) && (!$homeintdom)) {
1724: undef($setcookie);
1725: }
1726: return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1727: }
1728:
1729: sub check_balancer_result {
1730: my ($result,@hosts) = @_;
1731: my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1732: if (ref($result) eq 'HASH') {
1733: if ($result->{'lonhost'} ne '') {
1734: my $currbalancer = $result->{'lonhost'};
1735: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1736: $is_balancer = 1;
1737: $currtargets = $result->{'targets'};
1738: $currrules = $result->{'rules'};
1739: }
1740: $dom_balancers = $currbalancer;
1741: } else {
1742: if (keys(%{$result})) {
1743: foreach my $key (keys(%{$result})) {
1744: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1745: (ref($result->{$key}) eq 'HASH')) {
1746: $is_balancer = 1;
1747: $currrules = $result->{$key}{'rules'};
1748: $currtargets = $result->{$key}{'targets'};
1749: $setcookie = $result->{$key}{'cookie'};
1750: last;
1751: }
1752: }
1753: $dom_balancers = join(',',sort(keys(%{$result})));
1754: }
1755: }
1756: }
1757: return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1758: }
1759:
1760: sub get_loadbalancer_targets {
1761: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1762: my $offloadto;
1763: if ($rule_in_effect eq 'none') {
1764: return [$perlvar{'lonHostID'}];
1765: } elsif ($rule_in_effect eq '') {
1766: $offloadto = $currtargets;
1767: } else {
1768: if ($rule_in_effect eq 'homeserver') {
1769: my $homeserver = &homeserver($uname,$udom);
1770: if ($homeserver ne 'no_host') {
1771: $offloadto = [$homeserver];
1772: }
1773: } elsif ($rule_in_effect eq 'externalbalancer') {
1774: my %domconfig =
1775: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1776: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1777: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1778: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1779: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1780: }
1781: }
1782: } else {
1783: my %servers = &internet_dom_servers($udom);
1784: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1785: if (&hostname($remotebalancer) ne '') {
1786: $offloadto = [$remotebalancer];
1787: }
1788: }
1789: } elsif (&hostname($rule_in_effect) ne '') {
1790: $offloadto = [$rule_in_effect];
1791: }
1792: }
1793: return $offloadto;
1794: }
1795:
1796: sub internet_dom_servers {
1797: my ($dom) = @_;
1798: my (%uniqservers,%servers);
1799: my $primaryserver = &hostname(&domain($dom,'primary'));
1800: my @machinedoms = &machine_domains($primaryserver);
1801: foreach my $mdom (@machinedoms) {
1802: my %currservers = %servers;
1803: my %server = &get_servers($mdom);
1804: %servers = (%currservers,%server);
1805: }
1806: my %by_hostname;
1807: foreach my $id (keys(%servers)) {
1808: push(@{$by_hostname{$servers{$id}}},$id);
1809: }
1810: foreach my $hostname (sort(keys(%by_hostname))) {
1811: if (@{$by_hostname{$hostname}} > 1) {
1812: my $match = 0;
1813: foreach my $id (@{$by_hostname{$hostname}}) {
1814: if (&host_domain($id) eq $dom) {
1815: $uniqservers{$id} = $hostname;
1816: $match = 1;
1817: }
1818: }
1819: unless ($match) {
1820: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1821: }
1822: } else {
1823: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1824: }
1825: }
1826: return %uniqservers;
1827: }
1828:
1829: sub trusted_domains {
1830: my ($cmdtype,$calldom) = @_;
1831: my ($trusted,$untrusted);
1832: if (&domain($calldom) eq '') {
1833: return ($trusted,$untrusted);
1834: }
1835: unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
1836: return ($trusted,$untrusted);
1837: }
1838: my $callprimary = &domain($calldom,'primary');
1839: my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
1840: if ($intcalldom eq '') {
1841: return ($trusted,$untrusted);
1842: }
1843:
1844: my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
1845: unless (defined($cached)) {
1846: my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
1847: &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
1848: $trustconfig = $domconfig{'trust'};
1849: }
1850: if (ref($trustconfig)) {
1851: my (%possexc,%possinc,@allexc,@allinc);
1852: if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
1853: if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
1854: map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}};
1855: }
1856: if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1857: $possinc{$intcalldom} = 1;
1858: map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
1859: }
1860: }
1861: if (keys(%possexc)) {
1862: if (keys(%possinc)) {
1863: foreach my $key (sort(keys(%possexc))) {
1864: next if ($key eq $intcalldom);
1865: unless ($possinc{$key}) {
1866: push(@allexc,$key);
1867: }
1868: }
1869: } else {
1870: @allexc = sort(keys(%possexc));
1871: }
1872: }
1873: if (keys(%possinc)) {
1874: $possinc{$intcalldom} = 1;
1875: @allinc = sort(keys(%possinc));
1876: }
1877: if ((@allexc > 0) || (@allinc > 0)) {
1878: my %doms_by_intdom;
1879: my %allintdoms = &all_host_intdom();
1880: my %alldoms = &all_host_domain();
1881: foreach my $key (%allintdoms) {
1882: if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
1883: unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
1884: push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
1885: }
1886: } else {
1887: $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}];
1888: }
1889: }
1890: foreach my $exc (@allexc) {
1891: if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1892: push(@{$untrusted},@{$doms_by_intdom{$exc}});
1893: }
1894: }
1895: foreach my $inc (@allinc) {
1896: if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1897: push(@{$trusted},@{$doms_by_intdom{$inc}});
1898: }
1899: }
1900: }
1901: }
1902: return ($trusted,$untrusted);
1903: }
1904:
1905: sub will_trust {
1906: my ($cmdtype,$domain,$possdom) = @_;
1907: return 1 if ($domain eq $possdom);
1908: my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
1909: my $willtrust;
1910: if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
1911: if (grep(/^\Q$domain\E$/,@{$trustedref})) {
1912: $willtrust = 1;
1913: }
1914: } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
1915: unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
1916: $willtrust = 1;
1917: }
1918: } else {
1919: $willtrust = 1;
1920: }
1921: return $willtrust;
1922: }
1923:
1924: # ---------------------- Find the homebase for a user from domain's lib servers
1925:
1926: my %homecache;
1927: sub homeserver {
1928: my ($uname,$udom,$ignoreBadCache)=@_;
1929: my $index="$uname:$udom";
1930:
1931: if (exists($homecache{$index})) { return $homecache{$index}; }
1932:
1933: my %servers = &get_servers($udom,'library');
1934: foreach my $tryserver (keys(%servers)) {
1935: next if ($ignoreBadCache ne 'true' &&
1936: exists($badServerCache{$tryserver}));
1937:
1938: my $answer=reply("home:$udom:$uname",$tryserver);
1939: if ($answer eq 'found') {
1940: delete($badServerCache{$tryserver});
1941: return $homecache{$index}=$tryserver;
1942: } elsif ($answer eq 'no_host') {
1943: $badServerCache{$tryserver}=1;
1944: }
1945: }
1946: return 'no_host';
1947: }
1948:
1949: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1950:
1951: sub idget {
1952: my ($udom,$idsref,$namespace)=@_;
1953: my %returnhash=();
1954: my @ids=();
1955: if (ref($idsref) eq 'ARRAY') {
1956: @ids = @{$idsref};
1957: } else {
1958: return %returnhash;
1959: }
1960: if ($namespace eq '') {
1961: $namespace = 'ids';
1962: }
1963:
1964: my %servers = &get_servers($udom,'library');
1965: foreach my $tryserver (keys(%servers)) {
1966: my $idlist=join('&', map { &escape($_); } @ids);
1967: if ($namespace eq 'ids') {
1968: $idlist=~tr/A-Z/a-z/;
1969: }
1970: my $reply;
1971: if ($namespace eq 'ids') {
1972: $reply=&reply("idget:$udom:".$idlist,$tryserver);
1973: } else {
1974: $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
1975: }
1976: my @answer=();
1977: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1978: @answer=split(/\&/,$reply);
1979: } ;
1980: my $i;
1981: for ($i=0;$i<=$#ids;$i++) {
1982: if ($answer[$i]) {
1983: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1984: }
1985: }
1986: }
1987: return %returnhash;
1988: }
1989:
1990: # ------------------------------------- Find the IDs behind a list of usernames
1991:
1992: sub idrget {
1993: my ($udom,@unames)=@_;
1994: my %returnhash=();
1995: foreach my $uname (@unames) {
1996: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1997: }
1998: return %returnhash;
1999: }
2000:
2001: # Store away a list of names and associated student/employee IDs or clicker IDs
2002:
2003: sub idput {
2004: my ($udom,$idsref,$uhom,$namespace)=@_;
2005: my %servers=();
2006: my %ids=();
2007: my %byid = ();
2008: if (ref($idsref) eq 'HASH') {
2009: %ids=%{$idsref};
2010: }
2011: if ($namespace eq '') {
2012: $namespace = 'ids';
2013: }
2014: foreach my $uname (keys(%ids)) {
2015: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
2016: if ($uhom eq '') {
2017: $uhom=&homeserver($uname,$udom);
2018: }
2019: if ($uhom ne 'no_host') {
2020: my $esc_unam=&escape($uname);
2021: if ($namespace eq 'ids') {
2022: my $id=&escape($ids{$uname});
2023: $id=~tr/A-Z/a-z/;
2024: my $esc_unam=&escape($uname);
2025: $servers{$uhom}.=$id.'='.$esc_unam.'&';
2026: } else {
2027: my @currids = split(/,/,$ids{$uname});
2028: foreach my $id (@currids) {
2029: $byid{$uhom}{$id} .= $uname.',';
2030: }
2031: }
2032: }
2033: }
2034: if ($namespace eq 'clickers') {
2035: foreach my $server (keys(%byid)) {
2036: if (ref($byid{$server}) eq 'HASH') {
2037: foreach my $id (keys(%{$byid{$server}})) {
2038: $byid{$server} =~ s/,$//;
2039: $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&';
2040: }
2041: }
2042: }
2043: }
2044: foreach my $server (keys(%servers)) {
2045: $servers{$server} =~ s/\&$//;
2046: if ($namespace eq 'ids') {
2047: &critical('idput:'.$udom.':'.$servers{$server},$server);
2048: } else {
2049: &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
2050: }
2051: }
2052: }
2053:
2054: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
2055:
2056: sub iddel {
2057: my ($udom,$idshashref,$uhome,$namespace)=@_;
2058: my %result=();
2059: my %ids=();
2060: my %byid = ();
2061: if (ref($idshashref) eq 'HASH') {
2062: %ids=%{$idshashref};
2063: } else {
2064: return %result;
2065: }
2066: if ($namespace eq '') {
2067: $namespace = 'ids';
2068: }
2069: my %servers=();
2070: while (my ($id,$unamestr) = each(%ids)) {
2071: if ($namespace eq 'ids') {
2072: my $uhom = $uhome;
2073: if ($uhom eq '') {
2074: $uhom=&homeserver($unamestr,$udom);
2075: }
2076: if ($uhom ne 'no_host') {
2077: $servers{$uhom}.='&'.&escape($id);
2078: }
2079: } else {
2080: my @curritems = split(/,/,$ids{$id});
2081: foreach my $uname (@curritems) {
2082: my $uhom = $uhome;
2083: if ($uhom eq '') {
2084: $uhom=&homeserver($uname,$udom);
2085: }
2086: if ($uhom ne 'no_host') {
2087: $byid{$uhom}{$id} .= $uname.',';
2088: }
2089: }
2090: }
2091: }
2092: if ($namespace eq 'clickers') {
2093: foreach my $server (keys(%byid)) {
2094: if (ref($byid{$server}) eq 'HASH') {
2095: foreach my $id (keys(%{$byid{$server}})) {
2096: $byid{$server}{$id} =~ s/,$//;
2097: $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
2098: }
2099: }
2100: }
2101: }
2102: foreach my $server (keys(%servers)) {
2103: $servers{$server} =~ s/\&$//;
2104: if ($namespace eq 'ids') {
2105: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
2106: } elsif ($namespace eq 'clickers') {
2107: $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
2108: }
2109: }
2110: return %result;
2111: }
2112:
2113: # ----- Update clicker ID-to-username look-ups in clickers.db on library server
2114:
2115: sub updateclickers {
2116: my ($udom,$action,$idshashref,$uhome,$critical) = @_;
2117: my %clickers;
2118: if (ref($idshashref) eq 'HASH') {
2119: %clickers=%{$idshashref};
2120: } else {
2121: return;
2122: }
2123: my $items='';
2124: foreach my $item (keys(%clickers)) {
2125: $items.=&escape($item).'='.&escape($clickers{$item}).'&';
2126: }
2127: $items=~s/\&$//;
2128: my $request = "updateclickers:$udom:$action:$items";
2129: if ($critical) {
2130: return &critical($request,$uhome);
2131: } else {
2132: return &reply($request,$uhome);
2133: }
2134: }
2135:
2136: # ------------------------------dump from db file owned by domainconfig user
2137: sub dump_dom {
2138: my ($namespace, $udom, $regexp) = @_;
2139:
2140: $udom ||= $env{'user.domain'};
2141:
2142: return () unless $udom;
2143:
2144: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
2145: }
2146:
2147: # ------------------------------------------ get items from domain db files
2148:
2149: sub get_dom {
2150: my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
2151: return if ($udom eq 'public');
2152: my $items='';
2153: foreach my $item (@$storearr) {
2154: $items.=&escape($item).'&';
2155: }
2156: $items=~s/\&$//;
2157: if (!$udom) {
2158: $udom=$env{'user.domain'};
2159: return if ($udom eq 'public');
2160: if (defined(&domain($udom,'primary'))) {
2161: $uhome=&domain($udom,'primary');
2162: } else {
2163: undef($uhome);
2164: }
2165: } else {
2166: if (!$uhome) {
2167: if (defined(&domain($udom,'primary'))) {
2168: $uhome=&domain($udom,'primary');
2169: }
2170: }
2171: }
2172: if ($udom && $uhome && ($uhome ne 'no_host')) {
2173: my $rep;
2174: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
2175: # domain information is hosted on this machine
2176: $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
2177: } else {
2178: if ($encrypt) {
2179: $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
2180: } else {
2181: $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
2182: }
2183: }
2184: my %returnhash;
2185: if ($rep eq '' || $rep =~ /^error: 2 /) {
2186: return %returnhash;
2187: }
2188: my @pairs=split(/\&/,$rep);
2189: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
2190: return @pairs;
2191: }
2192: my $i=0;
2193: foreach my $item (@$storearr) {
2194: $returnhash{$item}=&thaw_unescape($pairs[$i]);
2195: $i++;
2196: }
2197: return %returnhash;
2198: } else {
2199: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
2200: }
2201: }
2202:
2203: # -------------------------------------------- put items in domain db files
2204:
2205: sub put_dom {
2206: my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
2207: if (!$udom) {
2208: $udom=$env{'user.domain'};
2209: if (defined(&domain($udom,'primary'))) {
2210: $uhome=&domain($udom,'primary');
2211: } else {
2212: undef($uhome);
2213: }
2214: } else {
2215: if (!$uhome) {
2216: if (defined(&domain($udom,'primary'))) {
2217: $uhome=&domain($udom,'primary');
2218: }
2219: }
2220: }
2221: if ($udom && $uhome && ($uhome ne 'no_host')) {
2222: my $items='';
2223: foreach my $item (keys(%$storehash)) {
2224: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
2225: }
2226: $items=~s/\&$//;
2227: if ($encrypt) {
2228: return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
2229: } else {
2230: return &reply("putdom:$udom:$namespace:$items",$uhome);
2231: }
2232: } else {
2233: &logthis("put_dom failed - no homeserver and/or domain");
2234: }
2235: }
2236:
2237: # --------------------- newput for items in db file owned by domainconfig user
2238: sub newput_dom {
2239: my ($namespace,$storehash,$udom) = @_;
2240: my $result;
2241: if (!$udom) {
2242: $udom=$env{'user.domain'};
2243: }
2244: if ($udom) {
2245: my $uname = &get_domainconfiguser($udom);
2246: $result = &newput($namespace,$storehash,$udom,$uname);
2247: }
2248: return $result;
2249: }
2250:
2251: # --------------------- delete for items in db file owned by domainconfig user
2252: sub del_dom {
2253: my ($namespace,$storearr,$udom)=@_;
2254: if (ref($storearr) eq 'ARRAY') {
2255: if (!$udom) {
2256: $udom=$env{'user.domain'};
2257: }
2258: if ($udom) {
2259: my $uname = &get_domainconfiguser($udom);
2260: return &del($namespace,$storearr,$udom,$uname);
2261: }
2262: }
2263: }
2264:
2265: # ----------------------------------construct domainconfig user for a domain
2266: sub get_domainconfiguser {
2267: my ($udom) = @_;
2268: return $udom.'-domainconfig';
2269: }
2270:
2271: sub retrieve_inst_usertypes {
2272: my ($udom) = @_;
2273: my (%returnhash,@order);
2274: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
2275: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
2276: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
2277: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
2278: } else {
2279: if (defined(&domain($udom,'primary'))) {
2280: my $uhome=&domain($udom,'primary');
2281: my $rep=&reply("inst_usertypes:$udom",$uhome);
2282: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
2283: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
2284: return (\%returnhash,\@order);
2285: }
2286: my ($hashitems,$orderitems) = split(/:/,$rep);
2287: my @pairs=split(/\&/,$hashitems);
2288: foreach my $item (@pairs) {
2289: my ($key,$value)=split(/=/,$item,2);
2290: $key = &unescape($key);
2291: next if ($key =~ /^error: 2 /);
2292: $returnhash{$key}=&thaw_unescape($value);
2293: }
2294: my @esc_order = split(/\&/,$orderitems);
2295: foreach my $item (@esc_order) {
2296: push(@order,&unescape($item));
2297: }
2298: } else {
2299: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
2300: }
2301: return (\%returnhash,\@order);
2302: }
2303: }
2304:
2305: sub is_domainimage {
2306: my ($url) = @_;
2307: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
2308: if (&domain($1) ne '') {
2309: return '1';
2310: }
2311: }
2312: return;
2313: }
2314:
2315: sub inst_directory_query {
2316: my ($srch) = @_;
2317: my $udom = $srch->{'srchdomain'};
2318: my %results;
2319: my $homeserver = &domain($udom,'primary');
2320: my $outcome;
2321: if ($homeserver ne '') {
2322: unless ($homeserver eq $perlvar{'lonHostID'}) {
2323: if ($srch->{'srchby'} eq 'email') {
2324: my $lcrev = &get_server_loncaparev($udom,$homeserver);
2325: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2326: if (($major eq '' && $minor eq '') || ($major < 2) ||
2327: (($major == 2) && ($minor < 12))) {
2328: return;
2329: }
2330: }
2331: }
2332: my $queryid=&reply("querysend:instdirsearch:".
2333: &escape($srch->{'srchby'}).':'.
2334: &escape($srch->{'srchterm'}).':'.
2335: &escape($srch->{'srchtype'}),$homeserver);
2336: my $host=&hostname($homeserver);
2337: if ($queryid !~/^\Q$host\E\_/) {
2338: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
2339: return;
2340: }
2341: my $response = &get_query_reply($queryid);
2342: my $maxtries = 5;
2343: my $tries = 1;
2344: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2345: $response = &get_query_reply($queryid);
2346: $tries ++;
2347: }
2348:
2349: if (!&error($response) && $response ne 'refused') {
2350: if ($response eq 'unavailable') {
2351: $outcome = $response;
2352: } else {
2353: $outcome = 'ok';
2354: my @matches = split(/\n/,$response);
2355: foreach my $match (@matches) {
2356: my ($key,$value) = split(/=/,$match);
2357: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2358: }
2359: }
2360: }
2361: }
2362: return ($outcome,%results);
2363: }
2364:
2365: sub usersearch {
2366: my ($srch) = @_;
2367: my $dom = $srch->{'srchdomain'};
2368: my %results;
2369: my %libserv = &all_library();
2370: my $query = 'usersearch';
2371: foreach my $tryserver (keys(%libserv)) {
2372: if (&host_domain($tryserver) eq $dom) {
2373: unless ($tryserver eq $perlvar{'lonHostID'}) {
2374: if ($srch->{'srchby'} eq 'email') {
2375: my $lcrev = &get_server_loncaparev($dom,$tryserver);
2376: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2377: next if (($major eq '' && $minor eq '') || ($major < 2) ||
2378: (($major == 2) && ($minor < 12)));
2379: }
2380: }
2381: my $host=&hostname($tryserver);
2382: my $queryid=
2383: &reply("querysend:".&escape($query).':'.
2384: &escape($srch->{'srchby'}).':'.
2385: &escape($srch->{'srchtype'}).':'.
2386: &escape($srch->{'srchterm'}),$tryserver);
2387: if ($queryid !~/^\Q$host\E\_/) {
2388: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
2389: next;
2390: }
2391: my $reply = &get_query_reply($queryid);
2392: my $maxtries = 1;
2393: my $tries = 1;
2394: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2395: $reply = &get_query_reply($queryid);
2396: $tries ++;
2397: }
2398: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2399: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2400: } else {
2401: my @matches;
2402: if ($reply =~ /\n/) {
2403: @matches = split(/\n/,$reply);
2404: } else {
2405: @matches = split(/\&/,$reply);
2406: }
2407: foreach my $match (@matches) {
2408: my ($uname,$udom,%userhash);
2409: foreach my $entry (split(/:/,$match)) {
2410: my ($key,$value) =
2411: map {&unescape($_);} split(/=/,$entry);
2412: $userhash{$key} = $value;
2413: if ($key eq 'username') {
2414: $uname = $value;
2415: } elsif ($key eq 'domain') {
2416: $udom = $value;
2417: }
2418: }
2419: $results{$uname.':'.$udom} = \%userhash;
2420: }
2421: }
2422: }
2423: }
2424: return %results;
2425: }
2426:
2427: sub get_instuser {
2428: my ($udom,$uname,$id) = @_;
2429: my $homeserver = &domain($udom,'primary');
2430: my ($outcome,%results);
2431: if ($homeserver ne '') {
2432: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2433: &escape($id).':'.&escape($udom),$homeserver);
2434: my $host=&hostname($homeserver);
2435: if ($queryid !~/^\Q$host\E\_/) {
2436: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2437: return;
2438: }
2439: my $response = &get_query_reply($queryid);
2440: my $maxtries = 5;
2441: my $tries = 1;
2442: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2443: $response = &get_query_reply($queryid);
2444: $tries ++;
2445: }
2446: if (!&error($response) && $response ne 'refused') {
2447: if ($response eq 'unavailable') {
2448: $outcome = $response;
2449: } else {
2450: $outcome = 'ok';
2451: my @matches = split(/\n/,$response);
2452: foreach my $match (@matches) {
2453: my ($key,$value) = split(/=/,$match);
2454: $results{&unescape($key)} = &thaw_unescape($value);
2455: }
2456: }
2457: }
2458: }
2459: my %userinfo;
2460: if (ref($results{$uname}) eq 'HASH') {
2461: %userinfo = %{$results{$uname}};
2462: }
2463: return ($outcome,%userinfo);
2464: }
2465:
2466: sub get_multiple_instusers {
2467: my ($udom,$users,$caller) = @_;
2468: my ($outcome,$results);
2469: if (ref($users) eq 'HASH') {
2470: my $count = keys(%{$users});
2471: my $requested = &freeze_escape($users);
2472: my $homeserver = &domain($udom,'primary');
2473: if ($homeserver ne '') {
2474: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2475: my $host=&hostname($homeserver);
2476: if ($queryid !~/^\Q$host\E\_/) {
2477: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2478: ' for host: '.$homeserver.'in domain '.$udom);
2479: return ($outcome,$results);
2480: }
2481: my $response = &get_query_reply($queryid);
2482: my $maxtries = 5;
2483: if ($count > 100) {
2484: $maxtries = 1+int($count/20);
2485: }
2486: my $tries = 1;
2487: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2488: $response = &get_query_reply($queryid);
2489: $tries ++;
2490: }
2491: if ($response eq '') {
2492: $results = {};
2493: foreach my $key (keys(%{$users})) {
2494: my ($uname,$id);
2495: if ($caller eq 'id') {
2496: $id = $key;
2497: } else {
2498: $uname = $key;
2499: }
2500: my ($resp,%info) = &get_instuser($udom,$uname,$id);
2501: $outcome = $resp;
2502: if ($resp eq 'ok') {
2503: %{$results} = (%{$results}, %info);
2504: } else {
2505: last;
2506: }
2507: }
2508: } elsif(!&error($response) && ($response ne 'refused')) {
2509: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2510: $outcome = $response;
2511: } else {
2512: ($outcome,my $userdata) = split(/=/,$response,2);
2513: if ($outcome eq 'ok') {
2514: $results = &thaw_unescape($userdata);
2515: }
2516: }
2517: }
2518: }
2519: }
2520: return ($outcome,$results);
2521: }
2522:
2523: sub inst_rulecheck {
2524: my ($udom,$uname,$id,$item,$rules) = @_;
2525: my %returnhash;
2526: if ($udom ne '') {
2527: if (ref($rules) eq 'ARRAY') {
2528: @{$rules} = map {&escape($_);} (@{$rules});
2529: my $rulestr = join(':',@{$rules});
2530: my $homeserver=&domain($udom,'primary');
2531: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
2532: my $response;
2533: if ($item eq 'username') {
2534: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2535: ':'.&escape($uname).':'.$rulestr,
2536: $homeserver));
2537: } elsif ($item eq 'id') {
2538: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2539: ':'.&escape($id).':'.$rulestr,
2540: $homeserver));
2541: } elsif ($item eq 'selfcreate') {
2542: $response=&unescape(&reply('instselfcreatecheck:'.
2543: &escape($udom).':'.&escape($uname).
2544: ':'.$rulestr,$homeserver));
2545: }
2546: if ($response ne 'refused') {
2547: my @pairs=split(/\&/,$response);
2548: foreach my $item (@pairs) {
2549: my ($key,$value)=split(/=/,$item,2);
2550: $key = &unescape($key);
2551: next if ($key =~ /^error: 2 /);
2552: $returnhash{$key}=&thaw_unescape($value);
2553: }
2554: }
2555: }
2556: }
2557: }
2558: return %returnhash;
2559: }
2560:
2561: sub inst_userrules {
2562: my ($udom,$check) = @_;
2563: my (%ruleshash,@ruleorder);
2564: if ($udom ne '') {
2565: my $homeserver=&domain($udom,'primary');
2566: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
2567: my $response;
2568: if ($check eq 'id') {
2569: $response=&reply('instidrules:'.&escape($udom),
2570: $homeserver);
2571: } elsif ($check eq 'email') {
2572: $response=&reply('instemailrules:'.&escape($udom),
2573: $homeserver);
2574: } else {
2575: $response=&reply('instuserrules:'.&escape($udom),
2576: $homeserver);
2577: }
2578: if (($response ne 'refused') && ($response ne 'error') &&
2579: ($response ne 'unknown_cmd') &&
2580: ($response ne 'no_such_host')) {
2581: my ($hashitems,$orderitems) = split(/:/,$response);
2582: my @pairs=split(/\&/,$hashitems);
2583: foreach my $item (@pairs) {
2584: my ($key,$value)=split(/=/,$item,2);
2585: $key = &unescape($key);
2586: next if ($key =~ /^error: 2 /);
2587: $ruleshash{$key}=&thaw_unescape($value);
2588: }
2589: my @esc_order = split(/\&/,$orderitems);
2590: foreach my $item (@esc_order) {
2591: push(@ruleorder,&unescape($item));
2592: }
2593: }
2594: }
2595: }
2596: return (\%ruleshash,\@ruleorder);
2597: }
2598:
2599: # ------------- Get Authentication, Language and User Tools Defaults for Domain
2600:
2601: sub get_domain_defaults {
2602: my ($domain,$ignore_cache) = @_;
2603: return if (($domain eq '') || ($domain eq 'public'));
2604: my $cachetime = 60*60*24;
2605: unless ($ignore_cache) {
2606: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2607: if (defined($cached)) {
2608: if (ref($result) eq 'HASH') {
2609: return %{$result};
2610: }
2611: }
2612: }
2613: my %domdefaults;
2614: my %domconfig =
2615: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
2616: 'requestcourses','inststatus',
2617: 'coursedefaults','usersessions',
2618: 'requestauthor','selfenrollment',
2619: 'coursecategories','ssl','autoenroll',
2620: 'trust','helpsettings','wafproxy'],$domain);
2621: my @coursetypes = ('official','unofficial','community','textbook','placement');
2622: if (ref($domconfig{'defaults'}) eq 'HASH') {
2623: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2624: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2625: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
2626: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
2627: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
2628: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
2629: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2630: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2631: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
2632: } else {
2633: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2634: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2635: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2636: }
2637: if (ref($domconfig{'quotas'}) eq 'HASH') {
2638: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2639: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2640: } else {
2641: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
2642: }
2643: my @usertools = ('aboutme','blog','webdav','portfolio');
2644: foreach my $item (@usertools) {
2645: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2646: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2647: }
2648: }
2649: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2650: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2651: }
2652: }
2653: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
2654: foreach my $item ('official','unofficial','community','textbook','placement') {
2655: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2656: }
2657: }
2658: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2659: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2660: }
2661: if (ref($domconfig{'inststatus'}) eq 'HASH') {
2662: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
2663: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2664: }
2665: }
2666: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
2667: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
2668: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2669: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2670: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2671: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2672: }
2673: foreach my $type (@coursetypes) {
2674: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2675: unless ($type eq 'community') {
2676: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2677: }
2678: }
2679: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2680: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2681: }
2682: if ($domdefaults{'postsubmit'} eq 'on') {
2683: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2684: $domdefaults{$type.'postsubtimeout'} =
2685: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2686: }
2687: }
2688: }
2689: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2690: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2691: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2692: if (@clonecodes) {
2693: $domdefaults{'canclone'} = join('+',@clonecodes);
2694: }
2695: }
2696: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2697: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2698: }
2699: if ($domconfig{'coursedefaults'}{'texengine'}) {
2700: $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
2701: }
2702: }
2703: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2704: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2705: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2706: }
2707: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2708: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2709: }
2710: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2711: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2712: }
2713: if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
2714: $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
2715: }
2716: }
2717: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2718: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2719: my @settings = ('types','registered','enroll_dates','access_dates','section',
2720: 'approval','limit');
2721: foreach my $type (@coursetypes) {
2722: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2723: my @mgrdc = ();
2724: foreach my $item (@settings) {
2725: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2726: push(@mgrdc,$item);
2727: }
2728: }
2729: if (@mgrdc) {
2730: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2731: }
2732: }
2733: }
2734: }
2735: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2736: foreach my $type (@coursetypes) {
2737: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2738: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2739: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2740: }
2741: }
2742: }
2743: }
2744: }
2745: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2746: $domdefaults{'catauth'} = 'std';
2747: $domdefaults{'catunauth'} = 'std';
2748: if ($domconfig{'coursecategories'}{'auth'}) {
2749: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2750: }
2751: if ($domconfig{'coursecategories'}{'unauth'}) {
2752: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2753: }
2754: }
2755: if (ref($domconfig{'ssl'}) eq 'HASH') {
2756: if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
2757: $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
2758: }
2759: if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
2760: $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
2761: }
2762: if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
2763: $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
2764: }
2765: }
2766: if (ref($domconfig{'trust'}) eq 'HASH') {
2767: my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
2768: foreach my $prefix (@prefixes) {
2769: if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
2770: $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
2771: }
2772: }
2773: }
2774: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2775: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2776: }
2777: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2778: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2779: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2780: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2781: }
2782: }
2783: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
2784: foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
2785: if ($domconfig{'wafproxy'}{$item}) {
2786: $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
2787: }
2788: }
2789: }
2790: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
2791: return %domdefaults;
2792: }
2793:
2794: sub get_dom_cats {
2795: my ($dom) = @_;
2796: return unless (&domain($dom));
2797: my ($cats,$cached)=&is_cached_new('cats',$dom);
2798: unless (defined($cached)) {
2799: my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
2800: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2801: if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
2802: %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
2803: } else {
2804: $cats = {};
2805: }
2806: } else {
2807: $cats = {};
2808: }
2809: &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
2810: }
2811: return $cats;
2812: }
2813:
2814: sub get_dom_instcats {
2815: my ($dom) = @_;
2816: return unless (&domain($dom));
2817: my ($instcats,$cached)=&is_cached_new('instcats',$dom);
2818: unless (defined($cached)) {
2819: my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
2820: my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
2821: if ($totcodes > 0) {
2822: my $caller = 'global';
2823: if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
2824: \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
2825: $instcats = {
2826: codes => \%codes,
2827: codetitles => \@codetitles,
2828: cat_titles => \%cat_titles,
2829: cat_order => \%cat_order,
2830: };
2831: &do_cache_new('instcats',$dom,$instcats,3600);
2832: }
2833: }
2834: }
2835: return $instcats;
2836: }
2837:
2838: sub retrieve_instcodes {
2839: my ($coursecodes,$dom) = @_;
2840: my $totcodes;
2841: my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
2842: foreach my $course (keys(%courses)) {
2843: if (ref($courses{$course}) eq 'HASH') {
2844: if ($courses{$course}{'inst_code'} ne '') {
2845: $$coursecodes{$course} = $courses{$course}{'inst_code'};
2846: $totcodes ++;
2847: }
2848: }
2849: }
2850: return $totcodes;
2851: }
2852:
2853: sub course_portal_url {
2854: my ($cnum,$cdom,$r) = @_;
2855: my $chome = &homeserver($cnum,$cdom);
2856: my $hostname = &hostname($chome);
2857: my $protocol = $protocol{$chome};
2858: $protocol = 'http' if ($protocol ne 'https');
2859: my %domdefaults = &get_domain_defaults($cdom);
2860: my $firsturl;
2861: if ($domdefaults{'portal_def'}) {
2862: $firsturl = $domdefaults{'portal_def'};
2863: } else {
2864: my $alias = &Apache::lonnet::use_proxy_alias($r,$chome);
2865: $hostname = $alias if ($alias ne '');
2866: $firsturl = $protocol.'://'.$hostname;
2867: }
2868: return $firsturl;
2869: }
2870:
2871: # --------------------------------------------- Get domain config for passwords
2872:
2873: sub get_passwdconf {
2874: my ($dom) = @_;
2875: my (%passwdconf,$gotconf,$lookup);
2876: my ($result,$cached)=&is_cached_new('passwdconf',$dom);
2877: if (defined($cached)) {
2878: if (ref($result) eq 'HASH') {
2879: %passwdconf = %{$result};
2880: $gotconf = 1;
2881: }
2882: }
2883: unless ($gotconf) {
2884: my %domconfig = &get_dom('configuration',['passwords'],$dom);
2885: if (ref($domconfig{'passwords'}) eq 'HASH') {
2886: %passwdconf = %{$domconfig{'passwords'}};
2887: }
2888: my $cachetime = 24*60*60;
2889: &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
2890: }
2891: return %passwdconf;
2892: }
2893:
2894: # --------------------------------------------------- Assign a key to a student
2895:
2896: sub assign_access_key {
2897: #
2898: # a valid key looks like uname:udom#comments
2899: # comments are being appended
2900: #
2901: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2902: $kdom=
2903: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
2904: $knum=
2905: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
2906: $cdom=
2907: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2908: $cnum=
2909: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2910: $udom=$env{'user.name'} unless (defined($udom));
2911: $uname=$env{'user.domain'} unless (defined($uname));
2912: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
2913: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
2914: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
2915: # assigned to this person
2916: # - this should not happen,
2917: # unless something went wrong
2918: # the first time around
2919: # ready to assign
2920: $logentry=$1.'; '.$logentry;
2921: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
2922: $kdom,$knum) eq 'ok') {
2923: # key now belongs to user
2924: my $envkey='key.'.$cdom.'_'.$cnum;
2925: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
2926: &appenv({'environment.'.$envkey => $ckey});
2927: return 'ok';
2928: } else {
2929: return
2930: 'error: Count not permanently assign key, will need to be re-entered later.';
2931: }
2932: } else {
2933: return 'error: Could not assign key, try again later.';
2934: }
2935: } elsif (!$existing{$ckey}) {
2936: # the key does not exist
2937: return 'error: The key does not exist';
2938: } else {
2939: # the key is somebody else's
2940: return 'error: The key is already in use';
2941: }
2942: }
2943:
2944: # ------------------------------------------ put an additional comment on a key
2945:
2946: sub comment_access_key {
2947: #
2948: # a valid key looks like uname:udom#comments
2949: # comments are being appended
2950: #
2951: my ($ckey,$cdom,$cnum,$logentry)=@_;
2952: $cdom=
2953: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2954: $cnum=
2955: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2956: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2957: if ($existing{$ckey}) {
2958: $existing{$ckey}.='; '.$logentry;
2959: # ready to assign
2960: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
2961: $cdom,$cnum) eq 'ok') {
2962: return 'ok';
2963: } else {
2964: return 'error: Count not store comment.';
2965: }
2966: } else {
2967: # the key does not exist
2968: return 'error: The key does not exist';
2969: }
2970: }
2971:
2972: # ------------------------------------------------------ Generate a set of keys
2973:
2974: sub generate_access_keys {
2975: my ($number,$cdom,$cnum,$logentry)=@_;
2976: $cdom=
2977: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2978: $cnum=
2979: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2980: unless (&allowed('mky',$cdom)) { return 0; }
2981: unless (($cdom) && ($cnum)) { return 0; }
2982: if ($number>10000) { return 0; }
2983: sleep(2); # make sure don't get same seed twice
2984: srand(time()^($$+($$<<15))); # from "Programming Perl"
2985: my $total=0;
2986: for (my $i=1;$i<=$number;$i++) {
2987: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2988: sprintf("%lx",int(100000*rand)).'-'.
2989: sprintf("%lx",int(100000*rand));
2990: $newkey=~s/1/g/g; # folks mix up 1 and l
2991: $newkey=~s/0/h/g; # and also 0 and O
2992: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2993: if ($existing{$newkey}) {
2994: $i--;
2995: } else {
2996: if (&put('accesskeys',
2997: { $newkey => '# generated '.localtime().
2998: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
2999: '; '.$logentry },
3000: $cdom,$cnum) eq 'ok') {
3001: $total++;
3002: }
3003: }
3004: }
3005: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
3006: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
3007: return $total;
3008: }
3009:
3010: # ------------------------------------------------------- Validate an accesskey
3011:
3012: sub validate_access_key {
3013: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
3014: $cdom=
3015: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
3016: $cnum=
3017: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
3018: $udom=$env{'user.domain'} unless (defined($udom));
3019: $uname=$env{'user.name'} unless (defined($uname));
3020: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
3021: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
3022: }
3023:
3024: # ------------------------------------- Find the section of student in a course
3025: sub devalidate_getsection_cache {
3026: my ($udom,$unam,$courseid)=@_;
3027: my $hashid="$udom:$unam:$courseid";
3028: &devalidate_cache_new('getsection',$hashid);
3029: }
3030:
3031: sub courseid_to_courseurl {
3032: my ($courseid) = @_;
3033: #already url style courseid
3034: return $courseid if ($courseid =~ m{^/});
3035:
3036: if (exists($env{'course.'.$courseid.'.num'})) {
3037: my $cnum = $env{'course.'.$courseid.'.num'};
3038: my $cdom = $env{'course.'.$courseid.'.domain'};
3039: return "/$cdom/$cnum";
3040: }
3041:
3042: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
3043: if (exists($courseinfo{'num'})) {
3044: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
3045: }
3046:
3047: return undef;
3048: }
3049:
3050: sub getsection {
3051: my ($udom,$unam,$courseid)=@_;
3052: my $cachetime=1800;
3053:
3054: my $hashid="$udom:$unam:$courseid";
3055: my ($result,$cached)=&is_cached_new('getsection',$hashid);
3056: if (defined($cached)) { return $result; }
3057:
3058: my %Pending;
3059: my %Expired;
3060: #
3061: # Each role can either have not started yet (pending), be active,
3062: # or have expired.
3063: #
3064: # If there is an active role, we are done.
3065: #
3066: # If there is more than one role which has not started yet,
3067: # choose the one which will start sooner
3068: # If there is one role which has not started yet, return it.
3069: #
3070: # If there is more than one expired role, choose the one which ended last.
3071: # If there is a role which has expired, return it.
3072: #
3073: $courseid = &courseid_to_courseurl($courseid);
3074: my %roleshash = &dump('roles',$udom,$unam,$courseid);
3075: foreach my $key (keys(%roleshash)) {
3076: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
3077: my $section=$1;
3078: if ($key eq $courseid.'_st') { $section=''; }
3079: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
3080: my $now=time;
3081: if (defined($end) && $end && ($now > $end)) {
3082: $Expired{$end}=$section;
3083: next;
3084: }
3085: if (defined($start) && $start && ($now < $start)) {
3086: $Pending{$start}=$section;
3087: next;
3088: }
3089: return &do_cache_new('getsection',$hashid,$section,$cachetime);
3090: }
3091: #
3092: # Presumedly there will be few matching roles from the above
3093: # loop and the sorting time will be negligible.
3094: if (scalar(keys(%Pending))) {
3095: my ($time) = sort {$a <=> $b} keys(%Pending);
3096: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
3097: }
3098: if (scalar(keys(%Expired))) {
3099: my @sorted = sort {$a <=> $b} keys(%Expired);
3100: my $time = pop(@sorted);
3101: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
3102: }
3103: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
3104: }
3105:
3106: sub save_cache {
3107: &purge_remembered();
3108: #&Apache::loncommon::validate_page();
3109: undef(%env);
3110: undef($env_loaded);
3111: }
3112:
3113: my $to_remember=-1;
3114: my %remembered;
3115: my %accessed;
3116: my $kicks=0;
3117: my $hits=0;
3118: sub make_key {
3119: my ($name,$id) = @_;
3120: if (length($id) > 65
3121: && length(&escape($id)) > 200) {
3122: $id=length($id).':'.&Digest::MD5::md5_hex($id);
3123: }
3124: return &escape($name.':'.$id);
3125: }
3126:
3127: sub devalidate_cache_new {
3128: my ($name,$id,$debug) = @_;
3129: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
3130: my $remembered_id=$name.':'.$id;
3131: $id=&make_key($name,$id);
3132: $memcache->delete($id);
3133: delete($remembered{$remembered_id});
3134: delete($accessed{$remembered_id});
3135: }
3136:
3137: sub is_cached_new {
3138: my ($name,$id,$debug) = @_;
3139: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
3140: if (exists($remembered{$remembered_id})) {
3141: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
3142: $accessed{$remembered_id}=[&gettimeofday()];
3143: $hits++;
3144: return ($remembered{$remembered_id},1);
3145: }
3146: $id=&make_key($name,$id);
3147: my $value = $memcache->get($id);
3148: if (!(defined($value))) {
3149: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
3150: return (undef,undef);
3151: }
3152: if ($value eq '__undef__') {
3153: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
3154: $value=undef;
3155: }
3156: &make_room($remembered_id,$value,$debug);
3157: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
3158: return ($value,1);
3159: }
3160:
3161: sub do_cache_new {
3162: my ($name,$id,$value,$time,$debug) = @_;
3163: my $remembered_id=$name.':'.$id;
3164: $id=&make_key($name,$id);
3165: my $setvalue=$value;
3166: if (!defined($setvalue)) {
3167: $setvalue='__undef__';
3168: }
3169: if (!defined($time) ) {
3170: $time=600;
3171: }
3172: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
3173: my $result = $memcache->set($id,$setvalue,$time);
3174: if (! $result) {
3175: &logthis("caching of id -> $id failed");
3176: $memcache->disconnect_all();
3177: }
3178: # need to make a copy of $value
3179: &make_room($remembered_id,$value,$debug);
3180: return $value;
3181: }
3182:
3183: sub make_room {
3184: my ($remembered_id,$value,$debug)=@_;
3185:
3186: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
3187: : $value;
3188: if ($to_remember<0) { return; }
3189: $accessed{$remembered_id}=[&gettimeofday()];
3190: if (scalar(keys(%remembered)) <= $to_remember) { return; }
3191: my $to_kick;
3192: my $max_time=0;
3193: foreach my $other (keys(%accessed)) {
3194: if (&tv_interval($accessed{$other}) > $max_time) {
3195: $to_kick=$other;
3196: $max_time=&tv_interval($accessed{$other});
3197: }
3198: }
3199: delete($remembered{$to_kick});
3200: delete($accessed{$to_kick});
3201: $kicks++;
3202: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
3203: return;
3204: }
3205:
3206: sub purge_remembered {
3207: #&logthis("Tossing ".scalar(keys(%remembered)));
3208: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
3209: undef(%remembered);
3210: undef(%accessed);
3211: }
3212: # ------------------------------------- Read an entry from a user's environment
3213:
3214: sub userenvironment {
3215: my ($udom,$unam,@what)=@_;
3216: my $items;
3217: foreach my $item (@what) {
3218: $items.=&escape($item).'&';
3219: }
3220: $items=~s/\&$//;
3221: my %returnhash=();
3222: my $uhome = &homeserver($unam,$udom);
3223: unless ($uhome eq 'no_host') {
3224: my @answer=split(/\&/,
3225: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
3226: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
3227: return %returnhash;
3228: }
3229: my $i;
3230: for ($i=0;$i<=$#what;$i++) {
3231: $returnhash{$what[$i]}=&unescape($answer[$i]);
3232: }
3233: }
3234: return %returnhash;
3235: }
3236:
3237: # ---------------------------------------------------------- Get a studentphoto
3238: sub studentphoto {
3239: my ($udom,$unam,$ext) = @_;
3240: my $home=&Apache::lonnet::homeserver($unam,$udom);
3241: if (defined($env{'request.course.id'})) {
3242: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
3243: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
3244: return(&retrievestudentphoto($udom,$unam,$ext));
3245: } else {
3246: my ($result,$perm_reqd)=
3247: &Apache::lonnet::auto_photo_permission($unam,$udom);
3248: if ($result eq 'ok') {
3249: if (!($perm_reqd eq 'yes')) {
3250: return(&retrievestudentphoto($udom,$unam,$ext));
3251: }
3252: }
3253: }
3254: }
3255: } else {
3256: my ($result,$perm_reqd) =
3257: &Apache::lonnet::auto_photo_permission($unam,$udom);
3258: if ($result eq 'ok') {
3259: if (!($perm_reqd eq 'yes')) {
3260: return(&retrievestudentphoto($udom,$unam,$ext));
3261: }
3262: }
3263: }
3264: return '/adm/lonKaputt/lonlogo_broken.gif';
3265: }
3266:
3267: sub retrievestudentphoto {
3268: my ($udom,$unam,$ext,$type) = @_;
3269: my $home=&Apache::lonnet::homeserver($unam,$udom);
3270: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
3271: if ($ret eq 'ok') {
3272: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
3273: if ($type eq 'thumbnail') {
3274: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
3275: }
3276: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
3277: return $tokenurl;
3278: } else {
3279: if ($type eq 'thumbnail') {
3280: return '/adm/lonKaputt/genericstudent_tn.gif';
3281: } else {
3282: return '/adm/lonKaputt/lonlogo_broken.gif';
3283: }
3284: }
3285: }
3286:
3287: # -------------------------------------------------------------------- New chat
3288:
3289: sub chatsend {
3290: my ($newentry,$anon,$group)=@_;
3291: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
3292: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3293: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
3294: &reply('chatsend:'.$cdom.':'.$cnum.':'.
3295: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
3296: &escape($newentry)).':'.$group,$chome);
3297: }
3298:
3299: # ------------------------------------------ Find current version of a resource
3300:
3301: sub getversion {
3302: my $fname=&clutter(shift);
3303: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
3304: return ¤tversion(&filelocation('',$fname));
3305: }
3306:
3307: sub currentversion {
3308: my $fname=shift;
3309: my $author=$fname;
3310: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3311: my ($udom,$uname)=split(/\//,$author);
3312: my $home=&homeserver($uname,$udom);
3313: if ($home eq 'no_host') {
3314: return -1;
3315: }
3316: my $answer=&reply("currentversion:$fname",$home);
3317: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3318: return -1;
3319: }
3320: return $answer;
3321: }
3322:
3323: #
3324: # Return special version number of resource if set by override, empty otherwise
3325: #
3326: sub usedversion {
3327: my $fname=shift;
3328: unless ($fname) { $fname=$env{'request.uri'}; }
3329: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
3330: if ($urlversion) { return $urlversion; }
3331: return '';
3332: }
3333:
3334: # ----------------------------- Subscribe to a resource, return URL if possible
3335:
3336: sub subscribe {
3337: my $fname=shift;
3338: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
3339: $fname=~s/[\n\r]//g;
3340: my $author=$fname;
3341: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3342: my ($udom,$uname)=split(/\//,$author);
3343: my $home=homeserver($uname,$udom);
3344: if ($home eq 'no_host') {
3345: return 'not_found';
3346: }
3347: my $answer=reply("sub:$fname",$home);
3348: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3349: $answer.=' by '.$home;
3350: }
3351: return $answer;
3352: }
3353:
3354: # -------------------------------------------------------------- Replicate file
3355:
3356: sub repcopy {
3357: my $filename=shift;
3358: $filename=~s/\/+/\//g;
3359: my $londocroot = $perlvar{'lonDocRoot'};
3360: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
3361: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
3362: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3363: $filename=~m{^/*(uploaded|editupload)/}) {
3364: return &repcopy_userfile($filename);
3365: }
3366: $filename=~s/[\n\r]//g;
3367: my $transname="$filename.in.transfer";
3368: # FIXME: this should flock
3369: if ((-e $filename) || (-e $transname)) { return 'ok'; }
3370: my $remoteurl=subscribe($filename);
3371: if ($remoteurl =~ /^con_lost by/) {
3372: &logthis("Subscribe returned $remoteurl: $filename");
3373: return 'unavailable';
3374: } elsif ($remoteurl eq 'not_found') {
3375: #&logthis("Subscribe returned not_found: $filename");
3376: return 'not_found';
3377: } elsif ($remoteurl =~ /^rejected by/) {
3378: &logthis("Subscribe returned $remoteurl: $filename");
3379: return 'forbidden';
3380: } elsif ($remoteurl eq 'directory') {
3381: return 'ok';
3382: } else {
3383: my $author=$filename;
3384: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3385: my ($udom,$uname)=split(/\//,$author);
3386: my $home=homeserver($uname,$udom);
3387: unless ($home eq $perlvar{'lonHostID'}) {
3388: my @parts=split(/\//,$filename);
3389: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
3390: if ($path ne "$londocroot/res") {
3391: &logthis("Malconfiguration for replication: $filename");
3392: return 'bad_request';
3393: }
3394: my $count;
3395: for ($count=5;$count<$#parts;$count++) {
3396: $path.="/$parts[$count]";
3397: if ((-e $path)!=1) {
3398: mkdir($path,0777);
3399: }
3400: }
3401: my $request=new HTTP::Request('GET',"$remoteurl");
3402: my $response;
3403: if ($remoteurl =~ m{/raw/}) {
3404: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
3405: } else {
3406: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
3407: }
3408: if ($response->is_error()) {
3409: unlink($transname);
3410: my $message=$response->status_line;
3411: &logthis("<font color=\"blue\">WARNING:"
3412: ." LWP get: $message: $filename</font>");
3413: return 'unavailable';
3414: } else {
3415: if ($remoteurl!~/\.meta$/) {
3416: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
3417: my $mresponse;
3418: if ($remoteurl =~ m{/raw/}) {
3419: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
3420: } else {
3421: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
3422: }
3423: if ($mresponse->is_error()) {
3424: unlink($filename.'.meta');
3425: &logthis(
3426: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
3427: }
3428: }
3429: rename($transname,$filename);
3430: return 'ok';
3431: }
3432: }
3433: }
3434: }
3435:
3436: # ------------------------------------------------- Unsubscribe from a resource
3437:
3438: sub unsubscribe {
3439: my ($fname) = @_;
3440: my $answer;
3441: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
3442: $fname=~s/[\n\r]//g;
3443: my $author=$fname;
3444: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3445: my ($udom,$uname)=split(/\//,$author);
3446: my $home=homeserver($uname,$udom);
3447: if ($home eq 'no_host') {
3448: $answer = 'no_host';
3449: } elsif (grep { $_ eq $home } ¤t_machine_ids()) {
3450: $answer = 'home';
3451: } else {
3452: my $defdom = $perlvar{'lonDefDomain'};
3453: if (&will_trust('content',$defdom,$udom)) {
3454: $answer = reply("unsub:$fname",$home);
3455: } else {
3456: $answer = 'untrusted';
3457: }
3458: }
3459: return $answer;
3460: }
3461:
3462: # ------------------------------------------------ Get server side include body
3463: sub ssi_body {
3464: my ($filelink,%form)=@_;
3465: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3466: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3467: }
3468: my $output='';
3469: my $response;
3470: if ($filelink=~/^https?\:/) {
3471: ($output,$response)=&externalssi($filelink);
3472: } else {
3473: $filelink .= $filelink=~/\?/ ? '&' : '?';
3474: $filelink .= 'inhibitmenu=yes';
3475: ($output,$response)=&ssi($filelink,%form);
3476: }
3477: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
3478: $output=~s/^.*?\<body[^\>]*\>//si;
3479: $output=~s/\<\/body\s*\>.*?$//si;
3480: if (wantarray) {
3481: return ($output, $response);
3482: } else {
3483: return $output;
3484: }
3485: }
3486:
3487: # --------------------------------------------------------- Server Side Include
3488:
3489: sub absolute_url {
3490: my ($host_name,$unalias,$keep_proto) = @_;
3491: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3492: if ($host_name eq '') {
3493: $host_name = $ENV{'SERVER_NAME'};
3494: }
3495: if ($unalias) {
3496: my $alias = &get_proxy_alias();
3497: if ($alias eq $host_name) {
3498: my $lonhost = $perlvar{'lonHostID'};
3499: my $hostname = &hostname($lonhost);
3500: my $lcproto;
3501: if (($keep_proto) || ($hostname eq '')) {
3502: $lcproto = $protocol;
3503: } else {
3504: $lcproto = $protocol{$lonhost};
3505: $lcproto = 'http' if ($lcproto ne 'https');
3506: $lcproto .= '://';
3507: }
3508: unless ($hostname eq '') {
3509: return $lcproto.$hostname;
3510: }
3511: }
3512: }
3513: return $protocol.$host_name;
3514: }
3515:
3516: #
3517: # Server side include.
3518: # Parameters:
3519: # fn Possibly encrypted resource name/id.
3520: # form Hash that describes how the rendering should be done
3521: # and other things.
3522: # Returns:
3523: # Scalar context: The content of the response.
3524: # Array context: 2 element list of the content and the full response object.
3525: #
3526: sub ssi {
3527:
3528: my ($fn,%form)=@_;
3529: my ($host,$request,$response);
3530: $host = &absolute_url('',1);
3531:
3532: $form{'no_update_last_known'}=1;
3533: &Apache::lonenc::check_encrypt(\$fn);
3534: if (%form) {
3535: $request=new HTTP::Request('POST',$host.$fn);
3536: $request->content(join('&',map {
3537: my $name = escape($_);
3538: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3539: ? join("&$name=", map {escape($_) } @{$form{$_}})
3540: : &escape($form{$_}) );
3541: } keys(%form)));
3542: } else {
3543: $request=new HTTP::Request('GET',$host.$fn);
3544: }
3545:
3546: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
3547: my $lonhost = $perlvar{'lonHostID'};
3548: my $islocal;
3549: if (($env{'request.course.id'}) &&
3550: ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
3551: ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
3552: ($form{'grade_symb'} ne '') &&
3553: (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
3554: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
3555: $islocal = 1;
3556: }
3557: $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
3558: '','','',$islocal);
3559:
3560: if (wantarray) {
3561: return ($response->content, $response);
3562: } else {
3563: return $response->content;
3564: }
3565: }
3566:
3567: sub externalssi {
3568: my ($url)=@_;
3569: my $request=new HTTP::Request('GET',$url);
3570: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
3571: if (wantarray) {
3572: return ($response->content, $response);
3573: } else {
3574: return $response->content;
3575: }
3576: }
3577:
3578:
3579: # If the local copy of a replicated resource is outdated, trigger a
3580: # connection from the homeserver to flush the delayed queue. If no update
3581: # happens, remove local copies of outdated resource (and corresponding
3582: # metadata file).
3583:
3584: sub remove_stale_resfile {
3585: my ($url) = @_;
3586: my $removed;
3587: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3588: my $audom = $1;
3589: my $auname = $2;
3590: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
3591: my $homeserver = &homeserver($auname,$audom);
3592: unless (($homeserver eq 'no_host') ||
3593: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3594: my $fname = &filelocation('',$url);
3595: if (-e $fname) {
3596: my $hostname = &hostname($homeserver);
3597: if ($hostname) {
3598: my $protocol = $protocol{$homeserver};
3599: $protocol = 'http' if ($protocol ne 'https');
3600: my $uri = &declutter($url);
3601: my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
3602: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
3603: if ($response->is_success()) {
3604: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3605: my $locmodtime = (stat($fname))[9];
3606: if ($locmodtime < $remmodtime) {
3607: my $stale;
3608: my $answer = &reply('pong',$homeserver);
3609: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3610: sleep(0.2);
3611: $locmodtime = (stat($fname))[9];
3612: if ($locmodtime < $remmodtime) {
3613: my $posstransfer = $fname.'.in.transfer';
3614: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3615: $removed = 1;
3616: } else {
3617: $stale = 1;
3618: }
3619: } else {
3620: $removed = 1;
3621: }
3622: } else {
3623: $stale = 1;
3624: }
3625: if ($stale) {
3626: if (unlink($fname)) {
3627: if ($uri!~/\.meta$/) {
3628: if (-e $fname.'.meta') {
3629: unlink($fname.'.meta');
3630: }
3631: }
3632: my $unsubresult = &unsubscribe($fname);
3633: unless ($unsubresult eq 'ok') {
3634: &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
3635: }
3636: $removed = 1;
3637: }
3638: }
3639: }
3640: }
3641: }
3642: }
3643: }
3644: }
3645: }
3646: return $removed;
3647: }
3648:
3649: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3650:
3651: sub allowuploaded {
3652: my ($srcurl,$url)=@_;
3653: $url=&clutter(&declutter($url));
3654: my $dir=$url;
3655: $dir=~s/\/[^\/]+$//;
3656: my %httpref=();
3657: my $httpurl=&hreflocation('',$url);
3658: $httpref{'httpref.'.$httpurl}=$srcurl;
3659: &Apache::lonnet::appenv(\%httpref);
3660: }
3661:
3662: #
3663: # Determine if the current user should be able to edit a particular resource,
3664: # when viewing in course context.
3665: # (a) When viewing resource used to determine if "Edit" item is included in
3666: # Functions.
3667: # (b) When displaying folder contents in course editor, used to determine if
3668: # "Edit" link will be displayed alongside resource.
3669: #
3670: # input: six args -- filename (decluttered), course number, course domain,
3671: # url, symb (if registered) and group (if this is a group
3672: # item -- e.g., bulletin board, group page etc.).
3673: # output: array of five scalars --
3674: # $cfile -- url for file editing if editable on current server
3675: # $home -- homeserver of resource (i.e., for author if published,
3676: # or course if uploaded.).
3677: # $switchserver -- 1 if server switch will be needed.
3678: # $forceedit -- 1 if icon/link should be to go to edit mode
3679: # $forceview -- 1 if icon/link should be to go to view mode
3680: #
3681:
3682: sub can_edit_resource {
3683: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3684: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3685: #
3686: # For aboutme pages user can only edit his/her own.
3687: #
3688: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
3689: my ($sdom,$sname) = ($1,$2);
3690: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3691: $home = $env{'user.home'};
3692: $cfile = $resurl;
3693: if ($env{'form.forceedit'}) {
3694: $forceview = 1;
3695: } else {
3696: $forceedit = 1;
3697: }
3698: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3699: } else {
3700: return;
3701: }
3702: }
3703:
3704: if ($env{'request.course.id'}) {
3705: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3706: if ($group ne '') {
3707: # if this is a group homepage or group bulletin board, check group privs
3708: my $allowed = 0;
3709: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3710: if ((&allowed('mdg',$env{'request.course.id'}.
3711: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3712: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3713: $allowed = 1;
3714: }
3715: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3716: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3717: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3718: $allowed = 1;
3719: }
3720: }
3721: if ($allowed) {
3722: $home=&homeserver($cnum,$cdom);
3723: if ($env{'form.forceedit'}) {
3724: $forceview = 1;
3725: } else {
3726: $forceedit = 1;
3727: }
3728: $cfile = $resurl;
3729: } else {
3730: return;
3731: }
3732: } else {
3733: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3734: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3735: return;
3736: }
3737: } elsif (!$crsedit) {
3738: #
3739: # No edit allowed where CC has switched to student role.
3740: #
3741: return;
3742: }
3743: }
3744: }
3745:
3746: if ($file ne '') {
3747: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
3748: if (&is_course_upload($file,$cnum,$cdom)) {
3749: $uploaded = 1;
3750: $incourse = 1;
3751: if ($file =~/\.(htm|html|css|js|txt)$/) {
3752: $cfile = &hreflocation('',$file);
3753: if ($env{'form.forceedit'}) {
3754: $forceview = 1;
3755: } else {
3756: $forceedit = 1;
3757: }
3758: }
3759: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3760: $incourse = 1;
3761: if ($env{'form.forceedit'}) {
3762: $forceview = 1;
3763: } else {
3764: $forceedit = 1;
3765: }
3766: $cfile = $resurl;
3767: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3768: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3769: $incourse = 1;
3770: if ($env{'form.forceedit'}) {
3771: $forceview = 1;
3772: } else {
3773: $forceedit = 1;
3774: }
3775: $cfile = $resurl;
3776: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
3777: $incourse = 1;
3778: $cfile = $resurl.'/smpedit';
3779: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
3780: $incourse = 1;
3781: if ($env{'form.forceedit'}) {
3782: $forceview = 1;
3783: } else {
3784: $forceedit = 1;
3785: }
3786: $cfile = $resurl;
3787: } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
3788: my ($map,$id,$res) = &decode_symb($symb);
3789: if ($map =~ /\.page$/) {
3790: $incourse = 1;
3791: if ($env{'form.forceedit'}) {
3792: $forceview = 1;
3793: $cfile = $map;
3794: } else {
3795: $forceedit = 1;
3796: $cfile = '/adm/wrapper'.$resurl;
3797: }
3798: }
3799: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
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/viewclasslist$}) {
3808: $incourse = 1;
3809: if ($env{'form.forceedit'}) {
3810: $forceview = 1;
3811: } else {
3812: $forceedit = 1;
3813: }
3814: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
3815: }
3816: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3817: my $template = '/res/lib/templates/simpleproblem.problem';
3818: if (&is_on_map($template)) {
3819: $incourse = 1;
3820: $forceview = 1;
3821: $cfile = $template;
3822: }
3823: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3824: $incourse = 1;
3825: if ($env{'form.forceedit'}) {
3826: $forceview = 1;
3827: } else {
3828: $forceedit = 1;
3829: }
3830: $cfile = $resurl;
3831: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3832: $incourse = 1;
3833: if ($env{'form.forceedit'}) {
3834: $forceview = 1;
3835: } else {
3836: $forceedit = 1;
3837: }
3838: $cfile = $resurl;
3839: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3840: $incourse = 1;
3841: $forceview = 1;
3842: if ($symb) {
3843: my ($map,$id,$res)=&decode_symb($symb);
3844: $env{'request.symb'} = $symb;
3845: $cfile = &clutter($res);
3846: } else {
3847: $cfile = $env{'form.suppurl'};
3848: my $escfile = &unescape($cfile);
3849: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
3850: $cfile = '/adm/wrapper'.$escfile;
3851: } else {
3852: $escfile =~ s{^http://}{};
3853: $cfile = &escape("/adm/wrapper/ext/$escfile");
3854: }
3855: }
3856: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3857: if ($env{'form.forceedit'}) {
3858: $forceview = 1;
3859: } else {
3860: $forceedit = 1;
3861: }
3862: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
3863: }
3864: }
3865: if ($uploaded || $incourse) {
3866: $home=&homeserver($cnum,$cdom);
3867: } elsif ($file !~ m{/$}) {
3868: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3869: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3870: # Check that the user has permission to edit this resource
3871: my $setpriv = 1;
3872: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3873: if (defined($cfudom)) {
3874: $home=&homeserver($cfuname,$cfudom);
3875: $cfile=$file;
3876: }
3877: }
3878: if (($cfile ne '') && (!$incourse || $uploaded) &&
3879: (($home ne '') && ($home ne 'no_host'))) {
3880: my @ids=¤t_machine_ids();
3881: unless (grep(/^\Q$home\E$/,@ids)) {
3882: $switchserver=1;
3883: }
3884: }
3885: }
3886: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3887: }
3888:
3889: sub is_course_upload {
3890: my ($file,$cnum,$cdom) = @_;
3891: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3892: $uploadpath =~ s{^\/}{};
3893: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3894: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3895: return 1;
3896: }
3897: return;
3898: }
3899:
3900: sub in_course {
3901: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3902: if ($hideprivileged) {
3903: my $skipuser;
3904: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3905: my @possdoms = ($cdom);
3906: if ($coursehash{'checkforpriv'}) {
3907: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3908: }
3909: if (&privileged($uname,$udom,\@possdoms)) {
3910: $skipuser = 1;
3911: if ($coursehash{'nothideprivileged'}) {
3912: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3913: my $user;
3914: if ($item =~ /:/) {
3915: $user = $item;
3916: } else {
3917: $user = join(':',split(/[\@]/,$item));
3918: }
3919: if ($user eq $uname.':'.$udom) {
3920: undef($skipuser);
3921: last;
3922: }
3923: }
3924: }
3925: if ($skipuser) {
3926: return 0;
3927: }
3928: }
3929: }
3930: $type ||= 'any';
3931: if (!defined($cdom) || !defined($cnum)) {
3932: my $cid = $env{'request.course.id'};
3933: $cdom = $env{'course.'.$cid.'.domain'};
3934: $cnum = $env{'course.'.$cid.'.num'};
3935: }
3936: my $typesref;
3937: if (($type eq 'any') || ($type eq 'all')) {
3938: $typesref = ['active','previous','future'];
3939: } elsif ($type eq 'previous' || $type eq 'future') {
3940: $typesref = [$type];
3941: }
3942: my %roles = &get_my_roles($uname,$udom,'userroles',
3943: $typesref,undef,[$cdom]);
3944: my ($tmp) = keys(%roles);
3945: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3946: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3947: if (@course_roles > 0) {
3948: return 1;
3949: }
3950: return 0;
3951: }
3952:
3953: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
3954: # input: action, courseID, current domain, intended
3955: # path to file, source of file, instruction to parse file for objects,
3956: # ref to hash for embedded objects,
3957: # ref to hash for codebase of java objects.
3958: # reference to scalar to accommodate mime type determined
3959: # from File::MMagic if $parser = parse.
3960: #
3961: # output: url to file (if action was uploaddoc),
3962: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
3963: #
3964: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3965: # course.
3966: #
3967: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3968: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3969: # course's home server.
3970: #
3971: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3972: # be copied from $source (current location) to
3973: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3974: # and will then be copied to
3975: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3976: # course's home server.
3977: #
3978: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3979: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
3980: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3981: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3982: # in course's home server.
3983: #
3984:
3985: sub process_coursefile {
3986: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3987: $mimetype)=@_;
3988: my $fetchresult;
3989: my $home=&homeserver($docuname,$docudom);
3990: if ($action eq 'propagate') {
3991: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3992: $home);
3993: } else {
3994: my $fpath = '';
3995: my $fname = $file;
3996: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3997: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3998: my $filepath = &build_filepath($fpath);
3999: if ($action eq 'copy') {
4000: if ($source eq '') {
4001: $fetchresult = 'no source file';
4002: return $fetchresult;
4003: } else {
4004: my $destination = $filepath.'/'.$fname;
4005: rename($source,$destination);
4006: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
4007: $home);
4008: }
4009: } elsif ($action eq 'uploaddoc') {
4010: open(my $fh,'>',$filepath.'/'.$fname);
4011: print $fh $env{'form.'.$source};
4012: close($fh);
4013: if ($parser eq 'parse') {
4014: my $mm = new File::MMagic;
4015: my $type = $mm->checktype_filename($filepath.'/'.$fname);
4016: if ($type eq 'text/html') {
4017: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
4018: unless ($parse_result eq 'ok') {
4019: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
4020: }
4021: }
4022: if (ref($mimetype)) {
4023: $$mimetype = $type;
4024: }
4025: }
4026: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
4027: $home);
4028: if ($fetchresult eq 'ok') {
4029: return '/uploaded/'.$fpath.'/'.$fname;
4030: } else {
4031: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
4032: ' to host '.$home.': '.$fetchresult);
4033: return '/adm/notfound.html';
4034: }
4035: }
4036: }
4037: unless ( $fetchresult eq 'ok') {
4038: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
4039: ' to host '.$home.': '.$fetchresult);
4040: }
4041: return $fetchresult;
4042: }
4043:
4044: sub build_filepath {
4045: my ($fpath) = @_;
4046: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
4047: unless ($fpath eq '') {
4048: my @parts=split('/',$fpath);
4049: foreach my $part (@parts) {
4050: $filepath.= '/'.$part;
4051: if ((-e $filepath)!=1) {
4052: mkdir($filepath,0777);
4053: }
4054: }
4055: }
4056: return $filepath;
4057: }
4058:
4059: sub store_edited_file {
4060: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
4061: my $file = $primary_url;
4062: $file =~ s#^/uploaded/$docudom/$docuname/##;
4063: my $fpath = '';
4064: my $fname = $file;
4065: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
4066: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
4067: my $filepath = &build_filepath($fpath);
4068: open(my $fh,'>',$filepath.'/'.$fname);
4069: print $fh $content;
4070: close($fh);
4071: my $home=&homeserver($docuname,$docudom);
4072: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
4073: $home);
4074: if ($$fetchresult eq 'ok') {
4075: return '/uploaded/'.$fpath.'/'.$fname;
4076: } else {
4077: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
4078: ' to host '.$home.': '.$$fetchresult);
4079: return '/adm/notfound.html';
4080: }
4081: }
4082:
4083: sub clean_filename {
4084: my ($fname,$args)=@_;
4085: # Replace Windows backslashes by forward slashes
4086: $fname=~s/\\/\//g;
4087: if (!$args->{'keep_path'}) {
4088: # Get rid of everything but the actual filename
4089: $fname=~s/^.*\/([^\/]+)$/$1/;
4090: }
4091: # Replace spaces by underscores
4092: $fname=~s/\s+/\_/g;
4093: # Transliterate non-ascii text to ascii
4094: my $lang = &Apache::lonlocal::current_language();
4095: $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
4096: # Replace all other weird characters by nothing
4097: $fname=~s{[^/\w\.\-]}{}g;
4098: # Replace all .\d. sequences with _\d. so they no longer look like version
4099: # numbers
4100: $fname=~s/\.(\d+)(?=\.)/_$1/g;
4101: # Replace three or more adjacent underscores with one for consistency
4102: # with loncfile::filename_check() so complete url can be extracted by
4103: # lonnet::decode_symb()
4104: $fname=~s/_{3,}/_/g;
4105: return $fname;
4106: }
4107:
4108: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
4109: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
4110: # image with the same aspect ratio as the original, but with dimensions which do
4111: # not exceed $resizewidth and $resizeheight.
4112:
4113: sub resizeImage {
4114: my ($img_path,$resizewidth,$resizeheight) = @_;
4115: my $ima = Image::Magick->new;
4116: my $resized;
4117: if (-e $img_path) {
4118: $ima->Read($img_path);
4119: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
4120: my $width = $ima->Get('width');
4121: my $height = $ima->Get('height');
4122: if ($width > $resizewidth) {
4123: my $factor = $width/$resizewidth;
4124: my $newheight = $height/$factor;
4125: $ima->Scale(width=>$resizewidth,height=>$newheight);
4126: $resized = 1;
4127: }
4128: }
4129: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
4130: my $width = $ima->Get('width');
4131: my $height = $ima->Get('height');
4132: if ($height > $resizeheight) {
4133: my $factor = $height/$resizeheight;
4134: my $newwidth = $width/$factor;
4135: $ima->Scale(width=>$newwidth,height=>$resizeheight);
4136: $resized = 1;
4137: }
4138: }
4139: if ($resized) {
4140: $ima->Write($img_path);
4141: }
4142: }
4143: return;
4144: }
4145:
4146: # --------------- Take an uploaded file and put it into the userfiles directory
4147: # input: $formname - the contents of the file are in $env{"form.$formname"}
4148: # the desired filename is in $env{"form.$formname.filename"}
4149: # $context - possible values: coursedoc, existingfile, overwrite,
4150: # canceloverwrite, scantron or ''.
4151: # if 'coursedoc': upload to the current course
4152: # if 'existingfile': write file to tmp/overwrites directory
4153: # if 'canceloverwrite': delete file written to tmp/overwrites directory
4154: # $context is passed as argument to &finishuserfileupload
4155: # $subdir - directory in userfile to store the file into
4156: # $parser - instruction to parse file for objects ($parser = parse) or
4157: # if context is 'scantron', $parser is hashref of csv column mapping
4158: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
4159: # Section => 4, CODE => 5, FirstQuestion => 9 }).
4160: # $allfiles - reference to hash for embedded objects
4161: # $codebase - reference to hash for codebase of java objects
4162: # $desuname - username for permanent storage of uploaded file
4163: # $dsetudom - domain for permanaent storage of uploaded file
4164: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
4165: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
4166: # $resizewidth - width (pixels) to which to resize uploaded image
4167: # $resizeheight - height (pixels) to which to resize uploaded image
4168: # $mimetype - reference to scalar to accommodate mime type determined
4169: # from File::MMagic.
4170: #
4171: # output: url of file in userspace, or error: <message>
4172: # or /adm/notfound.html if failure to upload occurse
4173:
4174: sub userfileupload {
4175: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
4176: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
4177: if (!defined($subdir)) { $subdir='unknown'; }
4178: my $fname=$env{'form.'.$formname.'.filename'};
4179: $fname=&clean_filename($fname);
4180: # See if there is anything left
4181: unless ($fname) { return 'error: no uploaded file'; }
4182: # If filename now begins with a . prepend unix timestamp _ milliseconds
4183: if ($fname =~ /^\./) {
4184: my ($s,$usec) = &gettimeofday();
4185: while (length($usec) < 6) {
4186: $usec = '0'.$usec;
4187: }
4188: $fname = $s.'_'.substr($usec,0,3).$fname;
4189: }
4190: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
4191: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
4192: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
4193: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
4194: my $now = time;
4195: my $filepath;
4196: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
4197: $filepath = 'tmp/helprequests/'.$now;
4198: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
4199: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
4200: '_'.$env{'user.domain'}.'/pending';
4201: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
4202: my ($docuname,$docudom);
4203: if ($destudom =~ /^$match_domain$/) {
4204: $docudom = $destudom;
4205: } else {
4206: $docudom = $env{'user.domain'};
4207: }
4208: if ($destuname =~ /^$match_username$/) {
4209: $docuname = $destuname;
4210: } else {
4211: $docuname = $env{'user.name'};
4212: }
4213: if (exists($env{'form.group'})) {
4214: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4215: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4216: }
4217: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
4218: if ($context eq 'canceloverwrite') {
4219: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
4220: if (-e $tempfile) {
4221: my @info = stat($tempfile);
4222: if ($info[9] eq $env{'form.timestamp'}) {
4223: unlink($tempfile);
4224: }
4225: }
4226: return;
4227: }
4228: }
4229: # Create the directory if not present
4230: my @parts=split(/\//,$filepath);
4231: my $fullpath = $perlvar{'lonDaemons'};
4232: for (my $i=0;$i<@parts;$i++) {
4233: $fullpath .= '/'.$parts[$i];
4234: if ((-e $fullpath)!=1) {
4235: mkdir($fullpath,0777);
4236: }
4237: }
4238: open(my $fh,'>',$fullpath.'/'.$fname);
4239: print $fh $env{'form.'.$formname};
4240: close($fh);
4241: if ($context eq 'existingfile') {
4242: my @info = stat($fullpath.'/'.$fname);
4243: return ($fullpath.'/'.$fname,$info[9]);
4244: } else {
4245: return $fullpath.'/'.$fname;
4246: }
4247: }
4248: if ($subdir eq 'scantron') {
4249: $fname = 'scantron_orig_'.$fname;
4250: } else {
4251: $fname="$subdir/$fname";
4252: }
4253: if ($context eq 'coursedoc') {
4254: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4255: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4256: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
4257: return &finishuserfileupload($docuname,$docudom,
4258: $formname,$fname,$parser,$allfiles,
4259: $codebase,$thumbwidth,$thumbheight,
4260: $resizewidth,$resizeheight,$context,$mimetype);
4261: } else {
4262: if ($env{'form.folder'}) {
4263: $fname=$env{'form.folder'}.'/'.$fname;
4264: }
4265: return &process_coursefile('uploaddoc',$docuname,$docudom,
4266: $fname,$formname,$parser,
4267: $allfiles,$codebase,$mimetype);
4268: }
4269: } elsif (defined($destuname)) {
4270: my $docuname=$destuname;
4271: my $docudom=$destudom;
4272: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4273: $parser,$allfiles,$codebase,
4274: $thumbwidth,$thumbheight,
4275: $resizewidth,$resizeheight,$context,$mimetype);
4276: } else {
4277: my $docuname=$env{'user.name'};
4278: my $docudom=$env{'user.domain'};
4279: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
4280: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4281: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4282: }
4283: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4284: $parser,$allfiles,$codebase,
4285: $thumbwidth,$thumbheight,
4286: $resizewidth,$resizeheight,$context,$mimetype);
4287: }
4288: }
4289:
4290: sub finishuserfileupload {
4291: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
4292: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
4293: my $path=$docudom.'/'.$docuname.'/';
4294: my $filepath=$perlvar{'lonDocRoot'};
4295:
4296: my ($fnamepath,$file,$fetchthumb);
4297: $file=$fname;
4298: if ($fname=~m|/|) {
4299: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
4300: $path.=$fnamepath.'/';
4301: }
4302: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
4303: my $count;
4304: for ($count=4;$count<=$#parts;$count++) {
4305: $filepath.="/$parts[$count]";
4306: if ((-e $filepath)!=1) {
4307: mkdir($filepath,0777);
4308: }
4309: }
4310:
4311: # Save the file
4312: {
4313: if (!open(FH,'>',$filepath.'/'.$file)) {
4314: &logthis('Failed to create '.$filepath.'/'.$file);
4315: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
4316: return '/adm/notfound.html';
4317: }
4318: if ($context eq 'overwrite') {
4319: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
4320: my $target = $filepath.'/'.$file;
4321: if (-e $source) {
4322: my @info = stat($source);
4323: if ($info[9] eq $env{'form.timestamp'}) {
4324: unless (&File::Copy::move($source,$target)) {
4325: &logthis('Failed to overwrite '.$filepath.'/'.$file);
4326: return "Moving from $source failed";
4327: }
4328: } else {
4329: return "Temporary file: $source had unexpected date/time for last modification";
4330: }
4331: } else {
4332: return "Temporary file: $source missing";
4333: }
4334: } elsif (!print FH ($env{'form.'.$formname})) {
4335: &logthis('Failed to write to '.$filepath.'/'.$file);
4336: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
4337: return '/adm/notfound.html';
4338: }
4339: close(FH);
4340: if ($resizewidth && $resizeheight) {
4341: my $mm = new File::MMagic;
4342: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
4343: if ($mime_type =~ m{^image/}) {
4344: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
4345: }
4346: }
4347: }
4348: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
4349: if (ref($mimetype)) {
4350: if ($$mimetype eq '') {
4351: my $mm = new File::MMagic;
4352: my $type = $mm->checktype_filename($filepath.'/'.$file);
4353: $$mimetype = $type;
4354: }
4355: }
4356: }
4357: if (($context ne 'scantron') && ($parser eq 'parse')) {
4358: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
4359: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
4360: $allfiles,$codebase);
4361: unless ($parse_result eq 'ok') {
4362: &logthis('Failed to parse '.$filepath.$file.
4363: ' for embedded media: '.$parse_result);
4364: }
4365: }
4366: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
4367: my $format = $env{'form.scantron_format'};
4368: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
4369: }
4370: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
4371: my $input = $filepath.'/'.$file;
4372: my $output = $filepath.'/'.'tn-'.$file;
4373: my $thumbsize = $thumbwidth.'x'.$thumbheight;
4374: my @args = ('convert','-sample',$thumbsize,$input,$output);
4375: system({$args[0]} @args);
4376: if (-e $filepath.'/'.'tn-'.$file) {
4377: $fetchthumb = 1;
4378: }
4379: }
4380:
4381: # Notify homeserver to grep it
4382: #
4383: my $docuhome=&homeserver($docuname,$docudom);
4384: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
4385: if ($fetchresult eq 'ok') {
4386: if ($fetchthumb) {
4387: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
4388: if ($thumbresult ne 'ok') {
4389: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
4390: $docuhome.': '.$thumbresult);
4391: }
4392: }
4393: #
4394: # Return the URL to it
4395: return '/uploaded/'.$path.$file;
4396: } else {
4397: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
4398: ': '.$fetchresult);
4399: return '/adm/notfound.html';
4400: }
4401: }
4402:
4403: sub extract_embedded_items {
4404: my ($fullpath,$allfiles,$codebase,$content) = @_;
4405: my @state = ();
4406: my (%lastids,%related,%shockwave,%flashvars);
4407: my %javafiles = (
4408: codebase => '',
4409: code => '',
4410: archive => ''
4411: );
4412: my %mediafiles = (
4413: src => '',
4414: movie => '',
4415: );
4416: my $p;
4417: if ($content) {
4418: $p = HTML::LCParser->new($content);
4419: } else {
4420: $p = HTML::LCParser->new($fullpath);
4421: }
4422: while (my $t=$p->get_token()) {
4423: if ($t->[0] eq 'S') {
4424: my ($tagname, $attr) = ($t->[1],$t->[2]);
4425: push(@state, $tagname);
4426: if (lc($tagname) eq 'allow') {
4427: &add_filetype($allfiles,$attr->{'src'},'src');
4428: }
4429: if (lc($tagname) eq 'img') {
4430: &add_filetype($allfiles,$attr->{'src'},'src');
4431: }
4432: if (lc($tagname) eq 'a') {
4433: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
4434: &add_filetype($allfiles,$attr->{'href'},'href');
4435: }
4436: }
4437: if (lc($tagname) eq 'script') {
4438: my $src;
4439: if ($attr->{'archive'} =~ /\.jar$/i) {
4440: &add_filetype($allfiles,$attr->{'archive'},'archive');
4441: } else {
4442: if ($attr->{'src'} ne '') {
4443: $src = $attr->{'src'};
4444: &add_filetype($allfiles,$src,'src');
4445: }
4446: }
4447: my $text = $p->get_trimmed_text();
4448: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4449: my @swfargs = split(/,/,$1);
4450: foreach my $item (@swfargs) {
4451: $item =~ s/["']//g;
4452: $item =~ s/^\s+//;
4453: $item =~ s/\s+$//;
4454: }
4455: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4456: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4457: push(@{$related{$swfargs[0]}},$swfargs[2]);
4458: } else {
4459: $related{$swfargs[0]} = [$swfargs[2]];
4460: }
4461: }
4462: }
4463: }
4464: if (lc($tagname) eq 'link') {
4465: if (lc($attr->{'rel'}) eq 'stylesheet') {
4466: &add_filetype($allfiles,$attr->{'href'},'href');
4467: }
4468: }
4469: if (lc($tagname) eq 'object' ||
4470: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4471: foreach my $item (keys(%javafiles)) {
4472: $javafiles{$item} = '';
4473: }
4474: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4475: $lastids{lc($tagname)} = $attr->{'id'};
4476: }
4477: }
4478: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4479: my $name = lc($attr->{'name'});
4480: foreach my $item (keys(%javafiles)) {
4481: if ($name eq $item) {
4482: $javafiles{$item} = $attr->{'value'};
4483: last;
4484: }
4485: }
4486: my $pathfrom;
4487: foreach my $item (keys(%mediafiles)) {
4488: if ($name eq $item) {
4489: $pathfrom = $attr->{'value'};
4490: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4491: &add_filetype($allfiles,$pathfrom,$name);
4492: last;
4493: }
4494: }
4495: if ($name eq 'flashvars') {
4496: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4497: }
4498: if ($pathfrom ne '') {
4499: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4500: $pathfrom);
4501: }
4502: }
4503: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4504: foreach my $item (keys(%javafiles)) {
4505: if ($attr->{$item}) {
4506: $javafiles{$item} = $attr->{$item};
4507: last;
4508: }
4509: }
4510: foreach my $item (keys(%mediafiles)) {
4511: if ($attr->{$item}) {
4512: &add_filetype($allfiles,$attr->{$item},$item);
4513: last;
4514: }
4515: }
4516: if (lc($tagname) eq 'embed') {
4517: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4518: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4519: $attr->{'src'});
4520: }
4521: }
4522: }
4523: if (lc($tagname) eq 'iframe') {
4524: my $src = $attr->{'src'} ;
4525: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4526: &add_filetype($allfiles,$src,'src');
4527: } elsif ($src =~ m{^/}) {
4528: if ($env{'request.course.id'}) {
4529: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4530: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4531: my $url = &hreflocation('',$fullpath);
4532: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4533: my $relpath = $1;
4534: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4535: &add_filetype($allfiles,$1,'src');
4536: }
4537: }
4538: }
4539: }
4540: }
4541: if ($t->[4] =~ m{/>$}) {
4542: pop(@state);
4543: }
4544: } elsif ($t->[0] eq 'E') {
4545: my ($tagname) = ($t->[1]);
4546: if ($javafiles{'codebase'} ne '') {
4547: $javafiles{'codebase'} .= '/';
4548: }
4549: if (lc($tagname) eq 'applet' ||
4550: lc($tagname) eq 'object' ||
4551: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4552: ) {
4553: foreach my $item (keys(%javafiles)) {
4554: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4555: my $file=$javafiles{'codebase'}.$javafiles{$item};
4556: &add_filetype($allfiles,$file,$item);
4557: }
4558: }
4559: }
4560: pop @state;
4561: }
4562: }
4563: foreach my $id (sort(keys(%flashvars))) {
4564: if ($shockwave{$id} ne '') {
4565: my @pairs = split(/\&/,$flashvars{$id});
4566: foreach my $pair (@pairs) {
4567: my ($key,$value) = split(/\=/,$pair);
4568: if ($key eq 'thumb') {
4569: &add_filetype($allfiles,$value,$key);
4570: } elsif ($key eq 'content') {
4571: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4572: my ($ext) = ($value =~ /\.([^.]+)$/);
4573: if ($ext ne '') {
4574: &add_filetype($allfiles,$path.$value,$ext);
4575: }
4576: }
4577: }
4578: }
4579: }
4580: return 'ok';
4581: }
4582:
4583: sub add_filetype {
4584: my ($allfiles,$file,$type)=@_;
4585: if (exists($allfiles->{$file})) {
4586: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4587: push(@{$allfiles->{$file}}, &escape($type));
4588: }
4589: } else {
4590: @{$allfiles->{$file}} = (&escape($type));
4591: }
4592: }
4593:
4594: sub embedded_dependency {
4595: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4596: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4597: if (($identifier ne '') &&
4598: (ref($related->{$identifier}) eq 'ARRAY') &&
4599: ($pathfrom ne '')) {
4600: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4601: foreach my $dep (@{$related->{$identifier}}) {
4602: &add_filetype($allfiles,$path.$dep,'object');
4603: }
4604: }
4605: }
4606: return;
4607: }
4608:
4609: sub bubblesheet_converter {
4610: my ($cdom,$fullpath,$config,$format) = @_;
4611: if ((&domain($cdom) ne '') &&
4612: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
4613: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
4614: my (%csvcols,%csvoptions);
4615: if (ref($config->{'fields'}) eq 'HASH') {
4616: %csvcols = %{$config->{'fields'}};
4617: }
4618: if (ref($config->{'options'}) eq 'HASH') {
4619: %csvoptions = %{$config->{'options'}};
4620: }
4621: my %csvbynum = reverse(%csvcols);
4622: my %scantronconf = &get_scantron_config($format,$cdom);
4623: if (keys(%scantronconf)) {
4624: my %bynum = (
4625: $scantronconf{CODEstart} => 'CODEstart',
4626: $scantronconf{IDstart} => 'IDstart',
4627: $scantronconf{PaperID} => 'PaperID',
4628: $scantronconf{FirstName} => 'FirstName',
4629: $scantronconf{LastName} => 'LastName',
4630: $scantronconf{Qstart} => 'Qstart',
4631: );
4632: my @ordered;
4633: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
4634: push(@ordered,$bynum{$item});
4635: }
4636: my %mapstart = (
4637: CODEstart => 'CODE',
4638: IDstart => 'ID',
4639: PaperID => 'PaperID',
4640: FirstName => 'FirstName',
4641: LastName => 'LastName',
4642: Qstart => 'FirstQuestion',
4643: );
4644: my %maplength = (
4645: CODEstart => 'CODElength',
4646: IDstart => 'IDlength',
4647: PaperID => 'PaperIDlength',
4648: FirstName => 'FirstNamelength',
4649: LastName => 'LastNamelength',
4650: );
4651: if (open(my $fh,'<',$fullpath)) {
4652: my $output;
4653: my %lettdig = &letter_to_digits();
4654: my %diglett = reverse(%lettdig);
4655: my $numletts = scalar(keys(%lettdig));
4656: my $num = 0;
4657: while (my $line=<$fh>) {
4658: $num ++;
4659: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
4660: $line =~ s{[\r\n]+$}{};
4661: my %found;
4662: my @values = split(/,/,$line);
4663: my ($qstart,$record);
4664: for (my $i=0; $i<@values; $i++) {
4665: if ((($qstart ne '') && ($i > $qstart)) ||
4666: ($csvbynum{$i} eq 'FirstQuestion')) {
4667: if ($values[$i] eq '') {
4668: $values[$i] = $scantronconf{'Qoff'};
4669: } elsif ($scantronconf{'Qon'} eq 'number') {
4670: if ($values[$i] =~ /^[A-Ja-j]$/) {
4671: $values[$i] = $lettdig{uc($values[$i])};
4672: }
4673: } elsif ($scantronconf{'Qon'} eq 'letter') {
4674: if ($values[$i] =~ /^[0-9]$/) {
4675: $values[$i] = $diglett{$values[$i]};
4676: }
4677: } else {
4678: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4679: my $digit;
4680: if ($values[$i] =~ /^[A-Ja-j]$/) {
4681: $digit = $lettdig{uc($values[$i])}-1;
4682: if ($values[$i] eq 'J') {
4683: $digit += $numletts;
4684: }
4685: } elsif ($values[$i] =~ /^[0-9]$/) {
4686: $digit = $values[$i]-1;
4687: if ($values[$i] eq '0') {
4688: $digit += $numletts;
4689: }
4690: }
4691: my $qval='';
4692: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
4693: if ($j == $digit) {
4694: $qval .= $scantronconf{'Qon'};
4695: } else {
4696: $qval .= $scantronconf{'Qoff'};
4697: }
4698: }
4699: $values[$i] = $qval;
4700: }
4701: }
4702: if (length($values[$i]) > $scantronconf{'Qlength'}) {
4703: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
4704: }
4705: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
4706: if ($numblank > 0) {
4707: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
4708: }
4709: if ($csvbynum{$i} eq 'FirstQuestion') {
4710: $qstart = $i;
4711: $found{$csvbynum{$i}} = $values[$i];
4712: } else {
4713: $found{'FirstQuestion'} .= $values[$i];
4714: }
4715: } elsif (exists($csvbynum{$i})) {
4716: if ($csvoptions{'rem'}) {
4717: $values[$i] =~ s/^\s+//;
4718: }
4719: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
4720: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
4721: $values[$i] = '0'.$values[$i];
4722: }
4723: }
4724: $found{$csvbynum{$i}} = $values[$i];
4725: }
4726: }
4727: foreach my $item (@ordered) {
4728: my $currlength = 1+length($record);
4729: my $numspaces = $scantronconf{$item} - $currlength;
4730: if ($numspaces > 0) {
4731: $record .= (' ' x $numspaces);
4732: }
4733: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
4734: unless ($item eq 'Qstart') {
4735: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
4736: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
4737: }
4738: }
4739: $record .= $found{$mapstart{$item}};
4740: }
4741: }
4742: $output .= "$record\n";
4743: }
4744: close($fh);
4745: if ($output) {
4746: if (open(my $fh,'>',$fullpath)) {
4747: print $fh $output;
4748: close($fh);
4749: }
4750: }
4751: }
4752: }
4753: return;
4754: }
4755: }
4756:
4757: sub letter_to_digits {
4758: my %lettdig = (
4759: A => 1,
4760: B => 2,
4761: C => 3,
4762: D => 4,
4763: E => 5,
4764: F => 6,
4765: G => 7,
4766: H => 8,
4767: I => 9,
4768: J => 0,
4769: );
4770: return %lettdig;
4771: }
4772:
4773: sub get_scantron_config {
4774: my ($which,$cdom) = @_;
4775: my @lines = &get_scantronformat_file($cdom);
4776: my %config;
4777: #FIXME probably should move to XML it has already gotten a bit much now
4778: foreach my $line (@lines) {
4779: my ($name,$descrip)=split(/:/,$line);
4780: if ($name ne $which ) { next; }
4781: chomp($line);
4782: my @config=split(/:/,$line);
4783: $config{'name'}=$config[0];
4784: $config{'description'}=$config[1];
4785: $config{'CODElocation'}=$config[2];
4786: $config{'CODEstart'}=$config[3];
4787: $config{'CODElength'}=$config[4];
4788: $config{'IDstart'}=$config[5];
4789: $config{'IDlength'}=$config[6];
4790: $config{'Qstart'}=$config[7];
4791: $config{'Qlength'}=$config[8];
4792: $config{'Qoff'}=$config[9];
4793: $config{'Qon'}=$config[10];
4794: $config{'PaperID'}=$config[11];
4795: $config{'PaperIDlength'}=$config[12];
4796: $config{'FirstName'}=$config[13];
4797: $config{'FirstNamelength'}=$config[14];
4798: $config{'LastName'}=$config[15];
4799: $config{'LastNamelength'}=$config[16];
4800: $config{'BubblesPerRow'}=$config[17];
4801: last;
4802: }
4803: return %config;
4804: }
4805:
4806: sub get_scantronformat_file {
4807: my ($cdom) = @_;
4808: if ($cdom eq '') {
4809: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4810: }
4811: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4812: my $gottab = 0;
4813: my @lines;
4814: if (ref($domconfig{'scantron'}) eq 'HASH') {
4815: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4816: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4817: if ($formatfile ne '-1') {
4818: @lines = split("\n",$formatfile,-1);
4819: $gottab = 1;
4820: }
4821: }
4822: }
4823: if (!$gottab) {
4824: my $confname = $cdom.'-domainconfig';
4825: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4826: my $formatfile = &getfile($default);
4827: if ($formatfile ne '-1') {
4828: @lines = split("\n",$formatfile,-1);
4829: $gottab = 1;
4830: }
4831: }
4832: if (!$gottab) {
4833: my @domains = ¤t_machine_domains();
4834: if (grep(/^\Q$cdom\E$/,@domains)) {
4835: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
4836: @lines = <$fh>;
4837: close($fh);
4838: }
4839: } else {
4840: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
4841: @lines = <$fh>;
4842: close($fh);
4843: }
4844: }
4845: }
4846: return @lines;
4847: }
4848:
4849: sub removeuploadedurl {
4850: my ($url)=@_;
4851: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
4852: return &removeuserfile($uname,$udom,$fname);
4853: }
4854:
4855: sub removeuserfile {
4856: my ($docuname,$docudom,$fname)=@_;
4857: my $home=&homeserver($docuname,$docudom);
4858: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
4859: if ($result eq 'ok') {
4860: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4861: my $metafile = $fname.'.meta';
4862: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
4863: my $url = "/uploaded/$docudom/$docuname/$fname";
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: sub mkdiruserfile {
4875: my ($docuname,$docudom,$dir)=@_;
4876: my $home=&homeserver($docuname,$docudom);
4877: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4878: }
4879:
4880: sub renameuserfile {
4881: my ($docuname,$docudom,$old,$new)=@_;
4882: my $home=&homeserver($docuname,$docudom);
4883: my $result = &reply("renameuserfile:$docudom:$docuname:".
4884: &escape("$old").':'.&escape("$new"),$home);
4885: if ($result eq 'ok') {
4886: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4887: my $oldmeta = $old.'.meta';
4888: my $newmeta = $new.'.meta';
4889: my $metaresult =
4890: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
4891: my $url = "/uploaded/$docudom/$docuname/$old";
4892: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
4893: my $sqlresult =
4894: &update_portfolio_table($docuname,$docudom,$file,
4895: 'portfolio_metadata',$group,
4896: 'delete');
4897: }
4898: }
4899: return $result;
4900: }
4901:
4902: # ------------------------------------------------------------------------- Log
4903:
4904: sub log {
4905: my ($dom,$nam,$hom,$what)=@_;
4906: return critical("log:$dom:$nam:$what",$hom);
4907: }
4908:
4909: # ------------------------------------------------------------------ Course Log
4910: #
4911: # This routine flushes several buffers of non-mission-critical nature
4912: #
4913:
4914: sub flushcourselogs {
4915: &logthis('Flushing log buffers');
4916: #
4917: # course logs
4918: # This is a log of all transactions in a course, which can be used
4919: # for data mining purposes
4920: #
4921: # It also collects the courseid database, which lists last transaction
4922: # times and course titles for all courseids
4923: #
4924: my %courseidbuffer=();
4925: foreach my $crsid (keys(%courselogs)) {
4926: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
4927: &escape($courselogs{$crsid}),
4928: $coursehombuf{$crsid}) eq 'ok') {
4929: delete $courselogs{$crsid};
4930: } else {
4931: &logthis('Failed to flush log buffer for '.$crsid);
4932: if (length($courselogs{$crsid})>40000) {
4933: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
4934: " exceeded maximum size, deleting.</font>");
4935: delete $courselogs{$crsid};
4936: }
4937: }
4938: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
4939: 'description' => $coursedescrbuf{$crsid},
4940: 'inst_code' => $courseinstcodebuf{$crsid},
4941: 'type' => $coursetypebuf{$crsid},
4942: 'owner' => $courseownerbuf{$crsid},
4943: };
4944: }
4945: #
4946: # Write course id database (reverse lookup) to homeserver of courses
4947: # Is used in pickcourse
4948: #
4949: foreach my $crs_home (keys(%courseidbuffer)) {
4950: my $response = &courseidput(&host_domain($crs_home),
4951: $courseidbuffer{$crs_home},
4952: $crs_home,'timeonly');
4953: }
4954: #
4955: # File accesses
4956: # Writes to the dynamic metadata of resources to get hit counts, etc.
4957: #
4958: foreach my $entry (keys(%accesshash)) {
4959: if ($entry =~ /___count$/) {
4960: my ($dom,$name);
4961: ($dom,$name,undef)=
4962: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
4963: if (! defined($dom) || $dom eq '' ||
4964: ! defined($name) || $name eq '') {
4965: my $cid = $env{'request.course.id'};
4966: #
4967: # FIXME 11/29/2021
4968: # Typo in rev. 1.458 (2003/12/09)??
4969: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
4970: #
4971: # While these ramain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
4972: # $dom and $name will always be null, so the &inc() call will default to storing this data
4973: # in a nohist_accesscount.db file for the user rather than the course.
4974: #
4975: # That said there is a lot of noise in the data being stored.
4976: # So counts for prtspool/ and adm/ etc. are recorded.
4977: #
4978: # A review of which items ending '___count' are written to %accesshash should likely be
4979: # made before deciding whether to set these to 'course.' instead of 'request.'
4980: #
4981: # Under the current scheme each user receives a nohist_accesscount.db file listing
4982: # accesses for things which are not published resources, regardless of course, and
4983: # there is not a nohist_accesscount.db file in a course, which might log accesses from
4984: # anyone in the course for things which are not published resources.
4985: #
4986: # For an author, nohist_accesscount.db ends up having records for other items
4987: # mixed up with the legitimate access counts for the author's published resources.
4988: #
4989: $dom = $env{'request.'.$cid.'.domain'};
4990: $name = $env{'request.'.$cid.'.num'};
4991: }
4992: my $value = $accesshash{$entry};
4993: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4994: my %temphash=($url => $value);
4995: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4996: if ($result eq 'ok') {
4997: delete $accesshash{$entry};
4998: }
4999: } else {
5000: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
5001: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
5002: my %temphash=($entry => $accesshash{$entry});
5003: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
5004: delete $accesshash{$entry};
5005: }
5006: }
5007: }
5008: #
5009: # Roles
5010: # Reverse lookup of user roles for course faculty/staff and co-authorship
5011: #
5012: foreach my $entry (keys(%userrolehash)) {
5013: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
5014: split(/\:/,$entry);
5015: if (&Apache::lonnet::put('nohist_userroles',
5016: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
5017: $rudom,$runame) eq 'ok') {
5018: delete $userrolehash{$entry};
5019: }
5020: }
5021: #
5022: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
5023: #
5024: my %domrolebuffer = ();
5025: foreach my $entry (keys(%domainrolehash)) {
5026: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
5027: if ($domrolebuffer{$rudom}) {
5028: $domrolebuffer{$rudom}.='&'.&escape($entry).
5029: '='.&escape($domainrolehash{$entry});
5030: } else {
5031: $domrolebuffer{$rudom}.=&escape($entry).
5032: '='.&escape($domainrolehash{$entry});
5033: }
5034: delete $domainrolehash{$entry};
5035: }
5036: foreach my $dom (keys(%domrolebuffer)) {
5037: my %servers;
5038: if (defined(&domain($dom,'primary'))) {
5039: my $primary=&domain($dom,'primary');
5040: my $hostname=&hostname($primary);
5041: $servers{$primary} = $hostname;
5042: } else {
5043: %servers = &get_servers($dom,'library');
5044: }
5045: foreach my $tryserver (keys(%servers)) {
5046: if (&reply('domroleput:'.$dom.':'.
5047: $domrolebuffer{$dom},$tryserver) eq 'ok') {
5048: last;
5049: } else {
5050: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
5051: }
5052: }
5053: }
5054: $dumpcount++;
5055: }
5056:
5057: sub courselog {
5058: my $what=shift;
5059: $what=time.':'.$what;
5060: unless ($env{'request.course.id'}) { return ''; }
5061: $coursedombuf{$env{'request.course.id'}}=
5062: $env{'course.'.$env{'request.course.id'}.'.domain'};
5063: $coursenumbuf{$env{'request.course.id'}}=
5064: $env{'course.'.$env{'request.course.id'}.'.num'};
5065: $coursehombuf{$env{'request.course.id'}}=
5066: $env{'course.'.$env{'request.course.id'}.'.home'};
5067: $coursedescrbuf{$env{'request.course.id'}}=
5068: $env{'course.'.$env{'request.course.id'}.'.description'};
5069: $courseinstcodebuf{$env{'request.course.id'}}=
5070: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
5071: $courseownerbuf{$env{'request.course.id'}}=
5072: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
5073: $coursetypebuf{$env{'request.course.id'}}=
5074: $env{'course.'.$env{'request.course.id'}.'.type'};
5075: if (defined $courselogs{$env{'request.course.id'}}) {
5076: $courselogs{$env{'request.course.id'}}.='&'.$what;
5077: } else {
5078: $courselogs{$env{'request.course.id'}}.=$what;
5079: }
5080: if (length($courselogs{$env{'request.course.id'}})>4048) {
5081: &flushcourselogs();
5082: }
5083: }
5084:
5085: sub courseacclog {
5086: my $fnsymb=shift;
5087: unless ($env{'request.course.id'}) { return ''; }
5088: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
5089: if ($fnsymb=~/$LONCAPA::assess_re/) {
5090: $what.=':POST';
5091: # FIXME: Probably ought to escape things....
5092: foreach my $key (keys(%env)) {
5093: if ($key=~/^form\.(.*)/) {
5094: my $formitem = $1;
5095: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
5096: $what.=':'.$formitem.'='.$env{$key};
5097: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
5098: if ($formitem eq 'proctorpassword') {
5099: $what.=':'.$formitem.'=' . '*' x length($env{$key});
5100: } else {
5101: $what.=':'.$formitem.'='.$env{$key};
5102: }
5103: }
5104: }
5105: }
5106: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
5107: # FIXME: We should not be depending on a form parameter that someone
5108: # editing lonsearchcat.pm might change in the future.
5109: if ($env{'form.phase'} eq 'course_search') {
5110: $what.= ':POST';
5111: # FIXME: Probably ought to escape things....
5112: foreach my $element ('courseexp','crsfulltext','crsrelated',
5113: 'crsdiscuss') {
5114: $what.=':'.$element.'='.$env{'form.'.$element};
5115: }
5116: }
5117: }
5118: &courselog($what);
5119: }
5120:
5121: sub countacc {
5122: my $url=&declutter(shift);
5123: return if (! defined($url) || $url eq '');
5124: unless ($env{'request.course.id'}) { return ''; }
5125: #
5126: # Mark that this url was used in this course
5127: #
5128: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
5129: #
5130: # Increase the access count for this resource in this child process
5131: #
5132: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
5133: $accesshash{$key}++;
5134: }
5135:
5136: sub linklog {
5137: my ($from,$to)=@_;
5138: $from=&declutter($from);
5139: $to=&declutter($to);
5140: $accesshash{$from.'___'.$to.'___comefrom'}=1;
5141: $accesshash{$to.'___'.$from.'___goto'}=1;
5142: }
5143:
5144: sub statslog {
5145: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
5146: if ($users<2) { return; }
5147: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
5148: 'course' => $env{'request.course.id'},
5149: 'sections' => '"all"',
5150: 'num_students' => $users,
5151: 'part' => $part,
5152: 'symb' => $symb,
5153: 'mean_tries' => $av_attempts,
5154: 'deg_of_diff' => $degdiff});
5155: foreach my $key (keys(%dynstore)) {
5156: $accesshash{$key}=$dynstore{$key};
5157: }
5158: }
5159:
5160: sub userrolelog {
5161: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
5162: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
5163: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5164: $userrolehash
5165: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
5166: =$tend.':'.$tstart;
5167: }
5168: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
5169: $userrolehash
5170: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
5171: =$tend.':'.$tstart;
5172: }
5173: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
5174: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5175: $domainrolehash
5176: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
5177: = $tend.':'.$tstart;
5178: }
5179: }
5180:
5181: sub courserolelog {
5182: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
5183: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
5184: my $cdom = $1;
5185: my $cnum = $2;
5186: my $sec = $3;
5187: my $namespace = 'rolelog';
5188: my %storehash = (
5189: role => $trole,
5190: start => $tstart,
5191: end => $tend,
5192: selfenroll => $selfenroll,
5193: context => $context,
5194: );
5195: if ($trole eq 'gr') {
5196: $namespace = 'groupslog';
5197: $storehash{'group'} = $sec;
5198: } else {
5199: $storehash{'section'} = $sec;
5200: }
5201: &write_log('course',$namespace,\%storehash,$delflag,$username,
5202: $domain,$cnum,$cdom);
5203: if (($trole ne 'st') || ($sec ne '')) {
5204: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
5205: }
5206: }
5207: return;
5208: }
5209:
5210: sub domainrolelog {
5211: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5212: if ($area =~ m{^/($match_domain)/$}) {
5213: my $cdom = $1;
5214: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
5215: my $namespace = 'rolelog';
5216: my %storehash = (
5217: role => $trole,
5218: start => $tstart,
5219: end => $tend,
5220: context => $context,
5221: );
5222: &write_log('domain',$namespace,\%storehash,$delflag,$username,
5223: $domain,$domconfiguser,$cdom);
5224: }
5225: return;
5226:
5227: }
5228:
5229: sub coauthorrolelog {
5230: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5231: if ($area =~ m{^/($match_domain)/($match_username)$}) {
5232: my $audom = $1;
5233: my $auname = $2;
5234: my $namespace = 'rolelog';
5235: my %storehash = (
5236: role => $trole,
5237: start => $tstart,
5238: end => $tend,
5239: context => $context,
5240: );
5241: &write_log('author',$namespace,\%storehash,$delflag,$username,
5242: $domain,$auname,$audom);
5243: }
5244: return;
5245: }
5246:
5247: sub get_course_adv_roles {
5248: my ($cid,$codes) = @_;
5249: $cid=$env{'request.course.id'} unless (defined($cid));
5250: my %coursehash=&coursedescription($cid);
5251: my $crstype = &Apache::loncommon::course_type($cid);
5252: my %nothide=();
5253: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
5254: if ($user !~ /:/) {
5255: $nothide{join(':',split(/[\@]/,$user))}=1;
5256: } else {
5257: $nothide{$user}=1;
5258: }
5259: }
5260: my @possdoms = ($coursehash{'domain'});
5261: if ($coursehash{'checkforpriv'}) {
5262: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
5263: }
5264: my %returnhash=();
5265: my %dumphash=
5266: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
5267: my $now=time;
5268: my %privileged;
5269: foreach my $entry (keys(%dumphash)) {
5270: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
5271: if (($tstart) && ($tstart<0)) { next; }
5272: if (($tend) && ($tend<$now)) { next; }
5273: if (($tstart) && ($now<$tstart)) { next; }
5274: my ($role,$username,$domain,$section)=split(/\:/,$entry);
5275: if ($username eq '' || $domain eq '') { next; }
5276: if ((&privileged($username,$domain,\@possdoms)) &&
5277: (!$nothide{$username.':'.$domain})) { next; }
5278: if ($role eq 'cr') { next; }
5279: if ($codes) {
5280: if ($section) { $role .= ':'.$section; }
5281: if ($returnhash{$role}) {
5282: $returnhash{$role}.=','.$username.':'.$domain;
5283: } else {
5284: $returnhash{$role}=$username.':'.$domain;
5285: }
5286: } else {
5287: my $key=&plaintext($role,$crstype);
5288: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
5289: if ($returnhash{$key}) {
5290: $returnhash{$key}.=','.$username.':'.$domain;
5291: } else {
5292: $returnhash{$key}=$username.':'.$domain;
5293: }
5294: }
5295: }
5296: return %returnhash;
5297: }
5298:
5299: sub get_my_roles {
5300: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
5301: unless (defined($uname)) { $uname=$env{'user.name'}; }
5302: unless (defined($udom)) { $udom=$env{'user.domain'}; }
5303: my (%dumphash,%nothide);
5304: if ($context eq 'userroles') {
5305: %dumphash = &dump('roles',$udom,$uname);
5306: } else {
5307: %dumphash = &dump('nohist_userroles',$udom,$uname);
5308: if ($hidepriv) {
5309: my %coursehash=&coursedescription($udom.'_'.$uname);
5310: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
5311: if ($user !~ /:/) {
5312: $nothide{join(':',split(/[\@]/,$user))} = 1;
5313: } else {
5314: $nothide{$user} = 1;
5315: }
5316: }
5317: }
5318: }
5319: my %returnhash=();
5320: my $now=time;
5321: my %privileged;
5322: foreach my $entry (keys(%dumphash)) {
5323: my ($role,$tend,$tstart);
5324: if ($context eq 'userroles') {
5325: next if ($entry =~ /^rolesdef/);
5326: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
5327: } else {
5328: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
5329: }
5330: if (($tstart) && ($tstart<0)) { next; }
5331: my $status = 'active';
5332: if (($tend) && ($tend<=$now)) {
5333: $status = 'previous';
5334: }
5335: if (($tstart) && ($now<$tstart)) {
5336: $status = 'future';
5337: }
5338: if (ref($types) eq 'ARRAY') {
5339: if (!grep(/^\Q$status\E$/,@{$types})) {
5340: next;
5341: }
5342: } else {
5343: if ($status ne 'active') {
5344: next;
5345: }
5346: }
5347: my ($rolecode,$username,$domain,$section,$area);
5348: if ($context eq 'userroles') {
5349: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
5350: (undef,$domain,$username,$section) = split(/\//,$area);
5351: } else {
5352: ($role,$username,$domain,$section) = split(/\:/,$entry);
5353: }
5354: if (ref($roledoms) eq 'ARRAY') {
5355: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
5356: next;
5357: }
5358: }
5359: if (ref($roles) eq 'ARRAY') {
5360: if (!grep(/^\Q$role\E$/,@{$roles})) {
5361: if ($role =~ /^cr\//) {
5362: if (!grep(/^cr$/,@{$roles})) {
5363: next;
5364: }
5365: } elsif ($role =~ /^gr\//) {
5366: if (!grep(/^gr$/,@{$roles})) {
5367: next;
5368: }
5369: } else {
5370: next;
5371: }
5372: }
5373: }
5374: if ($hidepriv) {
5375: my @privroles = ('dc','su');
5376: if ($context eq 'userroles') {
5377: next if (grep(/^\Q$role\E$/,@privroles));
5378: } else {
5379: my $possdoms = [$domain];
5380: if (ref($roledoms) eq 'ARRAY') {
5381: push(@{$possdoms},@{$roledoms});
5382: }
5383: if (&privileged($username,$domain,$possdoms,\@privroles)) {
5384: if (!$nothide{$username.':'.$domain}) {
5385: next;
5386: }
5387: }
5388: }
5389: }
5390: if ($withsec) {
5391: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
5392: $tstart.':'.$tend;
5393: } else {
5394: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
5395: }
5396: }
5397: return %returnhash;
5398: }
5399:
5400: sub get_all_adhocroles {
5401: my ($dom) = @_;
5402: my @roles_by_num = ();
5403: my %domdefaults = &get_domain_defaults($dom);
5404: my (%description,%access_in_dom,%access_info);
5405: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
5406: my $count = 0;
5407: my %domcurrent = %{$domdefaults{'adhocroles'}};
5408: my %ordered;
5409: foreach my $role (sort(keys(%domcurrent))) {
5410: my ($order,$desc,$access_in_dom);
5411: if (ref($domcurrent{$role}) eq 'HASH') {
5412: $order = $domcurrent{$role}{'order'};
5413: $desc = $domcurrent{$role}{'desc'};
5414: $access_in_dom{$role} = $domcurrent{$role}{'access'};
5415: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
5416: }
5417: if ($order eq '') {
5418: $order = $count;
5419: }
5420: $ordered{$order} = $role;
5421: if ($desc ne '') {
5422: $description{$role} = $desc;
5423: } else {
5424: $description{$role}= $role;
5425: }
5426: $count++;
5427: }
5428: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
5429: push(@roles_by_num,$ordered{$item});
5430: }
5431: }
5432: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
5433: }
5434:
5435: sub get_my_adhocroles {
5436: my ($cid,$checkreg) = @_;
5437: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
5438: if ($env{'request.course.id'} eq $cid) {
5439: $cdom = $env{'course.'.$cid.'.domain'};
5440: $cnum = $env{'course.'.$cid.'.num'};
5441: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
5442: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
5443: $cdom = $1;
5444: $cnum = $2;
5445: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
5446: $cdom,$cnum);
5447: }
5448: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
5449: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5450: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
5451: if ($rosterhash{$user} ne '') {
5452: my $type = (split(/:/,$rosterhash{$user}))[5];
5453: return ([],{}) if ($type eq 'auto');
5454: }
5455: }
5456: if (($cdom ne '') && ($cnum ne '')) {
5457: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
5458: my $then=$env{'user.login.time'};
5459: my $update=$env{'user.update.time'};
5460: if (!$update) {
5461: $update = $then;
5462: }
5463: my @liveroles;
5464: foreach my $role ('dh','da') {
5465: if ($env{"user.role.$role./$cdom/"}) {
5466: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
5467: my $limit = $update;
5468: if ($env{'request.role'} eq "$role./$cdom/") {
5469: $limit = $then;
5470: }
5471: my $activerole = 1;
5472: if ($tstart && $tstart>$limit) { $activerole = 0; }
5473: if ($tend && $tend <$limit) { $activerole = 0; }
5474: if ($activerole) {
5475: push(@liveroles,$role);
5476: }
5477: }
5478: }
5479: if (@liveroles) {
5480: if (&homeserver($cnum,$cdom) ne 'no_host') {
5481: my ($accessref,$accessinfo,%access_in_dom);
5482: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5483: if (ref($roles_by_num) eq 'ARRAY') {
5484: if (@{$roles_by_num}) {
5485: my %settings;
5486: if ($env{'request.course.id'} eq $cid) {
5487: foreach my $envkey (keys(%env)) {
5488: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5489: $settings{$1} = $env{$envkey};
5490: }
5491: }
5492: } else {
5493: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5494: }
5495: my %setincrs;
5496: if ($settings{'internal.adhocaccess'}) {
5497: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5498: }
5499: my @statuses;
5500: if ($env{'environment.inststatus'}) {
5501: @statuses = split(/,/,$env{'environment.inststatus'});
5502: }
5503: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5504: if (ref($accessref) eq 'HASH') {
5505: %access_in_dom = %{$accessref};
5506: }
5507: foreach my $role (@{$roles_by_num}) {
5508: my ($curraccess,@okstatus,@personnel);
5509: if ($setincrs{$role}) {
5510: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5511: if ($curraccess eq 'status') {
5512: @okstatus = split(/\&/,$rest);
5513: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5514: @personnel = split(/\&/,$rest);
5515: }
5516: } else {
5517: $curraccess = $access_in_dom{$role};
5518: if (ref($accessinfo) eq 'HASH') {
5519: if ($curraccess eq 'status') {
5520: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5521: @okstatus = @{$accessinfo->{$role}};
5522: }
5523: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5524: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5525: @personnel = @{$accessinfo->{$role}};
5526: }
5527: }
5528: }
5529: }
5530: if ($curraccess eq 'none') {
5531: next;
5532: } elsif ($curraccess eq 'all') {
5533: push(@possroles,$role);
5534: } elsif ($curraccess eq 'dh') {
5535: if (grep(/^dh$/,@liveroles)) {
5536: push(@possroles,$role);
5537: } else {
5538: next;
5539: }
5540: } elsif ($curraccess eq 'da') {
5541: if (grep(/^da$/,@liveroles)) {
5542: push(@possroles,$role);
5543: } else {
5544: next;
5545: }
5546: } elsif ($curraccess eq 'status') {
5547: if (@okstatus) {
5548: if (!@statuses) {
5549: if (grep(/^default$/,@okstatus)) {
5550: push(@possroles,$role);
5551: }
5552: } else {
5553: foreach my $status (@okstatus) {
5554: if (grep(/^\Q$status\E$/,@statuses)) {
5555: push(@possroles,$role);
5556: last;
5557: }
5558: }
5559: }
5560: }
5561: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5562: if (grep(/^\Q$user\E$/,@personnel)) {
5563: if ($curraccess eq 'exc') {
5564: push(@possroles,$role);
5565: }
5566: } elsif ($curraccess eq 'inc') {
5567: push(@possroles,$role);
5568: }
5569: }
5570: }
5571: }
5572: }
5573: }
5574: }
5575: }
5576: }
5577: unless (ref($description) eq 'HASH') {
5578: if (ref($roles_by_num) eq 'ARRAY') {
5579: my %desc;
5580: map { $desc{$_} = $_; } (@{$roles_by_num});
5581: $description = \%desc;
5582: } else {
5583: $description = {};
5584: }
5585: }
5586: return (\@possroles,$description);
5587: }
5588:
5589: # ----------------------------------------------------- Frontpage Announcements
5590: #
5591: #
5592:
5593: sub postannounce {
5594: my ($server,$text)=@_;
5595: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
5596: unless ($text=~/\w/) { $text=''; }
5597: return &reply('setannounce:'.&escape($text),$server);
5598: }
5599:
5600: sub getannounce {
5601:
5602: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
5603: my $announcement='';
5604: while (my $line = <$fh>) { $announcement .= $line; }
5605: close($fh);
5606: if ($announcement=~/\w/) {
5607: return
5608: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
5609: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
5610: } else {
5611: return '';
5612: }
5613: } else {
5614: return '';
5615: }
5616: }
5617:
5618: # ---------------------------------------------------------- Course ID routines
5619: # Deal with domain's nohist_courseid.db files
5620: #
5621:
5622: sub courseidput {
5623: my ($domain,$storehash,$coursehome,$caller) = @_;
5624: return unless (ref($storehash) eq 'HASH');
5625: my $outcome;
5626: if ($caller eq 'timeonly') {
5627: my $cids = '';
5628: foreach my $item (keys(%$storehash)) {
5629: $cids.=&escape($item).'&';
5630: }
5631: $cids=~s/\&$//;
5632: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5633: $coursehome);
5634: } else {
5635: my $items = '';
5636: foreach my $item (keys(%$storehash)) {
5637: $items.= &escape($item).'='.
5638: &freeze_escape($$storehash{$item}).'&';
5639: }
5640: $items=~s/\&$//;
5641: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5642: $coursehome);
5643: }
5644: if ($outcome eq 'unknown_cmd') {
5645: my $what;
5646: foreach my $cid (keys(%$storehash)) {
5647: $what .= &escape($cid).'=';
5648: foreach my $item ('description','inst_code','owner','type') {
5649: $what .= &escape($storehash->{$cid}{$item}).':';
5650: }
5651: $what =~ s/\:$/&/;
5652: }
5653: $what =~ s/\&$//;
5654: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5655: } else {
5656: return $outcome;
5657: }
5658: }
5659:
5660: sub courseiddump {
5661: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
5662: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
5663: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
5664: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
5665: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
5666: my $as_hash = 1;
5667: my %returnhash;
5668: if (!$domfilter) { $domfilter=''; }
5669: my %libserv = &all_library();
5670: foreach my $tryserver (keys(%libserv)) {
5671: if ( ( $hostidflag == 1
5672: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5673: || (!defined($hostidflag)) ) {
5674:
5675: if (($domfilter eq '') ||
5676: (&host_domain($tryserver) eq $domfilter)) {
5677: my $rep;
5678: if (grep { $_ eq $tryserver } current_machine_ids()) {
5679: $rep = LONCAPA::Lond::dump_course_id_handler(
5680: join(":", (&host_domain($tryserver), $sincefilter,
5681: &escape($descfilter), &escape($instcodefilter),
5682: &escape($ownerfilter), &escape($coursefilter),
5683: &escape($typefilter), &escape($regexp_ok),
5684: $as_hash, &escape($selfenrollonly),
5685: &escape($catfilter), $showhidden, $caller,
5686: &escape($cloner), &escape($cc_clone), $cloneonly,
5687: &escape($createdbefore), &escape($createdafter),
5688: &escape($creationcontext),$domcloner,$hasuniquecode,
5689: $reqcrsdom,&escape($reqinstcode))));
5690: } else {
5691: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5692: $sincefilter.':'.&escape($descfilter).':'.
5693: &escape($instcodefilter).':'.&escape($ownerfilter).
5694: ':'.&escape($coursefilter).':'.&escape($typefilter).
5695: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5696: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5697: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5698: &escape($cc_clone).':'.$cloneonly.':'.
5699: &escape($createdbefore).':'.&escape($createdafter).':'.
5700: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5701: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
5702: }
5703:
5704: my @pairs=split(/\&/,$rep);
5705: foreach my $item (@pairs) {
5706: my ($key,$value)=split(/\=/,$item,2);
5707: $key = &unescape($key);
5708: next if ($key =~ /^error: 2 /);
5709: my $result = &thaw_unescape($value);
5710: if (ref($result) eq 'HASH') {
5711: $returnhash{$key}=$result;
5712: } else {
5713: my @responses = split(/:/,$value);
5714: my @items = ('description','inst_code','owner','type');
5715: for (my $i=0; $i<@responses; $i++) {
5716: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
5717: }
5718: }
5719: }
5720: }
5721: }
5722: }
5723: return %returnhash;
5724: }
5725:
5726: sub courselastaccess {
5727: my ($cdom,$cnum,$hostidref) = @_;
5728: my %returnhash;
5729: if ($cdom && $cnum) {
5730: my $chome = &homeserver($cnum,$cdom);
5731: if ($chome ne 'no_host') {
5732: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5733: &extract_lastaccess(\%returnhash,$rep);
5734: }
5735: } else {
5736: if (!$cdom) { $cdom=''; }
5737: my %libserv = &all_library();
5738: foreach my $tryserver (keys(%libserv)) {
5739: if (ref($hostidref) eq 'ARRAY') {
5740: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5741: }
5742: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5743: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5744: &extract_lastaccess(\%returnhash,$rep);
5745: }
5746: }
5747: }
5748: return %returnhash;
5749: }
5750:
5751: sub extract_lastaccess {
5752: my ($returnhash,$rep) = @_;
5753: if (ref($returnhash) eq 'HASH') {
5754: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5755: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5756: $rep eq '') {
5757: my @pairs=split(/\&/,$rep);
5758: foreach my $item (@pairs) {
5759: my ($key,$value)=split(/\=/,$item,2);
5760: $key = &unescape($key);
5761: next if ($key =~ /^error: 2 /);
5762: $returnhash->{$key} = &thaw_unescape($value);
5763: }
5764: }
5765: }
5766: return;
5767: }
5768:
5769: # ---------------------------------------------------------- DC e-mail
5770:
5771: sub dcmailput {
5772: my ($domain,$msgid,$message,$server)=@_;
5773: my $status = &Apache::lonnet::critical(
5774: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5775: &escape($message),$server);
5776: return $status;
5777: }
5778:
5779: sub dcmaildump {
5780: my ($dom,$startdate,$enddate,$senders) = @_;
5781: my %returnhash=();
5782:
5783: if (defined(&domain($dom,'primary'))) {
5784: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5785: &escape($enddate).':';
5786: my @esc_senders=map { &escape($_)} @$senders;
5787: $cmd.=&escape(join('&',@esc_senders));
5788: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
5789: my ($key,$value) = split(/\=/,$line,2);
5790: if (($key) && ($value)) {
5791: $returnhash{&unescape($key)} = &unescape($value);
5792: }
5793: }
5794: }
5795: return %returnhash;
5796: }
5797: # ---------------------------------------------------------- Domain roles
5798:
5799: sub get_domain_roles {
5800: my ($dom,$roles,$startdate,$enddate)=@_;
5801: if ((!defined($startdate)) || ($startdate eq '')) {
5802: $startdate = '.';
5803: }
5804: if ((!defined($enddate)) || ($enddate eq '')) {
5805: $enddate = '.';
5806: }
5807: my $rolelist;
5808: if (ref($roles) eq 'ARRAY') {
5809: $rolelist = join('&',@{$roles});
5810: }
5811: my %personnel = ();
5812:
5813: my %servers = &get_servers($dom,'library');
5814: foreach my $tryserver (keys(%servers)) {
5815: %{$personnel{$tryserver}}=();
5816: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5817: &escape($startdate).':'.
5818: &escape($enddate).':'.
5819: &escape($rolelist), $tryserver))) {
5820: my ($key,$value) = split(/\=/,$line,2);
5821: if (($key) && ($value)) {
5822: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5823: }
5824: }
5825: }
5826: return %personnel;
5827: }
5828:
5829: sub get_active_domroles {
5830: my ($dom,$roles) = @_;
5831: return () unless (ref($roles) eq 'ARRAY');
5832: my $now = time;
5833: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5834: my %domroles;
5835: foreach my $server (keys(%dompersonnel)) {
5836: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5837: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5838: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5839: }
5840: }
5841: return %domroles;
5842: }
5843:
5844: # ----------------------------------------------------------- Interval timing
5845:
5846: {
5847: # Caches needed for speedup of navmaps
5848: # We don't want to cache this for very long at all (5 seconds at most)
5849: #
5850: # The user for whom we cache
5851: my $cachedkey='';
5852: # The cached times for this user
5853: my %cachedtimes=();
5854: # When this was last done
5855: my $cachedtime='';
5856:
5857: sub load_all_first_access {
5858: my ($uname,$udom,$ignorecache)=@_;
5859: if (($cachedkey eq $uname.':'.$udom) &&
5860: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
5861: (!$ignorecache)) {
5862: return;
5863: }
5864: $cachedtime=time;
5865: $cachedkey=$uname.':'.$udom;
5866: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
5867: }
5868:
5869: sub get_first_access {
5870: my ($type,$argsymb,$argmap,$ignorecache)=@_;
5871: my ($symb,$courseid,$udom,$uname)=&whichuser();
5872: if ($argsymb) { $symb=$argsymb; }
5873: my ($map,$id,$res)=&decode_symb($symb);
5874: if ($argmap) { $map = $argmap; }
5875: if ($type eq 'course') {
5876: $res='course';
5877: } elsif ($type eq 'map') {
5878: $res=&symbread($map);
5879: } else {
5880: $res=$symb;
5881: }
5882: &load_all_first_access($uname,$udom,$ignorecache);
5883: return $cachedtimes{"$courseid\0$res"};
5884: }
5885:
5886: sub set_first_access {
5887: my ($type,$interval)=@_;
5888: my ($symb,$courseid,$udom,$uname)=&whichuser();
5889: my ($map,$id,$res)=&decode_symb($symb);
5890: if ($type eq 'course') {
5891: $res='course';
5892: } elsif ($type eq 'map') {
5893: $res=&symbread($map);
5894: } else {
5895: $res=$symb;
5896: }
5897: $cachedkey='';
5898: my $firstaccess=&get_first_access($type,$symb,$map);
5899: if ($firstaccess) {
5900: &logthis("First access time already set ($firstaccess) when attempting ".
5901: "to set new value (type: $type, extent: $res) for $uname:$udom ".
5902: "in $courseid");
5903: return 'already_set';
5904: } else {
5905: my $start = time;
5906: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5907: $udom,$uname);
5908: if ($putres eq 'ok') {
5909: &put('timerinterval',{"$courseid\0$res"=>$interval},
5910: $udom,$uname);
5911: &appenv(
5912: {
5913: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5914: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5915: }
5916: );
5917: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
5918: $cachedtimes{"$courseid\0$res"} = $start;
5919: }
5920: } elsif ($putres ne 'refused') {
5921: &logthis("Result: $putres when attempting to set first access time ".
5922: "(type: $type, extent: $res) for $uname:$udom in $courseid");
5923: }
5924: return $putres;
5925: }
5926: return 'already_set';
5927: }
5928: }
5929:
5930: # --------------------------------------------- Set Expire Date for Spreadsheet
5931:
5932: sub expirespread {
5933: my ($uname,$udom,$stype,$usymb)=@_;
5934: my $cid=$env{'request.course.id'};
5935: if ($cid) {
5936: my $now=time;
5937: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
5938: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5939: $env{'course.'.$cid.'.num'}.
5940: ':nohist_expirationdates:'.
5941: &escape($key).'='.$now,
5942: $env{'course.'.$cid.'.home'})
5943: }
5944: return 'ok';
5945: }
5946:
5947: # ----------------------------------------------------- Devalidate Spreadsheets
5948:
5949: sub devalidate {
5950: my ($symb,$uname,$udom)=@_;
5951: my $cid=$env{'request.course.id'};
5952: if ($cid) {
5953: # delete the stored spreadsheets for
5954: # - the student level sheet of this user in course's homespace
5955: # - the assessment level sheet for this resource
5956: # for this user in user's homespace
5957: # - current conditional state info
5958: my $key=$uname.':'.$udom.':';
5959: my $status=
5960: &del('nohist_calculatedsheets',
5961: [$key.'studentcalc:'],
5962: $env{'course.'.$cid.'.domain'},
5963: $env{'course.'.$cid.'.num'})
5964: .' '.
5965: &del('nohist_calculatedsheets_'.$cid,
5966: [$key.'assesscalc:'.$symb],$udom,$uname);
5967: unless ($status eq 'ok ok') {
5968: &logthis('Could not devalidate spreadsheet '.
5969: $uname.' at '.$udom.' for '.
5970: $symb.': '.$status);
5971: }
5972: &delenv('user.state.'.$cid);
5973: }
5974: }
5975:
5976: sub get_scalar {
5977: my ($string,$end) = @_;
5978: my $value;
5979: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5980: $value = $1;
5981: } elsif ($$string =~ s/^([^&]*?)&//) {
5982: $value = $1;
5983: }
5984: return &unescape($value);
5985: }
5986:
5987: sub array2str {
5988: my (@array) = @_;
5989: my $result=&arrayref2str(\@array);
5990: $result=~s/^__ARRAY_REF__//;
5991: $result=~s/__END_ARRAY_REF__$//;
5992: return $result;
5993: }
5994:
5995: sub arrayref2str {
5996: my ($arrayref) = @_;
5997: my $result='__ARRAY_REF__';
5998: foreach my $elem (@$arrayref) {
5999: if(ref($elem) eq 'ARRAY') {
6000: $result.=&arrayref2str($elem).'&';
6001: } elsif(ref($elem) eq 'HASH') {
6002: $result.=&hashref2str($elem).'&';
6003: } elsif(ref($elem)) {
6004: #print("Got a ref of ".(ref($elem))." skipping.");
6005: } else {
6006: $result.=&escape($elem).'&';
6007: }
6008: }
6009: $result=~s/\&$//;
6010: $result .= '__END_ARRAY_REF__';
6011: return $result;
6012: }
6013:
6014: sub hash2str {
6015: my (%hash) = @_;
6016: my $result=&hashref2str(\%hash);
6017: $result=~s/^__HASH_REF__//;
6018: $result=~s/__END_HASH_REF__$//;
6019: return $result;
6020: }
6021:
6022: sub hashref2str {
6023: my ($hashref)=@_;
6024: my $result='__HASH_REF__';
6025: foreach my $key (sort(keys(%$hashref))) {
6026: if (ref($key) eq 'ARRAY') {
6027: $result.=&arrayref2str($key).'=';
6028: } elsif (ref($key) eq 'HASH') {
6029: $result.=&hashref2str($key).'=';
6030: } elsif (ref($key)) {
6031: $result.='=';
6032: #print("Got a ref of ".(ref($key))." skipping.");
6033: } else {
6034: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
6035: }
6036:
6037: if(ref($hashref->{$key}) eq 'ARRAY') {
6038: $result.=&arrayref2str($hashref->{$key}).'&';
6039: } elsif(ref($hashref->{$key}) eq 'HASH') {
6040: $result.=&hashref2str($hashref->{$key}).'&';
6041: } elsif(ref($hashref->{$key})) {
6042: $result.='&';
6043: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
6044: } else {
6045: $result.=&escape($hashref->{$key}).'&';
6046: }
6047: }
6048: $result=~s/\&$//;
6049: $result .= '__END_HASH_REF__';
6050: return $result;
6051: }
6052:
6053: sub str2hash {
6054: my ($string)=@_;
6055: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
6056: return %$hash;
6057: }
6058:
6059: sub str2hashref {
6060: my ($string) = @_;
6061:
6062: my %hash;
6063:
6064: if($string !~ /^__HASH_REF__/) {
6065: if (! ($string eq '' || !defined($string))) {
6066: $hash{'error'}='Not hash reference';
6067: }
6068: return (\%hash, $string);
6069: }
6070:
6071: $string =~ s/^__HASH_REF__//;
6072:
6073: while($string !~ /^__END_HASH_REF__/) {
6074: #key
6075: my $key='';
6076: if($string =~ /^__HASH_REF__/) {
6077: ($key, $string)=&str2hashref($string);
6078: if(defined($key->{'error'})) {
6079: $hash{'error'}='Bad data';
6080: return (\%hash, $string);
6081: }
6082: } elsif($string =~ /^__ARRAY_REF__/) {
6083: ($key, $string)=&str2arrayref($string);
6084: if($key->[0] eq 'Array reference error') {
6085: $hash{'error'}='Bad data';
6086: return (\%hash, $string);
6087: }
6088: } else {
6089: $string =~ s/^(.*?)=//;
6090: $key=&unescape($1);
6091: }
6092: $string =~ s/^=//;
6093:
6094: #value
6095: my $value='';
6096: if($string =~ /^__HASH_REF__/) {
6097: ($value, $string)=&str2hashref($string);
6098: if(defined($value->{'error'})) {
6099: $hash{'error'}='Bad data';
6100: return (\%hash, $string);
6101: }
6102: } elsif($string =~ /^__ARRAY_REF__/) {
6103: ($value, $string)=&str2arrayref($string);
6104: if($value->[0] eq 'Array reference error') {
6105: $hash{'error'}='Bad data';
6106: return (\%hash, $string);
6107: }
6108: } else {
6109: $value=&get_scalar(\$string,'__END_HASH_REF__');
6110: }
6111: $string =~ s/^&//;
6112:
6113: $hash{$key}=$value;
6114: }
6115:
6116: $string =~ s/^__END_HASH_REF__//;
6117:
6118: return (\%hash, $string);
6119: }
6120:
6121: sub str2array {
6122: my ($string)=@_;
6123: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
6124: return @$array;
6125: }
6126:
6127: sub str2arrayref {
6128: my ($string) = @_;
6129: my @array;
6130:
6131: if($string !~ /^__ARRAY_REF__/) {
6132: if (! ($string eq '' || !defined($string))) {
6133: $array[0]='Array reference error';
6134: }
6135: return (\@array, $string);
6136: }
6137:
6138: $string =~ s/^__ARRAY_REF__//;
6139:
6140: while($string !~ /^__END_ARRAY_REF__/) {
6141: my $value='';
6142: if($string =~ /^__HASH_REF__/) {
6143: ($value, $string)=&str2hashref($string);
6144: if(defined($value->{'error'})) {
6145: $array[0] ='Array reference error';
6146: return (\@array, $string);
6147: }
6148: } elsif($string =~ /^__ARRAY_REF__/) {
6149: ($value, $string)=&str2arrayref($string);
6150: if($value->[0] eq 'Array reference error') {
6151: $array[0] ='Array reference error';
6152: return (\@array, $string);
6153: }
6154: } else {
6155: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
6156: }
6157: $string =~ s/^&//;
6158:
6159: push(@array, $value);
6160: }
6161:
6162: $string =~ s/^__END_ARRAY_REF__//;
6163:
6164: return (\@array, $string);
6165: }
6166:
6167: # -------------------------------------------------------------------Temp Store
6168:
6169: sub tmpreset {
6170: my ($symb,$namespace,$domain,$stuname) = @_;
6171: if (!$symb) {
6172: $symb=&symbread();
6173: if (!$symb) { $symb= $env{'request.url'}; }
6174: }
6175: $symb=escape($symb);
6176:
6177: if (!$namespace) { $namespace=$env{'request.state'}; }
6178: $namespace=~s/\//\_/g;
6179: $namespace=~s/\W//g;
6180:
6181: if (!$domain) { $domain=$env{'user.domain'}; }
6182: if (!$stuname) { $stuname=$env{'user.name'}; }
6183: if ($domain eq 'public' && $stuname eq 'public') {
6184: $stuname=&get_requestor_ip();
6185: }
6186: my $path=LONCAPA::tempdir();
6187: my %hash;
6188: if (tie(%hash,'GDBM_File',
6189: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
6190: &GDBM_WRCREAT(),0640)) {
6191: foreach my $key (keys(%hash)) {
6192: if ($key=~ /:$symb/) {
6193: delete($hash{$key});
6194: }
6195: }
6196: }
6197: }
6198:
6199: sub tmpstore {
6200: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
6201:
6202: if (!$symb) {
6203: $symb=&symbread();
6204: if (!$symb) { $symb= $env{'request.url'}; }
6205: }
6206: $symb=escape($symb);
6207:
6208: if (!$namespace) {
6209: # I don't think we would ever want to store this for a course.
6210: # it seems this will only be used if we don't have a course.
6211: #$namespace=$env{'request.course.id'};
6212: #if (!$namespace) {
6213: $namespace=$env{'request.state'};
6214: #}
6215: }
6216: $namespace=~s/\//\_/g;
6217: $namespace=~s/\W//g;
6218: if (!$domain) { $domain=$env{'user.domain'}; }
6219: if (!$stuname) { $stuname=$env{'user.name'}; }
6220: if ($domain eq 'public' && $stuname eq 'public') {
6221: $stuname=&get_requestor_ip();
6222: }
6223: my $now=time;
6224: my %hash;
6225: my $path=LONCAPA::tempdir();
6226: if (tie(%hash,'GDBM_File',
6227: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
6228: &GDBM_WRCREAT(),0640)) {
6229: $hash{"version:$symb"}++;
6230: my $version=$hash{"version:$symb"};
6231: my $allkeys='';
6232: foreach my $key (keys(%$storehash)) {
6233: $allkeys.=$key.':';
6234: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
6235: }
6236: $hash{"$version:$symb:timestamp"}=$now;
6237: $allkeys.='timestamp';
6238: $hash{"$version:keys:$symb"}=$allkeys;
6239: if (untie(%hash)) {
6240: return 'ok';
6241: } else {
6242: return "error:$!";
6243: }
6244: } else {
6245: return "error:$!";
6246: }
6247: }
6248:
6249: # -----------------------------------------------------------------Temp Restore
6250:
6251: sub tmprestore {
6252: my ($symb,$namespace,$domain,$stuname) = @_;
6253:
6254: if (!$symb) {
6255: $symb=&symbread();
6256: if (!$symb) { $symb= $env{'request.url'}; }
6257: }
6258: $symb=escape($symb);
6259:
6260: if (!$namespace) { $namespace=$env{'request.state'}; }
6261:
6262: if (!$domain) { $domain=$env{'user.domain'}; }
6263: if (!$stuname) { $stuname=$env{'user.name'}; }
6264: if ($domain eq 'public' && $stuname eq 'public') {
6265: $stuname=&get_requestor_ip();
6266: }
6267: my %returnhash;
6268: $namespace=~s/\//\_/g;
6269: $namespace=~s/\W//g;
6270: my %hash;
6271: my $path=LONCAPA::tempdir();
6272: if (tie(%hash,'GDBM_File',
6273: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
6274: &GDBM_READER(),0640)) {
6275: my $version=$hash{"version:$symb"};
6276: $returnhash{'version'}=$version;
6277: my $scope;
6278: for ($scope=1;$scope<=$version;$scope++) {
6279: my $vkeys=$hash{"$scope:keys:$symb"};
6280: my @keys=split(/:/,$vkeys);
6281: my $key;
6282: $returnhash{"$scope:keys"}=$vkeys;
6283: foreach $key (@keys) {
6284: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
6285: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
6286: }
6287: }
6288: if (!(untie(%hash))) {
6289: return "error:$!";
6290: }
6291: } else {
6292: return "error:$!";
6293: }
6294: return %returnhash;
6295: }
6296:
6297: # ----------------------------------------------------------------------- Store
6298:
6299: sub store {
6300: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
6301: my $home='';
6302:
6303: if ($stuname) { $home=&homeserver($stuname,$domain); }
6304:
6305: $symb=&symbclean($symb);
6306: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
6307:
6308: if (!$domain) { $domain=$env{'user.domain'}; }
6309: if (!$stuname) { $stuname=$env{'user.name'}; }
6310:
6311: &devalidate($symb,$stuname,$domain);
6312:
6313: $symb=escape($symb);
6314: if (!$namespace) {
6315: unless ($namespace=$env{'request.course.id'}) {
6316: return '';
6317: }
6318: }
6319: if (!$home) { $home=$env{'user.home'}; }
6320:
6321: $$storehash{'ip'}=&get_requestor_ip();
6322: $$storehash{'host'}=$perlvar{'lonHostID'};
6323:
6324: my $namevalue='';
6325: foreach my $key (keys(%$storehash)) {
6326: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6327: }
6328: $namevalue=~s/\&$//;
6329: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
6330: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
6331: }
6332:
6333: # -------------------------------------------------------------- Critical Store
6334:
6335: sub cstore {
6336: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
6337: my $home='';
6338:
6339: if ($stuname) { $home=&homeserver($stuname,$domain); }
6340:
6341: $symb=&symbclean($symb);
6342: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
6343:
6344: if (!$domain) { $domain=$env{'user.domain'}; }
6345: if (!$stuname) { $stuname=$env{'user.name'}; }
6346:
6347: &devalidate($symb,$stuname,$domain);
6348:
6349: $symb=escape($symb);
6350: if (!$namespace) {
6351: unless ($namespace=$env{'request.course.id'}) {
6352: return '';
6353: }
6354: }
6355: if (!$home) { $home=$env{'user.home'}; }
6356:
6357: $$storehash{'ip'}=&get_requestor_ip();
6358: $$storehash{'host'}=$perlvar{'lonHostID'};
6359:
6360: my $namevalue='';
6361: foreach my $key (keys(%$storehash)) {
6362: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6363: }
6364: $namevalue=~s/\&$//;
6365: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
6366: return critical
6367: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
6368: }
6369:
6370: # --------------------------------------------------------------------- Restore
6371:
6372: sub restore {
6373: my ($symb,$namespace,$domain,$stuname) = @_;
6374: my $home='';
6375:
6376: if ($stuname) { $home=&homeserver($stuname,$domain); }
6377:
6378: if (!$symb) {
6379: return if ($namespace eq 'courserequests');
6380: unless ($symb=escape(&symbread())) { return ''; }
6381: } else {
6382: unless ($namespace eq 'courserequests') {
6383: $symb=&escape(&symbclean($symb));
6384: }
6385: }
6386: if (!$namespace) {
6387: unless ($namespace=$env{'request.course.id'}) {
6388: return '';
6389: }
6390: }
6391: if (!$domain) { $domain=$env{'user.domain'}; }
6392: if (!$stuname) { $stuname=$env{'user.name'}; }
6393: if (!$home) { $home=$env{'user.home'}; }
6394: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6395:
6396: my %returnhash=();
6397: foreach my $line (split(/\&/,$answer)) {
6398: my ($name,$value)=split(/\=/,$line);
6399: $returnhash{&unescape($name)}=&thaw_unescape($value);
6400: }
6401: my $version;
6402: for ($version=1;$version<=$returnhash{'version'};$version++) {
6403: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6404: $returnhash{$item}=$returnhash{$version.':'.$item};
6405: }
6406: }
6407: return %returnhash;
6408: }
6409:
6410: # ---------------------------------------------------------- Course Description
6411: #
6412: #
6413:
6414: sub coursedescription {
6415: my ($courseid,$args)=@_;
6416: $courseid=~s/^\///;
6417: $courseid=~s/\_/\//g;
6418: my ($cdomain,$cnum)=split(/\//,$courseid);
6419: my $chome=&homeserver($cnum,$cdomain);
6420: my $normalid=$cdomain.'_'.$cnum;
6421: # need to always cache even if we get errors otherwise we keep
6422: # trying and trying and trying to get the course description.
6423: my %envhash=();
6424: my %returnhash=();
6425:
6426: my $expiretime=600;
6427: if ($env{'request.course.id'} eq $normalid) {
6428: $expiretime=120;
6429: }
6430:
6431: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6432: if (!$args->{'freshen_cache'}
6433: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6434: foreach my $key (keys(%env)) {
6435: next if ($key !~ /^\Q$prefix\E(.*)/);
6436: my ($setting) = $1;
6437: $returnhash{$setting} = $env{$key};
6438: }
6439: return %returnhash;
6440: }
6441:
6442: # get the data again
6443:
6444: if (!$args->{'one_time'}) {
6445: $envhash{'course.'.$normalid.'.last_cache'}=time;
6446: }
6447:
6448: if ($chome ne 'no_host') {
6449: %returnhash=&dump('environment',$cdomain,$cnum);
6450: if (!exists($returnhash{'con_lost'})) {
6451: my $username = $env{'user.name'}; # Defult username
6452: if(defined $args->{'user'}) {
6453: $username = $args->{'user'};
6454: }
6455: $returnhash{'home'}= $chome;
6456: $returnhash{'domain'} = $cdomain;
6457: $returnhash{'num'} = $cnum;
6458: if (!defined($returnhash{'type'})) {
6459: $returnhash{'type'} = 'Course';
6460: }
6461: while (my ($name,$value) = each %returnhash) {
6462: $envhash{'course.'.$normalid.'.'.$name}=$value;
6463: }
6464: $returnhash{'url'}=&clutter($returnhash{'url'});
6465: $returnhash{'fn'}=LONCAPA::tempdir() .
6466: $username.'_'.$cdomain.'_'.$cnum;
6467: $envhash{'course.'.$normalid.'.home'}=$chome;
6468: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6469: $envhash{'course.'.$normalid.'.num'}=$cnum;
6470: }
6471: }
6472: if (!$args->{'one_time'}) {
6473: &appenv(\%envhash);
6474: }
6475: return %returnhash;
6476: }
6477:
6478: sub update_released_required {
6479: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6480: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6481: $cid = $env{'request.course.id'};
6482: $cdom = $env{'course.'.$cid.'.domain'};
6483: $cnum = $env{'course.'.$cid.'.num'};
6484: $chome = $env{'course.'.$cid.'.home'};
6485: }
6486: if ($needsrelease) {
6487: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6488: my $needsupdate;
6489: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6490: $needsupdate = 1;
6491: } else {
6492: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6493: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6494: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6495: $needsupdate = 1;
6496: }
6497: }
6498: if ($needsupdate) {
6499: my %needshash = (
6500: 'internal.releaserequired' => $needsrelease,
6501: );
6502: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6503: if ($putresult eq 'ok') {
6504: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6505: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6506: if (ref($crsinfo{$cid}) eq 'HASH') {
6507: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6508: &courseidput($cdom,\%crsinfo,$chome,'notime');
6509: }
6510: }
6511: }
6512: }
6513: return;
6514: }
6515:
6516: # -------------------------------------------------See if a user is privileged
6517:
6518: sub privileged {
6519: my ($username,$domain,$possdomains,$possroles)=@_;
6520: my $now = time;
6521: my $roles;
6522: if (ref($possroles) eq 'ARRAY') {
6523: $roles = $possroles;
6524: } else {
6525: $roles = ['dc','su'];
6526: }
6527: if (ref($possdomains) eq 'ARRAY') {
6528: my %privileged = &privileged_by_domain($possdomains,$roles);
6529: foreach my $dom (@{$possdomains}) {
6530: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6531: (ref($privileged{$dom}) eq 'HASH')) {
6532: foreach my $role (@{$roles}) {
6533: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6534: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6535: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6536: return 1 unless (($end && $end < $now) ||
6537: ($start && $start > $now));
6538: }
6539: }
6540: }
6541: }
6542: }
6543: } else {
6544: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6545: my $now = time;
6546:
6547: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
6548: my ($trole, $tend, $tstart) = split(/_/, $role);
6549: if (grep(/^\Q$trole\E$/,@{$roles})) {
6550: return 1 unless ($tend && $tend < $now)
6551: or ($tstart && $tstart > $now);
6552: }
6553: }
6554: }
6555: return 0;
6556: }
6557:
6558: sub privileged_by_domain {
6559: my ($domains,$roles) = @_;
6560: my %privileged = ();
6561: my $cachetime = 60*60*24;
6562: my $now = time;
6563: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6564: return %privileged;
6565: }
6566: foreach my $dom (@{$domains}) {
6567: next if (ref($privileged{$dom}) eq 'HASH');
6568: my $needroles;
6569: foreach my $role (@{$roles}) {
6570: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6571: if (defined($cached)) {
6572: if (ref($result) eq 'HASH') {
6573: $privileged{$dom}{$role} = $result;
6574: }
6575: } else {
6576: $needroles = 1;
6577: }
6578: }
6579: if ($needroles) {
6580: my %dompersonnel = &get_domain_roles($dom,$roles);
6581: $privileged{$dom} = {};
6582: foreach my $server (keys(%dompersonnel)) {
6583: if (ref($dompersonnel{$server}) eq 'HASH') {
6584: foreach my $item (keys(%{$dompersonnel{$server}})) {
6585: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6586: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6587: next if ($end && $end < $now);
6588: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6589: $dompersonnel{$server}{$item};
6590: }
6591: }
6592: }
6593: if (ref($privileged{$dom}) eq 'HASH') {
6594: foreach my $role (@{$roles}) {
6595: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6596: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6597: } else {
6598: my %hash = ();
6599: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6600: }
6601: }
6602: }
6603: }
6604: }
6605: return %privileged;
6606: }
6607:
6608: # -------------------------------------------------------- Get user privileges
6609:
6610: sub rolesinit {
6611: my ($domain, $username) = @_;
6612: my %userroles = ('user.login.time' => time);
6613: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6614:
6615: # firstaccess and timerinterval are related to timed maps/resources.
6616: # also, blocking can be triggered by an activating timer
6617: # it's saved in the user's %env.
6618: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6619: my %timerinterval = &dump('timerinterval', $domain, $username);
6620: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
6621: %timerintchk, %timerintenv);
6622:
6623: foreach my $key (keys(%firstaccess)) {
6624: my ($cid, $rest) = split(/\0/, $key);
6625: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6626: }
6627:
6628: foreach my $key (keys(%timerinterval)) {
6629: my ($cid,$rest) = split(/\0/,$key);
6630: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6631: }
6632:
6633: my %allroles=();
6634: my %allgroups=();
6635:
6636: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
6637: my $role = $rolesdump{$area};
6638: $area =~ s/\_\w\w$//;
6639:
6640: my ($trole, $tend, $tstart, $group_privs);
6641:
6642: if ($role =~ /^cr/) {
6643: # Custom role, defined by a user
6644: # e.g., user.role.cr/msu/smith/mynewrole
6645: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6646: $trole = $1;
6647: ($tend, $tstart) = split('_', $2);
6648: } else {
6649: $trole = $role;
6650: }
6651: } elsif ($role =~ m|^gr/|) {
6652: # Role of member in a group, defined within a course/community
6653: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6654: ($trole, $tend, $tstart) = split(/_/, $role);
6655: next if $tstart eq '-1';
6656: ($trole, $group_privs) = split(/\//, $trole);
6657: $group_privs = &unescape($group_privs);
6658: } else {
6659: # Just a normal role, defined in roles.tab
6660: ($trole, $tend, $tstart) = split(/_/,$role);
6661: }
6662:
6663: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6664: $username);
6665: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6666:
6667: # role expired or not available yet?
6668: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6669: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6670:
6671: next if $area eq '' or $trole eq '';
6672:
6673: my $spec = "$trole.$area";
6674: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6675:
6676: if ($trole =~ /^cr\//) {
6677: # Custom role, defined by a user
6678: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6679: } elsif ($trole eq 'gr') {
6680: # Role of a member in a group, defined within a course/community
6681: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6682: next;
6683: } else {
6684: # Normal role, defined in roles.tab
6685: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6686: }
6687:
6688: my $cid = $tdomain.'_'.$trest;
6689: unless ($firstaccchk{$cid}) {
6690: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6691: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6692: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6693: $coursetimerstarts{$cid}{$item};
6694: }
6695: }
6696: $firstaccchk{$cid} = 1;
6697: }
6698: unless ($timerintchk{$cid}) {
6699: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6700: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6701: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6702: $coursetimerintervals{$cid}{$item};
6703: }
6704: }
6705: $timerintchk{$cid} = 1;
6706: }
6707: }
6708:
6709: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6710: \%allroles, \%allgroups);
6711: $env{'user.adv'} = $userroles{'user.adv'};
6712: $env{'user.rar'} = $userroles{'user.rar'};
6713:
6714: return (\%userroles,\%firstaccenv,\%timerintenv);
6715: }
6716:
6717: sub set_arearole {
6718: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6719: unless ($nolog) {
6720: # log the associated role with the area
6721: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6722: }
6723: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
6724: }
6725:
6726: sub custom_roleprivs {
6727: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6728: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
6729: my $homsvr = &homeserver($rauthor,$rdomain);
6730: if (&hostname($homsvr) ne '') {
6731: my ($rdummy,$roledef)=
6732: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6733: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6734: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6735: if (defined($syspriv)) {
6736: if ($trest =~ /^$match_community$/) {
6737: $syspriv =~ s/bre\&S//;
6738: }
6739: $$allroles{'cm./'}.=':'.$syspriv;
6740: $$allroles{$spec.'./'}.=':'.$syspriv;
6741: }
6742: if ($tdomain ne '') {
6743: if (defined($dompriv)) {
6744: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6745: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6746: }
6747: if (($trest ne '') && (defined($coursepriv))) {
6748: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6749: my $rolename = $1;
6750: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6751: }
6752: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6753: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6754: }
6755: }
6756: }
6757: }
6758: }
6759:
6760: sub course_adhocrole_privs {
6761: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6762: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6763: if ($overrides{"internal.adhocpriv.$rolename"}) {
6764: my (%currprivs,%storeprivs);
6765: foreach my $item (split(/:/,$coursepriv)) {
6766: my ($priv,$restrict) = split(/\&/,$item);
6767: $currprivs{$priv} = $restrict;
6768: }
6769: my (%possadd,%possremove,%full);
6770: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6771: my ($priv,$restrict)=split(/\&/,$item);
6772: $full{$priv} = $restrict;
6773: }
6774: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6775: next if ($item eq '');
6776: my ($rule,$rest) = split(/=/,$item);
6777: next unless (($rule eq 'off') || ($rule eq 'on'));
6778: foreach my $priv (split(/:/,$rest)) {
6779: if ($priv ne '') {
6780: if ($rule eq 'off') {
6781: $possremove{$priv} = 1;
6782: } else {
6783: $possadd{$priv} = 1;
6784: }
6785: }
6786: }
6787: }
6788: foreach my $priv (sort(keys(%full))) {
6789: if (exists($currprivs{$priv})) {
6790: unless (exists($possremove{$priv})) {
6791: $storeprivs{$priv} = $currprivs{$priv};
6792: }
6793: } elsif (exists($possadd{$priv})) {
6794: $storeprivs{$priv} = $full{$priv};
6795: }
6796: }
6797: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6798: }
6799: return $coursepriv;
6800: }
6801:
6802: sub group_roleprivs {
6803: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6804: my $access = 1;
6805: my $now = time;
6806: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6807: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6808: if ($access) {
6809: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
6810: $$allgroups{$course}{$group} .=':'.$group_privs;
6811: }
6812: }
6813:
6814: sub standard_roleprivs {
6815: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6816: if (defined($pr{$trole.':s'})) {
6817: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6818: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6819: }
6820: if ($tdomain ne '') {
6821: if (defined($pr{$trole.':d'})) {
6822: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6823: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6824: }
6825: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6826: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6827: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6828: }
6829: }
6830: }
6831:
6832: sub set_userprivs {
6833: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
6834: my $author=0;
6835: my $adv=0;
6836: my $rar=0;
6837: my %grouproles = ();
6838: if (keys(%{$allgroups}) > 0) {
6839: my @groupkeys;
6840: foreach my $role (keys(%{$allroles})) {
6841: push(@groupkeys,$role);
6842: }
6843: if (ref($groups_roles) eq 'HASH') {
6844: foreach my $key (keys(%{$groups_roles})) {
6845: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6846: push(@groupkeys,$key);
6847: }
6848: }
6849: }
6850: if (@groupkeys > 0) {
6851: foreach my $role (@groupkeys) {
6852: my ($trole,$area,$sec,$extendedarea);
6853: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6854: $trole = $1;
6855: $area = $2;
6856: $sec = $3;
6857: $extendedarea = $area.$sec;
6858: if (exists($$allgroups{$area})) {
6859: foreach my $group (keys(%{$$allgroups{$area}})) {
6860: my $spec = $trole.'.'.$extendedarea;
6861: $grouproles{$spec.'.'.$area.'/'.$group} =
6862: $$allgroups{$area}{$group};
6863: }
6864: }
6865: }
6866: }
6867: }
6868: }
6869: foreach my $group (keys(%grouproles)) {
6870: $$allroles{$group} = $grouproles{$group};
6871: }
6872: foreach my $role (keys(%{$allroles})) {
6873: my %thesepriv;
6874: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
6875: foreach my $item (split(/:/,$$allroles{$role})) {
6876: if ($item ne '') {
6877: my ($privilege,$restrictions)=split(/&/,$item);
6878: if ($restrictions eq '') {
6879: $thesepriv{$privilege}='F';
6880: } elsif ($thesepriv{$privilege} ne 'F') {
6881: $thesepriv{$privilege}.=$restrictions;
6882: }
6883: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
6884: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
6885: }
6886: }
6887: my $thesestr='';
6888: foreach my $priv (sort(keys(%thesepriv))) {
6889: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6890: }
6891: $userroles->{'user.priv.'.$role} = $thesestr;
6892: }
6893: return ($author,$adv,$rar);
6894: }
6895:
6896: sub role_status {
6897: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
6898: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
6899: my ($one,$two) = split(m{\./},$rolekey,2);
6900: (undef,undef,$$role) = split(/\./,$one,3);
6901: unless (!defined($$role) || $$role eq '') {
6902: $$where = '/'.$two;
6903: $$trolecode=$$role.'.'.$$where;
6904: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6905: $$tstatus='is';
6906: if ($$tstart && $$tstart>$update) {
6907: $$tstatus='future';
6908: if ($$tstart<$now) {
6909: if ($$tstart && $$tstart>$refresh) {
6910: if (($$where ne '') && ($$role ne '')) {
6911: my (%allroles,%allgroups,$group_privs,
6912: %groups_roles,@rolecodes);
6913: my %userroles = (
6914: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6915: );
6916: @rolecodes = ('cm');
6917: my $spec=$$role.'.'.$$where;
6918: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6919: if ($$role =~ /^cr\//) {
6920: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
6921: push(@rolecodes,'cr');
6922: } elsif ($$role eq 'gr') {
6923: push(@rolecodes,$$role);
6924: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6925: $env{'user.name'});
6926: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
6927: (undef,my $group_privs) = split(/\//,$trole);
6928: $group_privs = &unescape($group_privs);
6929: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
6930: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
6931: &get_groups_roles($tdomain,$trest,
6932: \%course_roles,\@rolecodes,
6933: \%groups_roles);
6934: } else {
6935: push(@rolecodes,$$role);
6936: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6937: }
6938: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6939: \%groups_roles);
6940: &appenv(\%userroles,\@rolecodes);
6941: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
6942: }
6943: }
6944: $$tstatus = 'is';
6945: }
6946: }
6947: if ($$tend) {
6948: if ($$tend<$update) {
6949: $$tstatus='expired';
6950: } elsif ($$tend<$now) {
6951: $$tstatus='will_not';
6952: }
6953: }
6954: }
6955: }
6956: }
6957:
6958: sub get_groups_roles {
6959: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6960: return unless((ref($cdom_courseroles) eq 'HASH') &&
6961: (ref($rolecodes) eq 'ARRAY') &&
6962: (ref($groups_roles) eq 'HASH'));
6963: if (keys(%{$cdom_courseroles}) > 0) {
6964: my ($cnum) = ($rest =~ /^($match_courseid)/);
6965: if ($cdom ne '' && $cnum ne '') {
6966: foreach my $key (keys(%{$cdom_courseroles})) {
6967: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6968: my $crsrole = $1;
6969: my $crssec = $2;
6970: if ($crsrole =~ /^cr/) {
6971: unless (grep(/^cr$/,@{$rolecodes})) {
6972: push(@{$rolecodes},'cr');
6973: }
6974: } else {
6975: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6976: push(@{$rolecodes},$crsrole);
6977: }
6978: }
6979: my $rolekey = "$crsrole./$cdom/$cnum";
6980: if ($crssec ne '') {
6981: $rolekey .= "/$crssec";
6982: }
6983: $rolekey .= './';
6984: $groups_roles->{$rolekey} = $rolecodes;
6985: }
6986: }
6987: }
6988: }
6989: return;
6990: }
6991:
6992: sub delete_env_groupprivs {
6993: my ($where,$courseroles,$possroles) = @_;
6994: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6995: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6996: unless (ref($courseroles->{$udom}) eq 'HASH') {
6997: %{$courseroles->{$udom}} =
6998: &get_my_roles('','','userroles',['active'],
6999: $possroles,[$udom],1);
7000: }
7001: if (ref($courseroles->{$udom}) eq 'HASH') {
7002: foreach my $item (keys(%{$courseroles->{$udom}})) {
7003: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
7004: my $area = '/'.$cdom.'/'.$cnum;
7005: my $privkey = "user.priv.$crsrole.$area";
7006: if ($crssec ne '') {
7007: $privkey .= '/'.$crssec;
7008: }
7009: $privkey .= ".$area/$group";
7010: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
7011: }
7012: }
7013: return;
7014: }
7015:
7016: sub check_adhoc_privs {
7017: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
7018: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
7019: if ($sec) {
7020: $cckey .= '/'.$sec;
7021: }
7022: my $setprivs;
7023: if ($env{$cckey}) {
7024: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
7025: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
7026: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
7027: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
7028: $setprivs = 1;
7029: }
7030: } else {
7031: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
7032: $setprivs = 1;
7033: }
7034: return $setprivs;
7035: }
7036:
7037: sub set_adhoc_privileges {
7038: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
7039: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
7040: my $area = '/'.$dcdom.'/'.$pickedcourse;
7041: if ($sec ne '') {
7042: $area .= '/'.$sec;
7043: }
7044: my $spec = $role.'.'.$area;
7045: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
7046: $env{'user.name'},1);
7047: my %rolehash = ();
7048: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
7049: my $rolename = $1;
7050: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
7051: my %domdef = &get_domain_defaults($dcdom);
7052: if (ref($domdef{'adhocroles'}) eq 'HASH') {
7053: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
7054: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
7055: }
7056: }
7057: } else {
7058: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
7059: }
7060: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
7061: &appenv(\%userroles,[$role,'cm']);
7062: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
7063: unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
7064: ($caller eq 'tiny')) {
7065: &appenv( {'request.role' => $spec,
7066: 'request.role.domain' => $dcdom,
7067: 'request.course.sec' => $sec,
7068: }
7069: );
7070: my $tadv=0;
7071: if (&allowed('adv') eq 'F') { $tadv=1; }
7072: &appenv({'request.role.adv' => $tadv});
7073: }
7074: }
7075:
7076: # --------------------------------------------------------------- get interface
7077:
7078: sub get {
7079: my ($namespace,$storearr,$udomain,$uname)=@_;
7080: my $items='';
7081: foreach my $item (@$storearr) {
7082: $items.=&escape($item).'&';
7083: }
7084: $items=~s/\&$//;
7085: if (!$udomain) { $udomain=$env{'user.domain'}; }
7086: if (!$uname) { $uname=$env{'user.name'}; }
7087: my $uhome=&homeserver($uname,$udomain);
7088:
7089: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
7090: my @pairs=split(/\&/,$rep);
7091: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
7092: return @pairs;
7093: }
7094: my %returnhash=();
7095: my $i=0;
7096: foreach my $item (@$storearr) {
7097: $returnhash{$item}=&thaw_unescape($pairs[$i]);
7098: $i++;
7099: }
7100: return %returnhash;
7101: }
7102:
7103: # --------------------------------------------------------------- del interface
7104:
7105: sub del {
7106: my ($namespace,$storearr,$udomain,$uname)=@_;
7107: my $items='';
7108: foreach my $item (@$storearr) {
7109: $items.=&escape($item).'&';
7110: }
7111:
7112: $items=~s/\&$//;
7113: if (!$udomain) { $udomain=$env{'user.domain'}; }
7114: if (!$uname) { $uname=$env{'user.name'}; }
7115: my $uhome=&homeserver($uname,$udomain);
7116: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
7117: }
7118:
7119: # -------------------------------------------------------------- dump interface
7120:
7121: sub unserialize {
7122: my ($rep, $escapedkeys) = @_;
7123:
7124: return {} if $rep =~ /^error/;
7125:
7126: my %returnhash=();
7127: foreach my $item (split(/\&/,$rep)) {
7128: my ($key, $value) = split(/=/, $item, 2);
7129: $key = unescape($key) unless $escapedkeys;
7130: next if $key =~ /^error: 2 /;
7131: $returnhash{$key} = &thaw_unescape($value);
7132: }
7133: #return %returnhash;
7134: return \%returnhash;
7135: }
7136:
7137: # see Lond::dump_with_regexp
7138: # if $escapedkeys hash keys won't get unescaped.
7139: sub dump {
7140: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
7141: if (!$udomain) { $udomain=$env{'user.domain'}; }
7142: if (!$uname) { $uname=$env{'user.name'}; }
7143: my $uhome=&homeserver($uname,$udomain);
7144:
7145: if ($regexp) {
7146: $regexp=&escape($regexp);
7147: } else {
7148: $regexp='.';
7149: }
7150: if (grep { $_ eq $uhome } current_machine_ids()) {
7151: # user is hosted on this machine
7152: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
7153: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
7154: return %{unserialize($reply, $escapedkeys)};
7155: }
7156: my $rep;
7157: if ($encrypt) {
7158: $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
7159: } else {
7160: $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
7161: }
7162: my @pairs=split(/\&/,$rep);
7163: my %returnhash=();
7164: if (!($rep =~ /^error/ )) {
7165: foreach my $item (@pairs) {
7166: my ($key,$value)=split(/=/,$item,2);
7167: $key = unescape($key) unless $escapedkeys;
7168: #$key = &unescape($key);
7169: next if ($key =~ /^error: 2 /);
7170: $returnhash{$key}=&thaw_unescape($value);
7171: }
7172: }
7173: return %returnhash;
7174: }
7175:
7176:
7177: # --------------------------------------------------------- dumpstore interface
7178:
7179: sub dumpstore {
7180: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
7181: # same as dump but keys must be escaped. They may contain colon separated
7182: # lists of values that may themself contain colons (e.g. symbs).
7183: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
7184: }
7185:
7186: # -------------------------------------------------------------- keys interface
7187:
7188: sub getkeys {
7189: my ($namespace,$udomain,$uname)=@_;
7190: if (!$udomain) { $udomain=$env{'user.domain'}; }
7191: if (!$uname) { $uname=$env{'user.name'}; }
7192: my $uhome=&homeserver($uname,$udomain);
7193: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
7194: my @keyarray=();
7195: foreach my $key (split(/\&/,$rep)) {
7196: next if ($key =~ /^error: 2 /);
7197: push(@keyarray,&unescape($key));
7198: }
7199: return @keyarray;
7200: }
7201:
7202: # --------------------------------------------------------------- currentdump
7203: sub currentdump {
7204: my ($courseid,$sdom,$sname)=@_;
7205: $courseid = $env{'request.course.id'} if (! defined($courseid));
7206: $sdom = $env{'user.domain'} if (! defined($sdom));
7207: $sname = $env{'user.name'} if (! defined($sname));
7208: my $uhome = &homeserver($sname,$sdom);
7209: my $rep;
7210:
7211: if (grep { $_ eq $uhome } current_machine_ids()) {
7212: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
7213: $courseid)));
7214: } else {
7215: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
7216: }
7217:
7218: return if ($rep =~ /^(error:|no_such_host)/);
7219: #
7220: my %returnhash=();
7221: #
7222: if ($rep eq 'unknown_cmd') {
7223: # an old lond will not know currentdump
7224: # Do a dump and make it look like a currentdump
7225: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
7226: return if ($tmp[0] =~ /^(error:|no_such_host)/);
7227: my %hash = @tmp;
7228: @tmp=();
7229: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
7230: } else {
7231: my @pairs=split(/\&/,$rep);
7232: foreach my $pair (@pairs) {
7233: my ($key,$value)=split(/=/,$pair,2);
7234: my ($symb,$param) = split(/:/,$key);
7235: $returnhash{&unescape($symb)}->{&unescape($param)} =
7236: &thaw_unescape($value);
7237: }
7238: }
7239: return %returnhash;
7240: }
7241:
7242: sub convert_dump_to_currentdump{
7243: my %hash = %{shift()};
7244: my %returnhash;
7245: # Code ripped from lond, essentially. The only difference
7246: # here is the unescaping done by lonnet::dump(). Conceivably
7247: # we might run in to problems with parameter names =~ /^v\./
7248: while (my ($key,$value) = each(%hash)) {
7249: my ($v,$symb,$param) = split(/:/,$key);
7250: $symb = &unescape($symb);
7251: $param = &unescape($param);
7252: next if ($v eq 'version' || $symb eq 'keys');
7253: next if (exists($returnhash{$symb}) &&
7254: exists($returnhash{$symb}->{$param}) &&
7255: $returnhash{$symb}->{'v.'.$param} > $v);
7256: $returnhash{$symb}->{$param}=$value;
7257: $returnhash{$symb}->{'v.'.$param}=$v;
7258: }
7259: #
7260: # Remove all of the keys in the hashes which keep track of
7261: # the version of the parameter.
7262: while (my ($symb,$param_hash) = each(%returnhash)) {
7263: # use a foreach because we are going to delete from the hash.
7264: foreach my $key (keys(%$param_hash)) {
7265: delete($param_hash->{$key}) if ($key =~ /^v\./);
7266: }
7267: }
7268: return \%returnhash;
7269: }
7270:
7271: # ------------------------------------------------------ critical inc interface
7272:
7273: sub cinc {
7274: return &inc(@_,'critical');
7275: }
7276:
7277: # --------------------------------------------------------------- inc interface
7278:
7279: sub inc {
7280: my ($namespace,$store,$udomain,$uname,$critical) = @_;
7281: if (!$udomain) { $udomain=$env{'user.domain'}; }
7282: if (!$uname) { $uname=$env{'user.name'}; }
7283: my $uhome=&homeserver($uname,$udomain);
7284: my $items='';
7285: if (! ref($store)) {
7286: # got a single value, so use that instead
7287: $items = &escape($store).'=&';
7288: } elsif (ref($store) eq 'SCALAR') {
7289: $items = &escape($$store).'=&';
7290: } elsif (ref($store) eq 'ARRAY') {
7291: $items = join('=&',map {&escape($_);} @{$store});
7292: } elsif (ref($store) eq 'HASH') {
7293: while (my($key,$value) = each(%{$store})) {
7294: $items.= &escape($key).'='.&escape($value).'&';
7295: }
7296: }
7297: $items=~s/\&$//;
7298: if ($critical) {
7299: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
7300: } else {
7301: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
7302: }
7303: }
7304:
7305: # --------------------------------------------------------------- put interface
7306:
7307: sub put {
7308: my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
7309: if (!$udomain) { $udomain=$env{'user.domain'}; }
7310: if (!$uname) { $uname=$env{'user.name'}; }
7311: my $uhome=&homeserver($uname,$udomain);
7312: my $items='';
7313: foreach my $item (keys(%$storehash)) {
7314: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
7315: }
7316: $items=~s/\&$//;
7317: if ($encrypt) {
7318: return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
7319: } else {
7320: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
7321: }
7322: }
7323:
7324: # ------------------------------------------------------------ newput interface
7325:
7326: sub newput {
7327: my ($namespace,$storehash,$udomain,$uname)=@_;
7328: if (!$udomain) { $udomain=$env{'user.domain'}; }
7329: if (!$uname) { $uname=$env{'user.name'}; }
7330: my $uhome=&homeserver($uname,$udomain);
7331: my $items='';
7332: foreach my $key (keys(%$storehash)) {
7333: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7334: }
7335: $items=~s/\&$//;
7336: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
7337: }
7338:
7339: # --------------------------------------------------------- putstore interface
7340:
7341: sub putstore {
7342: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
7343: if (!$udomain) { $udomain=$env{'user.domain'}; }
7344: if (!$uname) { $uname=$env{'user.name'}; }
7345: my $uhome=&homeserver($uname,$udomain);
7346: my $items='';
7347: foreach my $key (keys(%$storehash)) {
7348: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7349: }
7350: $items=~s/\&$//;
7351: my $esc_symb=&escape($symb);
7352: my $esc_v=&escape($version);
7353: my $reply =
7354: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
7355: $uhome);
7356: if (($tolog) && ($reply eq 'ok')) {
7357: my $namevalue='';
7358: foreach my $key (keys(%{$storehash})) {
7359: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7360: }
7361: my $ip = &get_requestor_ip();
7362: $namevalue .= 'ip='.&escape($ip).
7363: '&host='.&escape($perlvar{'lonHostID'}).
7364: '&version='.$esc_v.
7365: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
7366: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
7367: }
7368: if ($reply eq 'unknown_cmd') {
7369: # gfall back to way things use to be done
7370: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7371: $uname);
7372: }
7373: return $reply;
7374: }
7375:
7376: sub old_putstore {
7377: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
7378: if (!$udomain) { $udomain=$env{'user.domain'}; }
7379: if (!$uname) { $uname=$env{'user.name'}; }
7380: my $uhome=&homeserver($uname,$udomain);
7381: my %newstorehash;
7382: foreach my $item (keys(%$storehash)) {
7383: my $key = $version.':'.&escape($symb).':'.$item;
7384: $newstorehash{$key} = $storehash->{$item};
7385: }
7386: my $items='';
7387: my %allitems = ();
7388: foreach my $item (keys(%newstorehash)) {
7389: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
7390: my $key = $1.':keys:'.$2;
7391: $allitems{$key} .= $3.':';
7392: }
7393: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
7394: }
7395: foreach my $item (keys(%allitems)) {
7396: $allitems{$item} =~ s/\:$//;
7397: $items.= $item.'='.$allitems{$item}.'&';
7398: }
7399: $items=~s/\&$//;
7400: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
7401: }
7402:
7403: # ------------------------------------------------------ critical put interface
7404:
7405: sub cput {
7406: my ($namespace,$storehash,$udomain,$uname)=@_;
7407: if (!$udomain) { $udomain=$env{'user.domain'}; }
7408: if (!$uname) { $uname=$env{'user.name'}; }
7409: my $uhome=&homeserver($uname,$udomain);
7410: my $items='';
7411: foreach my $item (keys(%$storehash)) {
7412: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
7413: }
7414: $items=~s/\&$//;
7415: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
7416: }
7417:
7418: # -------------------------------------------------------------- eget interface
7419:
7420: sub eget {
7421: my ($namespace,$storearr,$udomain,$uname)=@_;
7422: my $items='';
7423: foreach my $item (@$storearr) {
7424: $items.=&escape($item).'&';
7425: }
7426: $items=~s/\&$//;
7427: if (!$udomain) { $udomain=$env{'user.domain'}; }
7428: if (!$uname) { $uname=$env{'user.name'}; }
7429: my $uhome=&homeserver($uname,$udomain);
7430: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
7431: my @pairs=split(/\&/,$rep);
7432: my %returnhash=();
7433: my $i=0;
7434: foreach my $item (@$storearr) {
7435: $returnhash{$item}=&thaw_unescape($pairs[$i]);
7436: $i++;
7437: }
7438: return %returnhash;
7439: }
7440:
7441: # ------------------------------------------------------------ tmpput interface
7442: sub tmpput {
7443: my ($storehash,$server,$context)=@_;
7444: my $items='';
7445: foreach my $item (keys(%$storehash)) {
7446: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
7447: }
7448: $items=~s/\&$//;
7449: if (defined($context)) {
7450: $items .= ':'.&escape($context);
7451: }
7452: return &reply("tmpput:$items",$server);
7453: }
7454:
7455: # ------------------------------------------------------------ tmpget interface
7456: sub tmpget {
7457: my ($token,$server)=@_;
7458: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7459: my $rep=&reply("tmpget:$token",$server);
7460: my %returnhash;
7461: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7462: return %returnhash;
7463: }
7464: foreach my $item (split(/\&/,$rep)) {
7465: my ($key,$value)=split(/=/,$item);
7466: $returnhash{&unescape($key)}=&thaw_unescape($value);
7467: }
7468: return %returnhash;
7469: }
7470:
7471: # ------------------------------------------------------------ tmpdel interface
7472: sub tmpdel {
7473: my ($token,$server)=@_;
7474: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7475: return &reply("tmpdel:$token",$server);
7476: }
7477:
7478: # ------------------------------------------------------------ get_timebased_id
7479:
7480: sub get_timebased_id {
7481: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7482: $maxtries) = @_;
7483: my ($newid,$error,$dellock);
7484: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7485: return ('','ok','invalid call to get suffix');
7486: }
7487:
7488: # set defaults for any optional args for which values were not supplied
7489: if ($who eq '') {
7490: $who = $env{'user.name'}.':'.$env{'user.domain'};
7491: }
7492: if (!$locktries) {
7493: $locktries = 3;
7494: }
7495: if (!$maxtries) {
7496: $maxtries = 10;
7497: }
7498:
7499: if (($cdom eq '') || ($cnum eq '')) {
7500: if ($env{'request.course.id'}) {
7501: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7502: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7503: }
7504: if (($cdom eq '') || ($cnum eq '')) {
7505: return ('','ok','call to get suffix not in course context');
7506: }
7507: }
7508:
7509: # construct locking item
7510: my $lockhash = {
7511: $prefix."\0".'locked_'.$keyid => $who,
7512: };
7513: my $tries = 0;
7514:
7515: # attempt to get lock on nohist_$namespace file
7516: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7517: while (($gotlock ne 'ok') && $tries <$locktries) {
7518: $tries ++;
7519: sleep 1;
7520: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7521: }
7522:
7523: # attempt to get unique identifier, based on current timestamp
7524: if ($gotlock eq 'ok') {
7525: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
7526: my $id = time;
7527: $newid = $id;
7528: if ($idtype eq 'addcode') {
7529: $newid .= &sixnum_code();
7530: }
7531: my $idtries = 0;
7532: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7533: if ($idtype eq 'concat') {
7534: $newid = $id.$idtries;
7535: } elsif ($idtype eq 'addcode') {
7536: $newid = $newid.&sixnum_code();
7537: } else {
7538: $newid ++;
7539: }
7540: $idtries ++;
7541: }
7542: if (!exists($inuse{$prefix."\0".$newid})) {
7543: my %new_item = (
7544: $prefix."\0".$newid => $who,
7545: );
7546: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
7547: $cdom,$cnum);
7548: if ($putresult ne 'ok') {
7549: undef($newid);
7550: $error = 'error saving new item: '.$putresult;
7551: }
7552: } else {
7553: undef($newid);
7554: $error = ('error: no unique suffix available for the new item ');
7555: }
7556: # remove lock
7557: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7558: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7559: } else {
7560: $error = "error: could not obtain lockfile\n";
7561: $dellock = 'ok';
7562: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7563: $dellock = 'nolock';
7564: }
7565: }
7566: return ($newid,$dellock,$error);
7567: }
7568:
7569: sub sixnum_code {
7570: my $code;
7571: for (0..6) {
7572: $code .= int( rand(9) );
7573: }
7574: return $code;
7575: }
7576:
7577: # -------------------------------------------------- portfolio access checking
7578:
7579: sub portfolio_access {
7580: my ($requrl,$clientip) = @_;
7581: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
7582: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
7583: if ($result) {
7584: my %setters;
7585: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7586: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
7587: &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
7588: if (($startblock && $endblock) || ($by_ip)) {
7589: return 'B';
7590: }
7591: } else {
7592: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
7593: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
7594: if (($startblock && $endblock) || ($by_ip)) {
7595: return 'B';
7596: }
7597: }
7598: }
7599: if ($result eq 'ok') {
7600: return 'F';
7601: } elsif ($result =~ /^[^:]+:guest_/) {
7602: return 'A';
7603: }
7604: return '';
7605: }
7606:
7607: sub get_portfolio_access {
7608: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
7609:
7610: if (!ref($access_hash)) {
7611: my $current_perms = &get_portfile_permissions($udom,$unum);
7612: my %access_controls = &get_access_controls($current_perms,$group,
7613: $file_name);
7614: $access_hash = $access_controls{$file_name};
7615: }
7616:
7617: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
7618: my $now = time;
7619: if (ref($access_hash) eq 'HASH') {
7620: foreach my $key (keys(%{$access_hash})) {
7621: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7622: if ($start > $now) {
7623: next;
7624: }
7625: if ($end && $end<$now) {
7626: next;
7627: }
7628: if ($scope eq 'public') {
7629: $public = $key;
7630: last;
7631: } elsif ($scope eq 'guest') {
7632: $guest = $key;
7633: } elsif ($scope eq 'domains') {
7634: push(@domains,$key);
7635: } elsif ($scope eq 'users') {
7636: push(@users,$key);
7637: } elsif ($scope eq 'course') {
7638: push(@courses,$key);
7639: } elsif ($scope eq 'group') {
7640: push(@groups,$key);
7641: } elsif ($scope eq 'ip') {
7642: push(@ips,$key);
7643: }
7644: }
7645: if ($public) {
7646: return 'ok';
7647: } elsif (@ips > 0) {
7648: my $allowed;
7649: foreach my $ipkey (@ips) {
7650: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7651: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7652: $allowed = 1;
7653: last;
7654: }
7655: }
7656: }
7657: if ($allowed) {
7658: return 'ok';
7659: }
7660: }
7661: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7662: if ($guest) {
7663: return $guest;
7664: }
7665: } else {
7666: if (@domains > 0) {
7667: foreach my $domkey (@domains) {
7668: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7669: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7670: return 'ok';
7671: }
7672: }
7673: }
7674: }
7675: if (@users > 0) {
7676: foreach my $userkey (@users) {
7677: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7678: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7679: if (ref($item) eq 'HASH') {
7680: if (($item->{'uname'} eq $env{'user.name'}) &&
7681: ($item->{'udom'} eq $env{'user.domain'})) {
7682: return 'ok';
7683: }
7684: }
7685: }
7686: }
7687: }
7688: }
7689: my %roleshash;
7690: my @courses_and_groups = @courses;
7691: push(@courses_and_groups,@groups);
7692: if (@courses_and_groups > 0) {
7693: my (%allgroups,%allroles);
7694: my ($start,$end,$role,$sec,$group);
7695: foreach my $envkey (%env) {
7696: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
7697: my $cid = $2.'_'.$3;
7698: if ($1 eq 'gr') {
7699: $group = $4;
7700: $allgroups{$cid}{$group} = $env{$envkey};
7701: } else {
7702: if ($4 eq '') {
7703: $sec = 'none';
7704: } else {
7705: $sec = $4;
7706: }
7707: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7708: }
7709: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
7710: my $cid = $2.'_'.$3;
7711: if ($4 eq '') {
7712: $sec = 'none';
7713: } else {
7714: $sec = $4;
7715: }
7716: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7717: }
7718: }
7719: if (keys(%allroles) == 0) {
7720: return;
7721: }
7722: foreach my $key (@courses_and_groups) {
7723: my %content = %{$$access_hash{$key}};
7724: my $cnum = $content{'number'};
7725: my $cdom = $content{'domain'};
7726: my $cid = $cdom.'_'.$cnum;
7727: if (!exists($allroles{$cid})) {
7728: next;
7729: }
7730: foreach my $role_id (keys(%{$content{'roles'}})) {
7731: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7732: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7733: my @status = @{$content{'roles'}{$role_id}{'access'}};
7734: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7735: foreach my $role (keys(%{$allroles{$cid}})) {
7736: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7737: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7738: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7739: if (grep/^all$/,@sections) {
7740: return 'ok';
7741: } else {
7742: if (grep/^$sec$/,@sections) {
7743: return 'ok';
7744: }
7745: }
7746: }
7747: }
7748: if (keys(%{$allgroups{$cid}}) == 0) {
7749: if (grep/^none$/,@groups) {
7750: return 'ok';
7751: }
7752: } else {
7753: if (grep/^all$/,@groups) {
7754: return 'ok';
7755: }
7756: foreach my $group (keys(%{$allgroups{$cid}})) {
7757: if (grep/^$group$/,@groups) {
7758: return 'ok';
7759: }
7760: }
7761: }
7762: }
7763: }
7764: }
7765: }
7766: }
7767: if ($guest) {
7768: return $guest;
7769: }
7770: }
7771: }
7772: return;
7773: }
7774:
7775: sub course_group_datechecker {
7776: my ($dates,$now,$status) = @_;
7777: my ($start,$end) = split(/\./,$dates);
7778: if (!$start && !$end) {
7779: return 'ok';
7780: }
7781: if (grep/^active$/,@{$status}) {
7782: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7783: return 'ok';
7784: }
7785: }
7786: if (grep/^previous$/,@{$status}) {
7787: if ($end > $now ) {
7788: return 'ok';
7789: }
7790: }
7791: if (grep/^future$/,@{$status}) {
7792: if ($start > $now) {
7793: return 'ok';
7794: }
7795: }
7796: return;
7797: }
7798:
7799: sub parse_portfolio_url {
7800: my ($url) = @_;
7801:
7802: my ($type,$udom,$unum,$group,$file_name);
7803:
7804: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
7805: $type = 1;
7806: $udom = $1;
7807: $unum = $2;
7808: $file_name = $3;
7809: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
7810: $type = 2;
7811: $udom = $1;
7812: $unum = $2;
7813: $group = $3;
7814: $file_name = $3.'/'.$4;
7815: }
7816: if (wantarray) {
7817: return ($type,$udom,$unum,$file_name,$group);
7818: }
7819: return $type;
7820: }
7821:
7822: sub is_portfolio_url {
7823: my ($url) = @_;
7824: return scalar(&parse_portfolio_url($url));
7825: }
7826:
7827: sub is_portfolio_file {
7828: my ($file) = @_;
7829: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
7830: return 1;
7831: }
7832: return;
7833: }
7834:
7835: sub usertools_access {
7836: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
7837: my ($access,%tools);
7838: if ($context eq '') {
7839: $context = 'tools';
7840: }
7841: if ($context eq 'requestcourses') {
7842: %tools = (
7843: official => 1,
7844: unofficial => 1,
7845: community => 1,
7846: textbook => 1,
7847: placement => 1,
7848: lti => 1,
7849: );
7850: } elsif ($context eq 'requestauthor') {
7851: %tools = (
7852: requestauthor => 1,
7853: );
7854: } else {
7855: %tools = (
7856: aboutme => 1,
7857: blog => 1,
7858: webdav => 1,
7859: portfolio => 1,
7860: );
7861: }
7862: return if (!defined($tools{$tool}));
7863:
7864: if (($udom eq '') || ($uname eq '')) {
7865: $udom = $env{'user.domain'};
7866: $uname = $env{'user.name'};
7867: }
7868:
7869: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7870: if ($action ne 'reload') {
7871: if ($context eq 'requestcourses') {
7872: return $env{'environment.canrequest.'.$tool};
7873: } elsif ($context eq 'requestauthor') {
7874: return $env{'environment.canrequest.author'};
7875: } else {
7876: return $env{'environment.availabletools.'.$tool};
7877: }
7878: }
7879: }
7880:
7881: my ($toolstatus,$inststatus,$envkey);
7882: if ($context eq 'requestauthor') {
7883: $envkey = $context;
7884: } else {
7885: $envkey = $context.'.'.$tool;
7886: }
7887:
7888: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7889: ($action ne 'reload')) {
7890: $toolstatus = $env{'environment.'.$envkey};
7891: $inststatus = $env{'environment.inststatus'};
7892: } else {
7893: if (ref($userenvref) eq 'HASH') {
7894: $toolstatus = $userenvref->{$envkey};
7895: $inststatus = $userenvref->{'inststatus'};
7896: } else {
7897: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7898: $toolstatus = $userenv{$envkey};
7899: $inststatus = $userenv{'inststatus'};
7900: }
7901: }
7902:
7903: if ($toolstatus ne '') {
7904: if ($toolstatus) {
7905: $access = 1;
7906: } else {
7907: $access = 0;
7908: }
7909: return $access;
7910: }
7911:
7912: my ($is_adv,%domdef);
7913: if (ref($is_advref) eq 'HASH') {
7914: $is_adv = $is_advref->{'is_adv'};
7915: } else {
7916: $is_adv = &is_advanced_user($udom,$uname);
7917: }
7918: if (ref($domdefref) eq 'HASH') {
7919: %domdef = %{$domdefref};
7920: } else {
7921: %domdef = &get_domain_defaults($udom);
7922: }
7923: if (ref($domdef{$tool}) eq 'HASH') {
7924: if ($is_adv) {
7925: if ($domdef{$tool}{'_LC_adv'} ne '') {
7926: if ($domdef{$tool}{'_LC_adv'}) {
7927: $access = 1;
7928: } else {
7929: $access = 0;
7930: }
7931: return $access;
7932: }
7933: }
7934: if ($inststatus ne '') {
7935: my ($hasaccess,$hasnoaccess);
7936: foreach my $affiliation (split(/:/,$inststatus)) {
7937: if ($domdef{$tool}{$affiliation} ne '') {
7938: if ($domdef{$tool}{$affiliation}) {
7939: $hasaccess = 1;
7940: } else {
7941: $hasnoaccess = 1;
7942: }
7943: }
7944: }
7945: if ($hasaccess || $hasnoaccess) {
7946: if ($hasaccess) {
7947: $access = 1;
7948: } elsif ($hasnoaccess) {
7949: $access = 0;
7950: }
7951: return $access;
7952: }
7953: } else {
7954: if ($domdef{$tool}{'default'} ne '') {
7955: if ($domdef{$tool}{'default'}) {
7956: $access = 1;
7957: } elsif ($domdef{$tool}{'default'} == 0) {
7958: $access = 0;
7959: }
7960: return $access;
7961: }
7962: }
7963: } else {
7964: if (($context eq 'tools') && ($tool ne 'webdav')) {
7965: $access = 1;
7966: } else {
7967: $access = 0;
7968: }
7969: return $access;
7970: }
7971: }
7972:
7973: sub is_course_owner {
7974: my ($cdom,$cnum,$udom,$uname) = @_;
7975: if (($udom eq '') || ($uname eq '')) {
7976: $udom = $env{'user.domain'};
7977: $uname = $env{'user.name'};
7978: }
7979: unless (($udom eq '') || ($uname eq '')) {
7980: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7981: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7982: return 1;
7983: } else {
7984: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7985: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7986: return 1;
7987: }
7988: }
7989: }
7990: }
7991: return;
7992: }
7993:
7994: sub is_advanced_user {
7995: my ($udom,$uname) = @_;
7996: if ($udom ne '' && $uname ne '') {
7997: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7998: if (wantarray) {
7999: return ($env{'user.adv'},$env{'user.author'});
8000: } else {
8001: return $env{'user.adv'};
8002: }
8003: }
8004: }
8005: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
8006: my %allroles;
8007: my ($is_adv,$is_author);
8008: foreach my $role (keys(%roleshash)) {
8009: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
8010: my $area = '/'.$tdomain.'/'.$trest;
8011: if ($sec ne '') {
8012: $area .= '/'.$sec;
8013: }
8014: if (($area ne '') && ($trole ne '')) {
8015: my $spec=$trole.'.'.$area;
8016: if ($trole =~ /^cr\//) {
8017: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
8018: } elsif ($trole ne 'gr') {
8019: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
8020: }
8021: if ($trole eq 'au') {
8022: $is_author = 1;
8023: }
8024: }
8025: }
8026: foreach my $role (keys(%allroles)) {
8027: last if ($is_adv);
8028: foreach my $item (split(/:/,$allroles{$role})) {
8029: if ($item ne '') {
8030: my ($privilege,$restrictions)=split(/&/,$item);
8031: if ($privilege eq 'adv') {
8032: $is_adv = 1;
8033: last;
8034: }
8035: }
8036: }
8037: }
8038: if (wantarray) {
8039: return ($is_adv,$is_author);
8040: }
8041: return $is_adv;
8042: }
8043:
8044: sub check_can_request {
8045: my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
8046: my $canreq = 0;
8047: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8048: $uname = $env{'user.name'};
8049: $udom = $env{'user.domain'};
8050: }
8051: my ($types,$typename) = &Apache::loncommon::course_types();
8052: my @options = ('approval','validate','autolimit');
8053: my $optregex = join('|',@options);
8054: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
8055: foreach my $type (@{$types}) {
8056: if (&usertools_access($uname,$udom,$type,undef,
8057: 'requestcourses')) {
8058: $canreq ++;
8059: if (ref($request_domains) eq 'HASH') {
8060: push(@{$request_domains->{$type}},$udom);
8061: }
8062: if ($dom eq $udom) {
8063: $can_request->{$type} = 1;
8064: }
8065: }
8066: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
8067: ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
8068: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
8069: if (@curr > 0) {
8070: foreach my $item (@curr) {
8071: if (ref($request_domains) eq 'HASH') {
8072: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
8073: if ($otherdom ne '') {
8074: if (ref($request_domains->{$type}) eq 'ARRAY') {
8075: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
8076: push(@{$request_domains->{$type}},$otherdom);
8077: }
8078: } else {
8079: push(@{$request_domains->{$type}},$otherdom);
8080: }
8081: }
8082: }
8083: }
8084: unless ($dom eq $env{'user.domain'}) {
8085: $canreq ++;
8086: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
8087: $can_request->{$type} = 1;
8088: }
8089: }
8090: }
8091: }
8092: }
8093: }
8094: return $canreq;
8095: }
8096:
8097: # ---------------------------------------------- Custom access rule evaluation
8098:
8099: sub customaccess {
8100: my ($priv,$uri)=@_;
8101: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
8102: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
8103: $udom = &LONCAPA::clean_domain($udom);
8104: $ucrs = &LONCAPA::clean_username($ucrs);
8105: my $access=0;
8106: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
8107: my ($effect,$realm,$role,$type)=split(/\:/,$right);
8108: if ($type eq 'user') {
8109: foreach my $scope (split(/\s*\,\s*/,$realm)) {
8110: my ($tdom,$tuname)=split(m{/},$scope);
8111: if ($tdom) {
8112: if ($tdom ne $env{'user.domain'}) { next; }
8113: }
8114: if ($tuname) {
8115: if ($tuname ne $env{'user.name'}) { next; }
8116: }
8117: $access=($effect eq 'allow');
8118: last;
8119: }
8120: } else {
8121: if ($role) {
8122: if ($role ne $urole) { next; }
8123: }
8124: foreach my $scope (split(/\s*\,\s*/,$realm)) {
8125: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
8126: if ($tdom) {
8127: if ($tdom ne $udom) { next; }
8128: }
8129: if ($tcrs) {
8130: if ($tcrs ne $ucrs) { next; }
8131: }
8132: if ($tsec) {
8133: if ($tsec ne $usec) { next; }
8134: }
8135: $access=($effect eq 'allow');
8136: last;
8137: }
8138: if ($realm eq '' && $role eq '') {
8139: $access=($effect eq 'allow');
8140: }
8141: }
8142: }
8143: return $access;
8144: }
8145:
8146: # ------------------------------------------------- Check for a user privilege
8147:
8148: sub allowed {
8149: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
8150: my $ver_orguri=$uri;
8151: $uri=&deversion($uri);
8152: my $orguri=$uri;
8153: $uri=&declutter($uri);
8154:
8155: if ($priv eq 'evb') {
8156: # Evade communication block restrictions for specified role in a course
8157: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
8158: return $1;
8159: } else {
8160: return;
8161: }
8162: }
8163:
8164: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
8165: # Free bre access to adm and meta resources
8166: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$}))
8167: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
8168: && ($priv eq 'bre')) {
8169: return 'F';
8170: }
8171:
8172: # Free bre access to user's own portfolio contents
8173: my ($space,$domain,$name,@dir)=split('/',$uri);
8174: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
8175: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
8176: my %setters;
8177: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
8178: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
8179: if (($startblock && $endblock) || ($by_ip)) {
8180: return 'B';
8181: } else {
8182: return 'F';
8183: }
8184: }
8185:
8186: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
8187: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
8188: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
8189: if (exists($env{'request.course.id'})) {
8190: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8191: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8192: if (($domain eq $cdom) && ($name eq $cnum)) {
8193: my $courseprivid=$env{'request.course.id'};
8194: $courseprivid=~s/\_/\//;
8195: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
8196: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
8197: return $1;
8198: } else {
8199: if ($env{'request.course.sec'}) {
8200: $courseprivid.='/'.$env{'request.course.sec'};
8201: }
8202: if ($env{'user.priv.'.$env{'request.role'}.'./'.
8203: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
8204: return $2;
8205: }
8206: }
8207: }
8208: }
8209: }
8210:
8211: # Free bre to public access
8212:
8213: if ($priv eq 'bre') {
8214: my $copyright;
8215: unless ($uri =~ /ext\.tool/) {
8216: $copyright=&metadata($uri,'copyright');
8217: }
8218: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
8219: return 'F';
8220: }
8221: if ($copyright eq 'priv') {
8222: $uri=~/([^\/]+)\/([^\/]+)\//;
8223: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
8224: return '';
8225: }
8226: }
8227: if ($copyright eq 'domain') {
8228: $uri=~/([^\/]+)\/([^\/]+)\//;
8229: unless (($env{'user.domain'} eq $1) ||
8230: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
8231: return '';
8232: }
8233: }
8234: if ($env{'request.role'}=~ /li\.\//) {
8235: # Library role, so allow browsing of resources in this domain.
8236: return 'F';
8237: }
8238: if ($copyright eq 'custom') {
8239: unless (&customaccess($priv,$uri)) { return ''; }
8240: }
8241: }
8242: # Domain coordinator is trying to create a course
8243: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
8244: # uri is the requested domain in this case.
8245: # comparison to 'request.role.domain' shows if the user has selected
8246: # a role of dc for the domain in question.
8247: return 'F' if ($uri eq $env{'request.role.domain'});
8248: }
8249:
8250: my $thisallowed='';
8251: my $statecond=0;
8252: my $courseprivid='';
8253:
8254: my $ownaccess;
8255: # Community Coordinator or Assistant Co-author browsing resource space.
8256: if (($priv eq 'bro') && ($env{'user.author'})) {
8257: if ($uri eq '') {
8258: $ownaccess = 1;
8259: } else {
8260: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
8261: my $udom = $env{'user.domain'};
8262: my $uname = $env{'user.name'};
8263: if ($uri =~ m{^\Q$udom\E/?$}) {
8264: $ownaccess = 1;
8265: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
8266: unless ($uri =~ m{\.\./}) {
8267: $ownaccess = 1;
8268: }
8269: } elsif (($udom ne 'public') && ($uname ne 'public')) {
8270: my $now = time;
8271: if ($uri =~ m{^([^/]+)/?$}) {
8272: my $adom = $1;
8273: foreach my $key (keys(%env)) {
8274: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
8275: my ($start,$end) = split(/\./,$env{$key});
8276: if (($now >= $start) && (!$end || $end > $now)) {
8277: $ownaccess = 1;
8278: last;
8279: }
8280: }
8281: }
8282: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
8283: my $adom = $1;
8284: my $aname = $2;
8285: foreach my $role ('ca','aa') {
8286: if ($env{"user.role.$role./$adom/$aname"}) {
8287: my ($start,$end) =
8288: split(/\./,$env{"user.role.$role./$adom/$aname"});
8289: if (($now >= $start) && (!$end || $end > $now)) {
8290: $ownaccess = 1;
8291: last;
8292: }
8293: }
8294: }
8295: }
8296: }
8297: }
8298: }
8299: }
8300:
8301: # Course
8302:
8303: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
8304: unless (($priv eq 'bro') && (!$ownaccess)) {
8305: $thisallowed.=$1;
8306: }
8307: }
8308:
8309: # Domain
8310:
8311: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
8312: =~/\Q$priv\E\&([^\:]*)/) {
8313: unless (($priv eq 'bro') && (!$ownaccess)) {
8314: $thisallowed.=$1;
8315: }
8316: }
8317:
8318: # User who is not author or co-author might still be able to edit
8319: # resource of an author in the domain (e.g., if Domain Coordinator).
8320: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
8321: (&allowed('mdc',$env{'request.course.id'}))) {
8322: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
8323: $thisallowed.=$1;
8324: }
8325: }
8326:
8327: # Course: uri itself is a course
8328: my $courseuri=$uri;
8329: $courseuri=~s/\_(\d)/\/$1/;
8330: $courseuri=~s/^([^\/])/\/$1/;
8331:
8332: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
8333: =~/\Q$priv\E\&([^\:]*)/) {
8334: if ($priv eq 'mip') {
8335: my $rem = $1;
8336: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
8337: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
8338: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8339: if ($cdom ne '') {
8340: my %passwdconf = &get_passwdconf($cdom);
8341: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
8342: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
8343: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
8344: my @inststatuses = split(':',$env{'environment.inststatus'});
8345: unless (@inststatuses) {
8346: @inststatuses = ('default');
8347: }
8348: foreach my $status (@inststatuses) {
8349: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
8350: $thisallowed.=$rem;
8351: }
8352: }
8353: }
8354: }
8355: }
8356: }
8357: }
8358: } else {
8359: unless (($priv eq 'bro') && (!$ownaccess)) {
8360: $thisallowed.=$1;
8361: }
8362: }
8363: }
8364:
8365: # URI is an uploaded document for this course, default permissions don't matter
8366: # not allowing 'edit' access (editupload) to uploaded course docs
8367: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
8368: $thisallowed='';
8369: my ($match)=&is_on_map($uri);
8370: if ($match) {
8371: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8372: =~/\Q$priv\E\&([^\:]*)/) {
8373: my $value = $1;
8374: my $deeplinkblock;
8375: unless ($nodeeplinkcheck) {
8376: $deeplinkblock = &deeplink_check($priv,$symb,$uri);
8377: }
8378: if ($deeplinkblock) {
8379: $thisallowed='D';
8380: } elsif ($noblockcheck) {
8381: $thisallowed.=$value;
8382: } else {
8383: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
8384: if (@blockers > 0) {
8385: $thisallowed = 'B';
8386: } else {
8387: $thisallowed.=$value;
8388: }
8389: }
8390: }
8391: } else {
8392: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
8393: if ($refuri) {
8394: if ($refuri =~ m|^/adm/|) {
8395: $thisallowed='F';
8396: } else {
8397: $refuri=&declutter($refuri);
8398: my ($match) = &is_on_map($refuri);
8399: if ($match) {
8400: my $deeplinkblock;
8401: unless ($nodeeplinkcheck) {
8402: $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8403: }
8404: if ($deeplinkblock) {
8405: $thisallowed='D';
8406: } elsif ($noblockcheck) {
8407: $thisallowed='F';
8408: } else {
8409: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
8410: if (@blockers > 0) {
8411: $thisallowed = 'B';
8412: } else {
8413: $thisallowed='F';
8414: }
8415: }
8416: }
8417: }
8418: }
8419: }
8420: }
8421:
8422: if ($priv eq 'bre'
8423: && $thisallowed ne 'F'
8424: && $thisallowed ne '2'
8425: && &is_portfolio_url($uri)) {
8426: $thisallowed = &portfolio_access($uri,$clientip);
8427: }
8428:
8429: # Full access at system, domain or course-wide level? Exit.
8430: if ($thisallowed=~/F/) {
8431: return 'F';
8432: }
8433:
8434: # If this is generating or modifying users, exit with special codes
8435:
8436: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
8437: if (($priv eq 'cca') || ($priv eq 'caa')) {
8438: my ($audom,$auname)=split('/',$uri);
8439: # no author name given, so this just checks on the general right to make a co-author in this domain
8440: unless ($auname) { return $thisallowed; }
8441: # an author name is given, so we are about to actually make a co-author for a certain account
8442: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8443: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8444: ($audom ne $env{'request.role.domain'}))) { return ''; }
8445: }
8446: return $thisallowed;
8447: }
8448: #
8449: # Gathered so far: system, domain and course wide privileges
8450: #
8451: # Course: See if uri or referer is an individual resource that is part of
8452: # the course
8453:
8454: if ($env{'request.course.id'}) {
8455:
8456: # If this is modifying password (internal auth) domains must match for user and user's role.
8457:
8458: if ($priv eq 'mip') {
8459: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
8460: return $thisallowed;
8461: } else {
8462: return '';
8463: }
8464: }
8465:
8466: $courseprivid=$env{'request.course.id'};
8467: if ($env{'request.course.sec'}) {
8468: $courseprivid.='/'.$env{'request.course.sec'};
8469: }
8470: $courseprivid=~s/\_/\//;
8471: my $checkreferer=1;
8472: my ($match,$cond)=&is_on_map($uri);
8473: if ($match) {
8474: $statecond=$cond;
8475: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
8476: =~/\Q$priv\E\&([^\:]*)/) {
8477: my $value = $1;
8478: if ($priv eq 'bre') {
8479: my $deeplinkblock;
8480: unless ($nodeeplinkcheck) {
8481: $deeplinkblock = &deeplink_check($priv,$symb,$uri);
8482: }
8483: if ($deeplinkblock) {
8484: $thisallowed = 'D';
8485: } elsif ($noblockcheck) {
8486: $thisallowed.=$value;
8487: } else {
8488: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
8489: if (@blockers > 0) {
8490: $thisallowed = 'B';
8491: } else {
8492: $thisallowed.=$value;
8493: }
8494: }
8495: } else {
8496: $thisallowed.=$value;
8497: }
8498: $checkreferer=0;
8499: }
8500: }
8501:
8502: if ($checkreferer) {
8503: my $refuri=$env{'httpref.'.$orguri};
8504: unless ($refuri) {
8505: foreach my $key (keys(%env)) {
8506: if ($key=~/^httpref\..*\*/) {
8507: my $pattern=$key;
8508: $pattern=~s/^httpref\.\/res\///;
8509: $pattern=~s/\*/\[\^\/\]\+/g;
8510: $pattern=~s/\//\\\//g;
8511: if ($orguri=~/$pattern/) {
8512: $refuri=$env{$key};
8513: }
8514: }
8515: }
8516: }
8517:
8518: if ($refuri) {
8519: $refuri=&declutter($refuri);
8520: my ($match,$cond)=&is_on_map($refuri);
8521: if ($match) {
8522: my $refstatecond=$cond;
8523: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
8524: =~/\Q$priv\E\&([^\:]*)/) {
8525: my $value = $1;
8526: if ($priv eq 'bre') {
8527: my $deeplinkblock;
8528: unless ($nodeeplinkcheck) {
8529: $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8530: }
8531: if ($deeplinkblock) {
8532: $thisallowed = 'D';
8533: } elsif ($noblockcheck) {
8534: $thisallowed.=$value;
8535: } else {
8536: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
8537: if (@blockers > 0) {
8538: $thisallowed = 'B';
8539: } else {
8540: $thisallowed.=$value;
8541: }
8542: }
8543: } else {
8544: $thisallowed.=$value;
8545: }
8546: $uri=$refuri;
8547: $statecond=$refstatecond;
8548: }
8549: }
8550: }
8551: }
8552: }
8553:
8554: #
8555: # Gathered now: all privileges that could apply, and condition number
8556: #
8557: #
8558: # Full or no access?
8559: #
8560:
8561: if ($thisallowed=~/F/) {
8562: return 'F';
8563: }
8564:
8565: unless ($thisallowed) {
8566: return '';
8567: }
8568:
8569: # Restrictions exist, deal with them
8570: #
8571: # C:according to course preferences
8572: # R:according to resource settings
8573: # L:unless locked
8574: # X:according to user session state
8575: #
8576:
8577: # Possibly locked functionality, check all courses
8578: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
8579: # Locks might take effect only after 10 minutes cache expiration for other
8580: # courses, and 2 minutes for current course, in which user has st or ta role
8581: # which is neither expired nor a future role (unless current course).
8582:
8583: my ($needlockcheck,$now,$crsonly);
8584: if ($thisallowed=~/L/) {
8585: $now = time;
8586: if ($priv eq 'bre') {
8587: if ($uri ne '') {
8588: if ($orguri =~ m{^/+res/}) {
8589: if ($uri =~ m{^lib/templates/}) {
8590: if ($env{'request.course.id'}) {
8591: $crsonly = 1;
8592: $needlockcheck = 1;
8593: }
8594: } else {
8595: $needlockcheck = 1;
8596: }
8597: } elsif ($env{'request.course.id'}) {
8598: my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
8599: if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
8600: ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
8601: $crsonly = 1;
8602: }
8603: $needlockcheck = 1;
8604: }
8605: }
8606: } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
8607: $needlockcheck = 1;
8608: }
8609: }
8610: if ($needlockcheck) {
8611: foreach my $envkey (keys(%env)) {
8612: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8613: my $courseid=$2;
8614: my $roleid=$1.'.'.$2;
8615: $courseid=~s/^\///;
8616: unless ($env{'request.role'} eq $roleid) {
8617: my ($start,$end) = split(/\./,$env{$envkey});
8618: next unless (($now >= $start) && (!$end || $end > $now));
8619: }
8620: my $expiretime=600;
8621: if ($env{'request.role'} eq $roleid) {
8622: $expiretime=120;
8623: }
8624: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8625: my $prefix='course.'.$cdom.'_'.$cnum.'.';
8626: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
8627: &coursedescription($courseid,{'freshen_cache' => 1});
8628: }
8629: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8630: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8631: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8632: &log($env{'user.domain'},$env{'user.name'},
8633: $env{'user.home'},
8634: 'Locked by res: '.$priv.' for '.$uri.' due to '.
8635: $cdom.'/'.$cnum.'/'.$csec.' expire '.
8636: $env{$prefix.'priv.'.$priv.'.lock.expire'});
8637: return '';
8638: }
8639: }
8640: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8641: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
8642: if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
8643: &log($env{'user.domain'},$env{'user.name'},
8644: $env{'user.home'},
8645: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
8646: $cdom.'/'.$cnum.'/'.$csec.' expire '.
8647: $env{$prefix.'priv.'.$priv.'.lock.expire'});
8648: return '';
8649: }
8650: }
8651: }
8652: }
8653: }
8654:
8655: #
8656: # Rest of the restrictions depend on selected course
8657: #
8658:
8659: unless ($env{'request.course.id'}) {
8660: if ($thisallowed eq 'A') {
8661: return 'A';
8662: } elsif ($thisallowed eq 'B') {
8663: return 'B';
8664: } else {
8665: return '1';
8666: }
8667: }
8668:
8669: #
8670: # Now user is definitely in a course
8671: #
8672:
8673:
8674: # Course preferences
8675:
8676: if ($thisallowed=~/C/) {
8677: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8678: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8679: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
8680: =~/\Q$rolecode\E/) {
8681: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
8682: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8683: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8684: $env{'request.course.id'});
8685: }
8686: return '';
8687: }
8688:
8689: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
8690: =~/\Q$unamedom\E/) {
8691: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
8692: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8693: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8694: $env{'request.course.id'});
8695: }
8696: return '';
8697: }
8698: }
8699:
8700: # Resource preferences
8701:
8702: if ($thisallowed=~/R/) {
8703: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8704: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
8705: if (($priv ne 'pch') && ($priv ne 'plc')) {
8706: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8707: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8708: }
8709: return '';
8710: }
8711: }
8712:
8713: # Restricted for deeplinked session?
8714:
8715: if ($env{'request.deeplink.login'}) {
8716: if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
8717: if (!$symb) { $symb=&symbread($uri,1); }
8718: if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
8719: return '';
8720: }
8721: }
8722: }
8723:
8724: # Restricted by state or randomout?
8725:
8726: if ($thisallowed=~/X/) {
8727: if ($env{'acc.randomout'}) {
8728: if (!$symb) { $symb=&symbread($uri,1); }
8729: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
8730: return '';
8731: }
8732: }
8733: if (&condval($statecond)) {
8734: return '2';
8735: } else {
8736: return '';
8737: }
8738: }
8739:
8740: if ($thisallowed eq 'A') {
8741: return 'A';
8742: } elsif ($thisallowed eq 'B') {
8743: return 'B';
8744: } elsif ($thisallowed eq 'D') {
8745: return 'D';
8746: }
8747: return 'F';
8748: }
8749:
8750: # ------------------------------------------- Check construction space access
8751:
8752: sub constructaccess {
8753: my ($url,$setpriv)=@_;
8754:
8755: # We do not allow editing of previous versions of files
8756: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8757:
8758: # Get username and domain from URL
8759: my ($ownername,$ownerdomain,$ownerhome);
8760:
8761: ($ownerdomain,$ownername) =
8762: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
8763:
8764: # The URL does not really point to any authorspace, forget it
8765: unless (($ownername) && ($ownerdomain)) { return ''; }
8766:
8767: # Now we need to see if the user has access to the authorspace of
8768: # $ownername at $ownerdomain
8769:
8770: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8771: # Real author for this?
8772: $ownerhome = $env{'user.home'};
8773: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8774: return ($ownername,$ownerdomain,$ownerhome);
8775: }
8776: } else {
8777: # Co-author for this?
8778: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
8779: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
8780: $ownerhome = &homeserver($ownername,$ownerdomain);
8781: return ($ownername,$ownerdomain,$ownerhome);
8782: }
8783: if ($env{'request.course.id'}) {
8784: if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
8785: ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
8786: if (&allowed('mdc',$env{'request.course.id'})) {
8787: $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
8788: return ($ownername,$ownerdomain,$ownerhome);
8789: }
8790: }
8791: }
8792: }
8793:
8794: # We don't have any access right now. If we are not possibly going to do anything about this,
8795: # we might as well leave
8796: unless ($setpriv) { return ''; }
8797:
8798: # Backdoor access?
8799: my $allowed=&allowed('eco',$ownerdomain);
8800: # Nope
8801: unless ($allowed) { return ''; }
8802: # Looks like we may have access, but could be locked by the owner of the construction space
8803: if ($allowed eq 'U') {
8804: my %blocked=&get('environment',['domcoord.author'],
8805: $ownerdomain,$ownername);
8806: # Is blocked by owner
8807: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
8808: }
8809: if (($allowed eq 'F') || ($allowed eq 'U')) {
8810: # Grant temporary access
8811: my $then=$env{'user.login.time'};
8812: my $update=$env{'user.update.time'};
8813: if (!$update) { $update = $then; }
8814: my $refresh=$env{'user.refresh.time'};
8815: if (!$refresh) { $refresh = $update; }
8816: my $now = time;
8817: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
8818: $now,'ca','constructaccess');
8819: $ownerhome = &homeserver($ownername,$ownerdomain);
8820: return($ownername,$ownerdomain,$ownerhome);
8821: }
8822: # No business here
8823: return '';
8824: }
8825:
8826: # ----------------------------------------------------------- Content Blocking
8827:
8828: {
8829: # Caches for faster Course Contents display where content blocking
8830: # is in operation (i.e., interval param set) for timed quiz.
8831: #
8832: # User for whom data are being temporarily cached.
8833: my $cacheduser='';
8834: # Course for which data are being temporarily cached.
8835: my $cachedcid='';
8836: # Cached blockers for this user (a hash of blocking items).
8837: my %cachedblockers=();
8838: # When the data were last cached.
8839: my $cachedlast='';
8840:
8841: sub load_all_blockers {
8842: my ($uname,$udom)=@_;
8843: if (($uname ne '') && ($udom ne '')) {
8844: if (($cacheduser eq $uname.':'.$udom) &&
8845: ($cachedcid eq $env{'request.course.id'}) &&
8846: (abs($cachedlast-time)<5)) {
8847: return;
8848: }
8849: }
8850: $cachedlast=time;
8851: $cacheduser=$uname.':'.$udom;
8852: $cachedcid=$env{'request.course.id'};
8853: %cachedblockers = &get_commblock_resources();
8854: return;
8855: }
8856:
8857: sub get_comm_blocks {
8858: my ($cdom,$cnum) = @_;
8859: if ($cdom eq '' || $cnum eq '') {
8860: return unless ($env{'request.course.id'});
8861: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8862: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8863: }
8864: my %commblocks;
8865: my $hashid=$cdom.'_'.$cnum;
8866: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8867: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8868: %commblocks = %{$blocksref};
8869: } else {
8870: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8871: my $cachetime = 600;
8872: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8873: }
8874: return %commblocks;
8875: }
8876:
8877: sub get_commblock_resources {
8878: my ($blocks) = @_;
8879: my %blockers = ();
8880: return %blockers unless ($env{'request.course.id'});
8881: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
8882: if ($env{'request.course.sec'}) {
8883: $courseurl .= '/'.$env{'request.course.sec'};
8884: }
8885: return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
8886: my %commblocks;
8887: if (ref($blocks) eq 'HASH') {
8888: %commblocks = %{$blocks};
8889: } else {
8890: %commblocks = &get_comm_blocks();
8891: }
8892: return %blockers unless (keys(%commblocks) > 0);
8893: my $navmap = Apache::lonnavmaps::navmap->new();
8894: return %blockers unless (ref($navmap));
8895: my $now = time;
8896: foreach my $block (keys(%commblocks)) {
8897: if ($block =~ /^(\d+)____(\d+)$/) {
8898: my ($start,$end) = ($1,$2);
8899: if ($start <= $now && $end >= $now) {
8900: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8901: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8902: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8903: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8904: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8905: }
8906: }
8907: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8908: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8909: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
8910: }
8911: }
8912: }
8913: }
8914: }
8915: } elsif ($block =~ /^firstaccess____(.+)$/) {
8916: my $item = $1;
8917: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8918: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8919: my (@interval,$mapname);
8920: my $type = 'map';
8921: if ($item eq 'course') {
8922: $type = 'course';
8923: @interval=&EXT("resource.0.interval");
8924: } else {
8925: if ($item =~ /___\d+___/) {
8926: $type = 'resource';
8927: @interval=&EXT("resource.0.interval",$item);
8928: } else {
8929: $mapname = &deversion($item);
8930: if (ref($navmap)) {
8931: my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
8932: @interval = ($timelimit,'map');
8933: }
8934: }
8935: }
8936: if ($interval[0] =~ /^(\d+)/) {
8937: my $timelimit = $1;
8938: my $first_access;
8939: if ($type eq 'resource') {
8940: $first_access=&get_first_access($interval[1],$item);
8941: } elsif ($type eq 'map') {
8942: $first_access=&get_first_access($interval[1],undef,$item);
8943: } else {
8944: $first_access=&get_first_access($interval[1]);
8945: }
8946: if ($first_access) {
8947: my $timesup = $first_access+$timelimit;
8948: if ($timesup > $now) {
8949: my $activeblock;
8950: if ($type eq 'resource') {
8951: if (ref($navmap)) {
8952: my $res = $navmap->getBySymb($item);
8953: if ($res->answerable()) {
8954: $activeblock = 1;
8955: }
8956: }
8957: } elsif ($type eq 'map') {
8958: my $mapsymb = &symbread($mapname,1);
8959: if (($mapsymb) && (ref($navmap))) {
8960: my $mapres = $navmap->getBySymb($mapsymb);
8961: if (ref($mapres)) {
8962: my $first = $mapres->map_start();
8963: my $finish = $mapres->map_finish();
8964: my $it = $navmap->getIterator($first,$finish,undef,0,0);
8965: if (ref($it)) {
8966: my $res;
8967: while ($res = $it->next(undef,1)) {
8968: next unless (ref($res));
8969: my $symb = $res->symb();
8970: next if (($symb eq $mapsymb) || ($symb eq ''));
8971: @interval=&EXT("resource.0.interval",$symb);
8972: if ($interval[1] eq 'map') {
8973: if ($res->answerable()) {
8974: $activeblock = 1;
8975: last;
8976: }
8977: }
8978: }
8979: }
8980: }
8981: }
8982: }
8983: if ($activeblock) {
8984: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8985: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8986: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8987: }
8988: }
8989: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8990: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8991: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
8992: }
8993: }
8994: }
8995: }
8996: }
8997: }
8998: }
8999: }
9000: }
9001: }
9002: return %blockers;
9003: }
9004:
9005: sub has_comm_blocking {
9006: my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
9007: my @blockers;
9008: return unless ($env{'request.course.id'});
9009: return unless ($priv eq 'bre');
9010: return if ($env{'request.state'} eq 'construct');
9011: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
9012: if ($env{'request.course.sec'}) {
9013: $courseurl .= '/'.$env{'request.course.sec'};
9014: }
9015: return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
9016: my %blockinfo;
9017: if (ref($blocks) eq 'HASH') {
9018: %blockinfo = &get_commblock_resources($blocks);
9019: } else {
9020: &load_all_blockers($env{'user.name'},$env{'user.domain'});
9021: %blockinfo = %cachedblockers;
9022: }
9023: return unless (keys(%blockinfo) > 0);
9024: my (%possibles,@symbs);
9025: if (!$symb) {
9026: $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
9027: }
9028: if ($symb) {
9029: @symbs = ($symb);
9030: } elsif (keys(%possibles)) {
9031: @symbs = keys(%possibles);
9032: }
9033: my $noblock;
9034: foreach my $symb (@symbs) {
9035: last if ($noblock);
9036: my ($map,$resid,$resurl)=&decode_symb($symb);
9037: foreach my $block (keys(%blockinfo)) {
9038: if ($block =~ /^firstaccess____(.+)$/) {
9039: my $item = $1;
9040: unless ($blocked) {
9041: if (($item eq $map) || ($item eq $symb)) {
9042: $noblock = 1;
9043: last;
9044: }
9045: }
9046: }
9047: if (ref($blockinfo{$block}) eq 'HASH') {
9048: if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
9049: if ($blockinfo{$block}{'resources'}{$symb}) {
9050: unless (grep(/^\Q$block\E$/,@blockers)) {
9051: push(@blockers,$block);
9052: }
9053: }
9054: }
9055: if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
9056: if ($blockinfo{$block}{'maps'}{$map}) {
9057: unless (grep(/^\Q$block\E$/,@blockers)) {
9058: push(@blockers,$block);
9059: }
9060: }
9061: }
9062: }
9063: }
9064: }
9065: unless ($noblock) {
9066: return @blockers;
9067: }
9068: return;
9069: }
9070: }
9071:
9072: sub deeplink_check {
9073: my ($priv,$symb,$uri) = @_;
9074: return unless ($env{'request.course.id'});
9075: return unless ($priv eq 'bre');
9076: return if ($env{'request.state'} eq 'construct');
9077: return if ($env{'request.role.adv'});
9078: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9079: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9080: my (%possibles,@symbs);
9081: if (!$symb) {
9082: $symb = &symbread($uri,1,1,1,\%possibles);
9083: }
9084: if ($symb) {
9085: @symbs = ($symb);
9086: } elsif (keys(%possibles)) {
9087: @symbs = keys(%possibles);
9088: }
9089:
9090: my ($deeplink_symb,$allow);
9091: if ($env{'request.deeplink.login'}) {
9092: $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
9093: }
9094: foreach my $symb (@symbs) {
9095: last if ($allow);
9096: my $deeplink = &EXT("resource.0.deeplink",$symb);
9097: if ($deeplink eq '') {
9098: $allow = 1;
9099: } else {
9100: my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
9101: if ($state ne 'only') {
9102: $allow = 1;
9103: } else {
9104: my $check_deeplink_entry;
9105: if ($protect ne 'none') {
9106: my ($acctype,$item) = split(/:/,$protect);
9107: if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
9108: if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
9109: $check_deeplink_entry = 1
9110: }
9111: } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
9112: if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
9113: $check_deeplink_entry = 1;
9114: }
9115: } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
9116: if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
9117: $check_deeplink_entry = 1;
9118: }
9119: }
9120: }
9121: if (($protect eq 'none') || ($check_deeplink_entry)) {
9122: if ($scope eq 'res') {
9123: if ($symb eq $deeplink_symb) {
9124: $allow = 1;
9125: }
9126: } elsif (($scope eq 'map') || ($scope eq 'rec')) {
9127: my ($map_from_symb,$map_from_login);
9128: $map_from_symb = &deversion((&decode_symb($symb))[0]);
9129: if ($deeplink_symb =~ /\.(page|sequence)$/) {
9130: $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
9131: } else {
9132: $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
9133: }
9134: if (($map_from_symb) && ($map_from_login)) {
9135: if ($map_from_symb eq $map_from_login) {
9136: $allow = 1;
9137: } elsif ($scope eq 'rec') {
9138: my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
9139: if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
9140: $allow = 1;
9141: }
9142: }
9143: }
9144: }
9145: }
9146: }
9147: }
9148: }
9149: return if ($allow);
9150: return 1;
9151: }
9152:
9153: # -------------------------------- Deversion and split uri into path an filename
9154:
9155: #
9156: # Removes the version from a URI and
9157: # splits it in to its filename and path to the filename.
9158: # Seems like File::Basename could have done this more clearly.
9159: # Parameters:
9160: # $uri - input URI
9161: # Returns:
9162: # Two element list consisting of
9163: # $pathname - the URI up to and excluding the trailing /
9164: # $filename - The part of the URI following the last /
9165: # NOTE:
9166: # Another realization of this is simply:
9167: # use File::Basename;
9168: # ...
9169: # $uri = shift;
9170: # $filename = basename($uri);
9171: # $path = dirname($uri);
9172: # return ($filename, $path);
9173: #
9174: # The implementation below is probably faster however.
9175: #
9176: sub split_uri_for_cond {
9177: my $uri=&deversion(&declutter(shift));
9178: my @uriparts=split(/\//,$uri);
9179: my $filename=pop(@uriparts);
9180: my $pathname=join('/',@uriparts);
9181: return ($pathname,$filename);
9182: }
9183: # --------------------------------------------------- Is a resource on the map?
9184:
9185: sub is_on_map {
9186: my ($pathname,$filename) = &split_uri_for_cond(shift);
9187: #Trying to find the conditional for the file
9188: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
9189: /\&\Q$filename\E\:([\d\|]+)\&/);
9190: if ($match) {
9191: return (1,$1);
9192: } else {
9193: return (0,0);
9194: }
9195: }
9196:
9197: # --------------------------------------------------------- Get symb from alias
9198:
9199: sub get_symb_from_alias {
9200: my $symb=shift;
9201: my ($map,$resid,$url)=&decode_symb($symb);
9202: # Already is a symb
9203: if ($url) { return $symb; }
9204: # Must be an alias
9205: my $aliassymb='';
9206: my %bighash;
9207: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9208: &GDBM_READER(),0640)) {
9209: my $rid=$bighash{'mapalias_'.$symb};
9210: if ($rid) {
9211: my ($mapid,$resid)=split(/\./,$rid);
9212: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
9213: $resid,$bighash{'src_'.$rid});
9214: }
9215: untie %bighash;
9216: }
9217: return $aliassymb;
9218: }
9219:
9220: # ----------------------------------------------------------------- Define Role
9221:
9222: sub definerole {
9223: if (allowed('mcr','/')) {
9224: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
9225: foreach my $role (split(':',$sysrole)) {
9226: my ($crole,$cqual)=split(/\&/,$role);
9227: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
9228: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
9229: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
9230: return "refused:s:$crole&$cqual";
9231: }
9232: }
9233: }
9234: foreach my $role (split(':',$domrole)) {
9235: my ($crole,$cqual)=split(/\&/,$role);
9236: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
9237: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
9238: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
9239: return "refused:d:$crole&$cqual";
9240: }
9241: }
9242: }
9243: foreach my $role (split(':',$courole)) {
9244: my ($crole,$cqual)=split(/\&/,$role);
9245: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
9246: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
9247: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
9248: return "refused:c:$crole&$cqual";
9249: }
9250: }
9251: }
9252: my $uhome;
9253: if (($uname ne '') && ($udom ne '')) {
9254: $uhome = &homeserver($uname,$udom);
9255: return $uhome if ($uhome eq 'no_host');
9256: } else {
9257: $uname = $env{'user.name'};
9258: $udom = $env{'user.domain'};
9259: $uhome = $env{'user.home'};
9260: }
9261: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
9262: "$udom:$uname:rolesdef_$rolename=".
9263: escape($sysrole.'_'.$domrole.'_'.$courole);
9264: return reply($command,$uhome);
9265: } else {
9266: return 'refused';
9267: }
9268: }
9269:
9270: # ---------------- Make a metadata query against the network of library servers
9271:
9272: sub metadata_query {
9273: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
9274: my %rhash;
9275: my %libserv = &all_library();
9276: my @server_list = (defined($server_array) ? @$server_array
9277: : keys(%libserv) );
9278: for my $server (@server_list) {
9279: my $domains = '';
9280: if (ref($domains_hash) eq 'HASH') {
9281: $domains = $domains_hash->{$server};
9282: }
9283: unless ($custom or $customshow) {
9284: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
9285: $rhash{$server}=$reply;
9286: }
9287: else {
9288: my $reply=&reply("querysend:".&escape($query).':'.
9289: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
9290: $server);
9291: $rhash{$server}=$reply;
9292: }
9293: }
9294: return \%rhash;
9295: }
9296:
9297: # ----------------------------------------- Send log queries and wait for reply
9298:
9299: sub log_query {
9300: my ($uname,$udom,$query,%filters)=@_;
9301: my $uhome=&homeserver($uname,$udom);
9302: if ($uhome eq 'no_host') { return 'error: no_host'; }
9303: my $uhost=&hostname($uhome);
9304: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
9305: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
9306: $uhome);
9307: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
9308: return get_query_reply($queryid);
9309: }
9310:
9311: # -------------------------- Update MySQL table for portfolio file
9312:
9313: sub update_portfolio_table {
9314: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
9315: if ($group ne '') {
9316: $file_name =~s /^\Q$group\E//;
9317: }
9318: my $homeserver = &homeserver($uname,$udom);
9319: my $queryid=
9320: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
9321: ':'.&escape($file_name).':'.$action,$homeserver);
9322: my $reply = &get_query_reply($queryid);
9323: return $reply;
9324: }
9325:
9326: # -------------------------- Update MySQL allusers table
9327:
9328: sub update_allusers_table {
9329: my ($uname,$udom,$names) = @_;
9330: my $homeserver = &homeserver($uname,$udom);
9331: my $queryid=
9332: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
9333: 'lastname='.&escape($names->{'lastname'}).'%%'.
9334: 'firstname='.&escape($names->{'firstname'}).'%%'.
9335: 'middlename='.&escape($names->{'middlename'}).'%%'.
9336: 'generation='.&escape($names->{'generation'}).'%%'.
9337: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
9338: 'id='.&escape($names->{'id'}),$homeserver);
9339: return;
9340: }
9341:
9342: # ------- Request retrieval of institutional classlists for course(s)
9343:
9344: sub fetch_enrollment_query {
9345: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
9346: my ($homeserver,$sleep,$loopmax);
9347: my $maxtries = 1;
9348: if ($context eq 'automated') {
9349: $homeserver = $perlvar{'lonHostID'};
9350: $sleep = 2;
9351: $loopmax = 100;
9352: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
9353: } else {
9354: $homeserver = &homeserver($cnum,$dom);
9355: }
9356: my $host=&hostname($homeserver);
9357: my $cmd = '';
9358: foreach my $affiliate (keys(%{$affiliatesref})) {
9359: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
9360: }
9361: $cmd =~ s/%%$//;
9362: $cmd = &escape($cmd);
9363: my $query = 'fetchenrollment';
9364: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
9365: unless ($queryid=~/^\Q$host\E\_/) {
9366: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
9367: return 'error: '.$queryid;
9368: }
9369: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
9370: my $tries = 1;
9371: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9372: $reply = &get_query_reply($queryid,$sleep,$loopmax);
9373: $tries ++;
9374: }
9375: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9376: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9377: } else {
9378: my @responses = split(/:/,$reply);
9379: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
9380: foreach my $line (@responses) {
9381: my ($key,$value) = split(/=/,$line,2);
9382: $$replyref{$key} = $value;
9383: }
9384: } else {
9385: my $pathname = LONCAPA::tempdir();
9386: foreach my $line (@responses) {
9387: my ($key,$value) = split(/=/,$line);
9388: $$replyref{$key} = $value;
9389: if ($value > 0) {
9390: foreach my $item (@{$$affiliatesref{$key}}) {
9391: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
9392: my $destname = $pathname.'/'.$filename;
9393: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
9394: if ($xml_classlist =~ /^error/) {
9395: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
9396: } else {
9397: if ( open(FILE,">",$destname) ) {
9398: print FILE &unescape($xml_classlist);
9399: close(FILE);
9400: } else {
9401: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
9402: }
9403: }
9404: }
9405: }
9406: }
9407: }
9408: return 'ok';
9409: }
9410: return 'error';
9411: }
9412:
9413: sub get_query_reply {
9414: my ($queryid,$sleep,$loopmax) = @_;
9415: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
9416: $sleep = 0.2;
9417: }
9418: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
9419: $loopmax = 100;
9420: }
9421: my $replyfile=LONCAPA::tempdir().$queryid;
9422: my $reply='';
9423: for (1..$loopmax) {
9424: sleep($sleep);
9425: if (-e $replyfile.'.end') {
9426: if (open(my $fh,"<",$replyfile)) {
9427: $reply = join('',<$fh>);
9428: close($fh);
9429: } else { return 'error: reply_file_error'; }
9430: return &unescape($reply);
9431: }
9432: }
9433: return 'timeout:'.$queryid;
9434: }
9435:
9436: sub courselog_query {
9437: #
9438: # possible filters:
9439: # url: url or symb
9440: # username
9441: # domain
9442: # action: view, submit, grade
9443: # start: timestamp
9444: # end: timestamp
9445: #
9446: my (%filters)=@_;
9447: unless ($env{'request.course.id'}) { return 'no_course'; }
9448: if ($filters{'url'}) {
9449: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
9450: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
9451: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
9452: }
9453: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
9454: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
9455: return &log_query($cname,$cdom,'courselog',%filters);
9456: }
9457:
9458: sub userlog_query {
9459: #
9460: # possible filters:
9461: # action: log check role
9462: # start: timestamp
9463: # end: timestamp
9464: #
9465: my ($uname,$udom,%filters)=@_;
9466: return &log_query($uname,$udom,'userlog',%filters);
9467: }
9468:
9469: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
9470:
9471: sub auto_run {
9472: my ($cnum,$cdom) = @_;
9473: my $response = 0;
9474: my $settings;
9475: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
9476: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
9477: $settings = $domconfig{'autoenroll'};
9478: if ($settings->{'run'} eq '1') {
9479: $response = 1;
9480: }
9481: } else {
9482: my $homeserver;
9483: if (&is_course($cdom,$cnum)) {
9484: $homeserver = &homeserver($cnum,$cdom);
9485: } else {
9486: $homeserver = &domain($cdom,'primary');
9487: }
9488: if ($homeserver ne 'no_host') {
9489: $response = &reply('autorun:'.$cdom,$homeserver);
9490: }
9491: }
9492: return $response;
9493: }
9494:
9495: sub auto_get_sections {
9496: my ($cnum,$cdom,$inst_coursecode) = @_;
9497: my $homeserver;
9498: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9499: $homeserver = &homeserver($cnum,$cdom);
9500: }
9501: if (!defined($homeserver)) {
9502: if ($cdom =~ /^$match_domain$/) {
9503: $homeserver = &domain($cdom,'primary');
9504: }
9505: }
9506: my @secs;
9507: if (defined($homeserver)) {
9508: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
9509: unless ($response eq 'refused') {
9510: @secs = split(/:/,$response);
9511: }
9512: }
9513: return @secs;
9514: }
9515:
9516: sub auto_new_course {
9517: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
9518: my $homeserver = &homeserver($cnum,$cdom);
9519: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
9520: return $response;
9521: }
9522:
9523: sub auto_validate_courseID {
9524: my ($cnum,$cdom,$inst_course_id) = @_;
9525: my $homeserver = &homeserver($cnum,$cdom);
9526: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
9527: return $response;
9528: }
9529:
9530: sub auto_validate_instcode {
9531: my ($cnum,$cdom,$instcode,$owner) = @_;
9532: my ($homeserver,$response);
9533: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9534: $homeserver = &homeserver($cnum,$cdom);
9535: }
9536: if (!defined($homeserver)) {
9537: if ($cdom =~ /^$match_domain$/) {
9538: $homeserver = &domain($cdom,'primary');
9539: }
9540: }
9541: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
9542: &escape($instcode).':'.&escape($owner),$homeserver));
9543: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
9544: return ($outcome,$description,$defaultcredits);
9545: }
9546:
9547: sub auto_validate_inst_crosslist {
9548: my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
9549: my ($homeserver,$response);
9550: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9551: $homeserver = &homeserver($cnum,$cdom);
9552: }
9553: if (!defined($homeserver)) {
9554: if ($cdom =~ /^$match_domain$/) {
9555: $homeserver = &domain($cdom,'primary');
9556: }
9557: }
9558: unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
9559: $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
9560: &escape($instcode).':'.&escape($inst_xlist).':'.
9561: &escape($coowner),$homeserver);
9562: }
9563: return $response;
9564: }
9565:
9566: sub auto_create_password {
9567: my ($cnum,$cdom,$authparam,$udom) = @_;
9568: my ($homeserver,$response);
9569: my $create_passwd = 0;
9570: my $authchk = '';
9571: if ($udom =~ /^$match_domain$/) {
9572: $homeserver = &domain($udom,'primary');
9573: }
9574: if ($homeserver eq '') {
9575: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9576: $homeserver = &homeserver($cnum,$cdom);
9577: }
9578: }
9579: if ($homeserver eq '') {
9580: $authchk = 'nodomain';
9581: } else {
9582: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
9583: if ($response eq 'refused') {
9584: $authchk = 'refused';
9585: } else {
9586: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
9587: }
9588: }
9589: return ($authparam,$create_passwd,$authchk);
9590: }
9591:
9592: sub auto_photo_permission {
9593: my ($cnum,$cdom,$students) = @_;
9594: my $homeserver = &homeserver($cnum,$cdom);
9595: my ($outcome,$perm_reqd,$conditions) =
9596: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
9597: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9598: return (undef,undef);
9599: }
9600: return ($outcome,$perm_reqd,$conditions);
9601: }
9602:
9603: sub auto_checkphotos {
9604: my ($uname,$udom,$pid) = @_;
9605: my $homeserver = &homeserver($uname,$udom);
9606: my ($result,$resulttype);
9607: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
9608: &escape($uname).':'.&escape($pid),
9609: $homeserver));
9610: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9611: return (undef,undef);
9612: }
9613: if ($outcome) {
9614: ($result,$resulttype) = split(/:/,$outcome);
9615: }
9616: return ($result,$resulttype);
9617: }
9618:
9619: sub auto_photochoice {
9620: my ($cnum,$cdom) = @_;
9621: my $homeserver = &homeserver($cnum,$cdom);
9622: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
9623: &escape($cdom),
9624: $homeserver)));
9625: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9626: return (undef,undef);
9627: }
9628: return ($update,$comment);
9629: }
9630:
9631: sub auto_photoupdate {
9632: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9633: my $homeserver = &homeserver($cnum,$dom);
9634: my $host=&hostname($homeserver);
9635: my $cmd = '';
9636: my $maxtries = 1;
9637: foreach my $affiliate (keys(%{$affiliatesref})) {
9638: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
9639: }
9640: $cmd =~ s/%%$//;
9641: $cmd = &escape($cmd);
9642: my $query = 'institutionalphotos';
9643: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9644: unless ($queryid=~/^\Q$host\E\_/) {
9645: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9646: return 'error: '.$queryid;
9647: }
9648: my $reply = &get_query_reply($queryid);
9649: my $tries = 1;
9650: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9651: $reply = &get_query_reply($queryid);
9652: $tries ++;
9653: }
9654: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9655: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9656: } else {
9657: my @responses = split(/:/,$reply);
9658: my $outcome = shift(@responses);
9659: foreach my $item (@responses) {
9660: my ($key,$value) = split(/=/,$item);
9661: $$photo{$key} = $value;
9662: }
9663: return $outcome;
9664: }
9665: return 'error';
9666: }
9667:
9668: sub auto_instcode_format {
9669: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9670: $cat_order) = @_;
9671: my $courses = '';
9672: my @homeservers;
9673: if ($caller eq 'global') {
9674: my %servers = &get_servers($codedom,'library');
9675: foreach my $tryserver (keys(%servers)) {
9676: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9677: push(@homeservers,$tryserver);
9678: }
9679: }
9680: } elsif ($caller eq 'requests') {
9681: if ($codedom =~ /^$match_domain$/) {
9682: my $chome = &domain($codedom,'primary');
9683: unless ($chome eq 'no_host') {
9684: push(@homeservers,$chome);
9685: }
9686: }
9687: } else {
9688: push(@homeservers,&homeserver($caller,$codedom));
9689: }
9690: foreach my $code (keys(%{$instcodes})) {
9691: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
9692: }
9693: chop($courses);
9694: my $ok_response = 0;
9695: my $response;
9696: while (@homeservers > 0 && $ok_response == 0) {
9697: my $server = shift(@homeservers);
9698: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9699: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9700: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
9701: split(/:/,$response);
9702: %{$codes} = (%{$codes},&str2hash($codes_str));
9703: push(@{$codetitles},&str2array($codetitles_str));
9704: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9705: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9706: $ok_response = 1;
9707: }
9708: }
9709: if ($ok_response) {
9710: return 'ok';
9711: } else {
9712: return $response;
9713: }
9714: }
9715:
9716: sub auto_instcode_defaults {
9717: my ($domain,$returnhash,$code_order) = @_;
9718: my @homeservers;
9719:
9720: my %servers = &get_servers($domain,'library');
9721: foreach my $tryserver (keys(%servers)) {
9722: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9723: push(@homeservers,$tryserver);
9724: }
9725: }
9726:
9727: my $response;
9728: foreach my $server (@homeservers) {
9729: $response=&reply('autoinstcodedefaults:'.$domain,$server);
9730: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9731:
9732: foreach my $pair (split(/\&/,$response)) {
9733: my ($name,$value)=split(/\=/,$pair);
9734: if ($name eq 'code_order') {
9735: @{$code_order} = split(/\&/,&unescape($value));
9736: } else {
9737: $returnhash->{&unescape($name)}=&unescape($value);
9738: }
9739: }
9740: return 'ok';
9741: }
9742:
9743: return $response;
9744: }
9745:
9746: sub auto_possible_instcodes {
9747: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9748: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9749: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9750: return;
9751: }
9752: my (@homeservers,$uhome);
9753: if (defined(&domain($domain,'primary'))) {
9754: $uhome=&domain($domain,'primary');
9755: push(@homeservers,&domain($domain,'primary'));
9756: } else {
9757: my %servers = &get_servers($domain,'library');
9758: foreach my $tryserver (keys(%servers)) {
9759: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9760: push(@homeservers,$tryserver);
9761: }
9762: }
9763: }
9764: my $response;
9765: foreach my $server (@homeservers) {
9766: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9767: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9768: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9769: split(':',$response);
9770: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9771: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
9772: foreach my $item (split('&',$cat_title)) {
9773: my ($name,$value)=split('=',$item);
9774: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
9775: }
9776: foreach my $item (split('&',$cat_order)) {
9777: my ($name,$value)=split('=',$item);
9778: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
9779: }
9780: return 'ok';
9781: }
9782: return $response;
9783: }
9784:
9785: sub auto_courserequest_checks {
9786: my ($dom) = @_;
9787: my ($homeserver,%validations);
9788: if ($dom =~ /^$match_domain$/) {
9789: $homeserver = &domain($dom,'primary');
9790: }
9791: unless ($homeserver eq 'no_host') {
9792: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9793: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9794: my @items = split(/&/,$response);
9795: foreach my $item (@items) {
9796: my ($key,$value) = split('=',$item);
9797: $validations{&unescape($key)} = &thaw_unescape($value);
9798: }
9799: }
9800: }
9801: return %validations;
9802: }
9803:
9804: sub auto_courserequest_validation {
9805: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
9806: my ($homeserver,$response);
9807: if ($dom =~ /^$match_domain$/) {
9808: $homeserver = &domain($dom,'primary');
9809: }
9810: unless ($homeserver eq 'no_host') {
9811: my $customdata;
9812: if (ref($custominfo) eq 'HASH') {
9813: $customdata = &freeze_escape($custominfo);
9814: }
9815: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
9816: ':'.&escape($crstype).':'.&escape($inststatuslist).
9817: ':'.&escape($instcode).':'.&escape($instseclist).':'.
9818: $customdata,$homeserver));
9819: }
9820: return $response;
9821: }
9822:
9823: sub auto_validate_class_sec {
9824: my ($cdom,$cnum,$owners,$inst_class) = @_;
9825: my $homeserver = &homeserver($cnum,$cdom);
9826: my $ownerlist;
9827: if (ref($owners) eq 'ARRAY') {
9828: $ownerlist = join(',',@{$owners});
9829: } else {
9830: $ownerlist = $owners;
9831: }
9832: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
9833: &escape($ownerlist).':'.$cdom,$homeserver);
9834: return $response;
9835: }
9836:
9837: sub auto_instsec_reformat {
9838: my ($cdom,$action,$instsecref) = @_;
9839: return unless(($action eq 'clutter') || ($action eq 'declutter'));
9840: my @homeservers;
9841: if (defined(&domain($cdom,'primary'))) {
9842: push(@homeservers,&domain($cdom,'primary'));
9843: } else {
9844: my %servers = &get_servers($cdom,'library');
9845: foreach my $tryserver (keys(%servers)) {
9846: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9847: push(@homeservers,$tryserver);
9848: }
9849: }
9850: }
9851: my $response;
9852: my %reformatted = %{$instsecref};
9853: foreach my $server (@homeservers) {
9854: if (ref($instsecref) eq 'HASH') {
9855: my $info = &freeze_escape($instsecref);
9856: my $response=&reply('autoinstsecreformat:'.$cdom.':'.
9857: $action.':'.$info,$server);
9858: next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
9859: my @items = split(/&/,$response);
9860: foreach my $item (@items) {
9861: my ($key,$value) = split(/=/,$item);
9862: $reformatted{&unescape($key)} = &thaw_unescape($value);
9863: }
9864: }
9865: }
9866: return %reformatted;
9867: }
9868:
9869: sub auto_validate_instclasses {
9870: my ($cdom,$cnum,$owners,$classesref) = @_;
9871: my ($homeserver,%validations);
9872: $homeserver = &homeserver($cnum,$cdom);
9873: unless ($homeserver eq 'no_host') {
9874: my $ownerlist;
9875: if (ref($owners) eq 'ARRAY') {
9876: $ownerlist = join(',',@{$owners});
9877: } else {
9878: $ownerlist = $owners;
9879: }
9880: if (ref($classesref) eq 'HASH') {
9881: my $classes = &freeze_escape($classesref);
9882: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
9883: ':'.$cdom.':'.$classes,$homeserver);
9884: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9885: my @items = split(/&/,$response);
9886: foreach my $item (@items) {
9887: my ($key,$value) = split('=',$item);
9888: $validations{&unescape($key)} = &thaw_unescape($value);
9889: }
9890: }
9891: }
9892: }
9893: return %validations;
9894: }
9895:
9896: sub auto_crsreq_update {
9897: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
9898: $code,$accessstart,$accessend,$inbound) = @_;
9899: my ($homeserver,%crsreqresponse);
9900: if ($cdom =~ /^$match_domain$/) {
9901: $homeserver = &domain($cdom,'primary');
9902: }
9903: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9904: my $info;
9905: if (ref($inbound) eq 'HASH') {
9906: $info = &freeze_escape($inbound);
9907: }
9908: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
9909: ':'.&escape($action).':'.&escape($ownername).':'.
9910: &escape($ownerdomain).':'.&escape($fullname).':'.
9911: &escape($title).':'.&escape($code).':'.
9912: &escape($accessstart).':'.&escape($accessend).':'.$info,
9913: $homeserver);
9914: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9915: my @items = split(/&/,$response);
9916: foreach my $item (@items) {
9917: my ($key,$value) = split('=',$item);
9918: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
9919: }
9920: }
9921: }
9922: return \%crsreqresponse;
9923: }
9924:
9925: sub auto_export_grades {
9926: my ($cdom,$cnum,$inforef,$gradesref) = @_;
9927: my ($homeserver,%exportresponse);
9928: if ($cdom =~ /^$match_domain$/) {
9929: $homeserver = &domain($cdom,'primary');
9930: }
9931: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9932: my $info;
9933: if (ref($inforef) eq 'HASH') {
9934: $info = &freeze_escape($inforef);
9935: }
9936: if (ref($gradesref) eq 'HASH') {
9937: my $grades = &freeze_escape($gradesref);
9938: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
9939: $info.':'.$grades,$homeserver);
9940: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
9941: my @items = split(/&/,$response);
9942: foreach my $item (@items) {
9943: my ($key,$value) = split('=',$item);
9944: $exportresponse{&unescape($key)} = &thaw_unescape($value);
9945: }
9946: }
9947: }
9948: }
9949: return \%exportresponse;
9950: }
9951:
9952: sub check_instcode_cloning {
9953: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
9954: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9955: return;
9956: }
9957: my $canclone;
9958: if (@{$code_order} > 0) {
9959: my $instcoderegexp ='^';
9960: my @clonecodes = split(/\&/,$cloner);
9961: foreach my $item (@{$code_order}) {
9962: if (grep(/^\Q$item\E=/,@clonecodes)) {
9963: foreach my $pair (@clonecodes) {
9964: my ($key,$val) = split(/\=/,$pair,2);
9965: $val = &unescape($val);
9966: if ($key eq $item) {
9967: $instcoderegexp .= '('.$val.')';
9968: last;
9969: }
9970: }
9971: } else {
9972: $instcoderegexp .= $codedefaults->{$item};
9973: }
9974: }
9975: $instcoderegexp .= '$';
9976: my (@from,@to);
9977: eval {
9978: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9979: (@to) = ($clonetocode =~ /$instcoderegexp/);
9980: };
9981: if ((@from > 0) && (@to > 0)) {
9982: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9983: if (!@diffs) {
9984: $canclone = 1;
9985: }
9986: }
9987: }
9988: return $canclone;
9989: }
9990:
9991: sub default_instcode_cloning {
9992: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
9993: my (%codedefaults,@code_order,$canclone);
9994: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
9995: %codedefaults = %{$codedefaultsref};
9996: @code_order = @{$codeorderref};
9997: } elsif ($clonedom) {
9998: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
9999: }
10000: if (($domdefclone) && (@code_order)) {
10001: my @clonecodes = split(/\+/,$domdefclone);
10002: my $instcoderegexp ='^';
10003: foreach my $item (@code_order) {
10004: if (grep(/^\Q$item\E$/,@clonecodes)) {
10005: $instcoderegexp .= '('.$codedefaults{$item}.')';
10006: } else {
10007: $instcoderegexp .= $codedefaults{$item};
10008: }
10009: }
10010: $instcoderegexp .= '$';
10011: my (@from,@to);
10012: eval {
10013: (@from) = ($clonefromcode =~ /$instcoderegexp/);
10014: (@to) = ($clonetocode =~ /$instcoderegexp/);
10015: };
10016: if ((@from > 0) && (@to > 0)) {
10017: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10018: if (!@diffs) {
10019: $canclone = 1;
10020: }
10021: }
10022: }
10023: return $canclone;
10024: }
10025:
10026: # ------------------------------------------------------- Course Group routines
10027:
10028: sub get_coursegroups {
10029: my ($cdom,$cnum,$group,$namespace) = @_;
10030: return(&dump($namespace,$cdom,$cnum,$group));
10031: }
10032:
10033: sub modify_coursegroup {
10034: my ($cdom,$cnum,$groupsettings) = @_;
10035: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
10036: }
10037:
10038: sub toggle_coursegroup_status {
10039: my ($cdom,$cnum,$group,$action) = @_;
10040: my ($from_namespace,$to_namespace);
10041: if ($action eq 'delete') {
10042: $from_namespace = 'coursegroups';
10043: $to_namespace = 'deleted_groups';
10044: } else {
10045: $from_namespace = 'deleted_groups';
10046: $to_namespace = 'coursegroups';
10047: }
10048: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
10049: if (my $tmp = &error(%curr_group)) {
10050: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
10051: return ('read error',$tmp);
10052: } else {
10053: my %savedsettings = %curr_group;
10054: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
10055: my $deloutcome;
10056: if ($result eq 'ok') {
10057: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
10058: } else {
10059: return ('write error',$result);
10060: }
10061: if ($deloutcome eq 'ok') {
10062: return 'ok';
10063: } else {
10064: return ('delete error',$deloutcome);
10065: }
10066: }
10067: }
10068:
10069: sub modify_group_roles {
10070: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
10071: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
10072: my $role = 'gr/'.&escape($userprivs);
10073: my ($uname,$udom) = split(/:/,$user);
10074: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
10075: if ($result eq 'ok') {
10076: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
10077: }
10078: return $result;
10079: }
10080:
10081: sub modify_coursegroup_membership {
10082: my ($cdom,$cnum,$membership) = @_;
10083: my $result = &put('groupmembership',$membership,$cdom,$cnum);
10084: return $result;
10085: }
10086:
10087: sub get_active_groups {
10088: my ($udom,$uname,$cdom,$cnum) = @_;
10089: my $now = time;
10090: my %groups = ();
10091: foreach my $key (keys(%env)) {
10092: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
10093: my ($start,$end) = split(/\./,$env{$key});
10094: if (($end!=0) && ($end<$now)) { next; }
10095: if (($start!=0) && ($start>$now)) { next; }
10096: if ($1 eq $cdom && $2 eq $cnum) {
10097: $groups{$3} = $env{$key} ;
10098: }
10099: }
10100: }
10101: return %groups;
10102: }
10103:
10104: sub get_group_membership {
10105: my ($cdom,$cnum,$group) = @_;
10106: return(&dump('groupmembership',$cdom,$cnum,$group));
10107: }
10108:
10109: sub get_users_groups {
10110: my ($udom,$uname,$courseid) = @_;
10111: my @usersgroups;
10112: my $cachetime=1800;
10113:
10114: my $hashid="$udom:$uname:$courseid";
10115: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
10116: if (defined($cached)) {
10117: @usersgroups = split(/:/,$grouplist);
10118: } else {
10119: $grouplist = '';
10120: my $courseurl = &courseid_to_courseurl($courseid);
10121: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
10122: my $access_end = $env{'course.'.$courseid.
10123: '.default_enrollment_end_date'};
10124: my $now = time;
10125: foreach my $key (keys(%roleshash)) {
10126: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10127: my $group = $1;
10128: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10129: my $start = $2;
10130: my $end = $1;
10131: if ($start == -1) { next; } # deleted from group
10132: if (($start!=0) && ($start>$now)) { next; }
10133: if (($end!=0) && ($end<$now)) {
10134: if ($access_end && $access_end < $now) {
10135: if ($access_end - $end < 86400) {
10136: push(@usersgroups,$group);
10137: }
10138: }
10139: next;
10140: }
10141: push(@usersgroups,$group);
10142: }
10143: }
10144: }
10145: @usersgroups = &sort_course_groups($courseid,@usersgroups);
10146: $grouplist = join(':',@usersgroups);
10147: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
10148: }
10149: return @usersgroups;
10150: }
10151:
10152: sub devalidate_getgroups_cache {
10153: my ($udom,$uname,$cdom,$cnum)=@_;
10154: my $courseid = $cdom.'_'.$cnum;
10155:
10156: my $hashid="$udom:$uname:$courseid";
10157: &devalidate_cache_new('getgroups',$hashid);
10158: }
10159:
10160: # ------------------------------------------------------------------ Plain Text
10161:
10162: sub plaintext {
10163: my ($short,$type,$cid,$forcedefault) = @_;
10164: if ($short =~ m{^cr/}) {
10165: return (split('/',$short))[-1];
10166: }
10167: if (!defined($cid)) {
10168: $cid = $env{'request.course.id'};
10169: }
10170: my %rolenames = (
10171: Course => 'std',
10172: Community => 'alt1',
10173: Placement => 'std',
10174: );
10175: if ($cid ne '') {
10176: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10177: unless ($forcedefault) {
10178: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
10179: &Apache::lonlocal::mt_escape(\$roletext);
10180: return &Apache::lonlocal::mt($roletext);
10181: }
10182: }
10183: }
10184: if ((defined($type)) && (defined($rolenames{$type})) &&
10185: (defined($rolenames{$type})) &&
10186: (defined($prp{$short}{$rolenames{$type}}))) {
10187: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
10188: } elsif ($cid ne '') {
10189: my $crstype = $env{'course.'.$cid.'.type'};
10190: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10191: (defined($prp{$short}{$rolenames{$crstype}}))) {
10192: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10193: }
10194: }
10195: return &Apache::lonlocal::mt($prp{$short}{'std'});
10196: }
10197:
10198: # ----------------------------------------------------------------- Assign Role
10199:
10200: sub assignrole {
10201: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10202: $context)=@_;
10203: my $mrole;
10204: if ($role =~ /^cr\//) {
10205: my $cwosec=$url;
10206: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10207: unless (&allowed('ccr',$cwosec)) {
10208: my $refused = 1;
10209: if ($context eq 'requestcourses') {
10210: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10211: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10212: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10213: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10214: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10215: if ($crsenv{'internal.courseowner'} eq
10216: $env{'user.name'}.':'.$env{'user.domain'}) {
10217: $refused = '';
10218: }
10219: }
10220: }
10221: }
10222: }
10223: if ($refused) {
10224: &logthis('Refused custom assignrole: '.
10225: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10226: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10227: return 'refused';
10228: }
10229: }
10230: $mrole='cr';
10231: } elsif ($role =~ /^gr\//) {
10232: my $cwogrp=$url;
10233: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
10234: unless (&allowed('mdg',$cwogrp)) {
10235: &logthis('Refused group assignrole: '.
10236: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10237: $env{'user.name'}.' at '.$env{'user.domain'});
10238: return 'refused';
10239: }
10240: $mrole='gr';
10241: } else {
10242: my $cwosec=$url;
10243: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10244: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10245: my $refused;
10246: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
10247: if (!(&allowed('c'.$role,$url))) {
10248: $refused = 1;
10249: }
10250: } else {
10251: $refused = 1;
10252: }
10253: if ($refused) {
10254: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10255: if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
10256: my %crsenv;
10257: if ($role eq 'cc' || $role eq 'co') {
10258: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10259: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10260: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10261: if ($crsenv{'internal.courseowner'} eq
10262: $env{'user.name'}.':'.$env{'user.domain'}) {
10263: $refused = '';
10264: }
10265: }
10266: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
10267: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10268: if ($crsenv{'internal.courseowner'} eq
10269: $env{'user.name'}.':'.$env{'user.domain'}) {
10270: $refused = '';
10271: }
10272: }
10273: }
10274: }
10275: } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10276: if ($role eq 'st') {
10277: $refused = '';
10278: } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10279: $refused = '';
10280: }
10281: } elsif ($context eq 'requestcourses') {
10282: my @possroles = ('st','ta','ep','in','cc','co');
10283: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
10284: my $wrongcc;
10285: if ($cnum =~ /^$match_community$/) {
10286: $wrongcc = 1 if ($role eq 'cc');
10287: } else {
10288: $wrongcc = 1 if ($role eq 'co');
10289: }
10290: unless ($wrongcc) {
10291: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10292: if ($crsenv{'internal.courseowner'} eq
10293: $env{'user.name'}.':'.$env{'user.domain'}) {
10294: $refused = '';
10295: }
10296: }
10297: }
10298: } elsif ($context eq 'requestauthor') {
10299: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
10300: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10301: if ($env{'environment.requestauthor'} eq 'automatic') {
10302: $refused = '';
10303: } else {
10304: my %domdefaults = &get_domain_defaults($udom);
10305: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10306: my $checkbystatus;
10307: if ($env{'user.adv'}) {
10308: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10309: if ($disposition eq 'automatic') {
10310: $refused = '';
10311: } elsif ($disposition eq '') {
10312: $checkbystatus = 1;
10313: }
10314: } else {
10315: $checkbystatus = 1;
10316: }
10317: if ($checkbystatus) {
10318: if ($env{'environment.inststatus'}) {
10319: my @inststatuses = split(/,/,$env{'environment.inststatus'});
10320: foreach my $type (@inststatuses) {
10321: if (($type ne '') &&
10322: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10323: $refused = '';
10324: }
10325: }
10326: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10327: $refused = '';
10328: }
10329: }
10330: }
10331: }
10332: }
10333: }
10334: if ($refused) {
10335: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10336: ' '.$role.' '.$end.' '.$start.' by '.
10337: $env{'user.name'}.' at '.$env{'user.domain'});
10338: return 'refused';
10339: }
10340: }
10341: } elsif ($role eq 'au') {
10342: if ($url ne '/'.$udom.'/') {
10343: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10344: ' to assign author role for '.$uname.':'.$udom.
10345: ' in domain: '.$url.' refused (wrong domain).');
10346: return 'refused';
10347: }
10348: }
10349: $mrole=$role;
10350: }
10351: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
10352: "$udom:$uname:$url".'_'."$mrole=$role";
10353: if ($end) { $command.='_'.$end; }
10354: if ($start) {
10355: if ($end) {
10356: $command.='_'.$start;
10357: } else {
10358: $command.='_0_'.$start;
10359: }
10360: }
10361: my $origstart = $start;
10362: my $origend = $end;
10363: my $delflag;
10364: # actually delete
10365: if ($deleteflag) {
10366: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
10367: # modify command to delete the role
10368: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
10369: "$udom:$uname:$url".'_'."$mrole";
10370: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
10371: # set start and finish to negative values for userrolelog
10372: $start=-1;
10373: $end=-1;
10374: $delflag = 1;
10375: }
10376: }
10377: # send command
10378: my $answer=&reply($command,&homeserver($uname,$udom));
10379: # log new user role if status is ok
10380: if ($answer eq 'ok') {
10381: &userrolelog($role,$uname,$udom,$url,$start,$end);
10382: if (($role eq 'cc') || ($role eq 'in') ||
10383: ($role eq 'ep') || ($role eq 'ad') ||
10384: ($role eq 'ta') || ($role eq 'st') ||
10385: ($role=~/^cr/) || ($role eq 'gr') ||
10386: ($role eq 'co')) {
10387: # for course roles, perform group memberships changes triggered by role change.
10388: unless ($role =~ /^gr/) {
10389: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10390: $origstart,$selfenroll,$context);
10391: }
10392: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10393: $selfenroll,$context);
10394: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10395: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10396: ($role eq 'da')) {
10397: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10398: $context);
10399: } elsif (($role eq 'ca') || ($role eq 'aa')) {
10400: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10401: $context);
10402: }
10403: if ($role eq 'cc') {
10404: &autoupdate_coowners($url,$end,$start,$uname,$udom);
10405: }
10406: }
10407: return $answer;
10408: }
10409:
10410: sub autoupdate_coowners {
10411: my ($url,$end,$start,$uname,$udom) = @_;
10412: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10413: if (($cdom ne '') && ($cnum ne '')) {
10414: my $now = time;
10415: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10416: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10417: my %coursehash = &coursedescription($cdom.'_'.$cnum);
10418: my $instcode = $coursehash{'internal.coursecode'};
10419: my $xlists = $coursehash{'internal.crosslistings'};
10420: if ($instcode ne '') {
10421: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10422: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10423: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10424: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10425: unless ($result eq 'valid') {
10426: if ($xlists ne '') {
10427: foreach my $xlist (split(',',$xlists)) {
10428: my ($inst_crosslist,$lcsec) = split(':',$xlist);
10429: $result =
10430: &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10431: $inst_crosslist,$uname.':'.$udom);
10432: last if ($result eq 'valid');
10433: }
10434: }
10435: }
10436: if ($result eq 'valid') {
10437: if ($coursehash{'internal.co-owners'}) {
10438: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10439: push(@newcoowners,$coowner);
10440: }
10441: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10442: push(@newcoowners,$uname.':'.$udom);
10443: }
10444: @newcoowners = sort(@newcoowners);
10445: } else {
10446: push(@newcoowners,$uname.':'.$udom);
10447: }
10448: } elsif ($coursehash{'internal.co-owners'}) {
10449: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10450: unless ($coowner eq $uname.':'.$udom) {
10451: push(@newcoowners,$coowner);
10452: }
10453: }
10454: unless (@newcoowners > 0) {
10455: $delcoowners = 1;
10456: $coowners = '';
10457: }
10458: }
10459: if (@newcoowners || $delcoowners) {
10460: &store_coowners($cdom,$cnum,$coursehash{'home'},
10461: $delcoowners,@newcoowners);
10462: }
10463: }
10464: }
10465: }
10466: }
10467: }
10468: }
10469:
10470: sub store_coowners {
10471: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10472: my $cid = $cdom.'_'.$cnum;
10473: my ($coowners,$delresult,$putresult);
10474: if (@newcoowners) {
10475: $coowners = join(',',@newcoowners);
10476: my %coownershash = (
10477: 'internal.co-owners' => $coowners,
10478: );
10479: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10480: if ($putresult eq 'ok') {
10481: if ($env{'course.'.$cid.'.num'} eq $cnum) {
10482: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10483: }
10484: }
10485: }
10486: if ($delcoowners) {
10487: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10488: if ($delresult eq 'ok') {
10489: if ($env{'course.'.$cid.'.internal.co-owners'}) {
10490: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10491: }
10492: }
10493: }
10494: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10495: my %crsinfo =
10496: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10497: if (ref($crsinfo{$cid}) eq 'HASH') {
10498: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10499: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10500: }
10501: }
10502: }
10503:
10504: # -------------------------------------------------- Modify user authentication
10505: # Overrides without validation
10506:
10507: sub modifyuserauth {
10508: my ($udom,$uname,$umode,$upass)=@_;
10509: my $uhome=&homeserver($uname,$udom);
10510: my $allowed;
10511: if (&allowed('mau',$udom)) {
10512: $allowed = 1;
10513: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10514: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10515: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10516: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10517: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10518: if (($cdom ne '') && ($cnum ne '')) {
10519: my $is_owner = &is_course_owner($cdom,$cnum);
10520: if ($is_owner) {
10521: $allowed = 1;
10522: }
10523: }
10524: }
10525: unless ($allowed) { return 'refused'; }
10526: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
10527: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10528: ' in domain '.$env{'request.role.domain'});
10529: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10530: &escape($upass),$uhome);
10531: my $ip = &get_requestor_ip();
10532: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
10533: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10534: '(Remote '.$ip.'): '.$reply);
10535: &log($udom,,$uname,$uhome,
10536: 'Authentication changed by '.$env{'user.domain'}.', '.
10537: $env{'user.name'}.', '.$umode.
10538: '(Remote '.$ip.'): '.$reply);
10539: unless ($reply eq 'ok') {
10540: &logthis('Authentication mode error: '.$reply);
10541: return 'error: '.$reply;
10542: }
10543: return 'ok';
10544: }
10545:
10546: # --------------------------------------------------------------- Modify a user
10547:
10548: sub modifyuser {
10549: my ($udom, $uname, $uid,
10550: $umode, $upass, $first,
10551: $middle, $last, $gene,
10552: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10553: $udom= &LONCAPA::clean_domain($udom);
10554: $uname=&LONCAPA::clean_username($uname);
10555: my $showcandelete = 'none';
10556: if (ref($candelete) eq 'ARRAY') {
10557: if (@{$candelete} > 0) {
10558: $showcandelete = join(', ',@{$candelete});
10559: }
10560: }
10561: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10562: $umode.', '.$first.', '.$middle.', '.
10563: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10564: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10565: ' desiredhome not specified').
10566: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10567: ' in domain '.$env{'request.role.domain'});
10568: my $uhome=&homeserver($uname,$udom,'true');
10569: my $newuser;
10570: if ($uhome eq 'no_host') {
10571: $newuser = 1;
10572: unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10573: ($umode eq 'lti')) {
10574: return 'error: more information needed to create new user';
10575: }
10576: }
10577: # ----------------------------------------------------------------- Create User
10578: if (($uhome eq 'no_host') &&
10579: (($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
10580: my $unhome='';
10581: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
10582: $unhome = $desiredhome;
10583: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10584: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10585: } else { # load balancing routine for determining $unhome
10586: my $loadm=10000000;
10587: my %servers = &get_servers($udom,'library');
10588: foreach my $tryserver (keys(%servers)) {
10589: my $answer=reply('load',$tryserver);
10590: if (($answer=~/\d+/) && ($answer<$loadm)) {
10591: $loadm=$answer;
10592: $unhome=$tryserver;
10593: }
10594: }
10595: }
10596: if (($unhome eq '') || ($unhome eq 'no_host')) {
10597: return 'error: unable to find a home server for '.$uname.
10598: ' in domain '.$udom;
10599: }
10600: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10601: &escape($upass),$unhome);
10602: unless ($reply eq 'ok') {
10603: return 'error: '.$reply;
10604: }
10605: $uhome=&homeserver($uname,$udom,'true');
10606: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10607: return 'error: unable verify users home machine.';
10608: }
10609: } # End of creation of new user
10610: # ---------------------------------------------------------------------- Add ID
10611: if ($uid) {
10612: $uid=~tr/A-Z/a-z/;
10613: my %uidhash=&idrget($udom,$uname);
10614: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
10615: && (!$forceid)) {
10616: unless ($uid eq $uidhash{$uname}) {
10617: return 'error: user id "'.$uid.'" does not match '.
10618: 'current user id "'.$uidhash{$uname}.'".';
10619: }
10620: } else {
10621: &idput($udom,{$uname => $uid},$uhome,'ids');
10622: }
10623: }
10624: # -------------------------------------------------------------- Add names, etc
10625: my @tmp=&get('environment',
10626: ['firstname','middlename','lastname','generation','id',
10627: 'permanentemail','inststatus'],
10628: $udom,$uname);
10629: my (%names,%oldnames);
10630: if ($tmp[0] =~ m/^error:.*/) {
10631: %names=();
10632: } else {
10633: %names = @tmp;
10634: %oldnames = %names;
10635: }
10636: #
10637: # If name, email and/or uid are blank (e.g., because an uploaded file
10638: # of users did not contain them), do not overwrite existing values
10639: # unless field is in $candelete array ref.
10640: #
10641:
10642: my @fields = ('firstname','middlename','lastname','generation',
10643: 'permanentemail','id');
10644: my %newvalues;
10645: if (ref($candelete) eq 'ARRAY') {
10646: foreach my $field (@fields) {
10647: if (grep(/^\Q$field\E$/,@{$candelete})) {
10648: if ($field eq 'firstname') {
10649: $names{$field} = $first;
10650: } elsif ($field eq 'middlename') {
10651: $names{$field} = $middle;
10652: } elsif ($field eq 'lastname') {
10653: $names{$field} = $last;
10654: } elsif ($field eq 'generation') {
10655: $names{$field} = $gene;
10656: } elsif ($field eq 'permanentemail') {
10657: $names{$field} = $email;
10658: } elsif ($field eq 'id') {
10659: $names{$field} = $uid;
10660: }
10661: }
10662: }
10663: }
10664: if ($first) { $names{'firstname'} = $first; }
10665: if (defined($middle)) { $names{'middlename'} = $middle; }
10666: if ($last) { $names{'lastname'} = $last; }
10667: if (defined($gene)) { $names{'generation'} = $gene; }
10668: if ($email) {
10669: $email=~s/[^\w\@\.\-\,]//gs;
10670: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10671: }
10672: if ($uid) { $names{'id'} = $uid; }
10673: if (defined($inststatus)) {
10674: $names{'inststatus'} = '';
10675: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10676: if (ref($usertypes) eq 'HASH') {
10677: my @okstatuses;
10678: foreach my $item (split(/:/,$inststatus)) {
10679: if (defined($usertypes->{$item})) {
10680: push(@okstatuses,$item);
10681: }
10682: }
10683: if (@okstatuses) {
10684: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10685: }
10686: }
10687: }
10688: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10689: $umode.', '.$first.', '.$middle.', '.
10690: $last.', '.$gene.', '.$email.', '.$inststatus;
10691: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10692: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10693: } else {
10694: $logmsg .= ' during self creation';
10695: }
10696: my $changed;
10697: if ($newuser) {
10698: $changed = 1;
10699: } else {
10700: foreach my $field (@fields) {
10701: if ($names{$field} ne $oldnames{$field}) {
10702: $changed = 1;
10703: last;
10704: }
10705: }
10706: }
10707: unless ($changed) {
10708: $logmsg = 'No changes in user information needed for: '.$logmsg;
10709: &logthis($logmsg);
10710: return 'ok';
10711: }
10712: my $reply = &put('environment', \%names, $udom,$uname);
10713: if ($reply ne 'ok') {
10714: return 'error: '.$reply;
10715: }
10716: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10717: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10718: }
10719: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10720: &devalidate_cache_new('namescache',$uname.':'.$udom);
10721: $logmsg = 'Success modifying user '.$logmsg;
10722: &logthis($logmsg);
10723: return 'ok';
10724: }
10725:
10726: # -------------------------------------------------------------- Modify student
10727:
10728: sub modifystudent {
10729: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10730: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10731: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10732: if (!$cid) {
10733: unless ($cid=$env{'request.course.id'}) {
10734: return 'not_in_class';
10735: }
10736: }
10737: # --------------------------------------------------------------- Make the user
10738: my $reply=&modifyuser
10739: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10740: $desiredhome,$email,$inststatus);
10741: unless ($reply eq 'ok') { return $reply; }
10742: # This will cause &modify_student_enrollment to get the uid from the
10743: # student's environment
10744: $uid = undef if (!$forceid);
10745: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10746: $gene,$usec,$end,$start,$type,$locktype,
10747: $cid,$selfenroll,$context,$credits,$instsec);
10748: return $reply;
10749: }
10750:
10751: sub modify_student_enrollment {
10752: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10753: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10754: my ($cdom,$cnum,$chome);
10755: if (!$cid) {
10756: unless ($cid=$env{'request.course.id'}) {
10757: return 'not_in_class';
10758: }
10759: $cdom=$env{'course.'.$cid.'.domain'};
10760: $cnum=$env{'course.'.$cid.'.num'};
10761: } else {
10762: ($cdom,$cnum)=split(/_/,$cid);
10763: }
10764: $chome=$env{'course.'.$cid.'.home'};
10765: if (!$chome) {
10766: $chome=&homeserver($cnum,$cdom);
10767: }
10768: if (!$chome) { return 'unknown_course'; }
10769: # Make sure the user exists
10770: my $uhome=&homeserver($uname,$udom);
10771: if (($uhome eq '') || ($uhome eq 'no_host')) {
10772: return 'error: no such user';
10773: }
10774: # Get student data if we were not given enough information
10775: if (!defined($first) || $first eq '' ||
10776: !defined($last) || $last eq '' ||
10777: !defined($uid) || $uid eq '' ||
10778: !defined($middle) || $middle eq '' ||
10779: !defined($gene) || $gene eq '') {
10780: # They did not supply us with enough data to enroll the student, so
10781: # we need to pick up more information.
10782: my %tmp = &get('environment',
10783: ['firstname','middlename','lastname', 'generation','id']
10784: ,$udom,$uname);
10785:
10786: #foreach my $key (keys(%tmp)) {
10787: # &logthis("key $key = ".$tmp{$key});
10788: #}
10789: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10790: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10791: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
10792: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
10793: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10794: }
10795: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10796: my $user = "$uname:$udom";
10797: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10798: my $reply=cput('classlist',
10799: {$user =>
10800: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10801: $cdom,$cnum);
10802: if (($reply eq 'ok') || ($reply eq 'delayed')) {
10803: &devalidate_getsection_cache($udom,$uname,$cid);
10804: } else {
10805: return 'error: '.$reply;
10806: }
10807: # Add student role to user
10808: my $uurl='/'.$cid;
10809: $uurl=~s/\_/\//g;
10810: if ($usec) {
10811: $uurl.='/'.$usec;
10812: }
10813: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10814: $selfenroll,$context);
10815: if ($result ne 'ok') {
10816: if ($old_entry{$user} ne '') {
10817: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10818: } else {
10819: $reply = &del('classlist',[$user],$cdom,$cnum);
10820: }
10821: }
10822: return $result;
10823: }
10824:
10825: sub format_name {
10826: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10827: my $name;
10828: if ($first ne 'lastname') {
10829: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10830: } else {
10831: if ($lastname=~/\S/) {
10832: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10833: $name=~s/\s+,/,/;
10834: } else {
10835: $name.= $firstname.' '.$middlename.' '.$generation;
10836: }
10837: }
10838: $name=~s/^\s+//;
10839: $name=~s/\s+$//;
10840: $name=~s/\s+/ /g;
10841: return $name;
10842: }
10843:
10844: # ------------------------------------------------- Write to course preferences
10845:
10846: sub writecoursepref {
10847: my ($courseid,%prefs)=@_;
10848: $courseid=~s/^\///;
10849: $courseid=~s/\_/\//g;
10850: my ($cdomain,$cnum)=split(/\//,$courseid);
10851: my $chome=homeserver($cnum,$cdomain);
10852: if (($chome eq '') || ($chome eq 'no_host')) {
10853: return 'error: no such course';
10854: }
10855: my $cstring='';
10856: foreach my $pref (keys(%prefs)) {
10857: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10858: }
10859: $cstring=~s/\&$//;
10860: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10861: }
10862:
10863: # ---------------------------------------------------------- Make/modify course
10864:
10865: sub createcourse {
10866: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10867: $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
10868: $url=&declutter($url);
10869: my $cid='';
10870: if ($context eq 'requestcourses') {
10871: my $can_create = 0;
10872: my ($ownername,$ownerdom) = split(':',$course_owner);
10873: if ($udom eq $ownerdom) {
10874: my $reload;
10875: if (($callercontext eq 'auto') &&
10876: ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
10877: $reload = 'reload';
10878: }
10879: if (&usertools_access($ownername,$ownerdom,$category,$reload,
10880: $context)) {
10881: $can_create = 1;
10882: }
10883: } else {
10884: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10885: $category);
10886: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10887: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10888: if (@curr > 0) {
10889: my @options = qw(approval validate autolimit);
10890: my $optregex = join('|',@options);
10891: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10892: $can_create = 1;
10893: }
10894: }
10895: }
10896: }
10897: if ($can_create) {
10898: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10899: unless (&allowed('ccc',$udom)) {
10900: return 'refused';
10901: }
10902: }
10903: } else {
10904: return 'refused';
10905: }
10906: } elsif (!&allowed('ccc',$udom)) {
10907: return 'refused';
10908: }
10909: # --------------------------------------------------------------- Get Unique ID
10910: my $uname;
10911: if ($cnum =~ /^$match_courseid$/) {
10912: my $chome=&homeserver($cnum,$udom,'true');
10913: if (($chome eq '') || ($chome eq 'no_host')) {
10914: $uname = $cnum;
10915: } else {
10916: $uname = &generate_coursenum($udom,$crstype);
10917: }
10918: } else {
10919: $uname = &generate_coursenum($udom,$crstype);
10920: }
10921: return $uname if ($uname =~ /^error/);
10922: # -------------------------------------------------- Check supplied server name
10923: if (!defined($course_server)) {
10924: if (defined(&domain($udom,'primary'))) {
10925: $course_server = &domain($udom,'primary');
10926: } else {
10927: $course_server = $env{'user.home'};
10928: }
10929: }
10930: my %host_servers =
10931: &Apache::lonnet::get_servers($udom,'library');
10932: unless ($host_servers{$course_server}) {
10933: return 'error: invalid home server for course: '.$course_server;
10934: }
10935: # ------------------------------------------------------------- Make the course
10936: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10937: $course_server);
10938: unless ($reply eq 'ok') { return 'error: '.$reply; }
10939: my $uhome=&homeserver($uname,$udom,'true');
10940: if (($uhome eq '') || ($uhome eq 'no_host')) {
10941: return 'error: no such course';
10942: }
10943: # ----------------------------------------------------------------- Course made
10944: # log existence
10945: my $now = time;
10946: my $newcourse = {
10947: $udom.'_'.$uname => {
10948: description => $description,
10949: inst_code => $inst_code,
10950: owner => $course_owner,
10951: type => $crstype,
10952: creator => $env{'user.name'}.':'.
10953: $env{'user.domain'},
10954: created => $now,
10955: context => $context,
10956: },
10957: };
10958: &courseidput($udom,$newcourse,$uhome,'notime');
10959: # set toplevel url
10960: my $topurl=$url;
10961: unless ($nonstandard) {
10962: # ------------------------------------------ For standard courses, make top url
10963: my $mapurl=&clutter($url);
10964: if ($mapurl eq '/res/') { $mapurl=''; }
10965: $env{'form.initmap'}=(<<ENDINITMAP);
10966: <map>
10967: <resource id="1" type="start"></resource>
10968: <resource id="2" src="$mapurl"></resource>
10969: <resource id="3" type="finish"></resource>
10970: <link index="1" from="1" to="2"></link>
10971: <link index="2" from="2" to="3"></link>
10972: </map>
10973: ENDINITMAP
10974: $topurl=&declutter(
10975: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10976: );
10977: }
10978: # ----------------------------------------------------------- Write preferences
10979: &writecoursepref($udom.'_'.$uname,
10980: ('description' => $description,
10981: 'url' => $topurl,
10982: 'internal.creator' => $env{'user.name'}.':'.
10983: $env{'user.domain'},
10984: 'internal.created' => $now,
10985: 'internal.creationcontext' => $context)
10986: );
10987: return '/'.$udom.'/'.$uname;
10988: }
10989:
10990: # ------------------------------------------------------------------- Create ID
10991: sub generate_coursenum {
10992: my ($udom,$crstype) = @_;
10993: my $domdesc = &domain($udom);
10994: return 'error: invalid domain' if ($domdesc eq '');
10995: my $first;
10996: if ($crstype eq 'Community') {
10997: $first = '0';
10998: } else {
10999: $first = int(1+rand(9));
11000: }
11001: my $uname=$first.
11002: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11003: substr($$.time,0,5).unpack("H8",pack("I32",time)).
11004: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11005: # ----------------------------------------------- Make sure that does not exist
11006: my $uhome=&homeserver($uname,$udom,'true');
11007: unless (($uhome eq '') || ($uhome eq 'no_host')) {
11008: if ($crstype eq 'Community') {
11009: $first = '0';
11010: } else {
11011: $first = int(1+rand(9));
11012: }
11013: $uname=$first.
11014: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11015: substr($$.time,0,5).unpack("H8",pack("I32",time)).
11016: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11017: $uhome=&homeserver($uname,$udom,'true');
11018: unless (($uhome eq '') || ($uhome eq 'no_host')) {
11019: return 'error: unable to generate unique course-ID';
11020: }
11021: }
11022: return $uname;
11023: }
11024:
11025: sub is_course {
11026: my ($cdom, $cnum) = scalar(@_) == 1 ?
11027: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
11028:
11029: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
11030: my $uhome=&homeserver($cnum,$cdom);
11031: my $iscourse;
11032: if (grep { $_ eq $uhome } current_machine_ids()) {
11033: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
11034: } else {
11035: my $hashid = $cdom.':'.$cnum;
11036: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
11037: unless (defined($cached)) {
11038: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
11039: $cnum,undef,undef,'.');
11040: $iscourse = 0;
11041: if (exists($courses{$cdom.'_'.$cnum})) {
11042: $iscourse = 1;
11043: }
11044: &do_cache_new('iscourse',$hashid,$iscourse,3600);
11045: }
11046: }
11047: return unless ($iscourse);
11048: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
11049: }
11050:
11051: sub store_userdata {
11052: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
11053: my $result;
11054: if ($datakey ne '') {
11055: if (ref($storehash) eq 'HASH') {
11056: if ($udom eq '' || $uname eq '') {
11057: $udom = $env{'user.domain'};
11058: $uname = $env{'user.name'};
11059: }
11060: my $uhome=&homeserver($uname,$udom);
11061: if (($uhome eq '') || ($uhome eq 'no_host')) {
11062: $result = 'error: no_host';
11063: } else {
11064: $storehash->{'ip'} = &get_requestor_ip();
11065: $storehash->{'host'} = $perlvar{'lonHostID'};
11066:
11067: my $namevalue='';
11068: foreach my $key (keys(%{$storehash})) {
11069: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
11070: }
11071: $namevalue=~s/\&$//;
11072: unless ($namespace eq 'courserequests') {
11073: $datakey = &escape($datakey);
11074: }
11075: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
11076: $namevalue,$uhome);
11077: }
11078: } else {
11079: $result = 'error: data to store was not a hash reference';
11080: }
11081: } else {
11082: $result= 'error: invalid requestkey';
11083: }
11084: return $result;
11085: }
11086:
11087: # ---------------------------------------------------------- Assign Custom Role
11088:
11089: sub assigncustomrole {
11090: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
11091: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
11092: $end,$start,$deleteflag,$selfenroll,$context);
11093: }
11094:
11095: # ----------------------------------------------------------------- Revoke Role
11096:
11097: sub revokerole {
11098: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
11099: my $now=time;
11100: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
11101: }
11102:
11103: # ---------------------------------------------------------- Revoke Custom Role
11104:
11105: sub revokecustomrole {
11106: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
11107: my $now=time;
11108: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
11109: $deleteflag,$selfenroll,$context);
11110: }
11111:
11112: # ------------------------------------------------------------ Disk usage
11113: sub diskusage {
11114: my ($udom,$uname,$directorypath,$getpropath)=@_;
11115: $directorypath =~ s/\/$//;
11116: my $listing=&reply('du2:'.&escape($directorypath).':'
11117: .&escape($getpropath).':'.&escape($uname).':'
11118: .&escape($udom),homeserver($uname,$udom));
11119: if ($listing eq 'unknown_cmd') {
11120: if ($getpropath) {
11121: $directorypath = &propath($udom,$uname).'/'.$directorypath;
11122: }
11123: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11124: }
11125: return $listing;
11126: }
11127:
11128: sub is_locked {
11129: my ($file_name, $domain, $user, $which) = @_;
11130: my @check;
11131: my $is_locked;
11132: push (@check,$file_name);
11133: my %locked = &get('file_permissions',\@check,
11134: $env{'user.domain'},$env{'user.name'});
11135: my ($tmp)=keys(%locked);
11136: if ($tmp=~/^error:/) { undef(%locked); }
11137:
11138: if (ref($locked{$file_name}) eq 'ARRAY') {
11139: $is_locked = 'false';
11140: foreach my $entry (@{$locked{$file_name}}) {
11141: if (ref($entry) eq 'ARRAY') {
11142: $is_locked = 'true';
11143: if (ref($which) eq 'ARRAY') {
11144: push(@{$which},$entry);
11145: } else {
11146: last;
11147: }
11148: }
11149: }
11150: } else {
11151: $is_locked = 'false';
11152: }
11153: return $is_locked;
11154: }
11155:
11156: sub declutter_portfile {
11157: my ($file) = @_;
11158: $file =~ s{^(/portfolio/|portfolio/)}{/};
11159: return $file;
11160: }
11161:
11162: # ------------------------------------------------------------- Mark as Read Only
11163:
11164: sub mark_as_readonly {
11165: my ($domain,$user,$files,$what) = @_;
11166: my %current_permissions = &dump('file_permissions',$domain,$user);
11167: my ($tmp)=keys(%current_permissions);
11168: if ($tmp=~/^error:/) { undef(%current_permissions); }
11169: foreach my $file (@{$files}) {
11170: $file = &declutter_portfile($file);
11171: push(@{$current_permissions{$file}},$what);
11172: }
11173: &put('file_permissions',\%current_permissions,$domain,$user);
11174: return;
11175: }
11176:
11177: # ------------------------------------------------------------Save Selected Files
11178:
11179: sub save_selected_files {
11180: my ($user, $path, @files) = @_;
11181: my $filename = $user."savedfiles";
11182: my @other_files = &files_not_in_path($user, $path);
11183: open (OUT,'>',LONCAPA::tempdir().$filename);
11184: foreach my $file (@files) {
11185: print (OUT $env{'form.currentpath'}.$file."\n");
11186: }
11187: foreach my $file (@other_files) {
11188: print (OUT $file."\n");
11189: }
11190: close (OUT);
11191: return 'ok';
11192: }
11193:
11194: sub clear_selected_files {
11195: my ($user) = @_;
11196: my $filename = $user."savedfiles";
11197: open (OUT,'>',LONCAPA::tempdir().$filename);
11198: print (OUT undef);
11199: close (OUT);
11200: return ("ok");
11201: }
11202:
11203: sub files_in_path {
11204: my ($user, $path) = @_;
11205: my $filename = $user."savedfiles";
11206: my %return_files;
11207: open (IN,'<',LONCAPA::tempdir().$filename);
11208: while (my $line_in = <IN>) {
11209: chomp ($line_in);
11210: my @paths_and_file = split (m!/!, $line_in);
11211: my $file_part = pop (@paths_and_file);
11212: my $path_part = join ('/', @paths_and_file);
11213: $path_part.='/';
11214: my $path_and_file = $path_part.$file_part;
11215: if ($path_part eq $path) {
11216: $return_files{$file_part}= 'selected';
11217: }
11218: }
11219: close (IN);
11220: return (\%return_files);
11221: }
11222:
11223: # called in portfolio select mode, to show files selected NOT in current directory
11224: sub files_not_in_path {
11225: my ($user, $path) = @_;
11226: my $filename = $user."savedfiles";
11227: my @return_files;
11228: my $path_part;
11229: open(IN, '<',LONCAPA::tempdir().$filename);
11230: while (my $line = <IN>) {
11231: #ok, I know it's clunky, but I want it to work
11232: my @paths_and_file = split(m|/|, $line);
11233: my $file_part = pop(@paths_and_file);
11234: chomp($file_part);
11235: my $path_part = join('/', @paths_and_file);
11236: $path_part .= '/';
11237: my $path_and_file = $path_part.$file_part;
11238: if ($path_part ne $path) {
11239: push(@return_files, ($path_and_file));
11240: }
11241: }
11242: close(OUT);
11243: return (@return_files);
11244: }
11245:
11246: #------------------------------Submitted/Handedback Portfolio Files Versioning
11247:
11248: sub portfiles_versioning {
11249: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11250: my $portfolio_root = '/userfiles/portfolio';
11251: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11252: foreach my $file (@{$portfiles}) {
11253: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11254: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11255: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11256: my $getpropath = 1;
11257: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11258: $stu_name,$getpropath);
11259: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11260: my $new_answer =
11261: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11262: if ($new_answer ne 'problem getting file') {
11263: push(@{$versioned_portfiles}, $directory.$new_answer);
11264: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11265: [$symb,$env{'request.course.id'},'graded']);
11266: }
11267: }
11268: }
11269:
11270: sub get_next_version {
11271: my ($answer_name, $answer_ext, $dir_list) = @_;
11272: my $version;
11273: if (ref($dir_list) eq 'ARRAY') {
11274: foreach my $row (@{$dir_list}) {
11275: my ($file) = split(/\&/,$row,2);
11276: my ($file_name,$file_version,$file_ext) =
11277: &file_name_version_ext($file);
11278: if (($file_name eq $answer_name) &&
11279: ($file_ext eq $answer_ext)) {
11280: # gets here if filename and extension match,
11281: # regardless of version
11282: if ($file_version ne '') {
11283: # a versioned file is found so save it for later
11284: if ($file_version > $version) {
11285: $version = $file_version;
11286: }
11287: }
11288: }
11289: }
11290: }
11291: $version ++;
11292: return($version);
11293: }
11294:
11295: sub version_selected_portfile {
11296: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11297: my ($answer_name,$answer_ver,$answer_ext) =
11298: &file_name_version_ext($file_name);
11299: my $new_answer;
11300: $env{'form.copy'} =
11301: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11302: if($env{'form.copy'} eq '-1') {
11303: $new_answer = 'problem getting file';
11304: } else {
11305: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11306: my $copy_result =
11307: &finishuserfileupload($stu_name,$domain,'copy',
11308: '/portfolio'.$directory.$new_answer);
11309: }
11310: undef($env{'form.copy'});
11311: return ($new_answer);
11312: }
11313:
11314: sub file_name_version_ext {
11315: my ($file)=@_;
11316: my @file_parts = split(/\./, $file);
11317: my ($name,$version,$ext);
11318: if (@file_parts > 1) {
11319: $ext=pop(@file_parts);
11320: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11321: $version=pop(@file_parts);
11322: }
11323: $name=join('.',@file_parts);
11324: } else {
11325: $name=join('.',@file_parts);
11326: }
11327: return($name,$version,$ext);
11328: }
11329:
11330: #----------------------------------------------Get portfolio file permissions
11331:
11332: sub get_portfile_permissions {
11333: my ($domain,$user) = @_;
11334: my %current_permissions = &dump('file_permissions',$domain,$user);
11335: my ($tmp)=keys(%current_permissions);
11336: if ($tmp=~/^error:/) { undef(%current_permissions); }
11337: return \%current_permissions;
11338: }
11339:
11340: #---------------------------------------------Get portfolio file access controls
11341:
11342: sub get_access_controls {
11343: my ($current_permissions,$group,$file) = @_;
11344: my %access;
11345: my $real_file = $file;
11346: $file =~ s/\.meta$//;
11347: if (defined($file)) {
11348: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11349: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
11350: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
11351: }
11352: }
11353: } else {
11354: foreach my $key (keys(%{$current_permissions})) {
11355: if ($key =~ /\0accesscontrol$/) {
11356: if (defined($group)) {
11357: if ($key !~ m-^\Q$group\E/-) {
11358: next;
11359: }
11360: }
11361: my ($fullpath) = split(/\0/,$key);
11362: if (ref($$current_permissions{$key}) eq 'HASH') {
11363: foreach my $control (keys(%{$$current_permissions{$key}})) {
11364: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11365: }
11366: }
11367: }
11368: }
11369: }
11370: return %access;
11371: }
11372:
11373: sub modify_access_controls {
11374: my ($file_name,$changes,$domain,$user)=@_;
11375: my ($outcome,$deloutcome);
11376: my %store_permissions;
11377: my %new_values;
11378: my %new_control;
11379: my %translation;
11380: my @deletions = ();
11381: my $now = time;
11382: if (exists($$changes{'activate'})) {
11383: if (ref($$changes{'activate'}) eq 'HASH') {
11384: my @newitems = sort(keys(%{$$changes{'activate'}}));
11385: my $numnew = scalar(@newitems);
11386: for (my $i=0; $i<$numnew; $i++) {
11387: my $newkey = $newitems[$i];
11388: my $newid = &Apache::loncommon::get_cgi_id();
11389: if ($newkey =~ /^\d+:/) {
11390: $newkey =~ s/^(\d+)/$newid/;
11391: $translation{$1} = $newid;
11392: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11393: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11394: $translation{$1} = $newid;
11395: }
11396: $new_values{$file_name."\0".$newkey} =
11397: $$changes{'activate'}{$newitems[$i]};
11398: $new_control{$newkey} = $now;
11399: }
11400: }
11401: }
11402: my %todelete;
11403: my %changed_items;
11404: foreach my $action ('delete','update') {
11405: if (exists($$changes{$action})) {
11406: if (ref($$changes{$action}) eq 'HASH') {
11407: foreach my $key (keys(%{$$changes{$action}})) {
11408: my ($itemnum) = ($key =~ /^([^:]+):/);
11409: if ($action eq 'delete') {
11410: $todelete{$itemnum} = 1;
11411: } else {
11412: $changed_items{$itemnum} = $key;
11413: }
11414: }
11415: }
11416: }
11417: }
11418: # get lock on access controls for file.
11419: my $lockhash = {
11420: $file_name."\0".'locked_access_records' => $env{'user.name'}.
11421: ':'.$env{'user.domain'},
11422: };
11423: my $tries = 0;
11424: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11425:
11426: while (($gotlock ne 'ok') && $tries < 10) {
11427: $tries ++;
11428: sleep(0.1);
11429: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11430: }
11431: if ($gotlock eq 'ok') {
11432: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11433: my ($tmp)=keys(%curr_permissions);
11434: if ($tmp=~/^error:/) { undef(%curr_permissions); }
11435: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11436: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11437: if (ref($curr_controls) eq 'HASH') {
11438: foreach my $control_item (keys(%{$curr_controls})) {
11439: my ($itemnum) = ($control_item =~ /^([^:]+):/);
11440: if (defined($todelete{$itemnum})) {
11441: push(@deletions,$file_name."\0".$control_item);
11442: } else {
11443: if (defined($changed_items{$itemnum})) {
11444: $new_control{$changed_items{$itemnum}} = $now;
11445: push(@deletions,$file_name."\0".$control_item);
11446: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11447: } else {
11448: $new_control{$control_item} = $$curr_controls{$control_item};
11449: }
11450: }
11451: }
11452: }
11453: }
11454: my ($group);
11455: if (&is_course($domain,$user)) {
11456: ($group,my $file) = split(/\//,$file_name,2);
11457: }
11458: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11459: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11460: $outcome = &put('file_permissions',\%new_values,$domain,$user);
11461: # remove lock
11462: my @del_lock = ($file_name."\0".'locked_access_records');
11463: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
11464: my $sqlresult =
11465: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
11466: $group);
11467: } else {
11468: $outcome = "error: could not obtain lockfile\n";
11469: }
11470: return ($outcome,$deloutcome,\%new_values,\%translation);
11471: }
11472:
11473: sub make_public_indefinitely {
11474: my (@requrl) = @_;
11475: return &automated_portfile_access('public',\@requrl);
11476: }
11477:
11478: sub automated_portfile_access {
11479: my ($accesstype,$addsref,$delsref,$info) = @_;
11480: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11481: return 'invalid';
11482: }
11483: my %urls;
11484: if (ref($addsref) eq 'ARRAY') {
11485: foreach my $requrl (@{$addsref}) {
11486: if (&is_portfolio_url($requrl)) {
11487: unless (exists($urls{$requrl})) {
11488: $urls{$requrl} = 'add';
11489: }
11490: }
11491: }
11492: }
11493: if (ref($delsref) eq 'ARRAY') {
11494: foreach my $requrl (@{$delsref}) {
11495: if (&is_portfolio_url($requrl)) {
11496: unless (exists($urls{$requrl})) {
11497: $urls{$requrl} = 'delete';
11498: }
11499: }
11500: }
11501: }
11502: unless (keys(%urls)) {
11503: return 'invalid';
11504: }
11505: my $ip;
11506: if ($accesstype eq 'ip') {
11507: if (ref($info) eq 'HASH') {
11508: if ($info->{'ip'} ne '') {
11509: $ip = $info->{'ip'};
11510: }
11511: }
11512: if ($ip eq '') {
11513: return 'invalid';
11514: }
11515: }
11516: my $errors;
11517: my $now = time;
11518: my %current_perms;
11519: foreach my $requrl (sort(keys(%urls))) {
11520: my $action;
11521: if ($urls{$requrl} eq 'add') {
11522: $action = 'activate';
11523: } else {
11524: $action = 'none';
11525: }
11526: my $aclnum = 0;
11527: my (undef,$udom,$unum,$file_name,$group) =
11528: &parse_portfolio_url($requrl);
11529: unless (exists($current_perms{$unum.':'.$udom})) {
11530: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11531: }
11532: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
11533: $group,$file_name);
11534: foreach my $key (keys(%{$access_controls{$file_name}})) {
11535: my ($num,$scope,$end,$start) =
11536: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11537: if ($scope eq $accesstype) {
11538: if (($start <= $now) && ($end == 0)) {
11539: if ($accesstype eq 'ip') {
11540: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11541: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11542: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11543: if ($urls{$requrl} eq 'add') {
11544: $action = 'none';
11545: last;
11546: } else {
11547: $action = 'delete';
11548: $aclnum = $num;
11549: last;
11550: }
11551: }
11552: }
11553: }
11554: } elsif ($accesstype eq 'public') {
11555: if ($urls{$requrl} eq 'add') {
11556: $action = 'none';
11557: last;
11558: } else {
11559: $action = 'delete';
11560: $aclnum = $num;
11561: last;
11562: }
11563: }
11564: } elsif ($accesstype eq 'public') {
11565: $action = 'update';
11566: $aclnum = $num;
11567: last;
11568: }
11569: }
11570: }
11571: if ($action eq 'none') {
11572: next;
11573: } else {
11574: my %changes;
11575: my $newend = 0;
11576: my $newstart = $now;
11577: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
11578: $changes{$action}{$newkey} = {
11579: type => $accesstype,
11580: time => {
11581: start => $newstart,
11582: end => $newend,
11583: },
11584: };
11585: if ($accesstype eq 'ip') {
11586: $changes{$action}{$newkey}{'ip'} = [$ip];
11587: }
11588: my ($outcome,$deloutcome,$new_values,$translation) =
11589: &modify_access_controls($file_name,\%changes,$udom,$unum);
11590: unless ($outcome eq 'ok') {
11591: $errors .= $outcome.' ';
11592: }
11593: }
11594: }
11595: if ($errors) {
11596: $errors =~ s/\s$//;
11597: return $errors;
11598: } else {
11599: return 'ok';
11600: }
11601: }
11602:
11603: #------------------------------------------------------Get Marked as Read Only
11604:
11605: sub get_marked_as_readonly {
11606: my ($domain,$user,$what,$group) = @_;
11607: my $current_permissions = &get_portfile_permissions($domain,$user);
11608: my @readonly_files;
11609: my $cmp1=$what;
11610: if (ref($what)) { $cmp1=join('',@{$what}) };
11611: while (my ($file_name,$value) = each(%{$current_permissions})) {
11612: if (defined($group)) {
11613: if ($file_name !~ m-^\Q$group\E/-) {
11614: next;
11615: }
11616: }
11617: if (ref($value) eq "ARRAY"){
11618: foreach my $stored_what (@{$value}) {
11619: my $cmp2=$stored_what;
11620: if (ref($stored_what) eq 'ARRAY') {
11621: $cmp2=join('',@{$stored_what});
11622: }
11623: if ($cmp1 eq $cmp2) {
11624: push(@readonly_files, $file_name);
11625: last;
11626: } elsif (!defined($what)) {
11627: push(@readonly_files, $file_name);
11628: last;
11629: }
11630: }
11631: }
11632: }
11633: return @readonly_files;
11634: }
11635: #-----------------------------------------------------------Get Marked as Read Only Hash
11636:
11637: sub get_marked_as_readonly_hash {
11638: my ($current_permissions,$group,$what) = @_;
11639: my %readonly_files;
11640: while (my ($file_name,$value) = each(%{$current_permissions})) {
11641: if (defined($group)) {
11642: if ($file_name !~ m-^\Q$group\E/-) {
11643: next;
11644: }
11645: }
11646: if (ref($value) eq "ARRAY"){
11647: foreach my $stored_what (@{$value}) {
11648: if (ref($stored_what) eq 'ARRAY') {
11649: foreach my $lock_descriptor(@{$stored_what}) {
11650: if ($lock_descriptor eq 'graded') {
11651: $readonly_files{$file_name} = 'graded';
11652: } elsif ($lock_descriptor eq 'handback') {
11653: $readonly_files{$file_name} = 'handback';
11654: } else {
11655: if (!exists($readonly_files{$file_name})) {
11656: $readonly_files{$file_name} = 'locked';
11657: }
11658: }
11659: }
11660: }
11661: }
11662: }
11663: }
11664: return %readonly_files;
11665: }
11666: # ------------------------------------------------------------ Unmark as Read Only
11667:
11668: sub unmark_as_readonly {
11669: # unmarks $file_name (if $file_name is defined), or all files locked by $what
11670: # for portfolio submissions, $what contains [$symb,$crsid]
11671: my ($domain,$user,$what,$file_name,$group) = @_;
11672: $file_name = &declutter_portfile($file_name);
11673: my $symb_crs = $what;
11674: if (ref($what)) { $symb_crs=join('',@$what); }
11675: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
11676: my ($tmp)=keys(%current_permissions);
11677: if ($tmp=~/^error:/) { undef(%current_permissions); }
11678: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
11679: foreach my $file (@readonly_files) {
11680: my $clean_file = &declutter_portfile($file);
11681: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
11682: my $current_locks = $current_permissions{$file};
11683: my @new_locks;
11684: my @del_keys;
11685: if (ref($current_locks) eq "ARRAY"){
11686: foreach my $locker (@{$current_locks}) {
11687: my $compare=$locker;
11688: if (ref($locker) eq 'ARRAY') {
11689: $compare=join('',@{$locker});
11690: if ($compare ne $symb_crs) {
11691: push(@new_locks, $locker);
11692: }
11693: }
11694: }
11695: if (scalar(@new_locks) > 0) {
11696: $current_permissions{$file} = \@new_locks;
11697: } else {
11698: push(@del_keys, $file);
11699: &del('file_permissions',\@del_keys, $domain, $user);
11700: delete($current_permissions{$file});
11701: }
11702: }
11703: }
11704: &put('file_permissions',\%current_permissions,$domain,$user);
11705: return;
11706: }
11707:
11708: # ------------------------------------------------------------ Directory lister
11709:
11710: sub dirlist {
11711: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
11712: $uri=~s/^\///;
11713: $uri=~s/\/$//;
11714: my ($udom, $uname);
11715: if ($getuserdir) {
11716: $udom = $userdomain;
11717: $uname = $username;
11718: } else {
11719: (undef,$udom,$uname)=split(/\//,$uri);
11720: if(defined($userdomain)) {
11721: $udom = $userdomain;
11722: }
11723: if(defined($username)) {
11724: $uname = $username;
11725: }
11726: }
11727: my ($dirRoot,$listing,@listing_results);
11728:
11729: $dirRoot = $perlvar{'lonDocRoot'};
11730: if (defined($getpropath)) {
11731: $dirRoot = &propath($udom,$uname);
11732: $dirRoot =~ s/\/$//;
11733: } elsif (defined($getuserdir)) {
11734: my $subdir=$uname.'__';
11735: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11736: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11737: ."/$udom/$subdir/$uname";
11738: } elsif (defined($alternateRoot)) {
11739: $dirRoot = $alternateRoot;
11740: }
11741:
11742: if($udom) {
11743: if($uname) {
11744: my $uhome = &homeserver($uname,$udom);
11745: if ($uhome eq 'no_host') {
11746: return ([],'no_host');
11747: }
11748: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11749: .$getuserdir.':'.&escape($dirRoot)
11750: .':'.&escape($uname).':'.&escape($udom),$uhome);
11751: if ($listing eq 'unknown_cmd') {
11752: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11753: } else {
11754: @listing_results = map { &unescape($_); } split(/:/,$listing);
11755: }
11756: if ($listing eq 'unknown_cmd') {
11757: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11758: @listing_results = split(/:/,$listing);
11759: } else {
11760: @listing_results = map { &unescape($_); } split(/:/,$listing);
11761: }
11762: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11763: ($listing eq 'rejected') || ($listing eq 'refused') ||
11764: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11765: return ([],$listing);
11766: } else {
11767: return (\@listing_results);
11768: }
11769: } elsif(!$alternateRoot) {
11770: my (%allusers,%listerror);
11771: my %servers = &get_servers($udom,'library');
11772: foreach my $tryserver (keys(%servers)) {
11773: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11774: &escape($udom),$tryserver);
11775: if ($listing eq 'unknown_cmd') {
11776: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11777: $udom, $tryserver);
11778: } else {
11779: @listing_results = map { &unescape($_); } split(/:/,$listing);
11780: }
11781: if ($listing eq 'unknown_cmd') {
11782: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11783: $udom, $tryserver);
11784: @listing_results = split(/:/,$listing);
11785: } else {
11786: @listing_results =
11787: map { &unescape($_); } split(/:/,$listing);
11788: }
11789: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11790: ($listing eq 'rejected') || ($listing eq 'refused') ||
11791: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11792: $listerror{$tryserver} = $listing;
11793: } else {
11794: foreach my $line (@listing_results) {
11795: my ($entry) = split(/&/,$line,2);
11796: $allusers{$entry} = 1;
11797: }
11798: }
11799: }
11800: my @alluserslist=();
11801: foreach my $user (sort(keys(%allusers))) {
11802: push(@alluserslist,$user.'&user');
11803: }
11804:
11805: if (!%listerror) {
11806: # no errors
11807: return (\@alluserslist);
11808: } elsif (scalar(keys(%servers)) == 1) {
11809: # one library server, one error
11810: my ($key) = keys(%listerror);
11811: return (\@alluserslist, $listerror{$key});
11812: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11813: # con_lost indicates that we might miss data from at least one
11814: # library server
11815: return (\@alluserslist, 'con_lost');
11816: } else {
11817: # multiple library servers and no con_lost -> data should be
11818: # complete.
11819: return (\@alluserslist);
11820: }
11821:
11822: } else {
11823: return ([],'missing username');
11824: }
11825: } elsif(!defined($getpropath)) {
11826: my $path = $perlvar{'lonDocRoot'}.'/res/';
11827: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11828: return (\@all_domains);
11829: } else {
11830: return ([],'missing domain');
11831: }
11832: }
11833:
11834: # --------------------------------------------- GetFileTimestamp
11835: # This function utilizes dirlist and returns the date stamp for
11836: # when it was last modified. It will also return an error of -1
11837: # if an error occurs
11838:
11839: sub GetFileTimestamp {
11840: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11841: $studentDomain = &LONCAPA::clean_domain($studentDomain);
11842: $studentName = &LONCAPA::clean_username($studentName);
11843: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11844: undef,$getuserdir);
11845: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11846: return -1;
11847: }
11848: if (ref($fileref) eq 'ARRAY') {
11849: my @stats = split('&',$fileref->[0]);
11850: # @stats contains first the filename, then the stat output
11851: return $stats[10]; # so this is 10 instead of 9.
11852: } else {
11853: return -1;
11854: }
11855: }
11856:
11857: sub stat_file {
11858: my ($uri) = @_;
11859: $uri = &clutter_with_no_wrapper($uri);
11860:
11861: my ($udom,$uname,$file);
11862: if ($uri =~ m-^/(uploaded|editupload)/-) {
11863: ($udom,$uname,$file) =
11864: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11865: $file = 'userfiles/'.$file;
11866: }
11867: if ($uri =~ m-^/res/-) {
11868: ($udom,$uname) =
11869: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11870: $file = $uri;
11871: }
11872:
11873: if (!$udom || !$uname || !$file) {
11874: # unable to handle the uri
11875: return ();
11876: }
11877: my $getpropath;
11878: if ($file =~ /^userfiles\//) {
11879: $getpropath = 1;
11880: }
11881: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11882: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11883: return ();
11884: } else {
11885: if (ref($listref) eq 'ARRAY') {
11886: my @stats = split('&',$listref->[0]);
11887: shift(@stats); #filename is first
11888: return @stats;
11889: }
11890: }
11891: return ();
11892: }
11893:
11894: # --------------------------------------------------------- recursedirs
11895: # Recursive function to traverse either a specific user's Authoring Space
11896: # or corresponding Published Resource Space, and populate the hash ref:
11897: # $dirhashref with URLs of all directories, and if $filehashref hash
11898: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11899: # or .rights files in resource space, and .meta, .save, .log, and .bak
11900: # files in Authoring Space.
11901: #
11902: # Inputs:
11903: #
11904: # $is_home - true if current server is home server for user's space
11905: # $context - either: priv, or res respectively for Authoring or Resource Space.
11906: # $docroot - Document root (i.e., /home/httpd/html
11907: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11908: # $relpath - Current path (relative to top level).
11909: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11910: # $filehashref - reference to hash to populate with URLs of files (Optional)
11911: #
11912: # Returns: nothing
11913: #
11914: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11915: #
11916: # Currently used by interface/londocs.pm to create linked select boxes for
11917: # directory and filename to import a Course "Author" resource into a course, and
11918: # also to create linked select boxes for Authoring Space and Directory to choose
11919: # save location for creation of a new "standard" problem from the Course Editor.
11920: #
11921:
11922: sub recursedirs {
11923: my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11924: return unless (ref($dirhashref) eq 'HASH');
11925: my $currpath = $docroot.$toppath;
11926: if ($relpath) {
11927: $currpath .= "/$relpath";
11928: }
11929: my $savefile;
11930: if (ref($filehashref)) {
11931: $savefile = 1;
11932: }
11933: if ($is_home) {
11934: if (opendir(my $dirh,$currpath)) {
11935: foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11936: next if ($item eq '');
11937: if (-d "$currpath/$item") {
11938: my $newpath;
11939: if ($relpath) {
11940: $newpath = "$relpath/$item";
11941: } else {
11942: $newpath = $item;
11943: }
11944: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11945: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11946: } elsif ($savefile) {
11947: if ($context eq 'priv') {
11948: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11949: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11950: }
11951: } else {
11952: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11953: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11954: }
11955: }
11956: }
11957: }
11958: closedir($dirh);
11959: }
11960: } else {
11961: my ($dirlistref,$listerror) =
11962: &dirlist($toppath.$relpath);
11963: my @dir_lines;
11964: my $dirptr=16384;
11965: if (ref($dirlistref) eq 'ARRAY') {
11966: foreach my $dir_line (sort
11967: {
11968: my ($afile)=split('&',$a,2);
11969: my ($bfile)=split('&',$b,2);
11970: return (lc($afile) cmp lc($bfile));
11971: } (@{$dirlistref})) {
11972: my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11973: split(/\&/,$dir_line,16);
11974: $item =~ s/\s+$//;
11975: next if (($item =~ /^\.\.?$/) || ($obs));
11976: if ($dirptr&$testdir) {
11977: my $newpath;
11978: if ($relpath) {
11979: $newpath = "$relpath/$item";
11980: } else {
11981: $relpath = '/';
11982: $newpath = $item;
11983: }
11984: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11985: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11986: } elsif ($savefile) {
11987: if ($context eq 'priv') {
11988: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11989: $filehashref->{$relpath}{$item} = 1;
11990: }
11991: } else {
11992: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11993: $filehashref->{$relpath}{$item} = 1;
11994: }
11995: }
11996: }
11997: }
11998: }
11999: }
12000: return;
12001: }
12002:
12003: # -------------------------------------------------------- Value of a Condition
12004:
12005: # gets the value of a specific preevaluated condition
12006: # stored in the string $env{user.state.<cid>}
12007: # or looks up a condition reference in the bighash and if if hasn't
12008: # already been evaluated recurses into docondval to get the value of
12009: # the condition, then memoizing it to
12010: # $env{user.state.<cid>.<condition>}
12011: sub directcondval {
12012: my $number=shift;
12013: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
12014: &Apache::lonuserstate::evalstate();
12015: }
12016: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
12017: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
12018: } elsif ($number =~ /^_/) {
12019: my $sub_condition;
12020: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12021: &GDBM_READER(),0640)) {
12022: $sub_condition=$bighash{'conditions'.$number};
12023: untie(%bighash);
12024: }
12025: my $value = &docondval($sub_condition);
12026: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
12027: return $value;
12028: }
12029: if ($env{'user.state.'.$env{'request.course.id'}}) {
12030: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
12031: } else {
12032: return 2;
12033: }
12034: }
12035:
12036: # get the collection of conditions for this resource
12037: sub condval {
12038: my $condidx=shift;
12039: my $allpathcond='';
12040: foreach my $cond (split(/\|/,$condidx)) {
12041: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
12042: $allpathcond.=
12043: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
12044: }
12045: }
12046: $allpathcond=~s/\|$//;
12047: return &docondval($allpathcond);
12048: }
12049:
12050: #evaluates an expression of conditions
12051: sub docondval {
12052: my ($allpathcond) = @_;
12053: my $result=0;
12054: if ($env{'request.course.id'}
12055: && defined($allpathcond)) {
12056: my $operand='|';
12057: my @stack;
12058: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
12059: if ($chunk eq '(') {
12060: push @stack,($operand,$result);
12061: } elsif ($chunk eq ')') {
12062: my $before=pop @stack;
12063: if (pop @stack eq '&') {
12064: $result=$result>$before?$before:$result;
12065: } else {
12066: $result=$result>$before?$result:$before;
12067: }
12068: } elsif (($chunk eq '&') || ($chunk eq '|')) {
12069: $operand=$chunk;
12070: } else {
12071: my $new=directcondval($chunk);
12072: if ($operand eq '&') {
12073: $result=$result>$new?$new:$result;
12074: } else {
12075: $result=$result>$new?$result:$new;
12076: }
12077: }
12078: }
12079: }
12080: return $result;
12081: }
12082:
12083: # ---------------------------------------------------- Devalidate courseresdata
12084:
12085: sub devalidatecourseresdata {
12086: my ($coursenum,$coursedomain)=@_;
12087: my $hashid=$coursenum.':'.$coursedomain;
12088: &devalidate_cache_new('courseres',$hashid);
12089: }
12090:
12091:
12092: # --------------------------------------------------- Course Resourcedata Query
12093: #
12094: # Parameters:
12095: # $coursenum - Number of the course.
12096: # $coursedomain - Domain at which the course was created.
12097: # Returns:
12098: # A hash of the course parameters along (I think) with timestamps
12099: # and version info.
12100:
12101: sub get_courseresdata {
12102: my ($coursenum,$coursedomain)=@_;
12103: my $coursehom=&homeserver($coursenum,$coursedomain);
12104: my $hashid=$coursenum.':'.$coursedomain;
12105: my ($result,$cached)=&is_cached_new('courseres',$hashid);
12106: my %dumpreply;
12107: unless (defined($cached)) {
12108: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
12109: $result=\%dumpreply;
12110: my ($tmp) = keys(%dumpreply);
12111: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12112: &do_cache_new('courseres',$hashid,$result,600);
12113: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
12114: return $tmp;
12115: } elsif ($tmp =~ /^(error)/) {
12116: $result=undef;
12117: &do_cache_new('courseres',$hashid,$result,600);
12118: }
12119: }
12120: return $result;
12121: }
12122:
12123: sub devalidateuserresdata {
12124: my ($uname,$udom)=@_;
12125: my $hashid="$udom:$uname";
12126: &devalidate_cache_new('userres',$hashid);
12127: }
12128:
12129: sub get_userresdata {
12130: my ($uname,$udom)=@_;
12131: #most student don\'t have any data set, check if there is some data
12132: if (&EXT_cache_status($udom,$uname)) { return undef; }
12133:
12134: my $hashid="$udom:$uname";
12135: my ($result,$cached)=&is_cached_new('userres',$hashid);
12136: if (!defined($cached)) {
12137: my %resourcedata=&dump('resourcedata',$udom,$uname);
12138: $result=\%resourcedata;
12139: &do_cache_new('userres',$hashid,$result,600);
12140: }
12141: my ($tmp)=keys(%$result);
12142: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12143: return $result;
12144: }
12145: #error 2 occurs when the .db doesn't exist
12146: if ($tmp!~/error: 2 /) {
12147: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12148: &logthis("<font color=\"blue\">WARNING:".
12149: " Trying to get resource data for ".
12150: $uname." at ".$udom.": ".
12151: $tmp."</font>");
12152: }
12153: } elsif ($tmp=~/error: 2 /) {
12154: #&EXT_cache_set($udom,$uname);
12155: &do_cache_new('userres',$hashid,undef,600);
12156: undef($tmp); # not really an error so don't send it back
12157: }
12158: return $tmp;
12159: }
12160: #----------------------------------------------- resdata - return resource data
12161: # Purpose:
12162: # Return resource data for either users or for a course.
12163: # Parameters:
12164: # $name - Course/user name.
12165: # $domain - Name of the domain the user/course is registered on.
12166: # $type - Type of thing $name is (must be 'course' or 'user')
12167: # $mapp - decluttered URL of enclosing map
12168: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
12169: # $recurseup - Ref to array of map URLs, starting with map containing
12170: # $mapp up through hierarchy of nested maps to top level map.
12171: # $courseid - CourseID (first part of param identifier).
12172: # $modifier - Middle part of param identifier.
12173: # $what - Last part of param identifier.
12174: # @which - Array of names of resources desired.
12175: # Returns:
12176: # The value of the first reasource in @which that is found in the
12177: # resource hash.
12178: # Exceptional Conditions:
12179: # If the $type passed in is not valid (not the string 'course' or
12180: # 'user', an undefined reference is returned.
12181: # If none of the resources are found, an undef is returned
12182: sub resdata {
12183: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12184: $modifier,$what,@which)=@_;
12185: my $result;
12186: if ($type eq 'course') {
12187: $result=&get_courseresdata($name,$domain);
12188: } elsif ($type eq 'user') {
12189: $result=&get_userresdata($name,$domain);
12190: }
12191: if (!ref($result)) { return $result; }
12192: foreach my $item (@which) {
12193: if ($item->[1] eq 'course') {
12194: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12195: unless ($$recursed) {
12196: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
12197: $$recursed = 1;
12198: }
12199: foreach my $item (@${recurseup}) {
12200: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12201: last if (defined($result->{$norecursechk}));
12202: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12203: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12204: }
12205: }
12206: }
12207: if (defined($result->{$item->[0]})) {
12208: return [$result->{$item->[0]},$item->[1]];
12209: }
12210: }
12211: return undef;
12212: }
12213:
12214: sub get_domain_lti {
12215: my ($cdom,$context) = @_;
12216: my ($name,%lti);
12217: if ($context eq 'consumer') {
12218: $name = 'ltitools';
12219: } elsif ($context eq 'provider') {
12220: $name = 'lti';
12221: } else {
12222: return %lti;
12223: }
12224: my ($result,$cached)=&is_cached_new($name,$cdom);
12225: if (defined($cached)) {
12226: if (ref($result) eq 'HASH') {
12227: %lti = %{$result};
12228: }
12229: } else {
12230: my %domconfig = &get_dom('configuration',[$name],$cdom);
12231: if (ref($domconfig{$name}) eq 'HASH') {
12232: %lti = %{$domconfig{$name}};
12233: my %encdomconfig = &get_dom('encconfig',[$name],$cdom,undef,1);
12234: if (ref($encdomconfig{$name}) eq 'HASH') {
12235: foreach my $id (keys(%lti)) {
12236: if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
12237: foreach my $item ('key','secret') {
12238: $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
12239: }
12240: }
12241: }
12242: }
12243: }
12244: my $cachetime = 24*60*60;
12245: &do_cache_new($name,$cdom,\%lti,$cachetime);
12246: }
12247: return %lti;
12248: }
12249:
12250: sub get_course_lti {
12251: my ($cnum,$cdom) = @_;
12252: my $hashid=$cdom.'_'.$cnum;
12253: my %courselti;
12254: my ($result,$cached)=&is_cached_new('courselti',$hashid);
12255: if (defined($cached)) {
12256: if (ref($result) eq 'HASH') {
12257: %courselti = %{$result};
12258: }
12259: } else {
12260: %courselti = &dump('lti',$cdom,$cnum,undef,undef,undef,1);
12261: my $cachetime = 24*60*60;
12262: &do_cache_new('courselti',$hashid,\%courselti,$cachetime);
12263: }
12264: return %courselti;
12265: }
12266:
12267: sub get_numsuppfiles {
12268: my ($cnum,$cdom,$ignorecache)=@_;
12269: my $hashid=$cnum.':'.$cdom;
12270: my ($suppcount,$cached);
12271: unless ($ignorecache) {
12272: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
12273: }
12274: unless (defined($cached)) {
12275: my $chome=&homeserver($cnum,$cdom);
12276: unless ($chome eq 'no_host') {
12277: ($suppcount,my $supptools,my $errors) = (0,0,0);
12278: my $suppmap = 'supplemental.sequence';
12279: ($suppcount,$supptools,$errors) =
12280: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
12281: $supptools,$errors);
12282: }
12283: &do_cache_new('suppcount',$hashid,$suppcount,600);
12284: }
12285: return $suppcount;
12286: }
12287:
12288: #
12289: # EXT resource caching routines
12290: #
12291:
12292: {
12293: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12294: #
12295: # The course for which we cache
12296: my $cachedmapkey='';
12297: # The cached recursive maps for this course
12298: my %cachedmaps=();
12299: # When this was last done
12300: my $cachedmaptime='';
12301:
12302: sub clear_EXT_cache_status {
12303: &delenv('cache.EXT.');
12304: }
12305:
12306: sub EXT_cache_status {
12307: my ($target_domain,$target_user) = @_;
12308: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12309: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
12310: # We know already the user has no data
12311: return 1;
12312: } else {
12313: return 0;
12314: }
12315: }
12316:
12317: sub EXT_cache_set {
12318: my ($target_domain,$target_user) = @_;
12319: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12320: #&appenv({$cachename => time});
12321: }
12322:
12323: # --------------------------------------------------------- Value of a Variable
12324: sub EXT {
12325:
12326: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
12327: unless ($varname) { return ''; }
12328: #get real user name/domain, courseid and symb
12329: my $courseid;
12330: my $publicuser;
12331: if ($symbparm) {
12332: $symbparm=&get_symb_from_alias($symbparm);
12333: }
12334: if (!($uname && $udom)) {
12335: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
12336: if (!$symbparm) { $symbparm=$cursymb; }
12337: } else {
12338: $courseid=$env{'request.course.id'};
12339: }
12340: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12341: my $rest;
12342: if (defined($therest[0])) {
12343: $rest=join('.',@therest);
12344: } else {
12345: $rest='';
12346: }
12347:
12348: my $qualifierrest=$qualifier;
12349: if ($rest) { $qualifierrest.='.'.$rest; }
12350: my $spacequalifierrest=$space;
12351: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
12352: if ($realm eq 'user') {
12353: # --------------------------------------------------------------- user.resource
12354: if ($space eq 'resource') {
12355: if ( (defined($Apache::lonhomework::parsing_a_problem)
12356: || defined($Apache::lonhomework::parsing_a_task))
12357: &&
12358: ($symbparm eq &symbread()) ) {
12359: # if we are in the middle of processing the resource the
12360: # get the value we are planning on committing
12361: if (defined($Apache::lonhomework::results{$qualifierrest})) {
12362: return $Apache::lonhomework::results{$qualifierrest};
12363: } else {
12364: return $Apache::lonhomework::history{$qualifierrest};
12365: }
12366: } else {
12367: my %restored;
12368: if ($publicuser || $env{'request.state'} eq 'construct') {
12369: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12370: } else {
12371: %restored=&restore($symbparm,$courseid,$udom,$uname);
12372: }
12373: return $restored{$qualifierrest};
12374: }
12375: # ----------------------------------------------------------------- user.access
12376: } elsif ($space eq 'access') {
12377: # FIXME - not supporting calls for a specific user
12378: return &allowed($qualifier,$rest);
12379: # ------------------------------------------ user.preferences, user.environment
12380: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
12381: if (($uname eq $env{'user.name'}) &&
12382: ($udom eq $env{'user.domain'})) {
12383: return $env{join('.',('environment',$qualifierrest))};
12384: } else {
12385: my %returnhash;
12386: if (!$publicuser) {
12387: %returnhash=&userenvironment($udom,$uname,
12388: $qualifierrest);
12389: }
12390: return $returnhash{$qualifierrest};
12391: }
12392: # ----------------------------------------------------------------- user.course
12393: } elsif ($space eq 'course') {
12394: # FIXME - not supporting calls for a specific user
12395: return $env{join('.',('request.course',$qualifier))};
12396: # ------------------------------------------------------------------- user.role
12397: } elsif ($space eq 'role') {
12398: # FIXME - not supporting calls for a specific user
12399: my ($role,$where)=split(/\./,$env{'request.role'});
12400: if ($qualifier eq 'value') {
12401: return $role;
12402: } elsif ($qualifier eq 'extent') {
12403: return $where;
12404: }
12405: # ----------------------------------------------------------------- user.domain
12406: } elsif ($space eq 'domain') {
12407: return $udom;
12408: # ------------------------------------------------------------------- user.name
12409: } elsif ($space eq 'name') {
12410: return $uname;
12411: # ---------------------------------------------------- Any other user namespace
12412: } else {
12413: my %reply;
12414: if (!$publicuser) {
12415: %reply=&get($space,[$qualifierrest],$udom,$uname);
12416: }
12417: return $reply{$qualifierrest};
12418: }
12419: } elsif ($realm eq 'query') {
12420: # ---------------------------------------------- pull stuff out of query string
12421: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12422: [$spacequalifierrest]);
12423: return $env{'form.'.$spacequalifierrest};
12424: } elsif ($realm eq 'request') {
12425: # ------------------------------------------------------------- request.browser
12426: if ($space eq 'browser') {
12427: return $env{'browser.'.$qualifier};
12428: # ------------------------------------------------------------ request.filename
12429: } else {
12430: return $env{'request.'.$spacequalifierrest};
12431: }
12432: } elsif ($realm eq 'course') {
12433: # ---------------------------------------------------------- course.description
12434: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
12435: } elsif ($realm eq 'resource') {
12436:
12437: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
12438: if (!$symbparm) { $symbparm=&symbread(); }
12439: }
12440:
12441: if ($qualifier eq '') {
12442: if ($space eq 'title') {
12443: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12444: return &gettitle($symbparm);
12445: }
12446:
12447: if ($space eq 'map') {
12448: my ($map) = &decode_symb($symbparm);
12449: return &symbread($map);
12450: }
12451: if ($space eq 'maptitle') {
12452: my ($map) = &decode_symb($symbparm);
12453: return &gettitle($map);
12454: }
12455: if ($space eq 'filename') {
12456: if ($symbparm) {
12457: return &clutter((&decode_symb($symbparm))[2]);
12458: }
12459: return &hreflocation('',$env{'request.filename'});
12460: }
12461:
12462: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12463: if ($space eq 'visibleparts') {
12464: my $navmap = Apache::lonnavmaps::navmap->new();
12465: my $item;
12466: if (ref($navmap)) {
12467: my $res = $navmap->getBySymb($symbparm);
12468: my $parts = $res->parts();
12469: if (ref($parts) eq 'ARRAY') {
12470: $item = join(',',@{$parts});
12471: }
12472: undef($navmap);
12473: }
12474: return $item;
12475: }
12476: }
12477: }
12478:
12479: my ($section, $group, @groups, @recurseup, $recursed);
12480: if (ref($recurseupref) eq 'ARRAY') {
12481: @recurseup = @{$recurseupref};
12482: $recursed = 1;
12483: }
12484: my ($courselevelm,$courseleveli,$courselevel,$mapp);
12485: if (($courseid eq '') && ($cid)) {
12486: $courseid = $cid;
12487: }
12488: if (($symbparm && $courseid) &&
12489: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
12490:
12491: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
12492:
12493: # ----------------------------------------------------- Cascading lookup scheme
12494: my $symbp=$symbparm;
12495: $mapp=&deversion((&decode_symb($symbp))[0]);
12496: my $symbparm=$symbp.'.'.$spacequalifierrest;
12497: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
12498: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
12499: if (($env{'user.name'} eq $uname) &&
12500: ($env{'user.domain'} eq $udom)) {
12501: $section=$env{'request.course.sec'};
12502: @groups = split(/:/,$env{'request.course.groups'});
12503: @groups=&sort_course_groups($courseid,@groups);
12504: } else {
12505: if (! defined($usection)) {
12506: $section=&getsection($udom,$uname,$courseid);
12507: } else {
12508: $section = $usection;
12509: }
12510: @groups = &get_users_groups($udom,$uname,$courseid);
12511: }
12512:
12513: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12514: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
12515: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
12516: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12517:
12518: $courselevel=$courseid.'.'.$spacequalifierrest;
12519: my $courselevelr=$courseid.'.'.$symbparm;
12520: $courseleveli=$courseid.'.'.$recurseparm;
12521: $courselevelm=$courseid.'.'.$mapparm;
12522:
12523: # ----------------------------------------------------------- first, check user
12524:
12525: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12526: \@recurseup,$courseid,'.',$spacequalifierrest,
12527: ([$courselevelr,'resource'],
12528: [$courselevelm,'map' ],
12529: [$courseleveli,'map' ],
12530: [$courselevel, 'course' ]));
12531: if (defined($userreply)) { return &get_reply($userreply); }
12532:
12533: # ------------------------------------------------ second, check some of course
12534: my $coursereply;
12535: if (@groups > 0) {
12536: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
12537: $recurseparm,$mapparm,$spacequalifierrest,
12538: $mapp,\$recursed,\@recurseup);
12539: if (defined($coursereply)) { return &get_reply($coursereply); }
12540: }
12541:
12542: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12543: $env{'course.'.$courseid.'.domain'},
12544: 'course',$mapp,\$recursed,\@recurseup,
12545: $courseid,'.['.$section.'].',$spacequalifierrest,
12546: ([$seclevelr, 'resource'],
12547: [$seclevelm, 'map' ],
12548: [$secleveli, 'map' ],
12549: [$seclevel, 'course' ],
12550: [$courselevelr,'resource']));
12551: if (defined($coursereply)) { return &get_reply($coursereply); }
12552:
12553: # ------------------------------------------------------ third, check map parms
12554: my %parmhash=();
12555: my $thisparm='';
12556: if (tie(%parmhash,'GDBM_File',
12557: $env{'request.course.fn'}.'_parms.db',
12558: &GDBM_READER(),0640)) {
12559: $thisparm=$parmhash{$symbparm};
12560: untie(%parmhash);
12561: }
12562: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
12563: }
12564: # ------------------------------------------ fourth, look in resource metadata
12565:
12566: my $what = $spacequalifierrest;
12567: $what=~s/\./\_/;
12568: my $filename;
12569: if (!$symbparm) { $symbparm=&symbread(); }
12570: if ($symbparm) {
12571: $filename=(&decode_symb($symbparm))[2];
12572: } else {
12573: $filename=$env{'request.filename'};
12574: }
12575: my $toolsymb;
12576: if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12577: $toolsymb = $symbparm;
12578: }
12579: my $metadata=&metadata($filename,$what,$toolsymb);
12580: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12581: $metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
12582: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12583:
12584: # ----------------------------------------------- fifth, look in rest of course
12585: if ($symbparm && defined($courseid) &&
12586: $courseid eq $env{'request.course.id'}) {
12587: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12588: $env{'course.'.$courseid.'.domain'},
12589: 'course',$mapp,\$recursed,\@recurseup,
12590: $courseid,'.',$spacequalifierrest,
12591: ([$courselevelm,'map' ],
12592: [$courseleveli,'map' ],
12593: [$courselevel, 'course']));
12594: if (defined($coursereply)) { return &get_reply($coursereply); }
12595: }
12596: # ------------------------------------------------------------------ Cascade up
12597: unless ($space eq '0') {
12598: my @parts=split(/_/,$space);
12599: my $id=pop(@parts);
12600: my $part=join('_',@parts);
12601: if ($part eq '') { $part='0'; }
12602: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
12603: $symbparm,$udom,$uname,$section,1);
12604: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
12605: }
12606: if ($recurse) { return undef; }
12607: my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
12608: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
12609: # ---------------------------------------------------- Any other user namespace
12610: } elsif ($realm eq 'environment') {
12611: # ----------------------------------------------------------------- environment
12612: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12613: return $env{'environment.'.$spacequalifierrest};
12614: } else {
12615: if ($uname eq 'anonymous' && $udom eq '') {
12616: return '';
12617: }
12618: my %returnhash=&userenvironment($udom,$uname,
12619: $spacequalifierrest);
12620: return $returnhash{$spacequalifierrest};
12621: }
12622: } elsif ($realm eq 'system') {
12623: # ----------------------------------------------------------------- system.time
12624: if ($space eq 'time') {
12625: return time;
12626: }
12627: } elsif ($realm eq 'server') {
12628: # ----------------------------------------------------------------- system.time
12629: if ($space eq 'name') {
12630: return $ENV{'SERVER_NAME'};
12631: }
12632: } elsif ($realm eq 'client') {
12633: if ($space eq 'remote_addr') {
12634: return &get_requestor_ip();
12635: }
12636: }
12637: return '';
12638: }
12639:
12640: sub get_reply {
12641: my ($reply_value) = @_;
12642: if (ref($reply_value) eq 'ARRAY') {
12643: if (wantarray) {
12644: return @$reply_value;
12645: }
12646: return $reply_value->[0];
12647: } else {
12648: return $reply_value;
12649: }
12650: }
12651:
12652: sub check_group_parms {
12653: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12654: $recursed,$recurseupref) = @_;
12655: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12656: [$what,'course']);
12657: my $coursereply;
12658: foreach my $group (@{$groups}) {
12659: my @groupitems = ();
12660: foreach my $level (@levels) {
12661: my $item = $courseid.'.['.$group.'].'.$level->[0];
12662: push(@groupitems,[$item,$level->[1]]);
12663: }
12664: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12665: $env{'course.'.$courseid.'.domain'},
12666: 'course',$mapp,$recursed,$recurseupref,
12667: $courseid,'.['.$group.'].',$what,
12668: @groupitems);
12669: last if (defined($coursereply));
12670: }
12671: return $coursereply;
12672: }
12673:
12674: sub get_map_hierarchy {
12675: my ($mapname,$courseid) = @_;
12676: my @recurseup = ();
12677: if ($mapname) {
12678: if (($cachedmapkey eq $courseid) &&
12679: (abs($cachedmaptime-time)<5)) {
12680: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12681: return @{$cachedmaps{$mapname}};
12682: }
12683: }
12684: my $navmap = Apache::lonnavmaps::navmap->new();
12685: if (ref($navmap)) {
12686: @recurseup = $navmap->recurseup_maps($mapname);
12687: undef($navmap);
12688: $cachedmaps{$mapname} = \@recurseup;
12689: $cachedmaptime=time;
12690: $cachedmapkey=$courseid;
12691: }
12692: }
12693: return @recurseup;
12694: }
12695:
12696: }
12697:
12698: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
12699: my ($courseid,@groups) = @_;
12700: @groups = sort(@groups);
12701: return @groups;
12702: }
12703:
12704: sub packages_tab_default {
12705: my ($uri,$varname,$toolsymb)=@_;
12706: my (undef,$part,$name)=split(/\./,$varname);
12707:
12708: my (@extension,@specifics,$do_default);
12709: foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
12710: my ($pack_type,$pack_part)=split(/_/,$package,2);
12711: if ($pack_type eq 'default') {
12712: $do_default=1;
12713: } elsif ($pack_type eq 'extension') {
12714: push(@extension,[$package,$pack_type,$pack_part]);
12715: } elsif ($pack_part eq $part || $pack_type eq 'part') {
12716: # only look at packages defaults for packages that this id is
12717: push(@specifics,[$package,$pack_type,$pack_part]);
12718: }
12719: }
12720: # first look for a package that matches the requested part id
12721: foreach my $package (@specifics) {
12722: my (undef,$pack_type,$pack_part)=@{$package};
12723: next if ($pack_part ne $part);
12724: if (defined($packagetab{"$pack_type&$name&default"})) {
12725: return $packagetab{"$pack_type&$name&default"};
12726: }
12727: }
12728: # look for any possible matching non extension_ package
12729: foreach my $package (@specifics) {
12730: my (undef,$pack_type,$pack_part)=@{$package};
12731: if (defined($packagetab{"$pack_type&$name&default"})) {
12732: return $packagetab{"$pack_type&$name&default"};
12733: }
12734: if ($pack_type eq 'part') { $pack_part='0'; }
12735: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12736: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
12737: }
12738: }
12739: # look for any posible extension_ match
12740: foreach my $package (@extension) {
12741: my ($package,$pack_type)=@{$package};
12742: if (defined($packagetab{"$pack_type&$name&default"})) {
12743: return $packagetab{"$pack_type&$name&default"};
12744: }
12745: if (defined($packagetab{$package."&$name&default"})) {
12746: return $packagetab{$package."&$name&default"};
12747: }
12748: }
12749: # look for a global default setting
12750: if ($do_default && defined($packagetab{"default&$name&default"})) {
12751: return $packagetab{"default&$name&default"};
12752: }
12753: return undef;
12754: }
12755:
12756: sub add_prefix_and_part {
12757: my ($prefix,$part)=@_;
12758: my $keyroot;
12759: if (defined($prefix) && $prefix !~ /^__/) {
12760: # prefix that has a part already
12761: $keyroot=$prefix;
12762: } elsif (defined($prefix)) {
12763: # prefix that is missing a part
12764: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12765: } else {
12766: # no prefix at all
12767: if (defined($part)) { $keyroot='_'.$part; }
12768: }
12769: return $keyroot;
12770: }
12771:
12772: # ---------------------------------------------------------------- Get metadata
12773:
12774: my %metaentry;
12775: my %importedpartids;
12776: my %importedrespids;
12777: sub metadata {
12778: my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
12779: $uri=&declutter($uri);
12780: # if it is a non metadata possible uri return quickly
12781: if (($uri eq '') ||
12782: (($uri =~ m|^/*adm/|) &&
12783: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
12784: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
12785: return undef;
12786: }
12787: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
12788: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
12789: return undef;
12790: }
12791: my $filename=$uri;
12792: $uri=~s/\.meta$//;
12793: #
12794: # Is the metadata already cached?
12795: # Look at timestamp of caching
12796: # Everything is cached by the main uri, libraries are never directly cached
12797: #
12798: if (!defined($liburi)) {
12799: my ($result,$cached)=&is_cached_new('meta',$uri);
12800: if (defined($cached)) { return $result->{':'.$what}; }
12801: }
12802:
12803: #
12804: # If the uri is for an external tool the file from
12805: # which metadata should be retrieved depends on whether
12806: # the tool had been configured to be gradable (set in the Course
12807: # Editor or Resource Editor).
12808: #
12809: # If a valid symb has been included as the third arg in the call
12810: # to &metadata() that can be used to retrieve the value of
12811: # parameter_0_gradable set for the resource, and included in the
12812: # uploaded map containing the tool. The value is retrieved via
12813: # &EXT(), if a valid symb is available. Otherwise the value of
12814: # gradable in the exttool_$marker.db file for the tool instance
12815: # is retrieved via &get().
12816: #
12817: # When lonuserstate::traceroute() calls lonnet::EXT() for
12818: # hiddenresource and encrypturl (during course initialization)
12819: # the map-level parameter for resource.0.gradable included in the
12820: # uploaded map containing the tool will not yet have been stored
12821: # in the user_course_parms.db file for the user's session, so in
12822: # this case fall back to retrieving gradable status from the
12823: # exttool_$marker.db file.
12824: #
12825: # In order to avoid an infinite loop, &metadata() will return
12826: # before a call to &EXT(), if the uri is for an external tool
12827: # and the $what for which metadata is being requested is
12828: # parameter_0_gradable or 0_gradable.
12829: #
12830:
12831: if ($uri =~ /ext\.tool$/) {
12832: if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12833: return;
12834: } else {
12835: my ($checked,$use_passback);
12836: if ($toolsymb ne '') {
12837: (undef,undef,my $tooluri) = &decode_symb($toolsymb);
12838: if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
12839: $checked = 1;
12840: if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12841: $use_passback = 1;
12842: }
12843: }
12844: }
12845: unless ($checked) {
12846: my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12847: $marker=~s/\D//g;
12848: if ($marker) {
12849: my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12850: $use_passback = $toolsettings{'gradable'};
12851: }
12852: }
12853: if ($use_passback) {
12854: $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12855: } else {
12856: $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12857: }
12858: }
12859: }
12860:
12861: {
12862: # Imported parts would go here
12863: my @origfiletagids=();
12864: my $importedparts=0;
12865:
12866: # Imported responseids would go here
12867: my $importedresponses=0;
12868: #
12869: # Is this a recursive call for a library?
12870: #
12871: # if (! exists($metacache{$uri})) {
12872: # $metacache{$uri}={};
12873: # }
12874: my $cachetime = 60*60;
12875: if ($liburi) {
12876: $liburi=&declutter($liburi);
12877: $filename=$liburi;
12878: } else {
12879: &devalidate_cache_new('meta',$uri);
12880: undef(%metaentry);
12881: }
12882: my %metathesekeys=();
12883: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
12884: my $metastring;
12885: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
12886: my $which = &hreflocation('','/'.($liburi || $uri));
12887: $metastring =
12888: &Apache::lonnet::ssi_body($which,
12889: ('grade_target' => 'meta'));
12890: $cachetime = 1; # only want this cached in the child not long term
12891: } elsif (($uri !~ m -^(editupload)/-) &&
12892: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
12893: my $file=&filelocation('',&clutter($filename));
12894: #push(@{$metaentry{$uri.'.file'}},$file);
12895: $metastring=&getfile($file);
12896: }
12897: my $parser=HTML::LCParser->new(\$metastring);
12898: my $token;
12899: undef %metathesekeys;
12900: while ($token=$parser->get_token) {
12901: if ($token->[0] eq 'S') {
12902: if (defined($token->[2]->{'package'})) {
12903: #
12904: # This is a package - get package info
12905: #
12906: my $package=$token->[2]->{'package'};
12907: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12908: if (defined($token->[2]->{'id'})) {
12909: $keyroot.='_'.$token->[2]->{'id'};
12910: }
12911: if ($metaentry{':packages'}) {
12912: $metaentry{':packages'}.=','.$package.$keyroot;
12913: } else {
12914: $metaentry{':packages'}=$package.$keyroot;
12915: }
12916: foreach my $pack_entry (keys(%packagetab)) {
12917: my $part=$keyroot;
12918: $part=~s/^\_//;
12919: if ($pack_entry=~/^\Q$package\E\&/ ||
12920: $pack_entry=~/^\Q$package\E_0\&/) {
12921: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
12922: # ignore package.tab specified default values
12923: # here &package_tab_default() will fetch those
12924: if ($subp eq 'default') { next; }
12925: my $value=$packagetab{$pack_entry};
12926: my $unikey;
12927: if ($pack =~ /_0$/) {
12928: $unikey='parameter_0_'.$name;
12929: $part=0;
12930: } else {
12931: $unikey='parameter'.$keyroot.'_'.$name;
12932: }
12933: if ($subp eq 'display') {
12934: $value.=' [Part: '.$part.']';
12935: }
12936: $metaentry{':'.$unikey.'.part'}=$part;
12937: $metathesekeys{$unikey}=1;
12938: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12939: $metaentry{':'.$unikey.'.'.$subp}=$value;
12940: }
12941: if (defined($metaentry{':'.$unikey.'.default'})) {
12942: $metaentry{':'.$unikey}=
12943: $metaentry{':'.$unikey.'.default'};
12944: }
12945: }
12946: }
12947: } else {
12948: #
12949: # This is not a package - some other kind of start tag
12950: #
12951: my $entry=$token->[1];
12952: my $unikey='';
12953:
12954: if ($entry eq 'import') {
12955: #
12956: # Importing a library here
12957: #
12958: my $location=$parser->get_text('/import');
12959: my $dir=$filename;
12960: $dir=~s|[^/]*$||;
12961: $location=&filelocation($dir,$location);
12962:
12963: my $importid=$token->[2]->{'id'};
12964: my $importmode=$token->[2]->{'importmode'};
12965: #
12966: # Check metadata for imported file to
12967: # see if it contained response items
12968: #
12969: my ($origfile,@libfilekeys);
12970: my %currmetaentry = %metaentry;
12971: @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12972: $depthcount+1));
12973: if (grep(/^responseorder$/,@libfilekeys)) {
12974: my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12975: undef,$depthcount+1);
12976: if ($libresponseorder ne '') {
12977: if ($#origfiletagids<0) {
12978: undef(%importedrespids);
12979: undef(%importedpartids);
12980: }
12981: my @respids = split(/\s*,\s*/,$libresponseorder);
12982: if (@respids) {
12983: $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12984: }
12985: if ($importedrespids{$importid} ne '') {
12986: $importedresponses = 1;
12987: # We need to get the original file and the imported file to get the response order correct
12988: # Load and inspect original file
12989: if ($#origfiletagids<0) {
12990: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12991: $origfile=&getfile($origfilelocation);
12992: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12993: }
12994: }
12995: }
12996: }
12997: # Do not overwrite contents of %metaentry hash for resource itself with
12998: # hash populated for imported library file
12999: %metaentry = %currmetaentry;
13000: undef(%currmetaentry);
13001: if ($importmode eq 'part') {
13002: # Import as part(s)
13003: $importedparts=1;
13004: # We need to get the original file and the imported file to get the part order correct
13005: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
13006: # Load and inspect original file if we didn't do that already
13007: if ($#origfiletagids<0) {
13008: undef(%importedrespids);
13009: undef(%importedpartids);
13010: if ($origfile eq '') {
13011: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13012: $origfile=&getfile($origfilelocation);
13013: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13014: }
13015: }
13016: my @impfilepartids;
13017: # If <partorder> tag is included in metadata for the imported file
13018: # get the parts in the imported file from that.
13019: if (grep(/^partorder$/,@libfilekeys)) {
13020: %currmetaentry = %metaentry;
13021: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13022: $depthcount+1);
13023: %metaentry = %currmetaentry;
13024: undef(%currmetaentry);
13025: if ($libpartorder ne '') {
13026: @impfilepartids=split(/\s*,\s*/,$libpartorder);
13027: }
13028: } else {
13029: # If no <partorder> tag available, load and inspect imported file
13030: my $impfile=&getfile($location);
13031: @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13032: }
13033: if ($#impfilepartids>=0) {
13034: # This problem had parts
13035: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
13036: } else {
13037: # Importing by turning a single problem into a problem part
13038: # It gets the import-tags ID as part-ID
13039: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
13040: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
13041: }
13042: } else {
13043: # Import as problem or as normal import
13044: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13045: unless ($importmode eq 'problem') {
13046: # Normal import
13047: if (defined($token->[2]->{'id'})) {
13048: $unikey.='_'.$token->[2]->{'id'};
13049: }
13050: }
13051: # Check metadata for imported file to
13052: # see if it contained parts
13053: if (grep(/^partorder$/,@libfilekeys)) {
13054: %currmetaentry = %metaentry;
13055: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13056: $depthcount+1);
13057: %metaentry = %currmetaentry;
13058: undef(%currmetaentry);
13059: if ($libpartorder ne '') {
13060: $importedparts = 1;
13061: $importedpartids{$token->[2]->{'id'}}=$libpartorder;
13062: }
13063: }
13064: }
13065: if ($depthcount<20) {
13066: my $metadata =
13067: &metadata($uri,'keys',$toolsymb,$location,$unikey,
13068: $depthcount+1);
13069: foreach my $meta (split(',',$metadata)) {
13070: $metaentry{':'.$meta}=$metaentry{':'.$meta};
13071: $metathesekeys{$meta}=1;
13072: }
13073: }
13074: } else {
13075: #
13076: # Not importing, some other kind of non-package, non-library start tag
13077: #
13078: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
13079: if (defined($token->[2]->{'id'})) {
13080: $unikey.='_'.$token->[2]->{'id'};
13081: }
13082: if (defined($token->[2]->{'name'})) {
13083: $unikey.='_'.$token->[2]->{'name'};
13084: }
13085: $metathesekeys{$unikey}=1;
13086: foreach my $param (@{$token->[3]}) {
13087: $metaentry{':'.$unikey.'.'.$param} =
13088: $token->[2]->{$param};
13089: }
13090: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
13091: my $default=$metaentry{':'.$unikey.'.default'};
13092: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
13093: # only ws inside the tag, and not in default, so use default
13094: # as value
13095: $metaentry{':'.$unikey}=$default;
13096: } elsif ( $internaltext =~ /\S/ ) {
13097: # something interesting inside the tag
13098: $metaentry{':'.$unikey}=$internaltext;
13099: } else {
13100: # no interesting values, don't set a default
13101: }
13102: # end of not-a-package not-a-library import
13103: }
13104: # end of not-a-package start tag
13105: }
13106: # the next is the end of "start tag"
13107: }
13108: }
13109: my ($extension) = ($uri =~ /\.(\w+)$/);
13110: $extension = lc($extension);
13111: if ($extension eq 'htm') { $extension='html'; }
13112:
13113: foreach my $key (keys(%packagetab)) {
13114: #no specific packages #how's our extension
13115: if ($key!~/^extension_\Q$extension\E&/) { next; }
13116: &metadata_create_package_def($uri,$key,'extension_'.$extension,
13117: \%metathesekeys);
13118: }
13119:
13120: if (!exists($metaentry{':packages'})
13121: || $packagetab{"import_defaults&extension_$extension"}) {
13122: foreach my $key (keys(%packagetab)) {
13123: #no specific packages well let's get default then
13124: if ($key!~/^default&/) { next; }
13125: &metadata_create_package_def($uri,$key,'default',
13126: \%metathesekeys);
13127: }
13128: }
13129: # are there custom rights to evaluate
13130: if ($metaentry{':copyright'} eq 'custom') {
13131:
13132: #
13133: # Importing a rights file here
13134: #
13135: unless ($depthcount) {
13136: my $location=$metaentry{':customdistributionfile'};
13137: my $dir=$filename;
13138: $dir=~s|[^/]*$||;
13139: $location=&filelocation($dir,$location);
13140: my $rights_metadata =
13141: &metadata($uri,'keys',$toolsymb,$location,'_rights',
13142: $depthcount+1);
13143: foreach my $rights (split(',',$rights_metadata)) {
13144: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
13145: $metathesekeys{$rights}=1;
13146: }
13147: }
13148: }
13149: # uniqifiy package listing
13150: my %seen;
13151: my @uniq_packages =
13152: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
13153: $metaentry{':packages'} = join(',',@uniq_packages);
13154:
13155: if (($importedresponses) || ($importedparts)) {
13156: if ($importedparts) {
13157: # We had imported parts and need to rebuild partorder
13158: $metaentry{':partorder'}='';
13159: $metathesekeys{'partorder'}=1;
13160: }
13161: if ($importedresponses) {
13162: # We had imported responses and need to rebuil responseorder
13163: $metaentry{':responseorder'}='';
13164: $metathesekeys{'responseorder'}=1;
13165: }
13166: for (my $index=0;$index<$#origfiletagids;$index+=2) {
13167: my $origid = $origfiletagids[$index+1];
13168: if ($origfiletagids[$index] eq 'part') {
13169: # Original part, part of the problem
13170: if ($importedparts) {
13171: $metaentry{':partorder'}.=','.$origid;
13172: }
13173: } elsif ($origfiletagids[$index] eq 'import') {
13174: if ($importedparts) {
13175: # We have imported parts at this position
13176: if ($importedpartids{$origid} ne '') {
13177: $metaentry{':partorder'}.=','.$importedpartids{$origid};
13178: }
13179: }
13180: if ($importedresponses) {
13181: # We have imported responses at this position
13182: if ($importedrespids{$origid} ne '') {
13183: $metaentry{':responseorder'}.=','.$importedrespids{$origid};
13184: }
13185: }
13186: } else {
13187: # Original response item, part of the problem
13188: if ($importedresponses) {
13189: $metaentry{':responseorder'}.=','.$origid;
13190: }
13191: }
13192: }
13193: if ($importedparts) {
13194: $metaentry{':partorder'}=~s/^\,//;
13195: }
13196: if ($importedresponses) {
13197: $metaentry{':responseorder'}=~s/^\,//;
13198: }
13199: }
13200: $metaentry{':keys'} = join(',',keys(%metathesekeys));
13201: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
13202: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
13203: unless ($liburi) {
13204: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
13205: }
13206: # this is the end of "was not already recently cached
13207: }
13208: return $metaentry{':'.$what};
13209: }
13210:
13211: sub metadata_create_package_def {
13212: my ($uri,$key,$package,$metathesekeys)=@_;
13213: my ($pack,$name,$subp)=split(/\&/,$key);
13214: if ($subp eq 'default') { next; }
13215:
13216: if (defined($metaentry{':packages'})) {
13217: $metaentry{':packages'}.=','.$package;
13218: } else {
13219: $metaentry{':packages'}=$package;
13220: }
13221: my $value=$packagetab{$key};
13222: my $unikey;
13223: $unikey='parameter_0_'.$name;
13224: $metaentry{':'.$unikey.'.part'}=0;
13225: $$metathesekeys{$unikey}=1;
13226: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13227: $metaentry{':'.$unikey.'.'.$subp}=$value;
13228: }
13229: if (defined($metaentry{':'.$unikey.'.default'})) {
13230: $metaentry{':'.$unikey}=
13231: $metaentry{':'.$unikey.'.default'};
13232: }
13233: }
13234:
13235: sub metadata_generate_part0 {
13236: my ($metadata,$metacache,$uri) = @_;
13237: my %allnames;
13238: foreach my $metakey (keys(%$metadata)) {
13239: if ($metakey=~/^parameter\_(.*)/) {
13240: my $part=$$metacache{':'.$metakey.'.part'};
13241: my $name=$$metacache{':'.$metakey.'.name'};
13242: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
13243: $allnames{$name}=$part;
13244: }
13245: }
13246: }
13247: foreach my $name (keys(%allnames)) {
13248: $$metadata{"parameter_0_$name"}=1;
13249: my $key=":parameter_0_$name";
13250: $$metacache{"$key.part"}='0';
13251: $$metacache{"$key.name"}=$name;
13252: $$metacache{"$key.type"}=$$metacache{':parameter_'.
13253: $allnames{$name}.'_'.$name.
13254: '.type'};
13255: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
13256: '.display'};
13257: my $expr='[Part: '.$allnames{$name}.']';
13258: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
13259: $$metacache{"$key.display"}=$olddis;
13260: }
13261: }
13262:
13263: # ------------------------------------------------------ Devalidate title cache
13264:
13265: sub devalidate_title_cache {
13266: my ($url)=@_;
13267: if (!$env{'request.course.id'}) { return; }
13268: my $symb=&symbread($url);
13269: if (!$symb) { return; }
13270: my $key=$env{'request.course.id'}."\0".$symb;
13271: &devalidate_cache_new('title',$key);
13272: }
13273:
13274: # ------------------------------------------------- Get the title of a course
13275:
13276: sub current_course_title {
13277: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
13278: }
13279: # ------------------------------------------------- Get the title of a resource
13280:
13281: sub gettitle {
13282: my $urlsymb=shift;
13283: my $symb=&symbread($urlsymb);
13284: if ($symb) {
13285: my $key=$env{'request.course.id'}."\0".$symb;
13286: my ($result,$cached)=&is_cached_new('title',$key);
13287: if (defined($cached)) {
13288: return $result;
13289: }
13290: my ($map,$resid,$url)=&decode_symb($symb);
13291: my $title='';
13292: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13293: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13294: } else {
13295: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13296: &GDBM_READER(),0640)) {
13297: my $mapid=$bighash{'map_pc_'.&clutter($map)};
13298: $title=$bighash{'title_'.$mapid.'.'.$resid};
13299: untie(%bighash);
13300: }
13301: }
13302: $title=~s/\&colon\;/\:/gs;
13303: if ($title) {
13304: # Remember both $symb and $title for dynamic metadata
13305: $accesshash{$symb.'___crstitle'}=$title;
13306: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
13307: # Cache this title and then return it
13308: return &do_cache_new('title',$key,$title,600);
13309: }
13310: $urlsymb=$url;
13311: }
13312: my $title=&metadata($urlsymb,'title');
13313: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
13314: return $title;
13315: }
13316:
13317: sub get_slot {
13318: my ($which,$cnum,$cdom)=@_;
13319: if (!$cnum || !$cdom) {
13320: (undef,my $courseid)=&whichuser();
13321: $cdom=$env{'course.'.$courseid.'.domain'};
13322: $cnum=$env{'course.'.$courseid.'.num'};
13323: }
13324: my $key=join("\0",'slots',$cdom,$cnum,$which);
13325: my %slotinfo;
13326: if (exists($remembered{$key})) {
13327: $slotinfo{$which} = $remembered{$key};
13328: } else {
13329: %slotinfo=&get('slots',[$which],$cdom,$cnum);
13330: &Apache::lonhomework::showhash(%slotinfo);
13331: my ($tmp)=keys(%slotinfo);
13332: if ($tmp=~/^error:/) { return (); }
13333: $remembered{$key} = $slotinfo{$which};
13334: }
13335: if (ref($slotinfo{$which}) eq 'HASH') {
13336: return %{$slotinfo{$which}};
13337: }
13338: return $slotinfo{$which};
13339: }
13340:
13341: sub get_reservable_slots {
13342: my ($cnum,$cdom,$uname,$udom) = @_;
13343: my $now = time;
13344: my $reservable_info;
13345: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13346: if (exists($remembered{$key})) {
13347: $reservable_info = $remembered{$key};
13348: } else {
13349: my %resv;
13350: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13351: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13352: $reservable_info = \%resv;
13353: $remembered{$key} = $reservable_info;
13354: }
13355: return $reservable_info;
13356: }
13357:
13358: sub get_course_slots {
13359: my ($cnum,$cdom) = @_;
13360: my $hashid=$cnum.':'.$cdom;
13361: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
13362: if (defined($cached)) {
13363: if (ref($result) eq 'HASH') {
13364: return %{$result};
13365: }
13366: } else {
13367: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
13368: my ($tmp) = keys(%slots);
13369: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
13370: &do_cache_new('allslots',$hashid,\%slots,600);
13371: return %slots;
13372: }
13373: }
13374: return;
13375: }
13376:
13377: sub devalidate_slots_cache {
13378: my ($cnum,$cdom)=@_;
13379: my $hashid=$cnum.':'.$cdom;
13380: &devalidate_cache_new('allslots',$hashid);
13381: }
13382:
13383: sub get_coursechange {
13384: my ($cdom,$cnum) = @_;
13385: if ($cdom eq '' || $cnum eq '') {
13386: return unless ($env{'request.course.id'});
13387: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13388: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13389: }
13390: my $hashid=$cdom.'_'.$cnum;
13391: my ($change,$cached)=&is_cached_new('crschange',$hashid);
13392: if ((defined($cached)) && ($change ne '')) {
13393: return $change;
13394: } else {
13395: my %crshash;
13396: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13397: if ($crshash{'internal.contentchange'} eq '') {
13398: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13399: if ($change eq '') {
13400: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13401: $change = $crshash{'internal.created'};
13402: }
13403: } else {
13404: $change = $crshash{'internal.contentchange'};
13405: }
13406: my $cachetime = 600;
13407: &do_cache_new('crschange',$hashid,$change,$cachetime);
13408: }
13409: return $change;
13410: }
13411:
13412: sub devalidate_coursechange_cache {
13413: my ($cnum,$cdom)=@_;
13414: my $hashid=$cnum.':'.$cdom;
13415: &devalidate_cache_new('crschange',$hashid);
13416: }
13417:
13418: # ------------------------------------------------- Update symbolic store links
13419:
13420: sub symblist {
13421: my ($mapname,%newhash)=@_;
13422: $mapname=&deversion(&declutter($mapname));
13423: my %hash;
13424: if (($env{'request.course.fn'}) && (%newhash)) {
13425: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13426: &GDBM_WRCREAT(),0640)) {
13427: foreach my $url (keys(%newhash)) {
13428: next if ($url eq 'last_known'
13429: && $env{'form.no_update_last_known'});
13430: $hash{declutter($url)}=&encode_symb($mapname,
13431: $newhash{$url}->[1],
13432: $newhash{$url}->[0]);
13433: }
13434: if (untie(%hash)) {
13435: return 'ok';
13436: }
13437: }
13438: }
13439: return 'error';
13440: }
13441:
13442: # --------------------------------------------------------------- Verify a symb
13443:
13444: sub symbverify {
13445: my ($symb,$thisurl,$encstate)=@_;
13446: my $thisfn=$thisurl;
13447: $thisfn=&declutter($thisfn);
13448: # direct jump to resource in page or to a sequence - will construct own symbs
13449: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13450: # check URL part
13451: my ($map,$resid,$url)=&decode_symb($symb);
13452:
13453: unless ($url eq $thisfn) { return 0; }
13454:
13455: $symb=&symbclean($symb);
13456: $thisurl=&deversion($thisurl);
13457: $thisfn=&deversion($thisfn);
13458:
13459: my %bighash;
13460: my $okay=0;
13461:
13462: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13463: &GDBM_READER(),0640)) {
13464: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13465: $thisurl =~ s/\?.+$//;
13466: if ($map =~ m{^uploaded/.+\.page$}) {
13467: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13468: $thisurl =~ s{^\Qhttp://https://\E}{https://};
13469: }
13470: }
13471: my $ids;
13472: if ($map =~ m{^uploaded/.+\.page$}) {
13473: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
13474: } else {
13475: $ids=$bighash{'ids_'.&clutter($thisurl)};
13476: }
13477: unless ($ids) {
13478: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
13479: $ids=$bighash{$idkey};
13480: }
13481: if ($ids) {
13482: # ------------------------------------------------------------------- Has ID(s)
13483: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
13484: $symb =~ s/\?.+$//;
13485: }
13486: foreach my $id (split(/\,/,$ids)) {
13487: my ($mapid,$resid)=split(/\./,$id);
13488: if (
13489: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
13490: eq $symb) {
13491: if (ref($encstate)) {
13492: $$encstate = $bighash{'encrypted_'.$id};
13493: }
13494: if (($env{'request.role.adv'}) ||
13495: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13496: ($thisurl eq '/adm/navmaps')) {
13497: $okay=1;
13498: last;
13499: }
13500: }
13501: }
13502: }
13503: untie(%bighash);
13504: }
13505: return $okay;
13506: }
13507:
13508: # --------------------------------------------------------------- Clean-up symb
13509:
13510: sub symbclean {
13511: my $symb=shift;
13512: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13513: # remove version from map
13514: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
13515:
13516: # remove version from URL
13517: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
13518:
13519: # remove wrapper
13520:
13521: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
13522: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
13523: return $symb;
13524: }
13525:
13526: # ---------------------------------------------- Split symb to find map and url
13527:
13528: sub encode_symb {
13529: my ($map,$resid,$url)=@_;
13530: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13531: }
13532:
13533: sub decode_symb {
13534: my $symb=shift;
13535: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13536: my ($map,$resid,$url)=split(/___/,$symb);
13537: return (&fixversion($map),$resid,&fixversion($url));
13538: }
13539:
13540: sub fixversion {
13541: my $fn=shift;
13542: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
13543: my %bighash;
13544: my $uri=&clutter($fn);
13545: my $key=$env{'request.course.id'}.'_'.$uri;
13546: # is this cached?
13547: my ($result,$cached)=&is_cached_new('courseresversion',$key);
13548: if (defined($cached)) { return $result; }
13549: # unfortunately not cached, or expired
13550: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13551: &GDBM_READER(),0640)) {
13552: if ($bighash{'version_'.$uri}) {
13553: my $version=$bighash{'version_'.$uri};
13554: unless (($version eq 'mostrecent') ||
13555: ($version==&getversion($uri))) {
13556: $uri=~s/\.(\w+)$/\.$version\.$1/;
13557: }
13558: }
13559: untie %bighash;
13560: }
13561: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
13562: }
13563:
13564: sub deversion {
13565: my $url=shift;
13566: $url=~s/\.\d+\.(\w+)$/\.$1/;
13567: return $url;
13568: }
13569:
13570: # ------------------------------------------------------ Return symb list entry
13571:
13572: sub symbread {
13573: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
13574: $ignoresymbdb,$noenccheck)=@_;
13575: my $cache_str='request.symbread.cached.'.$thisfn;
13576: if (defined($env{$cache_str})) {
13577: unless (ref($possibles) eq 'HASH') {
13578: if ($ignorecachednull) {
13579: return $env{$cache_str} unless ($env{$cache_str} eq '');
13580: } else {
13581: return $env{$cache_str};
13582: }
13583: }
13584: }
13585: # no filename provided? try from environment
13586: unless ($thisfn) {
13587: if ($env{'request.symb'}) {
13588: return $env{$cache_str}=&symbclean($env{'request.symb'});
13589: }
13590: $thisfn=$env{'request.filename'};
13591: }
13592: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13593: # is that filename actually a symb? Verify, clean, and return
13594: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
13595: if (&symbverify($thisfn,$1)) {
13596: return $env{$cache_str}=&symbclean($thisfn);
13597: }
13598: }
13599: $thisfn=declutter($thisfn);
13600: my %hash;
13601: my %bighash;
13602: my $syval='';
13603: if (($env{'request.course.fn'}) && ($thisfn)) {
13604: my $targetfn = $thisfn;
13605: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
13606: $targetfn = 'adm/wrapper/'.$thisfn;
13607: }
13608: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
13609: $targetfn=$1;
13610: }
13611: unless ($ignoresymbdb) {
13612: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13613: &GDBM_READER(),0640)) {
13614: $syval=$hash{$targetfn};
13615: untie(%hash);
13616: }
13617: if ($syval && $checkforblock) {
13618: my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
13619: if (@blockers) {
13620: $syval='';
13621: }
13622: }
13623: }
13624: # ---------------------------------------------------------- There was an entry
13625: if ($syval) {
13626: #unless ($syval=~/\_\d+$/) {
13627: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
13628: #&appenv({'request.ambiguous' => $thisfn});
13629: #return $env{$cache_str}='';
13630: #}
13631: #$syval.=$1;
13632: #}
13633: } else {
13634: # ------------------------------------------------------- Was not in symb table
13635: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13636: &GDBM_READER(),0640)) {
13637: # ---------------------------------------------- Get ID(s) for current resource
13638: my $ids=$bighash{'ids_'.&clutter($thisfn)};
13639: unless ($ids) {
13640: $ids=$bighash{'ids_/'.$thisfn};
13641: }
13642: unless ($ids) {
13643: # alias?
13644: $ids=$bighash{'mapalias_'.$thisfn};
13645: }
13646: if ($ids) {
13647: # ------------------------------------------------------------------- Has ID(s)
13648: my @possibilities=split(/\,/,$ids);
13649: if ($#possibilities==0) {
13650: # ----------------------------------------------- There is only one possibility
13651: my ($mapid,$resid)=split(/\./,$ids);
13652: $syval=&encode_symb($bighash{'map_id_'.$mapid},
13653: $resid,$thisfn);
13654: if (ref($possibles) eq 'HASH') {
13655: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13656: $possibles->{$syval} = 1;
13657: }
13658: }
13659: if ($checkforblock) {
13660: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13661: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
13662: if (@blockers) {
13663: $syval = '';
13664: untie(%bighash);
13665: return $env{$cache_str}='';
13666: }
13667: }
13668: }
13669: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13670: # ------------------------------------------ There is more than one possibility
13671: my $realpossible=0;
13672: foreach my $id (@possibilities) {
13673: my $file=$bighash{'src_'.$id};
13674: my $canaccess;
13675: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13676: $canaccess = 1;
13677: } else {
13678: $canaccess = &allowed('bre',$file);
13679: }
13680: if ($canaccess) {
13681: my ($mapid,$resid)=split(/\./,$id);
13682: if ($bighash{'map_type_'.$mapid} ne 'page') {
13683: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13684: $resid,$thisfn);
13685: next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
13686: next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
13687: if ($checkforblock) {
13688: my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
13689: if (@blockers > 0) {
13690: $syval = '';
13691: } else {
13692: $syval = $poss_syval;
13693: $realpossible++;
13694: }
13695: } else {
13696: $syval = $poss_syval;
13697: $realpossible++;
13698: }
13699: if ($syval) {
13700: if (ref($possibles) eq 'HASH') {
13701: $possibles->{$syval} = 1;
13702: }
13703: }
13704: }
13705: }
13706: }
13707: if ($realpossible!=1) { $syval=''; }
13708: } else {
13709: $syval='';
13710: }
13711: }
13712: untie(%bighash);
13713: }
13714: }
13715: if ($syval) {
13716: return $env{$cache_str}=$syval;
13717: }
13718: }
13719: &appenv({'request.ambiguous' => $thisfn});
13720: return $env{$cache_str}='';
13721: }
13722:
13723: # ---------------------------------------------------------- Return random seed
13724:
13725: sub numval {
13726: my $txt=shift;
13727: $txt=~tr/A-J/0-9/;
13728: $txt=~tr/a-j/0-9/;
13729: $txt=~tr/K-T/0-9/;
13730: $txt=~tr/k-t/0-9/;
13731: $txt=~tr/U-Z/0-5/;
13732: $txt=~tr/u-z/0-5/;
13733: $txt=~s/\D//g;
13734: if ($_64bit) { if ($txt > 2**32) { return -1; } }
13735: return int($txt);
13736: }
13737:
13738: sub numval2 {
13739: my $txt=shift;
13740: $txt=~tr/A-J/0-9/;
13741: $txt=~tr/a-j/0-9/;
13742: $txt=~tr/K-T/0-9/;
13743: $txt=~tr/k-t/0-9/;
13744: $txt=~tr/U-Z/0-5/;
13745: $txt=~tr/u-z/0-5/;
13746: $txt=~s/\D//g;
13747: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13748: my $total;
13749: foreach my $val (@txts) { $total+=$val; }
13750: if ($_64bit) { if ($total > 2**32) { return -1; } }
13751: return int($total);
13752: }
13753:
13754: sub numval3 {
13755: use integer;
13756: my $txt=shift;
13757: $txt=~tr/A-J/0-9/;
13758: $txt=~tr/a-j/0-9/;
13759: $txt=~tr/K-T/0-9/;
13760: $txt=~tr/k-t/0-9/;
13761: $txt=~tr/U-Z/0-5/;
13762: $txt=~tr/u-z/0-5/;
13763: $txt=~s/\D//g;
13764: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13765: my $total;
13766: foreach my $val (@txts) { $total+=$val; }
13767: if ($_64bit) { $total=(($total<<32)>>32); }
13768: return $total;
13769: }
13770:
13771: sub digest {
13772: my ($data)=@_;
13773: my $digest=&Digest::MD5::md5($data);
13774: my ($a,$b,$c,$d)=unpack("iiii",$digest);
13775: my ($e,$f);
13776: {
13777: use integer;
13778: $e=($a+$b);
13779: $f=($c+$d);
13780: if ($_64bit) {
13781: $e=(($e<<32)>>32);
13782: $f=(($f<<32)>>32);
13783: }
13784: }
13785: if (wantarray) {
13786: return ($e,$f);
13787: } else {
13788: my $g;
13789: {
13790: use integer;
13791: $g=($e+$f);
13792: if ($_64bit) {
13793: $g=(($g<<32)>>32);
13794: }
13795: }
13796: return $g;
13797: }
13798: }
13799:
13800: sub latest_rnd_algorithm_id {
13801: return '64bit5';
13802: }
13803:
13804: sub get_rand_alg {
13805: my ($courseid)=@_;
13806: if (!$courseid) { $courseid=(&whichuser())[1]; }
13807: if ($courseid) {
13808: return $env{"course.$courseid.rndseed"};
13809: }
13810: return &latest_rnd_algorithm_id();
13811: }
13812:
13813: sub validCODE {
13814: my ($CODE)=@_;
13815: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13816: return 0;
13817: }
13818:
13819: sub getCODE {
13820: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
13821: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13822: defined($Apache::lonhomework::parsing_a_task) ) &&
13823: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
13824: return $Apache::lonhomework::history{'resource.CODE'};
13825: }
13826: return undef;
13827: }
13828: #
13829: # Determines the random seed for a specific context:
13830: #
13831: # parameters:
13832: # symb - in course context the symb for the seed.
13833: # course_id - The course id of the form domain_coursenum.
13834: # domain - Domain for the user.
13835: # course - Course for the user.
13836: # cenv - environment of the course.
13837: #
13838: # NOTE:
13839: # All parameters are picked out of the environment if missing
13840: # or not defined.
13841: # If a symb cannot be determined the current time is used instead.
13842: #
13843: # For a given well defined symb, courside, domain, username,
13844: # and course environment, the seed is reproducible.
13845: #
13846: sub rndseed {
13847: my ($symb,$courseid,$domain,$username, $cenv)=@_;
13848: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
13849: if (!defined($symb)) {
13850: unless ($symb=$wsymb) { return time; }
13851: }
13852: if (!defined $courseid) {
13853: $courseid=$wcourseid;
13854: }
13855: if (!defined $domain) { $domain=$wdomain; }
13856: if (!defined $username) { $username=$wusername }
13857:
13858: my $which;
13859: if (defined($cenv->{'rndseed'})) {
13860: $which = $cenv->{'rndseed'};
13861: } else {
13862: $which =&get_rand_alg($courseid);
13863: }
13864: if (defined(&getCODE())) {
13865:
13866: if ($which eq '64bit5') {
13867: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
13868: } elsif ($which eq '64bit4') {
13869: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
13870: } else {
13871: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
13872: }
13873: } elsif ($which eq '64bit5') {
13874: return &rndseed_64bit5($symb,$courseid,$domain,$username);
13875: } elsif ($which eq '64bit4') {
13876: return &rndseed_64bit4($symb,$courseid,$domain,$username);
13877: } elsif ($which eq '64bit3') {
13878: return &rndseed_64bit3($symb,$courseid,$domain,$username);
13879: } elsif ($which eq '64bit2') {
13880: return &rndseed_64bit2($symb,$courseid,$domain,$username);
13881: } elsif ($which eq '64bit') {
13882: return &rndseed_64bit($symb,$courseid,$domain,$username);
13883: }
13884: return &rndseed_32bit($symb,$courseid,$domain,$username);
13885: }
13886:
13887: sub rndseed_32bit {
13888: my ($symb,$courseid,$domain,$username)=@_;
13889: {
13890: use integer;
13891: my $symbchck=unpack("%32C*",$symb) << 27;
13892: my $symbseed=numval($symb) << 22;
13893: my $namechck=unpack("%32C*",$username) << 17;
13894: my $nameseed=numval($username) << 12;
13895: my $domainseed=unpack("%32C*",$domain) << 7;
13896: my $courseseed=unpack("%32C*",$courseid);
13897: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
13898: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13899: #&logthis("rndseed :$num:$symb");
13900: if ($_64bit) { $num=(($num<<32)>>32); }
13901: return $num;
13902: }
13903: }
13904:
13905: sub rndseed_64bit {
13906: my ($symb,$courseid,$domain,$username)=@_;
13907: {
13908: use integer;
13909: my $symbchck=unpack("%32S*",$symb) << 21;
13910: my $symbseed=numval($symb) << 10;
13911: my $namechck=unpack("%32S*",$username);
13912:
13913: my $nameseed=numval($username) << 21;
13914: my $domainseed=unpack("%32S*",$domain) << 10;
13915: my $courseseed=unpack("%32S*",$courseid);
13916:
13917: my $num1=$symbchck+$symbseed+$namechck;
13918: my $num2=$nameseed+$domainseed+$courseseed;
13919: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13920: #&logthis("rndseed :$num:$symb");
13921: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13922: return "$num1,$num2";
13923: }
13924: }
13925:
13926: sub rndseed_64bit2 {
13927: my ($symb,$courseid,$domain,$username)=@_;
13928: {
13929: use integer;
13930: # strings need to be an even # of cahracters long, it it is odd the
13931: # last characters gets thrown away
13932: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13933: my $symbseed=numval($symb) << 10;
13934: my $namechck=unpack("%32S*",$username.' ');
13935:
13936: my $nameseed=numval($username) << 21;
13937: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13938: my $courseseed=unpack("%32S*",$courseid.' ');
13939:
13940: my $num1=$symbchck+$symbseed+$namechck;
13941: my $num2=$nameseed+$domainseed+$courseseed;
13942: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13943: #&logthis("rndseed :$num:$symb");
13944: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13945: return "$num1,$num2";
13946: }
13947: }
13948:
13949: sub rndseed_64bit3 {
13950: my ($symb,$courseid,$domain,$username)=@_;
13951: {
13952: use integer;
13953: # strings need to be an even # of cahracters long, it it is odd the
13954: # last characters gets thrown away
13955: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13956: my $symbseed=numval2($symb) << 10;
13957: my $namechck=unpack("%32S*",$username.' ');
13958:
13959: my $nameseed=numval2($username) << 21;
13960: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13961: my $courseseed=unpack("%32S*",$courseid.' ');
13962:
13963: my $num1=$symbchck+$symbseed+$namechck;
13964: my $num2=$nameseed+$domainseed+$courseseed;
13965: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13966: #&logthis("rndseed :$num1:$num2:$_64bit");
13967: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13968:
13969: return "$num1:$num2";
13970: }
13971: }
13972:
13973: sub rndseed_64bit4 {
13974: my ($symb,$courseid,$domain,$username)=@_;
13975: {
13976: use integer;
13977: # strings need to be an even # of cahracters long, it it is odd the
13978: # last characters gets thrown away
13979: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13980: my $symbseed=numval3($symb) << 10;
13981: my $namechck=unpack("%32S*",$username.' ');
13982:
13983: my $nameseed=numval3($username) << 21;
13984: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13985: my $courseseed=unpack("%32S*",$courseid.' ');
13986:
13987: my $num1=$symbchck+$symbseed+$namechck;
13988: my $num2=$nameseed+$domainseed+$courseseed;
13989: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13990: #&logthis("rndseed :$num1:$num2:$_64bit");
13991: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13992:
13993: return "$num1:$num2";
13994: }
13995: }
13996:
13997: sub rndseed_64bit5 {
13998: my ($symb,$courseid,$domain,$username)=@_;
13999: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
14000: return "$num1:$num2";
14001: }
14002:
14003: sub rndseed_CODE_64bit {
14004: my ($symb,$courseid,$domain,$username)=@_;
14005: {
14006: use integer;
14007: my $symbchck=unpack("%32S*",$symb.' ') << 16;
14008: my $symbseed=numval2($symb);
14009: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14010: my $CODEseed=numval(&getCODE());
14011: my $courseseed=unpack("%32S*",$courseid.' ');
14012: my $num1=$symbseed+$CODEchck;
14013: my $num2=$CODEseed+$courseseed+$symbchck;
14014: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14015: #&logthis("rndseed :$num1:$num2:$symb");
14016: if ($_64bit) { $num1=(($num1<<32)>>32); }
14017: if ($_64bit) { $num2=(($num2<<32)>>32); }
14018: return "$num1:$num2";
14019: }
14020: }
14021:
14022: sub rndseed_CODE_64bit4 {
14023: my ($symb,$courseid,$domain,$username)=@_;
14024: {
14025: use integer;
14026: my $symbchck=unpack("%32S*",$symb.' ') << 16;
14027: my $symbseed=numval3($symb);
14028: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14029: my $CODEseed=numval3(&getCODE());
14030: my $courseseed=unpack("%32S*",$courseid.' ');
14031: my $num1=$symbseed+$CODEchck;
14032: my $num2=$CODEseed+$courseseed+$symbchck;
14033: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14034: #&logthis("rndseed :$num1:$num2:$symb");
14035: if ($_64bit) { $num1=(($num1<<32)>>32); }
14036: if ($_64bit) { $num2=(($num2<<32)>>32); }
14037: return "$num1:$num2";
14038: }
14039: }
14040:
14041: sub rndseed_CODE_64bit5 {
14042: my ($symb,$courseid,$domain,$username)=@_;
14043: my $code = &getCODE();
14044: my ($num1,$num2)=&digest("$symb,$courseid,$code");
14045: return "$num1:$num2";
14046: }
14047:
14048: sub setup_random_from_rndseed {
14049: my ($rndseed)=@_;
14050: if ($rndseed =~/([,:])/) {
14051: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
14052: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
14053: &Math::Random::random_set_seed_from_phrase($rndseed);
14054: } else {
14055: &Math::Random::random_set_seed($num1,$num2);
14056: }
14057: } else {
14058: &Math::Random::random_set_seed_from_phrase($rndseed);
14059: }
14060: }
14061:
14062: sub latest_receipt_algorithm_id {
14063: return 'receipt3';
14064: }
14065:
14066: sub recunique {
14067: my $fucourseid=shift;
14068: my $unique;
14069: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
14070: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14071: $unique=$env{"course.$fucourseid.internal.encseed"};
14072: } else {
14073: $unique=$perlvar{'lonReceipt'};
14074: }
14075: return unpack("%32C*",$unique);
14076: }
14077:
14078: sub recprefix {
14079: my $fucourseid=shift;
14080: my $prefix;
14081: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
14082: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14083: $prefix=$env{"course.$fucourseid.internal.encpref"};
14084: } else {
14085: $prefix=$perlvar{'lonHostID'};
14086: }
14087: return unpack("%32C*",$prefix);
14088: }
14089:
14090: sub ireceipt {
14091: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
14092:
14093: my $return =&recprefix($fucourseid).'-';
14094:
14095: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
14096: $env{'request.state'} eq 'construct') {
14097: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
14098: return $return;
14099: }
14100:
14101: my $cuname=unpack("%32C*",$funame);
14102: my $cudom=unpack("%32C*",$fudom);
14103: my $cucourseid=unpack("%32C*",$fucourseid);
14104: my $cusymb=unpack("%32C*",$fusymb);
14105: my $cunique=&recunique($fucourseid);
14106: my $cpart=unpack("%32S*",$part);
14107: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
14108:
14109: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
14110:
14111: $return.= ($cunique%$cuname+
14112: $cunique%$cudom+
14113: $cusymb%$cuname+
14114: $cusymb%$cudom+
14115: $cucourseid%$cuname+
14116: $cucourseid%$cudom+
14117: $cpart%$cuname+
14118: $cpart%$cudom);
14119: } else {
14120: $return.= ($cunique%$cuname+
14121: $cunique%$cudom+
14122: $cusymb%$cuname+
14123: $cusymb%$cudom+
14124: $cucourseid%$cuname+
14125: $cucourseid%$cudom);
14126: }
14127: return $return;
14128: }
14129:
14130: sub receipt {
14131: my ($part)=@_;
14132: my ($symb,$courseid,$domain,$name) = &whichuser();
14133: return &ireceipt($name,$domain,$courseid,$symb,$part);
14134: }
14135:
14136: sub whichuser {
14137: my ($passedsymb)=@_;
14138: my ($symb,$courseid,$domain,$name,$publicuser);
14139: if (defined($env{'form.grade_symb'})) {
14140: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
14141: my $allowed=&allowed('vgr',$tmp_courseid);
14142: if (!$allowed &&
14143: exists($env{'request.course.sec'}) &&
14144: $env{'request.course.sec'} !~ /^\s*$/) {
14145: $allowed=&allowed('vgr',$tmp_courseid.
14146: '/'.$env{'request.course.sec'});
14147: }
14148: if ($allowed) {
14149: ($symb)=&get_env_multiple('form.grade_symb');
14150: $courseid=$tmp_courseid;
14151: ($domain)=&get_env_multiple('form.grade_domain');
14152: ($name)=&get_env_multiple('form.grade_username');
14153: return ($symb,$courseid,$domain,$name,$publicuser);
14154: }
14155: }
14156: if (!$passedsymb) {
14157: $symb=&symbread();
14158: } else {
14159: $symb=$passedsymb;
14160: }
14161: $courseid=$env{'request.course.id'};
14162: $domain=$env{'user.domain'};
14163: $name=$env{'user.name'};
14164: if ($name eq 'public' && $domain eq 'public') {
14165: if (!defined($env{'form.username'})) {
14166: $env{'form.username'}.=time.rand(10000000);
14167: }
14168: $name.=$env{'form.username'};
14169: }
14170: return ($symb,$courseid,$domain,$name,$publicuser);
14171:
14172: }
14173:
14174: # ------------------------------------------------------------ Serves up a file
14175: # returns either the contents of the file or
14176: # -1 if the file doesn't exist
14177: #
14178: # if the target is a file that was uploaded via DOCS,
14179: # a check will be made to see if a current copy exists on the local server,
14180: # if it does this will be served, otherwise a copy will be retrieved from
14181: # the home server for the course and stored in /home/httpd/html/userfiles on
14182: # the local server.
14183:
14184: sub getfile {
14185: my ($file) = @_;
14186: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
14187: &repcopy($file);
14188: return &readfile($file);
14189: }
14190:
14191: sub repcopy_userfile {
14192: my ($file)=@_;
14193: my $londocroot = $perlvar{'lonDocRoot'};
14194: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
14195: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
14196: my ($cdom,$cnum,$filename) =
14197: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
14198: my $uri="/uploaded/$cdom/$cnum/$filename";
14199: if (-e "$file") {
14200: # we already have a local copy, check it out
14201: my @fileinfo = stat($file);
14202: my $rtncode;
14203: my $info;
14204: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
14205: if ($lwpresp ne 'ok') {
14206: # there is no such file anymore, even though we had a local copy
14207: if ($rtncode eq '404') {
14208: unlink($file);
14209: }
14210: return -1;
14211: }
14212: if ($info < $fileinfo[9]) {
14213: # nice, the file we have is up-to-date, just say okay
14214: return 'ok';
14215: } else {
14216: # the file is outdated, get rid of it
14217: unlink($file);
14218: }
14219: }
14220: # one way or the other, at this point, we don't have the file
14221: # construct the correct path for the file
14222: my @parts = ($cdom,$cnum);
14223: if ($filename =~ m|^(.+)/[^/]+$|) {
14224: push @parts, split(/\//,$1);
14225: }
14226: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
14227: foreach my $part (@parts) {
14228: $path .= '/'.$part;
14229: if (!-e $path) {
14230: mkdir($path,0770);
14231: }
14232: }
14233: # now the path exists for sure
14234: # get a user agent
14235: my $transferfile=$file.'.in.transfer';
14236: # FIXME: this should flock
14237: if (-e $transferfile) { return 'ok'; }
14238: my $request;
14239: $uri=~s/^\///;
14240: my $homeserver = &homeserver($cnum,$cdom);
14241: my $hostname = &hostname($homeserver);
14242: my $protocol = $protocol{$homeserver};
14243: $protocol = 'http' if ($protocol ne 'https');
14244: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
14245: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
14246: # did it work?
14247: if ($response->is_error()) {
14248: unlink($transferfile);
14249: &logthis("Userfile repcopy failed for $uri");
14250: return -1;
14251: }
14252: # worked, rename the transfer file
14253: rename($transferfile,$file);
14254: return 'ok';
14255: }
14256:
14257: sub tokenwrapper {
14258: my $uri=shift;
14259: $uri=~s|^https?\://([^/]+)||;
14260: $uri=~s|^/||;
14261: $env{'user.environment'}=~/\/([^\/]+)\.id/;
14262: my $token=$1;
14263: my (undef,$udom,$uname,$file)=split('/',$uri,4);
14264: if ($udom && $uname && $file) {
14265: $file=~s|(\?\.*)*$||;
14266: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
14267: my $homeserver = &homeserver($uname,$udom);
14268: my $hostname = &hostname($homeserver);
14269: my $protocol = $protocol{$homeserver};
14270: $protocol = 'http' if ($protocol ne 'https');
14271: return $protocol.'://'.$hostname.'/'.$uri.
14272: (($uri=~/\?/)?'&':'?').'token='.$token.
14273: '&tokenissued='.$perlvar{'lonHostID'};
14274: } else {
14275: return '/adm/notfound.html';
14276: }
14277: }
14278:
14279: # call with reqtype HEAD: get last modification time
14280: # call with reqtype GET: get the file contents
14281: # Do not call this with reqtype GET for large files! It loads everything into memory
14282: #
14283: sub getuploaded {
14284: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
14285: $uri=~s/^\///;
14286: my $homeserver = &homeserver($cnum,$cdom);
14287: my $hostname = &hostname($homeserver);
14288: my $protocol = $protocol{$homeserver};
14289: $protocol = 'http' if ($protocol ne 'https');
14290: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
14291: my $request=new HTTP::Request($reqtype,$uri);
14292: my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
14293: $$rtncode = $response->code;
14294: if (! $response->is_success()) {
14295: return 'failed';
14296: }
14297: if ($reqtype eq 'HEAD') {
14298: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
14299: } elsif ($reqtype eq 'GET') {
14300: $$info = $response->content;
14301: }
14302: return 'ok';
14303: }
14304:
14305: sub readfile {
14306: my $file = shift;
14307: if ( (! -e $file ) || ($file eq '') ) { return -1; };
14308: my $fh;
14309: open($fh,"<",$file);
14310: my $a='';
14311: while (my $line = <$fh>) { $a .= $line; }
14312: return $a;
14313: }
14314:
14315: sub filelocation {
14316: my ($dir,$file) = @_;
14317: my $location;
14318: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
14319:
14320: if ($file =~ m-^/adm/-) {
14321: $file=~s-^/adm/wrapper/-/-;
14322: $file=~s-^/adm/coursedocs/showdoc/-/-;
14323: }
14324:
14325: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
14326: $location = $file;
14327: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
14328: my ($udom,$uname,$filename)=
14329: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
14330: my $home=&homeserver($uname,$udom);
14331: my $is_me=0;
14332: my @ids=¤t_machine_ids();
14333: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
14334: if ($is_me) {
14335: $location=propath($udom,$uname).'/userfiles/'.$filename;
14336: } else {
14337: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14338: $udom.'/'.$uname.'/'.$filename;
14339: }
14340: } elsif ($file =~ m-^/adm/-) {
14341: $location = $perlvar{'lonDocRoot'}.'/'.$file;
14342: } else {
14343: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
14344: $file=~s:^/(res|priv)/:/:;
14345: my $space=$1;
14346: if ( !( $file =~ m:^/:) ) {
14347: $location = $dir. '/'.$file;
14348: } else {
14349: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
14350: }
14351: }
14352: $location=~s://+:/:g; # remove duplicate /
14353: while ($location=~m{/\.\./}) {
14354: if ($location =~ m{/[^/]+/\.\./}) {
14355: $location=~ s{/[^/]+/\.\./}{/}g;
14356: } else {
14357: $location=~ s{/\.\./}{/}g;
14358: }
14359: } #remove dir/..
14360: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14361: return $location;
14362: }
14363:
14364: sub hreflocation {
14365: my ($dir,$file)=@_;
14366: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
14367: $file=filelocation($dir,$file);
14368: } elsif ($file=~m-^/adm/-) {
14369: $file=~s-^/adm/wrapper/-/-;
14370: $file=~s-^/adm/coursedocs/showdoc/-/-;
14371: }
14372: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14373: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14374: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
14375: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14376: {/uploaded/$1/$2/}x;
14377: }
14378: if ($file=~ m{^/userfiles/}) {
14379: $file =~ s{^/userfiles/}{/uploaded/};
14380: }
14381: return $file;
14382: }
14383:
14384:
14385:
14386:
14387:
14388: sub current_machine_domains {
14389: return &machine_domains(&hostname($perlvar{'lonHostID'}));
14390: }
14391:
14392: sub machine_domains {
14393: my ($hostname) = @_;
14394: my @domains;
14395: my %hostname = &all_hostnames();
14396: while( my($id, $name) = each(%hostname)) {
14397: # &logthis("-$id-$name-$hostname-");
14398: if ($hostname eq $name) {
14399: push(@domains,&host_domain($id));
14400: }
14401: }
14402: return @domains;
14403: }
14404:
14405: sub current_machine_ids {
14406: return &machine_ids(&hostname($perlvar{'lonHostID'}));
14407: }
14408:
14409: sub machine_ids {
14410: my ($hostname) = @_;
14411: $hostname ||= &hostname($perlvar{'lonHostID'});
14412: my @ids;
14413: my %name_to_host = &all_names();
14414: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14415: return @{ $name_to_host{$hostname} };
14416: }
14417: return;
14418: }
14419:
14420: sub additional_machine_domains {
14421: my @domains;
14422: if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
14423: if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
14424: while (my $line = <$fh>) {
14425: chomp($line);
14426: $line =~ s/\s//g;
14427: push(@domains,$line);
14428: }
14429: close($fh);
14430: }
14431: }
14432: return @domains;
14433: }
14434:
14435: sub default_login_domain {
14436: my $domain = $perlvar{'lonDefDomain'};
14437: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14438: foreach my $posdom (¤t_machine_domains(),
14439: &additional_machine_domains()) {
14440: if (lc($posdom) eq lc($testdomain)) {
14441: $domain=$posdom;
14442: last;
14443: }
14444: }
14445: return $domain;
14446: }
14447:
14448: sub shared_institution {
14449: my ($dom,$lonhost) = @_;
14450: if ($lonhost eq '') {
14451: $lonhost = $perlvar{'lonHostID'};
14452: }
14453: my $same_intdom;
14454: my $hostintdom = &internet_dom($lonhost);
14455: if ($hostintdom ne '') {
14456: my %iphost = &get_iphost();
14457: my $primary_id = &domain($dom,'primary');
14458: my $primary_ip = &get_host_ip($primary_id);
14459: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14460: foreach my $id (@{$iphost{$primary_ip}}) {
14461: my $intdom = &internet_dom($id);
14462: if ($intdom eq $hostintdom) {
14463: $same_intdom = 1;
14464: last;
14465: }
14466: }
14467: }
14468: }
14469: return $same_intdom;
14470: }
14471:
14472: sub uses_sts {
14473: my ($ignore_cache) = @_;
14474: my $lonhost = $perlvar{'lonHostID'};
14475: my $hostname = &hostname($lonhost);
14476: my $sts_on;
14477: if ($protocol{$lonhost} eq 'https') {
14478: my $cachetime = 12*3600;
14479: if (!$ignore_cache) {
14480: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14481: if (defined($cached)) {
14482: return $sts_on;
14483: }
14484: }
14485: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14486: my $request=new HTTP::Request('HEAD',$url);
14487: my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14488: if ($response->is_success) {
14489: my $has_sts = $response->header('Strict-Transport-Security');
14490: if ($has_sts eq '') {
14491: $sts_on = 0;
14492: } else {
14493: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14494: my $maxage = $1;
14495: if ($maxage) {
14496: $sts_on = 1;
14497: } else {
14498: $sts_on = 0;
14499: }
14500: } else {
14501: $sts_on = 0;
14502: }
14503: }
14504: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14505: }
14506: }
14507: return;
14508: }
14509:
14510: sub waf_allssl {
14511: my ($host_name) = @_;
14512: my $alias = &get_proxy_alias();
14513: if ($host_name eq '') {
14514: $host_name = $ENV{'SERVER_NAME'};
14515: }
14516: if (($host_name ne '') && ($alias eq $host_name)) {
14517: my $serverhomedom = &host_domain($perlvar{'lonHostID'});
14518: my %defdomdefaults = &get_domain_defaults($serverhomedom);
14519: if ($defdomdefaults{'waf_sslopt'}) {
14520: return $defdomdefaults{'waf_sslopt'};
14521: }
14522: }
14523: return;
14524: }
14525:
14526: sub get_requestor_ip {
14527: my ($r,$nolookup,$noproxy) = @_;
14528: my $from_ip;
14529: if (ref($r)) {
14530: if ($r->can('useragent_ip')) {
14531: if ($noproxy && $r->can('client_ip')) {
14532: $from_ip = $r->client_ip();
14533: } else {
14534: $from_ip = $r->useragent_ip();
14535: }
14536: } elsif ($r->connection->can('remote_ip')) {
14537: $from_ip = $r->connection->remote_ip();
14538: } else {
14539: $from_ip = $r->get_remote_host($nolookup);
14540: }
14541: } else {
14542: $from_ip = $ENV{'REMOTE_ADDR'};
14543: }
14544: return $from_ip if ($noproxy);
14545: # Who controls proxy settings for server
14546: my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
14547: my $proxyinfo = &get_proxy_settings($dom_in_use);
14548: if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
14549: if ($proxyinfo->{'vpnint'}) {
14550: if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
14551: return $from_ip;
14552: }
14553: }
14554: if ($proxyinfo->{'trusted'}) {
14555: if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
14556: my $ipheader = $proxyinfo->{'ipheader'};
14557: my ($ip,$xfor);
14558: if (ref($r)) {
14559: if ($ipheader) {
14560: $ip = $r->headers_in->{$ipheader};
14561: }
14562: $xfor = $r->headers_in->{'X-Forwarded-For'};
14563: } else {
14564: if ($ipheader) {
14565: $ip = $ENV{'HTTP_'.uc($ipheader)};
14566: }
14567: $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
14568: }
14569: if (($ip eq '') && ($xfor ne '')) {
14570: foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
14571: unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
14572: $ip = $poss_ip;
14573: last;
14574: }
14575: }
14576: }
14577: if ($ip ne '') {
14578: return $ip;
14579: }
14580: }
14581: }
14582: }
14583: return $from_ip;
14584: }
14585:
14586: sub get_proxy_settings {
14587: my ($dom_in_use) = @_;
14588: my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
14589: my $proxyinfo = {
14590: ipheader => $domdefaults{'waf_ipheader'},
14591: trusted => $domdefaults{'waf_trusted'},
14592: vpnint => $domdefaults{'waf_vpnint'},
14593: vpnext => $domdefaults{'waf_vpnext'},
14594: sslopt => $domdefaults{'waf_sslopt'},
14595: };
14596: return $proxyinfo;
14597: }
14598:
14599: sub ip_match {
14600: my ($ip,$pattern_str) = @_;
14601: $ip=Net::CIDR::cidrvalidate($ip);
14602: if ($ip) {
14603: return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
14604: }
14605: return;
14606: }
14607:
14608: sub get_proxy_alias {
14609: my ($lonid) = @_;
14610: if ($lonid eq '') {
14611: $lonid = $perlvar{'lonHostID'};
14612: }
14613: if (!defined(&hostname($lonid))) {
14614: return;
14615: }
14616: if ($lonid ne '') {
14617: my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
14618: if ($cached) {
14619: return $alias;
14620: }
14621: my $dom = &Apache::lonnet::host_domain($lonid);
14622: if ($dom ne '') {
14623: my $cachetime = 60*60*24;
14624: my %domconfig =
14625: &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
14626: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14627: if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
14628: $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
14629: }
14630: }
14631: return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
14632: }
14633: }
14634: return;
14635: }
14636:
14637: sub use_proxy_alias {
14638: my ($r,$lonid) = @_;
14639: my $alias = &get_proxy_alias($lonid);
14640: if ($alias) {
14641: my $dom = &host_domain($lonid);
14642: if ($dom ne '') {
14643: my $proxyinfo = &get_proxy_settings($dom);
14644: my ($vpnint,$remote_ip);
14645: if (ref($proxyinfo) eq 'HASH') {
14646: $vpnint = $proxyinfo->{'vpnint'};
14647: if ($vpnint) {
14648: $remote_ip = &get_requestor_ip($r,1,1);
14649: }
14650: }
14651: unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
14652: return $alias;
14653: }
14654: }
14655: }
14656: return;
14657: }
14658:
14659: sub alias_shibboleth {
14660: my ($lonid) = @_;
14661: if ($lonid eq '') {
14662: $lonid = $perlvar{'lonHostID'};
14663: }
14664: if (!defined(&hostname($lonid))) {
14665: return;
14666: }
14667: if ($lonid ne '') {
14668: my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
14669: if ($cached) {
14670: return $use_alias;
14671: }
14672: my $dom = &Apache::lonnet::host_domain($lonid);
14673: if ($dom ne '') {
14674: my $cachetime = 60*60*24;
14675: my %domconfig =
14676: &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
14677: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14678: if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
14679: $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
14680: }
14681: }
14682: return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
14683: }
14684: }
14685: return;
14686: }
14687:
14688: sub get_saml_landing {
14689: my ($lonid) = @_;
14690: if ($lonid eq '') {
14691: my $defdom = &default_login_domain();
14692: my @hosts = ¤t_machine_ids();
14693: if (@hosts > 1) {
14694: foreach my $hostid (@hosts) {
14695: if (&host_domain($hostid) eq $defdom) {
14696: $lonid = $hostid;
14697: last;
14698: }
14699: }
14700: } else {
14701: $lonid = $perlvar{'lonHostID'};
14702: }
14703: if ($lonid) {
14704: unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
14705: return;
14706: }
14707: } else {
14708: return;
14709: }
14710: } elsif (!defined(&hostname($lonid))) {
14711: return;
14712: }
14713: my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
14714: if ($cached) {
14715: return $landing;
14716: }
14717: my $dom = &Apache::lonnet::host_domain($lonid);
14718: if ($dom ne '') {
14719: my $cachetime = 60*60*24;
14720: my %domconfig =
14721: &Apache::lonnet::get_dom('configuration',['login'],$dom);
14722: if (ref($domconfig{'login'}) eq 'HASH') {
14723: if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
14724: if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
14725: $landing = 1;
14726: }
14727: }
14728: }
14729: return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
14730: }
14731: return;
14732: }
14733:
14734: # ------------------------------------------------------------- Declutters URLs
14735:
14736: sub declutter {
14737: my $thisfn=shift;
14738: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14739: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
14740: $thisfn=~s{^/home/httpd/html}{};
14741: }
14742: $thisfn=~s/^\///;
14743: $thisfn=~s|^adm/wrapper/||;
14744: $thisfn=~s|^adm/coursedocs/showdoc/||;
14745: $thisfn=~s/^res\///;
14746: $thisfn=~s/^priv\///;
14747: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
14748: $thisfn=~s/\?.+$//;
14749: }
14750: return $thisfn;
14751: }
14752:
14753: # ------------------------------------------------------------- Clutter up URLs
14754:
14755: sub clutter {
14756: my $thisfn='/'.&declutter(shift);
14757: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
14758: || $thisfn =~ m{^/adm/(includes|pages)} ) {
14759: $thisfn='/res'.$thisfn;
14760: }
14761: if ($thisfn !~m|^/adm|) {
14762: if ($thisfn =~ m|^/ext/|) {
14763: $thisfn='/adm/wrapper'.$thisfn;
14764: } else {
14765: my ($ext) = ($thisfn =~ /\.(\w+)$/);
14766: my $embstyle=&Apache::loncommon::fileembstyle($ext);
14767: if ($embstyle eq 'ssi'
14768: || ($embstyle eq 'hdn')
14769: || ($embstyle eq 'rat')
14770: || ($embstyle eq 'prv')
14771: || ($embstyle eq 'ign')) {
14772: #do nothing with these
14773: } elsif (($embstyle eq 'img')
14774: || ($embstyle eq 'emb')
14775: || ($embstyle eq 'wrp')) {
14776: $thisfn='/adm/wrapper'.$thisfn;
14777: } elsif ($embstyle eq 'unk'
14778: && $thisfn!~/\.(sequence|page)$/) {
14779: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
14780: } else {
14781: # &logthis("Got a blank emb style");
14782: }
14783: }
14784: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
14785: $thisfn='/adm/wrapper'.$thisfn;
14786: }
14787: return $thisfn;
14788: }
14789:
14790: sub clutter_with_no_wrapper {
14791: my $uri = &clutter(shift);
14792: if ($uri =~ m-^/adm/-) {
14793: $uri =~ s-^/adm/wrapper/-/-;
14794: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
14795: }
14796: return $uri;
14797: }
14798:
14799: sub freeze_escape {
14800: my ($value)=@_;
14801: if (ref($value)) {
14802: $value=&nfreeze($value);
14803: return '__FROZEN__'.&escape($value);
14804: }
14805: return &escape($value);
14806: }
14807:
14808:
14809: sub thaw_unescape {
14810: my ($value)=@_;
14811: if ($value =~ /^__FROZEN__/) {
14812: substr($value,0,10,undef);
14813: $value=&unescape($value);
14814: return &thaw($value);
14815: }
14816: return &unescape($value);
14817: }
14818:
14819: sub correct_line_ends {
14820: my ($result)=@_;
14821: $$result =~s/\r\n/\n/mg;
14822: $$result =~s/\r/\n/mg;
14823: }
14824: # ================================================================ Main Program
14825:
14826: sub goodbye {
14827: &logthis("Starting Shut down");
14828: #not converted to using infrastruture and probably shouldn't be
14829: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
14830: #converted
14831: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
14832: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14833: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14834: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
14835: #1.1 only
14836: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14837: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14838: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14839: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14840: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
14841: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14842: &logthis(sprintf("%-20s is %s",'hits',$hits));
14843: &flushcourselogs();
14844: &logthis("Shutting down");
14845: }
14846:
14847: sub get_dns {
14848: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
14849: if (!$ignore_cache) {
14850: my ($content,$cached)=
14851: &Apache::lonnet::is_cached_new('dns',$url);
14852: if ($cached) {
14853: &$func($content,$hashref);
14854: return;
14855: }
14856: }
14857:
14858: my %alldns;
14859: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
14860: foreach my $dns (<$config>) {
14861: next if ($dns !~ /^\^(\S*)/x);
14862: my $line = $1;
14863: my ($host,$protocol) = split(/:/,$line);
14864: if ($protocol ne 'https') {
14865: $protocol = 'http';
14866: }
14867: $alldns{$host} = $protocol;
14868: }
14869: close($config);
14870: }
14871: while (%alldns) {
14872: my ($dns) = sort { $b cmp $a } keys(%alldns);
14873: my ($contents,@content);
14874: if ($dns eq Sys::Hostname::FQDN::fqdn()) {
14875: my $command = (split('/',$url))[3];
14876: my ($dir,$file) = &parse_getdns_url($command,$url);
14877: delete($alldns{$dns});
14878: next if (($dir eq '') || ($file eq ''));
14879: if (open(my $config,'<',"$dir/$file")) {
14880: @content = <$config>;
14881: close($config);
14882: }
14883: if ($url eq '/adm/dns/loncapaCRL') {
14884: $contents = join('',@content);
14885: }
14886: } else {
14887: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
14888: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
14889: delete($alldns{$dns});
14890: next if ($response->is_error());
14891: if ($url eq '/adm/dns/loncapaCRL') {
14892: $contents = $response->content;
14893: } else {
14894: @content = split("\n",$response->content);
14895: }
14896: }
14897: if ($url eq '/adm/dns/loncapaCRL') {
14898: return &$func($contents);
14899: } else {
14900: unless ($nocache) {
14901: &do_cache_new('dns',$url,\@content,30*24*60*60);
14902: }
14903: &$func(\@content,$hashref);
14904: return;
14905: }
14906: }
14907: my $which = (split('/',$url,4))[3];
14908: if ($which eq 'loncapaCRL') {
14909: my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14910: if (-e $diskfile) {
14911: &logthis("unable to contact DNS, on disk file $diskfile not updated");
14912: } else {
14913: &logthis("unable to contact DNS, no on disk file $diskfile available");
14914: }
14915: } else {
14916: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
14917: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14918: my @content = <$config>;
14919: close($config);
14920: &$func(\@content,$hashref);
14921: }
14922: }
14923: return;
14924: }
14925:
14926: # ------------------------------------------------------Get DNS checksums file
14927: sub parse_dns_checksums_tab {
14928: my ($lines,$hashref) = @_;
14929: my $lonhost = $perlvar{'lonHostID'};
14930: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
14931: my $loncaparev = &get_server_loncaparev($machine_dom);
14932: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14933: my $webconfdir = '/etc/httpd/conf';
14934: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14935: $webconfdir = '/etc/apache2';
14936: } elsif ($distro =~ /^sles(\d+)$/) {
14937: if ($1 >= 10) {
14938: $webconfdir = '/etc/apache2';
14939: }
14940: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14941: if ($1 >= 10.0) {
14942: $webconfdir = '/etc/apache2';
14943: }
14944: }
14945: my ($release,$timestamp) = split(/\-/,$loncaparev);
14946: my (%chksum,%revnum);
14947: if (ref($lines) eq 'ARRAY') {
14948: chomp(@{$lines});
14949: my $version = shift(@{$lines});
14950: if ($version eq $release) {
14951: foreach my $line (@{$lines}) {
14952: my ($file,$version,$shasum) = split(/,/,$line);
14953: if ($file =~ m{^/etc/httpd/conf}) {
14954: if ($webconfdir eq '/etc/apache2') {
14955: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14956: }
14957: }
14958: $chksum{$file} = $shasum;
14959: $revnum{$file} = $version;
14960: }
14961: if (ref($hashref) eq 'HASH') {
14962: %{$hashref} = (
14963: sums => \%chksum,
14964: versions => \%revnum,
14965: );
14966: }
14967: }
14968: }
14969: return;
14970: }
14971:
14972: sub fetch_dns_checksums {
14973: my %checksums;
14974: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
14975: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
14976: my ($release,$timestamp) = split(/\-/,$loncaparev);
14977: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
14978: \%checksums);
14979: return \%checksums;
14980: }
14981:
14982: sub fetch_crl_pemfile {
14983: return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
14984: }
14985:
14986: sub save_crl_pem {
14987: my ($content) = @_;
14988: my ($msg,$hadchanges);
14989: if ($content ne '') {
14990: my $now = time;
14991: my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
14992: my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
14993: if (open(my $fh,'>',"$tmpcrl")) {
14994: print $fh $content;
14995: close($fh);
14996: if (-e $lonca) {
14997: if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
14998: my $check = <PIPE>;
14999: close(PIPE);
15000: chomp($check);
15001: if ($check eq 'verify OK') {
15002: my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15003: my $backup;
15004: if (-e $dest) {
15005: if (&File::Copy::move($dest,"$dest.bak")) {
15006: $backup = 'ok';
15007: }
15008: }
15009: if (&File::Copy::move($tmpcrl,$dest)) {
15010: $msg = 'ok';
15011: if ($backup) {
15012: my (%oldnums,%newnums);
15013: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
15014: while (<PIPE>) {
15015: $oldnums{(split(/:/))[1]} = 1;
15016: }
15017: close(PIPE);
15018: }
15019: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
15020: while(<PIPE>) {
15021: $newnums{(split(/:/))[1]} = 1;
15022: }
15023: close(PIPE);
15024: }
15025: foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
15026: unless (exists($oldnums{$key})) {
15027: $hadchanges = 1;
15028: last;
15029: }
15030: }
15031: unless ($hadchanges) {
15032: foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
15033: unless (exists($newnums{$key})) {
15034: $hadchanges = 1;
15035: last;
15036: }
15037: }
15038: }
15039: }
15040: }
15041: } else {
15042: unlink($tmpcrl);
15043: }
15044: } else {
15045: unlink($tmpcrl);
15046: }
15047: } else {
15048: unlink($tmpcrl);
15049: }
15050: }
15051: }
15052: return ($msg,$hadchanges);
15053: }
15054:
15055: sub parse_getdns_url {
15056: my ($command,$url) = @_;
15057: my $dir = $perlvar{'lonTabDir'};
15058: my $file;
15059: if ($command eq 'hosts') {
15060: $file = 'dns_hosts.tab';
15061: } elsif ($command eq 'domain') {
15062: $file = 'dns_domain.tab';
15063: } elsif ($command eq 'checksums') {
15064: my $version = (split('/',$url))[4];
15065: $file = "dns_checksums/$version.tab",
15066: } elsif ($command eq 'loncapaCRL') {
15067: $dir = $perlvar{'lonCertificateDirectory'};
15068: $file = $perlvar{'lonnetCertRevocationList'};
15069: }
15070: return ($dir,$file);
15071: }
15072:
15073: # ------------------------------------------------------------ Read domain file
15074: {
15075: my $loaded;
15076: my %domain;
15077:
15078: sub parse_domain_tab {
15079: my ($lines) = @_;
15080: foreach my $line (@$lines) {
15081: next if ($line =~ /^(\#|\s*$ )/x);
15082:
15083: chomp($line);
15084: my ($name,@elements) = split(/:/,$line,9);
15085: my %this_domain;
15086: foreach my $field ('description', 'auth_def', 'auth_arg_def',
15087: 'lang_def', 'city', 'longi', 'lati',
15088: 'primary') {
15089: $this_domain{$field} = shift(@elements);
15090: }
15091: $domain{$name} = \%this_domain;
15092: }
15093: }
15094:
15095: sub reset_domain_info {
15096: undef($loaded);
15097: undef(%domain);
15098: }
15099:
15100: sub load_domain_tab {
15101: my ($ignore_cache,$nocache) = @_;
15102: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
15103: my $fh;
15104: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
15105: my @lines = <$fh>;
15106: &parse_domain_tab(\@lines);
15107: }
15108: close($fh);
15109: $loaded = 1;
15110: }
15111:
15112: sub domain {
15113: &load_domain_tab() if (!$loaded);
15114:
15115: my ($name,$what) = @_;
15116: return if ( !exists($domain{$name}) );
15117:
15118: if (!$what) {
15119: return $domain{$name}{'description'};
15120: }
15121: return $domain{$name}{$what};
15122: }
15123:
15124: sub domain_info {
15125: &load_domain_tab() if (!$loaded);
15126: return %domain;
15127: }
15128:
15129: }
15130:
15131:
15132: # ------------------------------------------------------------- Read hosts file
15133: {
15134: my %hostname;
15135: my %hostdom;
15136: my %libserv;
15137: my $loaded;
15138: my %name_to_host;
15139: my %internetdom;
15140: my %LC_dns_serv;
15141:
15142: sub parse_hosts_tab {
15143: my ($file) = @_;
15144: foreach my $configline (@$file) {
15145: next if ($configline =~ /^(\#|\s*$ )/x);
15146: chomp($configline);
15147: if ($configline =~ /^\^/) {
15148: if ($configline =~ /^\^([\w.\-]+)/) {
15149: $LC_dns_serv{$1} = 1;
15150: }
15151: next;
15152: }
15153: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
15154: $name=~s/\s//g;
15155: if ($id && $domain && $role && $name) {
15156: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
15157: my $curr = $hostname{$id};
15158: my $skip;
15159: if (ref($name_to_host{$curr}) eq 'ARRAY') {
15160: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
15161: $skip = 1;
15162: } else {
15163: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
15164: }
15165: }
15166: unless ($skip) {
15167: push(@{$name_to_host{$name}},$id);
15168: }
15169: } else {
15170: push(@{$name_to_host{$name}},$id);
15171: }
15172: $hostname{$id}=$name;
15173: $hostdom{$id}=$domain;
15174: if ($role eq 'library') { $libserv{$id}=$name; }
15175: if (defined($protocol)) {
15176: if ($protocol eq 'https') {
15177: $protocol{$id} = $protocol;
15178: } else {
15179: $protocol{$id} = 'http';
15180: }
15181: } else {
15182: $protocol{$id} = 'http';
15183: }
15184: if (defined($intdom)) {
15185: $internetdom{$id} = $intdom;
15186: }
15187: }
15188: }
15189: }
15190:
15191: sub reset_hosts_info {
15192: &purge_remembered();
15193: &reset_domain_info();
15194: &reset_hosts_ip_info();
15195: undef(%internetdom);
15196: undef(%name_to_host);
15197: undef(%hostname);
15198: undef(%hostdom);
15199: undef(%libserv);
15200: undef($loaded);
15201: }
15202:
15203: sub load_hosts_tab {
15204: my ($ignore_cache,$nocache) = @_;
15205: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
15206: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
15207: my @config = <$config>;
15208: &parse_hosts_tab(\@config);
15209: close($config);
15210: $loaded=1;
15211: }
15212:
15213: sub hostname {
15214: &load_hosts_tab() if (!$loaded);
15215:
15216: my ($lonid) = @_;
15217: return $hostname{$lonid};
15218: }
15219:
15220: sub all_hostnames {
15221: &load_hosts_tab() if (!$loaded);
15222:
15223: return %hostname;
15224: }
15225:
15226: sub all_names {
15227: my ($ignore_cache,$nocache) = @_;
15228: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
15229:
15230: return %name_to_host;
15231: }
15232:
15233: sub all_host_domain {
15234: &load_hosts_tab() if (!$loaded);
15235: return %hostdom;
15236: }
15237:
15238: sub all_host_intdom {
15239: &load_hosts_tab() if (!$loaded);
15240: return %internetdom;
15241: }
15242:
15243: sub is_library {
15244: &load_hosts_tab() if (!$loaded);
15245:
15246: return exists($libserv{$_[0]});
15247: }
15248:
15249: sub all_library {
15250: &load_hosts_tab() if (!$loaded);
15251:
15252: return %libserv;
15253: }
15254:
15255: sub unique_library {
15256: #2x reverse removes all hostnames that appear more than once
15257: my %unique = reverse &all_library();
15258: return reverse %unique;
15259: }
15260:
15261: sub get_servers {
15262: &load_hosts_tab() if (!$loaded);
15263:
15264: my ($domain,$type) = @_;
15265: my %possible_hosts = ($type eq 'library') ? %libserv
15266: : %hostname;
15267: my %result;
15268: if (ref($domain) eq 'ARRAY') {
15269: while ( my ($host,$hostname) = each(%possible_hosts)) {
15270: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
15271: $result{$host} = $hostname;
15272: }
15273: }
15274: } else {
15275: while ( my ($host,$hostname) = each(%possible_hosts)) {
15276: if ($hostdom{$host} eq $domain) {
15277: $result{$host} = $hostname;
15278: }
15279: }
15280: }
15281: return %result;
15282: }
15283:
15284: sub get_unique_servers {
15285: my %unique = reverse &get_servers(@_);
15286: return reverse %unique;
15287: }
15288:
15289: sub host_domain {
15290: &load_hosts_tab() if (!$loaded);
15291:
15292: my ($lonid) = @_;
15293: return $hostdom{$lonid};
15294: }
15295:
15296: sub all_domains {
15297: &load_hosts_tab() if (!$loaded);
15298:
15299: my %seen;
15300: my @uniq = grep(!$seen{$_}++, values(%hostdom));
15301: return @uniq;
15302: }
15303:
15304: sub internet_dom {
15305: &load_hosts_tab() if (!$loaded);
15306:
15307: my ($lonid) = @_;
15308: return $internetdom{$lonid};
15309: }
15310:
15311: sub is_LC_dns {
15312: &load_hosts_tab() if (!$loaded);
15313:
15314: my ($hostname) = @_;
15315: return exists($LC_dns_serv{$hostname});
15316: }
15317:
15318: }
15319:
15320: {
15321: my %iphost;
15322: my %name_to_ip;
15323: my %lonid_to_ip;
15324:
15325: sub get_hosts_from_ip {
15326: my ($ip) = @_;
15327: my %iphosts = &get_iphost();
15328: if (ref($iphosts{$ip})) {
15329: return @{$iphosts{$ip}};
15330: }
15331: return;
15332: }
15333:
15334: sub reset_hosts_ip_info {
15335: undef(%iphost);
15336: undef(%name_to_ip);
15337: undef(%lonid_to_ip);
15338: }
15339:
15340: sub get_host_ip {
15341: my ($lonid) = @_;
15342: if (exists($lonid_to_ip{$lonid})) {
15343: return $lonid_to_ip{$lonid};
15344: }
15345: my $name=&hostname($lonid);
15346: my $ip = gethostbyname($name);
15347: return if (!$ip || length($ip) ne 4);
15348: $ip=inet_ntoa($ip);
15349: $name_to_ip{$name} = $ip;
15350: $lonid_to_ip{$lonid} = $ip;
15351: return $ip;
15352: }
15353:
15354: sub get_iphost {
15355: my ($ignore_cache,$nocache) = @_;
15356:
15357: if (!$ignore_cache) {
15358: if (%iphost) {
15359: return %iphost;
15360: }
15361: my ($ip_info,$cached)=
15362: &Apache::lonnet::is_cached_new('iphost','iphost');
15363: if ($cached) {
15364: %iphost = %{$ip_info->[0]};
15365: %name_to_ip = %{$ip_info->[1]};
15366: %lonid_to_ip = %{$ip_info->[2]};
15367: return %iphost;
15368: }
15369: }
15370:
15371: # get yesterday's info for fallback
15372: my %old_name_to_ip;
15373: my ($ip_info,$cached)=
15374: &Apache::lonnet::is_cached_new('iphost','iphost');
15375: if ($cached) {
15376: %old_name_to_ip = %{$ip_info->[1]};
15377: }
15378:
15379: my %name_to_host = &all_names($ignore_cache,$nocache);
15380: foreach my $name (keys(%name_to_host)) {
15381: my $ip;
15382: if (!exists($name_to_ip{$name})) {
15383: $ip = gethostbyname($name);
15384: if (!$ip || length($ip) ne 4) {
15385: if (defined($old_name_to_ip{$name})) {
15386: $ip = $old_name_to_ip{$name};
15387: &logthis("Can't find $name defaulting to old $ip");
15388: } else {
15389: &logthis("Name $name no IP found");
15390: next;
15391: }
15392: } else {
15393: $ip=inet_ntoa($ip);
15394: }
15395: $name_to_ip{$name} = $ip;
15396: } else {
15397: $ip = $name_to_ip{$name};
15398: }
15399: foreach my $id (@{ $name_to_host{$name} }) {
15400: $lonid_to_ip{$id} = $ip;
15401: }
15402: push(@{$iphost{$ip}},@{$name_to_host{$name}});
15403: }
15404: unless ($nocache) {
15405: &do_cache_new('iphost','iphost',
15406: [\%iphost,\%name_to_ip,\%lonid_to_ip],
15407: 48*60*60);
15408: }
15409:
15410: return %iphost;
15411: }
15412:
15413: #
15414: # Given a DNS returns the loncapa host name for that DNS
15415: #
15416: sub host_from_dns {
15417: my ($dns) = @_;
15418: my @hosts;
15419: my $ip;
15420:
15421: if (exists($name_to_ip{$dns})) {
15422: $ip = $name_to_ip{$dns};
15423: }
15424: if (!$ip) {
15425: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
15426: if (length($ip) == 4) {
15427: $ip = &IO::Socket::inet_ntoa($ip);
15428: }
15429: }
15430: if ($ip) {
15431: @hosts = get_hosts_from_ip($ip);
15432: return $hosts[0];
15433: }
15434: return undef;
15435: }
15436:
15437: sub get_internet_names {
15438: my ($lonid) = @_;
15439: return if ($lonid eq '');
15440: my ($idnref,$cached)=
15441: &Apache::lonnet::is_cached_new('internetnames',$lonid);
15442: if ($cached) {
15443: return $idnref;
15444: }
15445: my $ip = &get_host_ip($lonid);
15446: my @hosts = &get_hosts_from_ip($ip);
15447: my %iphost = &get_iphost();
15448: my (@idns,%seen);
15449: foreach my $id (@hosts) {
15450: my $dom = &host_domain($id);
15451: my $prim_id = &domain($dom,'primary');
15452: my $prim_ip = &get_host_ip($prim_id);
15453: next if ($seen{$prim_ip});
15454: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
15455: foreach my $id (@{$iphost{$prim_ip}}) {
15456: my $intdom = &internet_dom($id);
15457: unless (grep(/^\Q$intdom\E$/,@idns)) {
15458: push(@idns,$intdom);
15459: }
15460: }
15461: }
15462: $seen{$prim_ip} = 1;
15463: }
15464: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
15465: }
15466:
15467: }
15468:
15469: sub all_loncaparevs {
15470: 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);
15471: }
15472:
15473: # ---------------------------------------------------------- Read loncaparev table
15474: {
15475: sub load_loncaparevs {
15476: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
15477: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
15478: while (my $configline=<$config>) {
15479: chomp($configline);
15480: my ($hostid,$loncaparev)=split(/:/,$configline);
15481: $loncaparevs{$hostid}=$loncaparev;
15482: }
15483: close($config);
15484: }
15485: }
15486: }
15487: }
15488:
15489: # ---------------------------------------------------------- Read serverhostID table
15490: {
15491: sub load_serverhomeIDs {
15492: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
15493: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
15494: while (my $configline=<$config>) {
15495: chomp($configline);
15496: my ($name,$id)=split(/:/,$configline);
15497: $serverhomeIDs{$name}=$id;
15498: }
15499: close($config);
15500: }
15501: }
15502: }
15503: }
15504:
15505:
15506: BEGIN {
15507:
15508: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
15509: unless ($readit) {
15510: {
15511: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
15512: %perlvar = (%perlvar,%{$configvars});
15513: }
15514:
15515:
15516: # ------------------------------------------------------ Read spare server file
15517: {
15518: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
15519:
15520: while (my $configline=<$config>) {
15521: chomp($configline);
15522: if ($configline) {
15523: my ($host,$type) = split(':',$configline,2);
15524: if (!defined($type) || $type eq '') { $type = 'default' };
15525: push(@{ $spareid{$type} }, $host);
15526: }
15527: }
15528: close($config);
15529: }
15530: # ------------------------------------------------------------ Read permissions
15531: {
15532: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
15533:
15534: while (my $configline=<$config>) {
15535: chomp($configline);
15536: if ($configline) {
15537: my ($role,$perm)=split(/ /,$configline);
15538: if ($perm ne '') { $pr{$role}=$perm; }
15539: }
15540: }
15541: close($config);
15542: }
15543:
15544: # -------------------------------------------- Read plain texts for permissions
15545: {
15546: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
15547:
15548: while (my $configline=<$config>) {
15549: chomp($configline);
15550: if ($configline) {
15551: my ($short,@plain)=split(/:/,$configline);
15552: %{$prp{$short}} = ();
15553: if (@plain > 0) {
15554: $prp{$short}{'std'} = $plain[0];
15555: for (my $i=1; $i<@plain; $i++) {
15556: $prp{$short}{'alt'.$i} = $plain[$i];
15557: }
15558: }
15559: }
15560: }
15561: close($config);
15562: }
15563:
15564: # ---------------------------------------------------------- Read package table
15565: {
15566: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
15567:
15568: while (my $configline=<$config>) {
15569: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
15570: chomp($configline);
15571: my ($short,$plain)=split(/:/,$configline);
15572: my ($pack,$name)=split(/\&/,$short);
15573: if ($plain ne '') {
15574: $packagetab{$pack.'&'.$name.'&name'}=$name;
15575: $packagetab{$short}=$plain;
15576: }
15577: }
15578: close($config);
15579: }
15580:
15581: # ---------------------------------------------------------- Read loncaparev table
15582:
15583: &load_loncaparevs();
15584:
15585: # ---------------------------------------------------------- Read serverhostID table
15586:
15587: &load_serverhomeIDs();
15588:
15589: # ---------------------------------------------------------- Read releaseslist XML
15590: {
15591: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
15592: if (-e $file) {
15593: my $parser = HTML::LCParser->new($file);
15594: while (my $token = $parser->get_token()) {
15595: if ($token->[0] eq 'S') {
15596: my $item = $token->[1];
15597: my $name = $token->[2]{'name'};
15598: my $value = $token->[2]{'value'};
15599: my $valuematch = $token->[2]{'valuematch'};
15600: my $namematch = $token->[2]{'namematch'};
15601: if ($item eq 'parameter') {
15602: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
15603: my $release = $parser->get_text();
15604: $release =~ s/(^\s*|\s*$ )//gx;
15605: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
15606: }
15607: } elsif ($item ne '' && $name ne '') {
15608: my $release = $parser->get_text();
15609: $release =~ s/(^\s*|\s*$ )//gx;
15610: $needsrelease{$item.':'.$name.':'.$value} = $release;
15611: }
15612: }
15613: }
15614: }
15615: }
15616:
15617: # ---------------------------------------------------------- Read managers table
15618: {
15619: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
15620: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
15621: while (my $configline=<$config>) {
15622: chomp($configline);
15623: next if ($configline =~ /^\#/);
15624: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
15625: $managerstab{$configline} = 1;
15626: }
15627: }
15628: close($config);
15629: }
15630: }
15631: }
15632:
15633: # ------------- set up temporary directory
15634: {
15635: $tmpdir = LONCAPA::tempdir();
15636:
15637: }
15638:
15639: # ------------- set default texengine (domain default overrides this)
15640: {
15641: $deftex = LONCAPA::texengine();
15642: }
15643:
15644: # ------------- set default minimum length for passwords for internal auth users
15645: {
15646: $passwdmin = LONCAPA::passwd_min();
15647: }
15648:
15649: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
15650: 'compress_threshold'=> 20_000,
15651: });
15652:
15653: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
15654: $dumpcount=0;
15655: $locknum=0;
15656:
15657: &logtouch();
15658: &logthis('<font color="yellow">INFO: Read configuration</font>');
15659: $readit=1;
15660: {
15661: use integer;
15662: my $test=(2**32)+1;
15663: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
15664: &logthis(" Detected 64bit platform ($_64bit)");
15665: }
15666: }
15667: }
15668:
15669: 1;
15670: __END__
15671:
15672: =pod
15673:
15674: =head1 NAME
15675:
15676: Apache::lonnet - Subroutines to ask questions about things in the network.
15677:
15678: =head1 SYNOPSIS
15679:
15680: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
15681:
15682: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
15683:
15684: Common parameters:
15685:
15686: =over 4
15687:
15688: =item *
15689:
15690: $uname : an internal username (if $cname expecting a course Id specifically)
15691:
15692: =item *
15693:
15694: $udom : a domain (if $cdom expecting a course's domain specifically)
15695:
15696: =item *
15697:
15698: $symb : a resource instance identifier
15699:
15700: =item *
15701:
15702: $namespace : the name of a .db file that contains the data needed or
15703: being set.
15704:
15705: =back
15706:
15707: =head1 OVERVIEW
15708:
15709: lonnet provides subroutines which interact with the
15710: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
15711: about classes, users, and resources.
15712:
15713: For many of these objects you can also use this to store data about
15714: them or modify them in various ways.
15715:
15716: =head2 Symbs
15717:
15718: To identify a specific instance of a resource, LON-CAPA uses symbols
15719: or "symbs"X<symb>. These identifiers are built from the URL of the
15720: map, the resource number of the resource in the map, and the URL of
15721: the resource itself. The latter is somewhat redundant, but might help
15722: if maps change.
15723:
15724: An example is
15725:
15726: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
15727:
15728: The respective map entry is
15729:
15730: <resource id="19" src="/res/msu/korte/tests/part12.problem"
15731: title="Problem 2">
15732: </resource>
15733:
15734: Symbs are used by the random number generator, as well as to store and
15735: restore data specific to a certain instance of for example a problem.
15736:
15737: =head2 Storing And Retrieving Data
15738:
15739: X<store()>X<cstore()>X<restore()>Three of the most important functions
15740: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
15741: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
15742: is is the non-critical message twin of cstore. These functions are for
15743: handlers to store a perl hash to a user's permanent data space in an
15744: easy manner, and to retrieve it again on another call. It is expected
15745: that a handler would use this once at the beginning to retrieve data,
15746: and then again once at the end to send only the new data back.
15747:
15748: The data is stored in the user's data directory on the user's
15749: homeserver under the ID of the course.
15750:
15751: The hash that is returned by restore will have all of the previous
15752: value for all of the elements of the hash.
15753:
15754: Example:
15755:
15756: #creating a hash
15757: my %hash;
15758: $hash{'foo'}='bar';
15759:
15760: #storing it
15761: &Apache::lonnet::cstore(\%hash);
15762:
15763: #changing a value
15764: $hash{'foo'}='notbar';
15765:
15766: #adding a new value
15767: $hash{'bar'}='foo';
15768: &Apache::lonnet::cstore(\%hash);
15769:
15770: #retrieving the hash
15771: my %history=&Apache::lonnet::restore();
15772:
15773: #print the hash
15774: foreach my $key (sort(keys(%history))) {
15775: print("\%history{$key} = $history{$key}");
15776: }
15777:
15778: Will print out:
15779:
15780: %history{1:foo} = bar
15781: %history{1:keys} = foo:timestamp
15782: %history{1:timestamp} = 990455579
15783: %history{2:bar} = foo
15784: %history{2:foo} = notbar
15785: %history{2:keys} = foo:bar:timestamp
15786: %history{2:timestamp} = 990455580
15787: %history{bar} = foo
15788: %history{foo} = notbar
15789: %history{timestamp} = 990455580
15790: %history{version} = 2
15791:
15792: Note that the special hash entries C<keys>, C<version> and
15793: C<timestamp> were added to the hash. C<version> will be equal to the
15794: total number of versions of the data that have been stored. The
15795: C<timestamp> attribute will be the UNIX time the hash was
15796: stored. C<keys> is available in every historical section to list which
15797: keys were added or changed at a specific historical revision of a
15798: hash.
15799:
15800: B<Warning>: do not store the hash that restore returns directly. This
15801: will cause a mess since it will restore the historical keys as if the
15802: were new keys. I.E. 1:foo will become 1:1:foo etc.
15803:
15804: Calling convention:
15805:
15806: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
15807: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
15808:
15809: For more detailed information, see lonnet specific documentation.
15810:
15811: =head1 RETURN MESSAGES
15812:
15813: =over 4
15814:
15815: =item * B<con_lost>: unable to contact remote host
15816:
15817: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15818: when the connection is brought back up
15819:
15820: =item * B<con_failed>: unable to contact remote host and unable to save message
15821: for later delivery
15822:
15823: =item * B<error:>: an error a occurred, a description of the error follows the :
15824:
15825: =item * B<no_such_host>: unable to fund a host associated with the user/domain
15826: that was requested
15827:
15828: =back
15829:
15830: =head1 PUBLIC SUBROUTINES
15831:
15832: =head2 Session Environment Functions
15833:
15834: =over 4
15835:
15836: =item *
15837: X<appenv()>
15838: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
15839: the user envirnoment file, and will be restored for each access this
15840: user makes during this session, also modifies the %env for the current
15841: process. Optional rolesarrayref - if defined contains a reference to an array
15842: of roles which are exempt from the restriction on modifying user.role entries
15843: in the user's environment.db and in %env.
15844:
15845: =item *
15846: X<delenv()>
15847: B<delenv($delthis,$regexp)>: removes all items from the session
15848: environment file that begin with $delthis. If the
15849: optional second arg - $regexp - is true, $delthis is treated as a
15850: regular expression, otherwise \Q$delthis\E is used.
15851: The values are also deleted from the current processes %env.
15852:
15853: =item * get_env_multiple($name)
15854:
15855: gets $name from the %env hash, it seemlessly handles the cases where multiple
15856: values may be defined and end up as an array ref.
15857:
15858: returns an array of values
15859:
15860: =back
15861:
15862: =head2 User Information
15863:
15864: =over 4
15865:
15866: =item *
15867: X<queryauthenticate()>
15868: B<queryauthenticate($uname,$udom)>: try to determine user's current
15869: authentication scheme
15870:
15871: =item *
15872: X<authenticate()>
15873: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
15874: authenticate user from domain's lib servers (first use the current
15875: one). C<$upass> should be the users password.
15876: $checkdefauth is optional (value is 1 if a check should be made to
15877: authenticate user using default authentication method, and allow
15878: account creation if username does not have account in the domain).
15879: $clientcancheckhost is optional (value is 1 if checking whether the
15880: server can host will occur on the client side in lonauth.pm).
15881:
15882: =item *
15883: X<homeserver()>
15884: B<homeserver($uname,$udom)>: find the server which has
15885: the user's directory and files (there must be only one), this caches
15886: the answer, and also caches if there is a borken connection.
15887:
15888: =item *
15889: X<idget()>
15890: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
15891: a list of student/employee IDs or clicker IDs
15892: (student/employee IDs are a unique resource in a domain, there must be
15893: only 1 ID per username, and only 1 username per ID in a specific domain).
15894: clickerIDs are not necessarily unique, as students might share clickers.
15895: (returns hash: id=>name,id=>name)
15896:
15897: =item *
15898: X<idrget()>
15899: B<idrget($udom,@unames)>: find the IDs behind a list of
15900: usernames (returns hash: name=>id,name=>id)
15901:
15902: =item *
15903: X<idput()>
15904: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
15905: names and associated student/employee IDs or clicker IDs.
15906:
15907: =item *
15908: X<iddel()>
15909: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
15910: student/employee ID or clicker ID username look-ups from domain.
15911: The homeserver ($uhome) and namespace ($namespace) are optional.
15912: If no $uhome is provided, it will be determined usig &homeserver()
15913: for each user. If no $namespace is provided, the default is ids.
15914:
15915: =item *
15916: X<updateclickers()>
15917: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
15918: clicker ID-to-username look-ups in clickers.db on library server.
15919: Permitted actions are add or del (i.e., add or delete). The
15920: clickers.db contains clickerID as keys (escaped), and each corresponding
15921: value is an escaped comma-separated list of usernames (for whom the
15922: library server is the homeserver), who registered that particular ID.
15923: If $critical is true, the update will be sent via &critical, otherwise
15924: &reply() will be used.
15925:
15926: =item *
15927: X<rolesinit()>
15928: B<rolesinit($udom,$username)>: get user privileges.
15929: returns user role, first access and timer interval hashes
15930:
15931: =item *
15932: X<privileged()>
15933: B<privileged($username,$domain)>: returns a true if user has a
15934: privileged and active role (i.e. su or dc), false otherwise.
15935:
15936: =item *
15937: X<getsection()>
15938: B<getsection($udom,$uname,$cname)>: finds the section of student in the
15939: course $cname, return section name/number or '' for "not in course"
15940: and '-1' for "no section"
15941:
15942: =item *
15943: X<userenvironment()>
15944: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
15945: passed in @what from the requested user's environment, returns a hash
15946:
15947: =item *
15948: X<userlog_query()>
15949: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
15950: activity.log file. %filters defines filters applied when parsing the
15951: log file. These can be start or end timestamps, or the type of action
15952: - log to look for Login or Logout events, check for Checkin or
15953: Checkout, role for role selection. The response is in the form
15954: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
15955: escaped strings of the action recorded in the activity.log file.
15956:
15957: =back
15958:
15959: =head2 User Roles
15960:
15961: =over 4
15962:
15963: =item *
15964:
15965: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
15966: returns codes for allowed actions.
15967:
15968: The first argument is required, all others are optional.
15969:
15970: $priv is the privilege being checked.
15971: $uri contains additional information about what is being checked for access (e.g.,
15972: URL, course ID etc.).
15973: $symb is the unique resource instance identifier in a course; if needed,
15974: but not provided, it will be retrieved via a call to &symbread().
15975: $role is the role for which a priv is being checked (only used if priv is evb).
15976: $clientip is the user's IP address (only used when checking for access to portfolio
15977: files).
15978: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
15979: prevents recursive calls to &allowed.
15980:
15981: F: full access
15982: U,I,K: authentication modes (cxx only)
15983: '': forbidden
15984: 1: user needs to choose course
15985: 2: browse allowed
15986: A: passphrase authentication needed
15987: B: access temporarily blocked because of a blocking event in a course.
15988: D: access blocked because access is required via session initiated via deep-link
15989:
15990: =item *
15991:
15992: constructaccess($url,$setpriv) : check for access to construction space URL
15993:
15994: See if the owner domain and name in the URL match those in the
15995: expected environment. If so, return three element list
15996: ($ownername,$ownerdomain,$ownerhome).
15997:
15998: Otherwise return the null string.
15999:
16000: If second argument 'setpriv' is true, it assigns the privileges,
16001: and returns the same three element list, unless the owner has
16002: blocked "ad hoc" Domain Coordinator access to the Author Space,
16003: in which case the null string is returned.
16004:
16005: =item *
16006:
16007: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
16008: define a custom role rolename set privileges in format of lonTabs/roles.tab
16009: for system, domain, and course level. $uname and $udom are optional (current
16010: user's username and domain will be used when either of $uname or $udom are absent.
16011:
16012: =item *
16013:
16014: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
16015: (rolesplain.tab); plain text explanation of a user role term.
16016: $type is Course (default) or Community.
16017: If $forcedefault evaluates to true, text returned will be default
16018: text for $type. Otherwise, if this is a course, the text returned
16019: will be a custom name for the role (if defined in the course's
16020: environment). If no custom name is defined the default is returned.
16021:
16022: =item *
16023:
16024: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
16025: All arguments are optional. Returns a hash of a roles, either for
16026: co-author/assistant author roles for a user's Construction Space
16027: (default), or if $context is 'userroles', roles for the user himself,
16028: In the hash, keys are set to colon-separated $uname,$udom,$role, and
16029: (optionally) if $withsec is true, a fourth colon-separated item - $section.
16030: For each key, value is set to colon-separated start and end times for
16031: the role. If no username and domain are specified, will default to
16032: current user/domain. Types, roles, and roledoms are references to arrays
16033: of role statuses (active, future or previous), roles
16034: (e.g., cc,in, st etc.) and domains of the roles which can be used
16035: to restrict the list of roles reported. If no array ref is
16036: provided for types, will default to return only active roles.
16037:
16038: =item *
16039:
16040: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
16041: user: $uname:$udom has a role in the course: $cdom_$cnum.
16042:
16043: Additional optional arguments are: $type (if role checking is to be restricted
16044: to certain user status types -- previous (expired roles), active (currently
16045: available roles) or future (roles available in the future), and
16046: $hideprivileged -- if true will not report course roles for users who
16047: have active Domain Coordinator role in course's domain or in additional
16048: domains (specified in 'Domains to check for privileged users' in course
16049: environment -- set via: Course Settings -> Classlists and staff listing).
16050:
16051: =item *
16052:
16053: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
16054: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
16055: $possdomains and $possroles are optional array refs -- to domains to check and
16056: roles to check. If $possdomains is not specified, a dump will be done of the
16057: users' roles.db to check for a dc or su role in any domain. This can be
16058: time consuming if &privileged is called repeatedly (e.g., when displaying a
16059: classlist), so in such cases, supplying a $possdomains array is preferred, as
16060: this then allows &privileged_by_domain() to be used, which caches the identity
16061: of privileged users, eliminating the need for repeated calls to &dump().
16062:
16063: =item *
16064:
16065: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
16066: where the outer hash keys are domains specified in the $possdomains array ref,
16067: next inner hash keys are privileged roles specified in the $roles array ref,
16068: and the innermost hash contains key = value pairs for username:domain = end:start
16069: for active or future "privileged" users with that role in that domain. To avoid
16070: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
16071: innerhash are cached using priv_$role and $dom as the identifiers.
16072:
16073: =back
16074:
16075: =head2 User Modification
16076:
16077: =over 4
16078:
16079: =item *
16080:
16081: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
16082: user for the level given by URL. Optional start and end dates (leave empty
16083: string or zero for "no date")
16084:
16085: =item *
16086:
16087: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
16088: change a users, password, possible return values are: ok,
16089: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
16090: refused
16091:
16092: =item *
16093:
16094: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
16095:
16096: =item *
16097:
16098: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
16099: $forceid,$desiredhome,$email,$inststatus,$candelete) :
16100:
16101: will update user information (firstname,middlename,lastname,generation,
16102: permanentemail), and if forceid is true, student/employee ID also.
16103: A user's institutional affiliation(s) can also be updated.
16104: User information fields will not be overwritten with empty entries
16105: unless the field is included in the $candelete array reference.
16106: This array is included when a single user is modified via "Manage Users",
16107: or when Autoupdate.pl is run by cron in a domain.
16108:
16109: =item *
16110:
16111: modifystudent
16112:
16113: modify a student's enrollment and identification information.
16114: The course id is resolved based on the current user's environment.
16115: This means the invoking user must be a course coordinator or otherwise
16116: associated with a course.
16117:
16118: This call is essentially a wrapper for lonnet::modifyuser and
16119: lonnet::modify_student_enrollment
16120:
16121: Inputs:
16122:
16123: =over 4
16124:
16125: =item B<$udom> Student's loncapa domain
16126:
16127: =item B<$uname> Student's loncapa login name
16128:
16129: =item B<$uid> Student/Employee ID
16130:
16131: =item B<$umode> Student's authentication mode
16132:
16133: =item B<$upass> Student's password
16134:
16135: =item B<$first> Student's first name
16136:
16137: =item B<$middle> Student's middle name
16138:
16139: =item B<$last> Student's last name
16140:
16141: =item B<$gene> Student's generation
16142:
16143: =item B<$usec> Student's section in course
16144:
16145: =item B<$end> Unix time of the roles expiration
16146:
16147: =item B<$start> Unix time of the roles start date
16148:
16149: =item B<$forceid> If defined, allow $uid to be changed
16150:
16151: =item B<$desiredhome> server to use as home server for student
16152:
16153: =item B<$email> Student's permanent e-mail address
16154:
16155: =item B<$type> Type of enrollment (auto or manual)
16156:
16157: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
16158:
16159: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
16160:
16161: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
16162:
16163: =item B<$context> role change context (shown in User Management Logs display in a course)
16164:
16165: =item B<$inststatus> institutional status of user - : separated string of escaped status types
16166:
16167: =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.
16168:
16169: =back
16170:
16171: =item *
16172:
16173: modify_student_enrollment
16174:
16175: Change a student's enrollment status in a class. The environment variable
16176: 'role.request.course' must be defined for this function to proceed.
16177:
16178: Inputs:
16179:
16180: =over 4
16181:
16182: =item $udom, student's domain
16183:
16184: =item $uname, student's name
16185:
16186: =item $uid, student's user id
16187:
16188: =item $first, student's first name
16189:
16190: =item $middle
16191:
16192: =item $last
16193:
16194: =item $gene
16195:
16196: =item $usec
16197:
16198: =item $end
16199:
16200: =item $start
16201:
16202: =item $type
16203:
16204: =item $locktype
16205:
16206: =item $cid
16207:
16208: =item $selfenroll
16209:
16210: =item $context
16211:
16212: =item $credits, number of credits student will earn from this class
16213:
16214: =item $instsec, institutional course section code for student
16215:
16216: =back
16217:
16218:
16219: =item *
16220:
16221: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
16222: custom role; give a custom role to a user for the level given by URL. Specify
16223: name and domain of role author, and role name
16224:
16225: =item *
16226:
16227: revokerole($udom,$uname,$url,$role) : revoke a role for url
16228:
16229: =item *
16230:
16231: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
16232:
16233: =back
16234:
16235: =head2 Course Infomation
16236:
16237: =over 4
16238:
16239: =item *
16240:
16241: coursedescription($courseid,$options) : returns a hash of information about the
16242: specified course id, including all environment settings for the
16243: course, the description of the course will be in the hash under the
16244: key 'description'
16245:
16246: $options is an optional parameter that if supplied is a hash reference that controls
16247: what how this function works. It has the following key/values:
16248:
16249: =over 4
16250:
16251: =item freshen_cache
16252:
16253: If defined, and the environment cache for the course is valid, it is
16254: returned in the returned hash.
16255:
16256: =item one_time
16257:
16258: If defined, the last cache time is set to _now_
16259:
16260: =item user
16261:
16262: If defined, the supplied username is used instead of the current user.
16263:
16264:
16265: =back
16266:
16267: =item *
16268:
16269: resdata($name,$domain,$type,@which) : request for current parameter
16270: setting for a specific $type, where $type is either 'course' or 'user',
16271: @what should be a list of parameters to ask about. This routine caches
16272: answers for 10 minutes.
16273:
16274: =item *
16275:
16276: get_courseresdata($courseid, $domain) : dump the entire course resource
16277: data base, returning a hash that is keyed by the resource name and has
16278: values that are the resource value. I believe that the timestamps and
16279: versions are also returned.
16280:
16281: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
16282: supplemental content area. This routine caches the number of files for
16283: 10 minutes.
16284:
16285: =back
16286:
16287: =head2 Course Modification
16288:
16289: =over 4
16290:
16291: =item *
16292:
16293: writecoursepref($courseid,%prefs) : write preferences (environment
16294: database) for a course
16295:
16296: =item *
16297:
16298: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
16299:
16300: =item *
16301:
16302: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
16303:
16304: =item *
16305:
16306: is_course($courseid), is_course($cdom, $cnum)
16307:
16308: Accepts either a combined $courseid (in the form of domain_courseid) or the
16309: two component version $cdom, $cnum. It checks if the specified course exists.
16310:
16311: Returns:
16312: undef if the course doesn't exist, otherwise
16313: in scalar context the combined courseid.
16314: in list context the two components of the course identifier, domain and
16315: courseid.
16316:
16317: =back
16318:
16319: =head2 Bubblesheet Configuration
16320:
16321: =over 4
16322:
16323: =item *
16324:
16325: get_scantron_config($which)
16326:
16327: $which - the name of the configuration to parse from the file.
16328:
16329: Parses and returns the bubblesheet configuration line selected as a
16330: hash of configuration file fields.
16331:
16332:
16333: Returns:
16334: If the named configuration is not in the file, an empty
16335: hash is returned.
16336:
16337: a hash with the fields
16338: name - internal name for the this configuration setup
16339: description - text to display to operator that describes this config
16340: CODElocation - if 0 or the string 'none'
16341: - no CODE exists for this config
16342: if -1 || the string 'letter'
16343: - a CODE exists for this config and is
16344: a string of letters
16345: Unsupported value (but planned for future support)
16346: if a positive integer
16347: - The CODE exists as the first n items from
16348: the question section of the form
16349: if the string 'number'
16350: - The CODE exists for this config and is
16351: a string of numbers
16352: CODEstart - (only matter if a CODE exists) column in the line where
16353: the CODE starts
16354: CODElength - length of the CODE
16355: IDstart - column where the student/employee ID starts
16356: IDlength - length of the student/employee ID info
16357: Qstart - column where the information from the bubbled
16358: 'questions' start
16359: Qlength - number of columns comprising a single bubble line from
16360: the sheet. (usually either 1 or 10)
16361: Qon - either a single character representing the character used
16362: to signal a bubble was chosen in the positional setup, or
16363: the string 'letter' if the letter of the chosen bubble is
16364: in the final, or 'number' if a number representing the
16365: chosen bubble is in the file (1->A 0->J)
16366: Qoff - the character used to represent that a bubble was
16367: left blank
16368: PaperID - if the scanning process generates a unique number for each
16369: sheet scanned the column that this ID number starts in
16370: PaperIDlength - number of columns that comprise the unique ID number
16371: for the sheet of paper
16372: FirstName - column that the first name starts in
16373: FirstNameLength - number of columns that the first name spans
16374: LastName - column that the last name starts in
16375: LastNameLength - number of columns that the last name spans
16376: BubblesPerRow - number of bubbles available in each row used to
16377: bubble an answer. (If not specified, 10 assumed).
16378:
16379:
16380: =item *
16381:
16382: get_scantronformat_file($cdom)
16383:
16384: $cdom - the course's domain (optional); if not supplied, uses
16385: domain for current $env{'request.course.id'}.
16386:
16387: Returns an array containing lines from the scantron format file for
16388: the domain of the course.
16389:
16390: If a url for a custom.tab file is listed in domain's configuration.db,
16391: lines are from this file.
16392:
16393: Otherwise, if a default.tab has been published in RES space by the
16394: domainconfig user, lines are from this file.
16395:
16396: Otherwise, fall back to getting lines from the legacy file on the
16397: local server: /home/httpd/lonTabs/default_scantronformat.tab
16398:
16399: =back
16400:
16401: =head2 Resource Subroutines
16402:
16403: =over 4
16404:
16405: =item *
16406:
16407: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
16408:
16409: =item *
16410:
16411: repcopy($filename) : subscribes to the requested file, and attempts to
16412: replicate from the owning library server, Might return
16413: 'unavailable', 'not_found', 'forbidden', 'ok', or
16414: 'bad_request', also attempts to grab the metadata for the
16415: resource. Expects the local filesystem pathname
16416: (/home/httpd/html/res/....)
16417:
16418: =back
16419:
16420: =head2 Resource Information
16421:
16422: =over 4
16423:
16424: =item *
16425:
16426: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
16427: and returns the value of a variety of different possible values,
16428: $varname should be a request string, and the other parameters can be
16429: used to specify who and what one is asking about. Ordinarily, $cid
16430: does not need to be specified, as it is retrived from
16431: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
16432: within lonuserstate::loadmap() when initializing a course, before
16433: $env{'request.course.id'} has been set, so it needs to be provided
16434: in that one case.
16435:
16436: Possible values for $varname are environment.lastname (or other item
16437: from the envirnment hash), user.name (or someother aspect about the
16438: user), resource.0.maxtries (or some other part and parameter of a
16439: resource)
16440:
16441: =item *
16442:
16443: directcondval($number) : get current value of a condition; reads from a state
16444: string
16445:
16446: =item *
16447:
16448: condval($condidx) : value of condition index based on state
16449:
16450: =item *
16451:
16452: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
16453: resource's metadata, $what should be either a specific key, or either
16454: 'keys' (to get a list of possible keys) or 'packages' to get a list of
16455: packages that this resource currently uses, the last 3 arguments are
16456: only used internally for recursive metadata.
16457:
16458: the toolsymb is only used where the uri is for an external tool (for which
16459: the uri as well as the symb are guaranteed to be unique).
16460:
16461: this function automatically caches all requests except any made recursively
16462: to retrieve a list of metadata keys for an imported library file ($liburi is
16463: defined).
16464:
16465: =item *
16466:
16467: metadata_query($query,$custom,$customshow) : make a metadata query against the
16468: network of library servers; returns file handle of where SQL and regex results
16469: will be stored for query
16470:
16471: =item *
16472:
16473: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
16474: return symbolic list entry (all arguments optional).
16475:
16476: Args: filename is the filename (including path) for the file for which a symb
16477: is required; donotrecurse, if true will prevent calls to allowed() being made
16478: to check access status if more than one resource was found in the bighash
16479: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
16480: a randompick); ignorecachednull, if true will prevent a symb of '' being
16481: returned if $env{$cache_str} is defined as ''; checkforblock if true will
16482: cause possible symbs to be checked to determine if they are subject to content
16483: blocking, if so they will not be included as possible symbs; possibles is a
16484: ref to a hash, which, as a side effect, will be populated with all possible
16485: symbs (content blocking not tested).
16486:
16487: returns the data handle
16488:
16489: =item *
16490:
16491: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
16492: and is a possible symb for the URL in $thisfn, and if is an encrypted
16493: resource that the user accessed using /enc/ returns a 1 on success, 0
16494: on failure, user must be in a course, as it assumes the existence of
16495: the course initial hash, and uses $env('request.course.id'}. The third
16496: arg is an optional reference to a scalar. If this arg is passed in the
16497: call to symbverify, it will be set to 1 if the symb has been set to be
16498: encrypted; otherwise it will be null.
16499:
16500: =item *
16501:
16502: symbclean($symb) : removes versions numbers from a symb, returns the
16503: cleaned symb
16504:
16505: =item *
16506:
16507: is_on_map($uri) : checks if the $uri is somewhere on the current
16508: course map, user must be in a course for it to work.
16509:
16510: =item *
16511:
16512: numval($salt) : return random seed value (addend for rndseed)
16513:
16514: =item *
16515:
16516: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
16517: a random seed, all arguments are optional, if they aren't sent it uses the
16518: environment to derive them. Note: if symb isn't sent and it can't get one
16519: from &symbread it will use the current time as its return value
16520:
16521: =item *
16522:
16523: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
16524: unfakeable, receipt
16525:
16526: =item *
16527:
16528: receipt() : API to ireceipt working off of env values; given out to users
16529:
16530: =item *
16531:
16532: countacc($url) : count the number of accesses to a given URL
16533:
16534: =item *
16535:
16536: 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
16537:
16538: =item *
16539:
16540: 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)
16541:
16542: =item *
16543:
16544: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
16545:
16546: =item *
16547:
16548: devalidate($symb) : devalidate temporary spreadsheet calculations,
16549: forcing spreadsheet to reevaluate the resource scores next time.
16550:
16551: =item *
16552:
16553: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
16554: when viewing in course context.
16555:
16556: input: six args -- filename (decluttered), course number, course domain,
16557: url, symb (if registered) and group (if this is a
16558: group item -- e.g., bulletin board, group page etc.).
16559:
16560: output: array of five scalars --
16561: $cfile -- url for file editing if editable on current server
16562: $home -- homeserver of resource (i.e., for author if published,
16563: or course if uploaded.).
16564: $switchserver -- 1 if server switch will be needed.
16565: $forceedit -- 1 if icon/link should be to go to edit mode
16566: $forceview -- 1 if icon/link should be to go to view mode
16567:
16568: =item *
16569:
16570: is_course_upload($file,$cnum,$cdom)
16571:
16572: Used in course context to determine if current file was uploaded to
16573: the course (i.e., would be found in /userfiles/docs on the course's
16574: homeserver.
16575:
16576: input: 3 args -- filename (decluttered), course number and course domain.
16577: output: boolean -- 1 if file was uploaded.
16578:
16579: =back
16580:
16581: =head2 Storing/Retreiving Data
16582:
16583: =over 4
16584:
16585: =item *
16586:
16587: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
16588: permanently for this url; hashref needs to be given and should be a \%hashname;
16589: the remaining args aren't required and if they aren't passed or are '' they will
16590: be derived from the env (with the exception of $laststore, which is an
16591: optional arg used when a user's submission is stored in grading).
16592: $laststore is $version=$timestamp, where $version is the most recent version
16593: number retrieved for the corresponding $symb in the $namespace db file, and
16594: $timestamp is the timestamp for that transaction (UNIX time).
16595: $laststore is currently only passed when cstore() is called by
16596: structuretags::finalize_storage().
16597:
16598: =item *
16599:
16600: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
16601: but uses critical subroutine
16602:
16603: =item *
16604:
16605: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
16606: all args are optional
16607:
16608: =item *
16609:
16610: dumpstore($namespace,$udom,$uname,$regexp,$range) :
16611: dumps the complete (or key matching regexp) namespace into a hash
16612: ($udom, $uname, $regexp, $range are optional) for a namespace that is
16613: normally &store()ed into
16614:
16615: $range should be either an integer '100' (give me the first 100
16616: matching records)
16617: or be two integers sperated by a - with no spaces
16618: '30-50' (give me the 30th through the 50th matching
16619: records)
16620:
16621:
16622: =item *
16623:
16624: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
16625: replaces a &store() version of data with a replacement set of data
16626: for a particular resource in a namespace passed in the $storehash hash
16627: reference. If $tolog is true, the transaction is logged in the courselog
16628: with an action=PUTSTORE.
16629:
16630: =item *
16631:
16632: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
16633: works very similar to store/cstore, but all data is stored in a
16634: temporary location and can be reset using tmpreset, $storehash should
16635: be a hash reference, returns nothing on success
16636:
16637: =item *
16638:
16639: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
16640: similar to restore, but all data is stored in a temporary location and
16641: can be reset using tmpreset. Returns a hash of values on success,
16642: error string otherwise.
16643:
16644: =item *
16645:
16646: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
16647: deltes all keys for $symb form the temporary storage hash.
16648:
16649: =item *
16650:
16651: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16652: reference filled in from namesp ($udom and $uname are optional)
16653:
16654: =item *
16655:
16656: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
16657: namesp ($udom and $uname are optional)
16658:
16659: =item *
16660:
16661: dump($namespace,$udom,$uname,$regexp,$range) :
16662: dumps the complete (or key matching regexp) namespace into a hash
16663: ($udom, $uname, $regexp, $range are optional)
16664:
16665: $range should be either an integer '100' (give me the first 100
16666: matching records)
16667: or be two integers sperated by a - with no spaces
16668: '30-50' (give me the 30th through the 50th matching
16669: records)
16670: =item *
16671:
16672: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
16673: $store can be a scalar, an array reference, or if the amount to be
16674: incremented is > 1, a hash reference.
16675:
16676: ($udom and $uname are optional)
16677:
16678: =item *
16679:
16680: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
16681: ($udom and $uname are optional)
16682:
16683: =item *
16684:
16685: cput($namespace,$storehash,$udom,$uname) : critical put
16686: ($udom and $uname are optional)
16687:
16688: =item *
16689:
16690: newput($namespace,$storehash,$udom,$uname) :
16691:
16692: Attempts to store the items in the $storehash, but only if they don't
16693: currently exist, if this succeeds you can be certain that you have
16694: successfully created a new key value pair in the $namespace db.
16695:
16696:
16697: Args:
16698: $namespace: name of database to store values to
16699: $storehash: hashref to store to the db
16700: $udom: (optional) domain of user containing the db
16701: $uname: (optional) name of user caontaining the db
16702:
16703: Returns:
16704: 'ok' -> succeeded in storing all keys of $storehash
16705: 'key_exists: <key>' -> failed to anything out of $storehash, as at
16706: least <key> already existed in the db (other
16707: requested keys may also already exist)
16708: 'error: <msg>' -> unable to tie the DB or other error occurred
16709: 'con_lost' -> unable to contact request server
16710: 'refused' -> action was not allowed by remote machine
16711:
16712:
16713: =item *
16714:
16715: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16716: reference filled in from namesp (encrypts the return communication)
16717: ($udom and $uname are optional)
16718:
16719: =item *
16720:
16721: log($udom,$name,$home,$message) : write to permanent log for user; use
16722: critical subroutine
16723:
16724: =item *
16725:
16726: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
16727: array reference filled in from namespace found in domain level on either
16728: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
16729:
16730: =item *
16731:
16732: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
16733: domain level either on specified domain server ($uhome) or primary domain
16734: server ($udom and $uhome are optional)
16735:
16736: =item *
16737:
16738: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
16739: for: authentication, language, quotas, timezone, date locale, and portal URL in
16740: the target domain.
16741:
16742: May also include additional key => value pairs for the following groups:
16743:
16744: =over
16745:
16746: =item
16747: disk quotas (MB allocated by default to portfolios and authoring spaces).
16748:
16749: =over
16750:
16751: =item defaultquota, authorquota
16752:
16753: =back
16754:
16755: =item
16756: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
16757: portfolio for users).
16758:
16759: =over
16760:
16761: =item
16762: aboutme, blog, webdav, portfolio
16763:
16764: =back
16765:
16766: =item
16767: requestcourses: ability to request courses, and how requests are processed.
16768:
16769: =over
16770:
16771: =item
16772: official, unofficial, community, textbook, placement
16773:
16774: =back
16775:
16776: =item
16777: inststatus: types of institutional affiliation, and order in which they are displayed.
16778:
16779: =over
16780:
16781: =item
16782: inststatustypes, inststatusorder, inststatusguest
16783:
16784: =back
16785:
16786: =item
16787: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
16788: for course's uploaded content.
16789:
16790: =over
16791:
16792: =item
16793: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
16794: communityquota, textbookquota, placementquota
16795:
16796: =back
16797:
16798: =item
16799: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16800: on your servers.
16801:
16802: =over
16803:
16804: =item
16805: remotesessions, hostedsessions
16806:
16807: =back
16808:
16809: =back
16810:
16811: In cases where a domain coordinator has never used the "Set Domain Configuration"
16812: utility to create a configuration.db file on a domain's primary library server
16813: only the following domain defaults: auth_def, auth_arg_def, lang_def
16814: -- corresponding values are authentication type (internal, krb4, krb5,
16815: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
16816: will be available. Values are retrieved from cache (if current), unless the
16817: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16818: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16819:
16820: Typical usage:
16821:
16822: %domdefaults = &get_domain_defaults($target_domain);
16823:
16824: =back
16825:
16826: =head2 Network Status Functions
16827:
16828: =over 4
16829:
16830: =item *
16831:
16832: dirlist() : return directory list based on URI (first arg).
16833:
16834: Inputs: 1 required, 5 optional.
16835:
16836: =over
16837:
16838: =item
16839: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16840:
16841: =item
16842: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
16843:
16844: =item
16845: $username - username of user/course to be listed. Extracted from $uri if absent.
16846:
16847: =item
16848: $getpropath - boolean: 1 if prepend path using &propath().
16849:
16850: =item
16851: $getuserdir - boolean: 1 if prepend path for "userfiles".
16852:
16853: =item
16854: $alternateRoot - path to prepend in place of path from $uri.
16855:
16856: =back
16857:
16858: Returns: Array of up to two items.
16859:
16860: =over
16861:
16862: a reference to an array of files/subdirectories
16863:
16864: =over
16865:
16866: Each element in the array of files/subdirectories is a & separated list of
16867: item name and the result of running stat on the item. If dirlist was requested
16868: for a file instead of a directory, the item name will be ''. For a directory
16869: listing, if the item is a metadata file, the element will end &N&M
16870: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
16871: default copyright set (1).
16872:
16873: =back
16874:
16875: a scalar containing error condition (if encountered).
16876:
16877: =over
16878:
16879: =item
16880: no_host (no homeserver identified for $username:$domain).
16881:
16882: =item
16883: no_such_host (server contacted for listing not identified as valid host).
16884:
16885: =item
16886: con_lost (connection to remote server failed).
16887:
16888: =item
16889: refused (invalid $username:$domain received on lond side).
16890:
16891: =item
16892: no_such_dir (directory at specified path on lond side does not exist).
16893:
16894: =item
16895: empty (directory at specified path on lond side is empty).
16896:
16897: =over
16898:
16899: This is currently not encountered because the &ls3, &ls2,
16900: &ls (_handler) routines on the lond side do not filter out
16901: . and .. from a directory listing.
16902:
16903: =back
16904:
16905: =back
16906:
16907: =back
16908:
16909: =item *
16910:
16911: spareserver() : find server with least workload from spare.tab
16912:
16913:
16914: =item *
16915:
16916: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
16917: if there is no corresponding loncapa host.
16918:
16919: =back
16920:
16921:
16922: =head2 Apache Request
16923:
16924: =over 4
16925:
16926: =item *
16927:
16928: ssi($url,%hash) : server side include, does a complete request cycle on url to
16929: localhost, posts hash
16930:
16931: =back
16932:
16933: =head2 Data to String to Data
16934:
16935: =over 4
16936:
16937: =item *
16938:
16939: hash2str(%hash) : convert a hash into a string complete with escaping and '='
16940: and '&' separators, supports elements that are arrayrefs and hashrefs
16941:
16942: =item *
16943:
16944: hashref2str($hashref) : convert a hashref into a string complete with
16945: escaping and '=' and '&' separators, supports elements that are
16946: arrayrefs and hashrefs
16947:
16948: =item *
16949:
16950: arrayref2str($arrayref) : convert an arrayref into a string complete
16951: with escaping and '&' separators, supports elements that are arrayrefs
16952: and hashrefs
16953:
16954: =item *
16955:
16956: str2hash($string) : convert string to hash using unescaping and
16957: splitting on '=' and '&', supports elements that are arrayrefs and
16958: hashrefs
16959:
16960: =item *
16961:
16962: str2array($string) : convert string to hash using unescaping and
16963: splitting on '&', supports elements that are arrayrefs and hashrefs
16964:
16965: =back
16966:
16967: =head2 Logging Routines
16968:
16969:
16970: These routines allow one to make log messages in the lonnet.log and
16971: lonnet.perm logfiles.
16972:
16973: =over 4
16974:
16975: =item *
16976:
16977: logtouch() : make sure the logfile, lonnet.log, exists
16978:
16979: =item *
16980:
16981: logthis() : append message to the normal lonnet.log file, it gets
16982: preiodically rolled over and deleted.
16983:
16984: =item *
16985:
16986: logperm() : append a permanent message to lonnet.perm.log, this log
16987: file never gets deleted by any automated portion of the system, only
16988: messages of critical importance should go in here.
16989:
16990:
16991: =back
16992:
16993: =head2 General File Helper Routines
16994:
16995: =over 4
16996:
16997: =item *
16998:
16999: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
17000: (a) files in /uploaded
17001: (i) If a local copy of the file exists -
17002: compares modification date of local copy with last-modified date for
17003: definitive version stored on home server for course. If local copy is
17004: stale, requests a new version from the home server and stores it.
17005: If the original has been removed from the home server, then local copy
17006: is unlinked.
17007: (ii) If local copy does not exist -
17008: requests the file from the home server and stores it.
17009:
17010: If $caller is 'uploadrep':
17011: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
17012: for request for files originally uploaded via DOCS.
17013: - returns 'ok' if fresh local copy now available, -1 otherwise.
17014:
17015: Otherwise:
17016: This indicates a call from the content generation phase of the request.
17017: - returns the entire contents of the file or -1.
17018:
17019: (b) files in /res
17020: - returns the entire contents of a file or -1;
17021: it properly subscribes to and replicates the file if neccessary.
17022:
17023:
17024: =item *
17025:
17026: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
17027: reference
17028:
17029: returns either a stat() list of data about the file or an empty list
17030: if the file doesn't exist or couldn't find out about it (connection
17031: problems or user unknown)
17032:
17033: =item *
17034:
17035: filelocation($dir,$file) : returns file system location of a file
17036: based on URI; meant to be "fairly clean" absolute reference, $dir is a
17037: directory that relative $file lookups are to looked in ($dir of /a/dir
17038: and a file of ../bob will become /a/bob)
17039:
17040: =item *
17041:
17042: hreflocation($dir,$file) : returns file system location or a URL; same as
17043: filelocation except for hrefs
17044:
17045: =item *
17046:
17047: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
17048: also removes beginning /home/httpd/html unless /priv/ follows it.
17049:
17050: =back
17051:
17052: =head2 Usererfile file routines (/uploaded*)
17053:
17054: =over 4
17055:
17056: =item *
17057:
17058: userfileupload(): main rotine for putting a file in a user or course's
17059: filespace, arguments are,
17060:
17061: formname - required - this is the name of the element in $env where the
17062: filename, and the contents of the file to create/modifed exist
17063: the filename is in $env{'form.'.$formname.'.filename'} and the
17064: contents of the file is located in $env{'form.'.$formname}
17065: context - if coursedoc, store the file in the course of the active role
17066: of the current user;
17067: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
17068: if 'canceloverwrite': delete file in tmp/overwrites directory
17069: subdir - required - subdirectory to put the file in under ../userfiles/
17070: if undefined, it will be placed in "unknown"
17071:
17072: (This routine calls clean_filename() to remove any dangerous
17073: characters from the filename, and then calls finuserfileupload() to
17074: complete the transaction)
17075:
17076: returns either the url of the uploaded file (/uploaded/....) if successful
17077: and /adm/notfound.html if unsuccessful
17078:
17079: =item *
17080:
17081: clean_filename(): routine for cleaing a filename up for storage in
17082: userfile space, argument is:
17083:
17084: filename - proposed filename
17085:
17086: returns: the new clean filename
17087:
17088: =item *
17089:
17090: finishuserfileupload(): routine that creates and sends the file to
17091: userspace, probably shouldn't be called directly
17092:
17093: docuname: username or courseid of destination for the file
17094: docudom: domain of user/course of destination for the file
17095: formname: same as for userfileupload()
17096: fname: filename (including subdirectories) for the file
17097: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
17098: if hashref, and context is scantron, will convert csv format to standard format
17099: allfiles: reference to hash used to store objects found by parser
17100: codebase: reference to hash used for codebases of java objects found by parser
17101: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
17102: thumbheight: height (pixels) of thumbnail to be created for uploaded image
17103: resizewidth: width to be used to resize image using resizeImage from ImageMagick
17104: resizeheight: height to be used to resize image using resizeImage from ImageMagick
17105: context: if 'overwrite', will move the uploaded file from its temporary location to
17106: userfiles to facilitate overwriting a previously uploaded file with same name.
17107: mimetype: reference to scalar to accommodate mime type determined
17108: from File::MMagic if $parser = parse.
17109:
17110: returns either the url of the uploaded file (/uploaded/....) if successful
17111: and /adm/notfound.html if unsuccessful (or an error message if context
17112: was 'overwrite').
17113:
17114:
17115: =item *
17116:
17117: renameuserfile(): renames an existing userfile to a new name
17118:
17119: Args:
17120: docuname: username or courseid of destination for the file
17121: docudom: domain of user/course of destination for the file
17122: old: current file name (including any subdirs under userfiles)
17123: new: desired file name (including any subdirs under userfiles)
17124:
17125: =item *
17126:
17127: mkdiruserfile(): creates a directory is a userfiles dir
17128:
17129: Args:
17130: docuname: username or courseid of destination for the file
17131: docudom: domain of user/course of destination for the file
17132: dir: dir to create (including any subdirs under userfiles)
17133:
17134: =item *
17135:
17136: removeuserfile(): removes a file that exists in userfiles
17137:
17138: Args:
17139: docuname: username or courseid of destination for the file
17140: docudom: domain of user/course of destination for the file
17141: fname: filname to delete (including any subdirs under userfiles)
17142:
17143: =item *
17144:
17145: removeuploadedurl(): convience function for removeuserfile()
17146:
17147: Args:
17148: url: a full /uploaded/... url to delete
17149:
17150: =item *
17151:
17152: get_portfile_permissions():
17153: Args:
17154: domain: domain of user or course contain the portfolio files
17155: user: name of user or num of course contain the portfolio files
17156: Returns:
17157: hashref of a dump of the proper file_permissions.db
17158:
17159:
17160: =item *
17161:
17162: get_access_controls():
17163:
17164: Args:
17165: current_permissions: the hash ref returned from get_portfile_permissions()
17166: group: (optional) the group you want the files associated with
17167: file: (optional) the file you want access info on
17168:
17169: Returns:
17170: a hash (keys are file names) of hashes containing
17171: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
17172: values are XML containing access control settings (see below)
17173:
17174: Internal notes:
17175:
17176: access controls are stored in file_permissions.db as key=value pairs.
17177: key -> path to file/file_name\0uniqueID:scope_end_start
17178: where scope -> public,guest,course,group,domains or users.
17179: end -> UNIX time for end of access (0 -> no end date)
17180: start -> UNIX time for start of access
17181:
17182: value -> XML description of access control
17183: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
17184: <start></start>
17185: <end></end>
17186:
17187: <password></password> for scope type = guest
17188:
17189: <domain></domain> for scope type = course or group
17190: <number></number>
17191: <roles id="">
17192: <role></role>
17193: <access></access>
17194: <section></section>
17195: <group></group>
17196: </roles>
17197:
17198: <dom></dom> for scope type = domains
17199:
17200: <users> for scope type = users
17201: <user>
17202: <uname></uname>
17203: <udom></udom>
17204: </user>
17205: </users>
17206: </scope>
17207:
17208: Access data is also aggregated for each file in an additional key=value pair:
17209: key -> path to file/file_name\0accesscontrol
17210: value -> reference to hash
17211: hash contains key = value pairs
17212: where key = uniqueID:scope_end_start
17213: value = UNIX time record was last updated
17214:
17215: Used to improve speed of look-ups of access controls for each file.
17216:
17217: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
17218:
17219: =item *
17220:
17221: modify_access_controls():
17222:
17223: Modifies access controls for a portfolio file
17224: Args
17225: 1. file name
17226: 2. reference to hash of required changes,
17227: 3. domain
17228: 4. username
17229: where domain,username are the domain of the portfolio owner
17230: (either a user or a course)
17231:
17232: Returns:
17233: 1. result of additions or updates ('ok' or 'error', with error message).
17234: 2. result of deletions ('ok' or 'error', with error message).
17235: 3. reference to hash of any new or updated access controls.
17236: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
17237: key = integer (inbound ID)
17238: value = uniqueID
17239:
17240: =item *
17241:
17242: get_timebased_id():
17243:
17244: Attempts to get a unique timestamp-based suffix for use with items added to a
17245: course via the Course Editor (e.g., folders, composite pages,
17246: group bulletin boards).
17247:
17248: Args: (first three required; six others optional)
17249:
17250: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
17251: docssequence, or name of group
17252:
17253: 2. keyid (alphanumeric): name of temporary locking key in hash,
17254: e.g., num, boardids
17255:
17256: 3. namespace: name of gdbm file used to store suffixes already assigned;
17257: file will be named nohist_namespace.db
17258:
17259: 4. cdom: domain of course; default is current course domain from %env
17260:
17261: 5. cnum: course number; default is current course number from %env
17262:
17263: 6. idtype: set to concat if an additional digit is to be appended to the
17264: unix timestamp to form the suffix, if the plain timestamp is already
17265: in use. Default is to not do this, but simply increment the unix
17266: timestamp by 1 until a unique key is obtained.
17267:
17268: 7. who: holder of locking key; defaults to user:domain for user.
17269:
17270: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
17271: retrying); default is 3.
17272:
17273: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
17274:
17275: Returns:
17276:
17277: 1. suffix obtained (numeric)
17278:
17279: 2. result of deleting locking key (ok if deleted, or lock never obtained)
17280:
17281: 3. error: contains (localized) error message if an error occurred.
17282:
17283:
17284: =back
17285:
17286: =head2 HTTP Helper Routines
17287:
17288: =over 4
17289:
17290: =item *
17291:
17292: escape() : unpack non-word characters into CGI-compatible hex codes
17293:
17294: =item *
17295:
17296: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
17297:
17298: =back
17299:
17300: =head1 PRIVATE SUBROUTINES
17301:
17302: =head2 Underlying communication routines (Shouldn't call)
17303:
17304: =over 4
17305:
17306: =item *
17307:
17308: subreply() : tries to pass a message to lonc, returns con_lost if incapable
17309:
17310: =item *
17311:
17312: reply() : uses subreply to send a message to remote machine, logs all failures
17313:
17314: =item *
17315:
17316: critical() : passes a critical message to another server; if cannot
17317: get through then place message in connection buffer directory and
17318: returns con_delayed, if incapable of saving message, returns
17319: con_failed
17320:
17321: =item *
17322:
17323: reconlonc() : tries to reconnect lonc client processes.
17324:
17325: =back
17326:
17327: =head2 Resource Access Logging
17328:
17329: =over 4
17330:
17331: =item *
17332:
17333: flushcourselogs() : flush (save) buffer logs and access logs
17334:
17335: =item *
17336:
17337: courselog($what) : save message for course in hash
17338:
17339: =item *
17340:
17341: courseacclog($what) : save message for course using &courselog(). Perform
17342: special processing for specific resource types (problems, exams, quizzes, etc).
17343:
17344: =item *
17345:
17346: goodbye() : flush course logs and log shutting down; it is called in srm.conf
17347: as a PerlChildExitHandler
17348:
17349: =back
17350:
17351: =head2 Other
17352:
17353: =over 4
17354:
17355: =item *
17356:
17357: symblist($mapname,%newhash) : update symbolic storage links
17358:
17359: =back
17360:
17361: =cut
17362:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>