1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.1431 2020/10/22 19:23:23 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 LONCAPA qw(:DEFAULT :match);
100: use LONCAPA::Configuration;
101: use LONCAPA::lonmetadata;
102: use LONCAPA::Lond;
103: use LONCAPA::LWPReq;
104: use LONCAPA::transliterate;
105:
106: use File::Copy;
107:
108: my $readit;
109: my $max_connection_retries = 20; # Or some such value.
110:
111: require Exporter;
112:
113: our @ISA = qw (Exporter);
114: our @EXPORT = qw(%env);
115:
116:
117: # ------------------------------------ Logging (parameters, docs, slots, roles)
118: {
119: my $logid;
120: sub write_log {
121: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
122: if ($context eq 'course') {
123: if (($cnum eq '') || ($cdom eq '')) {
124: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
125: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
126: }
127: }
128: $logid ++;
129: my $now = time();
130: my $id=$now.'00000'.$$.'00000'.$logid;
131: my $logentry = {
132: $id => {
133: 'exe_uname' => $env{'user.name'},
134: 'exe_udom' => $env{'user.domain'},
135: 'exe_time' => $now,
136: 'exe_ip' => $ENV{'REMOTE_ADDR'},
137: 'delflag' => $delflag,
138: 'logentry' => $storehash,
139: 'uname' => $uname,
140: 'udom' => $udom,
141: }
142: };
143: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
144: }
145: }
146:
147: sub logtouch {
148: my $execdir=$perlvar{'lonDaemons'};
149: unless (-e "$execdir/logs/lonnet.log") {
150: open(my $fh,">>","$execdir/logs/lonnet.log");
151: close $fh;
152: }
153: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
154: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
155: }
156:
157: sub logthis {
158: my $message=shift;
159: my $execdir=$perlvar{'lonDaemons'};
160: my $now=time;
161: my $local=localtime($now);
162: if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
163: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
164: print $fh $logstring;
165: close($fh);
166: }
167: return 1;
168: }
169:
170: sub logperm {
171: my $message=shift;
172: my $execdir=$perlvar{'lonDaemons'};
173: my $now=time;
174: my $local=localtime($now);
175: if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
176: print $fh "$now:$message:$local\n";
177: close($fh);
178: }
179: return 1;
180: }
181:
182: sub create_connection {
183: my ($hostname,$lonid) = @_;
184: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
185: Type => SOCK_STREAM,
186: Timeout => 10);
187: return 0 if (!$client);
188: print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
189: my $result = <$client>;
190: chomp($result);
191: return 1 if ($result eq 'done');
192: return 0;
193: }
194:
195: sub get_server_timezone {
196: my ($cnum,$cdom) = @_;
197: my $home=&homeserver($cnum,$cdom);
198: if ($home ne 'no_host') {
199: my $cachetime = 24*3600;
200: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
201: if (defined($cached)) {
202: return $timezone;
203: } else {
204: my $timezone = &reply('servertimezone',$home);
205: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
206: }
207: }
208: }
209:
210: sub get_server_distarch {
211: my ($lonhost,$ignore_cache) = @_;
212: if (defined($lonhost)) {
213: if (!defined(&hostname($lonhost))) {
214: return;
215: }
216: my $cachetime = 12*3600;
217: if (!$ignore_cache) {
218: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
219: if (defined($cached)) {
220: return $distarch;
221: }
222: }
223: my $rep = &reply('serverdistarch',$lonhost);
224: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
225: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
226: $rep eq '') {
227: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
228: }
229: }
230: return;
231: }
232:
233: sub get_servercerts_info {
234: my ($lonhost,$hostname,$context) = @_;
235: return if ($lonhost eq '');
236: if ($hostname eq '') {
237: $hostname = &hostname($lonhost);
238: }
239: return if ($hostname eq '');
240: my ($rep,$uselocal);
241: if ($context eq 'install') {
242: $uselocal = 1;
243: } elsif (grep { $_ eq $lonhost } ¤t_machine_ids()) {
244: $uselocal = 1;
245: }
246: if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
247: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
248: if ($distro eq '') {
249: $uselocal = 0;
250: } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
251: if ($1 < 6) {
252: $uselocal = 0;
253: }
254: } elsif ($distro =~ /^(?:sles)(\d+)$/) {
255: if ($1 < 12) {
256: $uselocal = 0;
257: }
258: }
259: }
260: if ($uselocal) {
261: $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
262: } else {
263: $rep=&reply('servercerts',$lonhost);
264: }
265: my ($result,%returnhash);
266: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
267: ($rep eq 'unknown_cmd')) {
268: $result = $rep;
269: } else {
270: $result = 'ok';
271: my @pairs=split(/\&/,$rep);
272: foreach my $item (@pairs) {
273: my ($key,$value)=split(/=/,$item,2);
274: my $what = &unescape($key);
275: $returnhash{$what}=&thaw_unescape($value);
276: }
277: }
278: return ($result,\%returnhash);
279: }
280:
281: sub get_server_loncaparev {
282: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
283: if (defined($lonhost)) {
284: if (!defined(&hostname($lonhost))) {
285: undef($lonhost);
286: }
287: }
288: if (!defined($lonhost)) {
289: if (defined(&domain($dom,'primary'))) {
290: $lonhost=&domain($dom,'primary');
291: if ($lonhost eq 'no_host') {
292: undef($lonhost);
293: }
294: }
295: }
296: if (defined($lonhost)) {
297: my $cachetime = 12*3600;
298: if (!$ignore_cache) {
299: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
300: if (defined($cached)) {
301: return $loncaparev;
302: }
303: }
304: my ($answer,$loncaparev);
305: my @ids=¤t_machine_ids();
306: if (grep(/^\Q$lonhost\E$/,@ids)) {
307: $answer = $perlvar{'lonVersion'};
308: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
309: $loncaparev = $1;
310: }
311: } else {
312: $answer = &reply('serverloncaparev',$lonhost);
313: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
314: if ($caller eq 'loncron') {
315: my $hostname = &hostname($lonhost);
316: my $protocol = $protocol{$lonhost};
317: $protocol = 'http' if ($protocol ne 'https');
318: my $url = $protocol.'://'.$hostname.'/adm/about.html';
319: my $request=new HTTP::Request('GET',$url);
320: my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
321: unless ($response->is_error()) {
322: my $content = $response->content;
323: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
324: $loncaparev = $1;
325: }
326: }
327: } else {
328: $loncaparev = $loncaparevs{$lonhost};
329: }
330: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
331: $loncaparev = $1;
332: }
333: }
334: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
335: }
336: }
337:
338: sub get_server_homeID {
339: my ($hostname,$ignore_cache,$caller) = @_;
340: unless ($ignore_cache) {
341: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
342: if (defined($cached)) {
343: return $serverhomeID;
344: }
345: }
346: my $cachetime = 12*3600;
347: my $serverhomeID;
348: if ($caller eq 'loncron') {
349: my @machine_ids = &machine_ids($hostname);
350: foreach my $id (@machine_ids) {
351: my $response = &reply('serverhomeID',$id);
352: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
353: $serverhomeID = $response;
354: last;
355: }
356: }
357: if ($serverhomeID eq '') {
358: $serverhomeID = $machine_ids[-1];
359: }
360: } else {
361: $serverhomeID = $serverhomeIDs{$hostname};
362: }
363: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
364: }
365:
366: sub get_remote_globals {
367: my ($lonhost,$whathash,$ignore_cache) = @_;
368: my ($result,%returnhash,%whatneeded);
369: if (ref($whathash) eq 'HASH') {
370: foreach my $what (sort(keys(%{$whathash}))) {
371: my $hashid = $lonhost.'-'.$what;
372: my ($response,$cached);
373: unless ($ignore_cache) {
374: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
375: }
376: if (defined($cached)) {
377: $returnhash{$what} = $response;
378: } else {
379: $whatneeded{$what} = 1;
380: }
381: }
382: if (keys(%whatneeded) == 0) {
383: $result = 'ok';
384: } else {
385: my $requested = &freeze_escape(\%whatneeded);
386: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
387: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
388: ($rep eq 'unknown_cmd')) {
389: $result = $rep;
390: } else {
391: $result = 'ok';
392: my @pairs=split(/\&/,$rep);
393: foreach my $item (@pairs) {
394: my ($key,$value)=split(/=/,$item,2);
395: my $what = &unescape($key);
396: my $hashid = $lonhost.'-'.$what;
397: $returnhash{$what}=&thaw_unescape($value);
398: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
399: }
400: }
401: }
402: }
403: return ($result,\%returnhash);
404: }
405:
406: sub remote_devalidate_cache {
407: my ($lonhost,$cachekeys) = @_;
408: my $items;
409: return unless (ref($cachekeys) eq 'ARRAY');
410: my $cachestr = join('&',@{$cachekeys});
411: my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
412: return $response;
413: }
414:
415: # -------------------------------------------------- Non-critical communication
416: sub subreply {
417: my ($cmd,$server)=@_;
418: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
419: #
420: # With loncnew process trimming, there's a timing hole between lonc server
421: # process exit and the master server picking up the listen on the AF_UNIX
422: # socket. In that time interval, a lock file will exist:
423:
424: my $lockfile=$peerfile.".lock";
425: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
426: sleep(0.1);
427: }
428: # At this point, either a loncnew parent is listening or an old lonc
429: # or loncnew child is listening so we can connect or everything's dead.
430: #
431: # We'll give the connection a few tries before abandoning it. If
432: # connection is not possible, we'll con_lost back to the client.
433: #
434: my $client;
435: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
436: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
437: Type => SOCK_STREAM,
438: Timeout => 10);
439: if ($client) {
440: last; # Connected!
441: } else {
442: &create_connection(&hostname($server),$server);
443: }
444: sleep(0.1); # Try again later if failed connection.
445: }
446: my $answer;
447: if ($client) {
448: print $client "sethost:$server:$cmd\n";
449: $answer=<$client>;
450: if (!$answer) { $answer="con_lost"; }
451: chomp($answer);
452: } else {
453: $answer = 'con_lost'; # Failed connection.
454: }
455: return $answer;
456: }
457:
458: sub reply {
459: my ($cmd,$server)=@_;
460: unless (defined(&hostname($server))) { return 'no_such_host'; }
461: my $answer=subreply($cmd,$server);
462: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
463: my $logged = $cmd;
464: if ($cmd =~ /^encrypt:([^:]+):/) {
465: my $subcmd = $1;
466: if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
467: ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
468: ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
469: (undef,undef,my @rest) = split(/:/,$cmd);
470: if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
471: splice(@rest,2,1,'Hidden');
472: } elsif ($subcmd eq 'passwd') {
473: splice(@rest,2,2,('Hidden','Hidden'));
474: } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
475: ($subcmd eq 'autoexportgrades')) {
476: splice(@rest,3,1,'Hidden');
477: }
478: $logged = join(':',('encrypt:'.$subcmd,@rest));
479: }
480: }
481: &logthis("<font color=\"blue\">WARNING:".
482: " $logged to $server returned $answer</font>");
483: }
484: return $answer;
485: }
486:
487: # ----------------------------------------------------------- Send USR1 to lonc
488:
489: sub reconlonc {
490: my ($lonid) = @_;
491: if ($lonid) {
492: my $hostname = &hostname($lonid);
493: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
494: if ($hostname && -e $peerfile) {
495: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
496: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
497: Type => SOCK_STREAM,
498: Timeout => 10);
499: if ($client) {
500: print $client ("reset_retries\n");
501: my $answer=<$client>;
502: #reset just this one.
503: }
504: }
505: return;
506: }
507:
508: &logthis("Trying to reconnect lonc");
509: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
510: if (open(my $fh,"<",$loncfile)) {
511: my $loncpid=<$fh>;
512: chomp($loncpid);
513: if (kill 0 => $loncpid) {
514: &logthis("lonc at pid $loncpid responding, sending USR1");
515: kill USR1 => $loncpid;
516: sleep 1;
517: } else {
518: &logthis(
519: "<font color=\"blue\">WARNING:".
520: " lonc at pid $loncpid not responding, giving up</font>");
521: }
522: } else {
523: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
524: }
525: }
526:
527: # ------------------------------------------------------ Critical communication
528:
529: sub critical {
530: my ($cmd,$server)=@_;
531: unless (&hostname($server)) {
532: &logthis("<font color=\"blue\">WARNING:".
533: " Critical message to unknown server ($server)</font>");
534: return 'no_such_host';
535: }
536: my $answer=reply($cmd,$server);
537: if ($answer eq 'con_lost') {
538: &reconlonc($server);
539: my $answer=reply($cmd,$server);
540: if ($answer eq 'con_lost') {
541: my $now=time;
542: my $middlename=$cmd;
543: $middlename=substr($middlename,0,16);
544: $middlename=~s/\W//g;
545: my $dfilename=
546: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
547: $dumpcount++;
548: {
549: my $dfh;
550: if (open($dfh,">",$dfilename)) {
551: print $dfh "$cmd\n";
552: close($dfh);
553: }
554: }
555: sleep 1;
556: my $wcmd='';
557: {
558: my $dfh;
559: if (open($dfh,"<",$dfilename)) {
560: $wcmd=<$dfh>;
561: close($dfh);
562: }
563: }
564: chomp($wcmd);
565: if ($wcmd eq $cmd) {
566: &logthis("<font color=\"blue\">WARNING: ".
567: "Connection buffer $dfilename: $cmd</font>");
568: &logperm("D:$server:$cmd");
569: return 'con_delayed';
570: } else {
571: &logthis("<font color=\"red\">CRITICAL:"
572: ." Critical connection failed: $server $cmd</font>");
573: &logperm("F:$server:$cmd");
574: return 'con_failed';
575: }
576: }
577: }
578: return $answer;
579: }
580:
581: # ------------------------------------------- check if return value is an error
582:
583: sub error {
584: my ($result) = @_;
585: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
586: if ($2 == 2) { return undef; }
587: return $1;
588: }
589: return undef;
590: }
591:
592: sub convert_and_load_session_env {
593: my ($lonidsdir,$handle)=@_;
594: my @profile;
595: {
596: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
597: if (!$opened) {
598: return 0;
599: }
600: flock($idf,LOCK_SH);
601: @profile=<$idf>;
602: close($idf);
603: }
604: my %temp_env;
605: foreach my $line (@profile) {
606: if ($line !~ m/=/) {
607: return 0;
608: }
609: chomp($line);
610: my ($envname,$envvalue)=split(/=/,$line,2);
611: $temp_env{&unescape($envname)} = &unescape($envvalue);
612: }
613: unlink("$lonidsdir/$handle.id");
614: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
615: 0640)) {
616: %disk_env = %temp_env;
617: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
618: untie(%disk_env);
619: }
620: return 1;
621: }
622:
623: # ------------------------------------------- Transfer profile into environment
624: my $env_loaded;
625: sub transfer_profile_to_env {
626: my ($lonidsdir,$handle,$force_transfer) = @_;
627: if (!$force_transfer && $env_loaded) { return; }
628:
629: if (!defined($lonidsdir)) {
630: $lonidsdir = $perlvar{'lonIDsDir'};
631: }
632: if (!defined($handle)) {
633: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
634: }
635:
636: my $convert;
637: {
638: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
639: if (!$opened) {
640: return;
641: }
642: flock($idf,LOCK_SH);
643: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
644: &GDBM_READER(),0640)) {
645: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
646: untie(%disk_env);
647: } else {
648: $convert = 1;
649: }
650: }
651: if ($convert) {
652: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
653: &logthis("Failed to load session, or convert session.");
654: }
655: }
656:
657: my %remove;
658: while ( my $envname = each(%env) ) {
659: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
660: if ($time < time-300) {
661: $remove{$key}++;
662: }
663: }
664: }
665:
666: $env{'user.environment'} = "$lonidsdir/$handle.id";
667: $env_loaded=1;
668: foreach my $expired_key (keys(%remove)) {
669: &delenv($expired_key);
670: }
671: }
672:
673: # ---------------------------------------------------- Check for valid session
674: sub check_for_valid_session {
675: my ($r,$name,$userhashref,$domref) = @_;
676: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
677: my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
678: if ($name eq 'lonDAV') {
679: $lonidsdir=$r->dir_config('lonDAVsessDir');
680: } else {
681: $lonidsdir=$r->dir_config('lonIDsDir');
682: if ($name eq '') {
683: $name = 'lonID';
684: }
685: }
686: if ($name eq 'lonID') {
687: $secure = 'lonSID';
688: $linkname = 'lonLinkID';
689: $pubname = 'lonPubID';
690: if (exists($cookies{$secure})) {
691: $lonid=$cookies{$secure};
692: } elsif (exists($cookies{$name})) {
693: $lonid=$cookies{$name};
694: } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
695: $lonid=$cookies{$linkname};
696: } elsif (exists($cookies{$pubname})) {
697: $lonid=$cookies{$pubname};
698: }
699: } else {
700: $lonid=$cookies{$name};
701: }
702: return undef if (!$lonid);
703:
704: my $handle=&LONCAPA::clean_handle($lonid->value);
705: if (-l "$lonidsdir/$handle.id") {
706: my $link = readlink("$lonidsdir/$handle.id");
707: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
708: $handle = $1;
709: }
710: }
711: if (!-e "$lonidsdir/$handle.id") {
712: if ((ref($domref)) && ($name eq 'lonID') &&
713: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
714: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
715: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
716: $$domref = $possudom;
717: }
718: }
719: return undef;
720: }
721:
722: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
723: return undef if (!$opened);
724:
725: flock($idf,LOCK_SH);
726: my %disk_env;
727: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
728: &GDBM_READER(),0640)) {
729: return undef;
730: }
731:
732: if (!defined($disk_env{'user.name'})
733: || !defined($disk_env{'user.domain'})) {
734: untie(%disk_env);
735: return undef;
736: }
737:
738: if (ref($userhashref) eq 'HASH') {
739: $userhashref->{'name'} = $disk_env{'user.name'};
740: $userhashref->{'domain'} = $disk_env{'user.domain'};
741: $userhashref->{'lti'} = $disk_env{'request.lti.login'};
742: if ($userhashref->{'lti'}) {
743: $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
744: $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
745: }
746: }
747: untie(%disk_env);
748:
749: return $handle;
750: }
751:
752: sub timed_flock {
753: my ($file,$lock_type) = @_;
754: my $failed=0;
755: eval {
756: local $SIG{__DIE__}='DEFAULT';
757: local $SIG{ALRM}=sub {
758: $failed=1;
759: die("failed lock");
760: };
761: alarm(13);
762: flock($file,$lock_type);
763: alarm(0);
764: };
765: if ($failed) {
766: return undef;
767: } else {
768: return 1;
769: }
770: }
771:
772: sub get_sessionfile_vars {
773: my ($handle,$lonidsdir,$storearr) = @_;
774: my %returnhash;
775: unless (ref($storearr) eq 'ARRAY') {
776: return %returnhash;
777: }
778: if (-l "$lonidsdir/$handle.id") {
779: my $link = readlink("$lonidsdir/$handle.id");
780: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
781: $handle = $1;
782: }
783: }
784: if ((-e "$lonidsdir/$handle.id") &&
785: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
786: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
787: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
788: if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
789: flock($idf,LOCK_SH);
790: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
791: &GDBM_READER(),0640)) {
792: foreach my $item (@{$storearr}) {
793: $returnhash{$item} = $disk_env{$item};
794: }
795: untie(%disk_env);
796: }
797: }
798: }
799: }
800: return %returnhash;
801: }
802:
803: # ---------------------------------------------------------- Append Environment
804:
805: sub appenv {
806: my ($newenv,$roles) = @_;
807: if (ref($newenv) eq 'HASH') {
808: foreach my $key (keys(%{$newenv})) {
809: my $refused = 0;
810: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
811: $refused = 1;
812: if (ref($roles) eq 'ARRAY') {
813: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
814: if (grep(/^\Q$role\E$/,@{$roles})) {
815: $refused = 0;
816: }
817: }
818: }
819: if ($refused) {
820: &logthis("<font color=\"blue\">WARNING: ".
821: "Attempt to modify environment ".$key." to ".$newenv->{$key}
822: .'</font>');
823: delete($newenv->{$key});
824: } else {
825: $env{$key}=$newenv->{$key};
826: }
827: }
828: my $lonids = $perlvar{'lonIDsDir'};
829: if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
830: my $opened = open(my $env_file,'+<',$env{'user.environment'});
831: if ($opened
832: && &timed_flock($env_file,LOCK_EX)
833: &&
834: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
835: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
836: while (my ($key,$value) = each(%{$newenv})) {
837: $disk_env{$key} = $value;
838: }
839: untie(%disk_env);
840: }
841: }
842: }
843: return 'ok';
844: }
845: # ----------------------------------------------------- Delete from Environment
846:
847: sub delenv {
848: my ($delthis,$regexp,$roles) = @_;
849: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
850: my $refused = 1;
851: if (ref($roles) eq 'ARRAY') {
852: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
853: if (grep(/^\Q$role\E$/,@{$roles})) {
854: $refused = 0;
855: }
856: }
857: if ($refused) {
858: &logthis("<font color=\"blue\">WARNING: ".
859: "Attempt to delete from environment ".$delthis);
860: return 'error';
861: }
862: }
863: my $opened = open(my $env_file,'+<',$env{'user.environment'});
864: if ($opened
865: && &timed_flock($env_file,LOCK_EX)
866: &&
867: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
868: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
869: foreach my $key (keys(%disk_env)) {
870: if ($regexp) {
871: if ($key=~/^$delthis/) {
872: delete($env{$key});
873: delete($disk_env{$key});
874: }
875: } else {
876: if ($key=~/^\Q$delthis\E/) {
877: delete($env{$key});
878: delete($disk_env{$key});
879: }
880: }
881: }
882: untie(%disk_env);
883: }
884: return 'ok';
885: }
886:
887: sub get_env_multiple {
888: my ($name) = @_;
889: my @values;
890: if (defined($env{$name})) {
891: # exists is it an array
892: if (ref($env{$name})) {
893: @values=@{ $env{$name} };
894: } else {
895: $values[0]=$env{$name};
896: }
897: }
898: return(@values);
899: }
900:
901: # ------------------------------------------------------------------- Locking
902:
903: sub set_lock {
904: my ($text)=@_;
905: $locknum++;
906: my $id=$$.'-'.$locknum;
907: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
908: 'session.lock.'.$id => $text});
909: return $id;
910: }
911:
912: sub get_locks {
913: my $num=0;
914: my %texts=();
915: foreach my $lock (split(/\,/,$env{'session.locks'})) {
916: if ($lock=~/\w/) {
917: $num++;
918: $texts{$lock}=$env{'session.lock.'.$lock};
919: }
920: }
921: return ($num,%texts);
922: }
923:
924: sub remove_lock {
925: my ($id)=@_;
926: my $newlocks='';
927: foreach my $lock (split(/\,/,$env{'session.locks'})) {
928: if (($lock=~/\w/) && ($lock ne $id)) {
929: $newlocks.=','.$lock;
930: }
931: }
932: &appenv({'session.locks' => $newlocks});
933: &delenv('session.lock.'.$id);
934: }
935:
936: sub remove_all_locks {
937: my $activelocks=$env{'session.locks'};
938: foreach my $lock (split(/\,/,$env{'session.locks'})) {
939: if ($lock=~/\w/) {
940: &remove_lock($lock);
941: }
942: }
943: }
944:
945:
946: # ------------------------------------------ Find out current server userload
947: sub userload {
948: my $numusers=0;
949: {
950: opendir(LONIDS,$perlvar{'lonIDsDir'});
951: my $filename;
952: my $curtime=time;
953: while ($filename=readdir(LONIDS)) {
954: next if ($filename eq '.' || $filename eq '..');
955: next if ($filename =~ /publicuser_\d+\.id/);
956: next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
957: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
958: if ($curtime-$mtime < 1800) { $numusers++; }
959: }
960: closedir(LONIDS);
961: }
962: my $userloadpercent=0;
963: my $maxuserload=$perlvar{'lonUserLoadLim'};
964: if ($maxuserload) {
965: $userloadpercent=100*$numusers/$maxuserload;
966: }
967: $userloadpercent=sprintf("%.2f",$userloadpercent);
968: return $userloadpercent;
969: }
970:
971: # ------------------------------ Find server with least workload from spare.tab
972:
973: sub spareserver {
974: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
975: my $spare_server;
976: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
977: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
978: : $userloadpercent;
979: my ($uint_dom,$remotesessions);
980: if (($udom ne '') && (&domain($udom) ne '')) {
981: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
982: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
983: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
984: $remotesessions = $udomdefaults{'remotesessions'};
985: }
986: my $spareshash = &this_host_spares($udom);
987: if (ref($spareshash) eq 'HASH') {
988: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
989: foreach my $try_server (@{ $spareshash->{'primary'} }) {
990: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
991: $try_server));
992: ($spare_server, $lowest_load) =
993: &compare_server_load($try_server, $spare_server, $lowest_load);
994: }
995: }
996:
997: my $found_server = ($spare_server ne '' && $lowest_load < 100);
998:
999: if (!$found_server) {
1000: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1001: foreach my $try_server (@{ $spareshash->{'default'} }) {
1002: next unless (&spare_can_host($udom,$uint_dom,
1003: $remotesessions,$try_server));
1004: ($spare_server, $lowest_load) =
1005: &compare_server_load($try_server, $spare_server, $lowest_load);
1006: }
1007: }
1008: }
1009: }
1010:
1011: if (!$want_server_name) {
1012: if (defined($spare_server)) {
1013: my $hostname = &hostname($spare_server);
1014: if (defined($hostname)) {
1015: my $protocol = 'http';
1016: if ($protocol{$spare_server} eq 'https') {
1017: $protocol = $protocol{$spare_server};
1018: }
1019: $spare_server = $protocol.'://'.$hostname;
1020: }
1021: }
1022: }
1023: return $spare_server;
1024: }
1025:
1026: sub compare_server_load {
1027: my ($try_server, $spare_server, $lowest_load, $required) = @_;
1028:
1029: if ($required) {
1030: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
1031: my $remoterev = &get_server_loncaparev(undef,$try_server);
1032: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
1033: if (($major eq '' && $minor eq '') ||
1034: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
1035: return ($spare_server,$lowest_load);
1036: }
1037: }
1038:
1039: my $loadans = &reply('load', $try_server);
1040: my $userloadans = &reply('userload',$try_server);
1041:
1042: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1043: return ($spare_server, $lowest_load); #didn't get a number from the server
1044: }
1045:
1046: my $load;
1047: if ($loadans =~ /\d/) {
1048: if ($userloadans =~ /\d/) {
1049: #both are numbers, pick the bigger one
1050: $load = ($loadans > $userloadans) ? $loadans
1051: : $userloadans;
1052: } else {
1053: $load = $loadans;
1054: }
1055: } else {
1056: $load = $userloadans;
1057: }
1058:
1059: if (($load =~ /\d/) && ($load < $lowest_load)) {
1060: $spare_server = $try_server;
1061: $lowest_load = $load;
1062: }
1063: return ($spare_server,$lowest_load);
1064: }
1065:
1066: # --------------------------- ask offload servers if user already has a session
1067: sub find_existing_session {
1068: my ($udom,$uname) = @_;
1069: my $spareshash = &this_host_spares($udom);
1070: if (ref($spareshash) eq 'HASH') {
1071: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
1072: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1073: return $try_server if (&has_user_session($try_server, $udom, $uname));
1074: }
1075: }
1076: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1077: foreach my $try_server (@{ $spareshash->{'default'} }) {
1078: return $try_server if (&has_user_session($try_server, $udom, $uname));
1079: }
1080: }
1081: }
1082: return;
1083: }
1084:
1085: sub delusersession {
1086: my ($lonid,$udom,$uname) = @_;
1087: my $uprimary_id = &domain($udom,'primary');
1088: my $uintdom = &internet_dom($uprimary_id);
1089: my $intdom = &internet_dom($lonid);
1090: my $serverhomedom = &host_domain($lonid);
1091: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1092: return &reply(join(':','delusersession',
1093: map {&escape($_)} ($udom,$uname)),$lonid);
1094: }
1095: return;
1096: }
1097:
1098: # check if user's browser sent load balancer cookie and server still has session
1099: # and is not overloaded.
1100: sub check_for_balancer_cookie {
1101: my ($r,$update_mtime) = @_;
1102: my ($otherserver,$cookie);
1103: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1104: if (exists($cookies{'balanceID'})) {
1105: my $balid = $cookies{'balanceID'};
1106: $cookie=&LONCAPA::clean_handle($balid->value);
1107: my $balancedir=$r->dir_config('lonBalanceDir');
1108: if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
1109: if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
1110: my ($possudom,$possuname) = ($1,$2);
1111: my $has_session = 0;
1112: if ((&domain($possudom) ne '') &&
1113: (&homeserver($possuname,$possudom) ne 'no_host')) {
1114: my $try_server;
1115: my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
1116: if ($opened) {
1117: flock($idf,LOCK_SH);
1118: while (my $line = <$idf>) {
1119: chomp($line);
1120: if (&hostname($line) ne '') {
1121: $try_server = $line;
1122: last;
1123: }
1124: }
1125: close($idf);
1126: if (($try_server) &&
1127: (&has_user_session($try_server,$possudom,$possuname))) {
1128: my $lowest_load = 30000;
1129: ($otherserver,$lowest_load) =
1130: &compare_server_load($try_server,undef,$lowest_load);
1131: if ($otherserver ne '' && $lowest_load < 100) {
1132: $has_session = 1;
1133: } else {
1134: undef($otherserver);
1135: }
1136: }
1137: }
1138: }
1139: if ($has_session) {
1140: if ($update_mtime) {
1141: my $atime = my $mtime = time;
1142: utime($atime,$mtime,"$balancedir/$cookie.id");
1143: }
1144: } else {
1145: unlink("$balancedir/$cookie.id");
1146: }
1147: }
1148: }
1149: }
1150: return ($otherserver,$cookie);
1151: }
1152:
1153: sub updatebalcookie {
1154: my ($cookie,$balancer,$lastentry)=@_;
1155: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1156: my ($udom,$uname) = ($1,$2);
1157: my $uprimary_id = &domain($udom,'primary');
1158: my $uintdom = &internet_dom($uprimary_id);
1159: my $intdom = &internet_dom($balancer);
1160: my $serverhomedom = &host_domain($balancer);
1161: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1162: return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
1163: }
1164: }
1165: return;
1166: }
1167:
1168: sub delbalcookie {
1169: my ($cookie,$balancer) =@_;
1170: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1171: my ($udom,$uname) = ($1,$2);
1172: my $uprimary_id = &domain($udom,'primary');
1173: my $uintdom = &internet_dom($uprimary_id);
1174: my $intdom = &internet_dom($balancer);
1175: my $serverhomedom = &host_domain($balancer);
1176: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1177: return &reply('delbalcookie:'.&escape($cookie),$balancer);
1178: }
1179: }
1180: }
1181:
1182: # -------------------------------- ask if server already has a session for user
1183: sub has_user_session {
1184: my ($lonid,$udom,$uname) = @_;
1185: my $result = &reply(join(':','userhassession',
1186: map {&escape($_)} ($udom,$uname)),$lonid);
1187: return 1 if ($result eq 'ok');
1188:
1189: return 0;
1190: }
1191:
1192: # --------- determine least loaded server in a user's domain which allows login
1193:
1194: sub choose_server {
1195: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1196: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1197: my %servers = &get_servers($udom);
1198: my $lowest_load = 30000;
1199: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1200: if ($skiploadbal) {
1201: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1202: unless (defined($cached)) {
1203: my $cachetime = 60*60*24;
1204: my %domconfig =
1205: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1206: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1207: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1208: $cachetime);
1209: }
1210: }
1211: }
1212: foreach my $lonhost (keys(%servers)) {
1213: if ($skiploadbal) {
1214: if (ref($balancers) eq 'HASH') {
1215: next if (exists($balancers->{$lonhost}));
1216: }
1217: }
1218: my $loginvia;
1219: if ($checkloginvia) {
1220: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1221: if ($loginvia) {
1222: my ($server,$path) = split(/:/,$loginvia);
1223: ($login_host, $lowest_load) =
1224: &compare_server_load($server, $login_host, $lowest_load, $required);
1225: if ($login_host eq $server) {
1226: $portal_path = $path;
1227: $isredirect = 1;
1228: }
1229: } else {
1230: ($login_host, $lowest_load) =
1231: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1232: if ($login_host eq $lonhost) {
1233: $portal_path = '';
1234: $isredirect = '';
1235: }
1236: }
1237: } else {
1238: ($login_host, $lowest_load) =
1239: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1240: }
1241: }
1242: if ($login_host ne '') {
1243: $hostname = &hostname($login_host);
1244: }
1245: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1246: }
1247:
1248: sub get_course_sessions {
1249: my ($cnum,$cdom,$lastactivity) = @_;
1250: my %servers = &internet_dom_servers($cdom);
1251: my %returnhash;
1252: foreach my $server (sort(keys(%servers))) {
1253: my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
1254: my @pairs=split(/\&/,$rep);
1255: unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
1256: foreach my $item (@pairs) {
1257: my ($key,$value)=split(/=/,$item,2);
1258: $key = &unescape($key);
1259: next if ($key =~ /^error: 2 /);
1260: if (exists($returnhash{$key})) {
1261: next if ($value < $returnhash{$key});
1262: }
1263: $returnhash{$key}=$value;
1264: }
1265: }
1266: }
1267: return %returnhash;
1268: }
1269:
1270: # --------------------------------------------- Try to change a user's password
1271:
1272: sub changepass {
1273: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1274: $currentpass = &escape($currentpass);
1275: $newpass = &escape($newpass);
1276: my $lonhost = $perlvar{'lonHostID'};
1277: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1278: $server);
1279: if (! $answer) {
1280: &logthis("No reply on password change request to $server ".
1281: "by $uname in domain $udom.");
1282: } elsif ($answer =~ "^ok") {
1283: &logthis("$uname in $udom successfully changed their password ".
1284: "on $server.");
1285: } elsif ($answer =~ "^pwchange_failure") {
1286: &logthis("$uname in $udom was unable to change their password ".
1287: "on $server. The action was blocked by either lcpasswd ".
1288: "or pwchange");
1289: } elsif ($answer =~ "^non_authorized") {
1290: &logthis("$uname in $udom did not get their password correct when ".
1291: "attempting to change it on $server.");
1292: } elsif ($answer =~ "^auth_mode_error") {
1293: &logthis("$uname in $udom attempted to change their password despite ".
1294: "not being locally or internally authenticated on $server.");
1295: } elsif ($answer =~ "^unknown_user") {
1296: &logthis("$uname in $udom attempted to change their password ".
1297: "on $server but were unable to because $server is not ".
1298: "their home server.");
1299: } elsif ($answer =~ "^refused") {
1300: &logthis("$server refused to change $uname in $udom password because ".
1301: "it was sent an unencrypted request to change the password.");
1302: } elsif ($answer =~ "invalid_client") {
1303: &logthis("$server refused to change $uname in $udom password because ".
1304: "it was a reset by e-mail originating from an invalid server.");
1305: } elsif ($answer =~ "^prioruse") {
1306: &logthis("$server refused to change $uname in $udom password because ".
1307: "the password had been used before");
1308: }
1309: return $answer;
1310: }
1311:
1312: # ----------------------- Try to determine user's current authentication scheme
1313:
1314: sub queryauthenticate {
1315: my ($uname,$udom)=@_;
1316: my $uhome=&homeserver($uname,$udom);
1317: if (!$uhome) {
1318: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1319: return 'no_host';
1320: }
1321: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1322: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1323: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1324: }
1325: return $answer;
1326: }
1327:
1328: # --------- Try to authenticate user from domain's lib servers (first this one)
1329:
1330: sub authenticate {
1331: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1332: $upass=&escape($upass);
1333: $uname= &LONCAPA::clean_username($uname);
1334: my $uhome=&homeserver($uname,$udom,1);
1335: my $newhome;
1336: if ((!$uhome) || ($uhome eq 'no_host')) {
1337: # Maybe the machine was offline and only re-appeared again recently?
1338: &reconlonc();
1339: # One more
1340: $uhome=&homeserver($uname,$udom,1);
1341: if (($uhome eq 'no_host') && $checkdefauth) {
1342: if (defined(&domain($udom,'primary'))) {
1343: $newhome=&domain($udom,'primary');
1344: }
1345: if ($newhome ne '') {
1346: $uhome = $newhome;
1347: }
1348: }
1349: if ((!$uhome) || ($uhome eq 'no_host')) {
1350: &logthis("User $uname at $udom is unknown in authenticate");
1351: return 'no_host';
1352: }
1353: }
1354: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1355: if ($answer eq 'authorized') {
1356: if ($newhome) {
1357: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1358: return 'no_account_on_host';
1359: } else {
1360: &logthis("User $uname at $udom authorized by $uhome");
1361: return $uhome;
1362: }
1363: }
1364: if ($answer eq 'non_authorized') {
1365: &logthis("User $uname at $udom rejected by $uhome");
1366: return 'no_host';
1367: }
1368: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1369: return 'no_host';
1370: }
1371:
1372: sub can_host_session {
1373: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1374: my $canhost = 1;
1375: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1376: if (ref($remotesessions) eq 'HASH') {
1377: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1378: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1379: $canhost = 0;
1380: } else {
1381: $canhost = 1;
1382: }
1383: }
1384: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1385: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1386: $canhost = 1;
1387: } else {
1388: $canhost = 0;
1389: }
1390: }
1391: if ($canhost) {
1392: if ($remotesessions->{'version'} ne '') {
1393: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1394: if ($reqmajor ne '' && $reqminor ne '') {
1395: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1396: my $major = $1;
1397: my $minor = $2;
1398: if (($major < $reqmajor ) ||
1399: (($major == $reqmajor) && ($minor < $reqminor))) {
1400: $canhost = 0;
1401: }
1402: } else {
1403: $canhost = 0;
1404: }
1405: }
1406: }
1407: }
1408: }
1409: if ($canhost) {
1410: if (ref($hostedsessions) eq 'HASH') {
1411: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1412: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1413: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1414: if (($uint_dom ne '') &&
1415: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1416: $canhost = 0;
1417: } else {
1418: $canhost = 1;
1419: }
1420: }
1421: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1422: if (($uint_dom ne '') &&
1423: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1424: $canhost = 1;
1425: } else {
1426: $canhost = 0;
1427: }
1428: }
1429: }
1430: }
1431: return $canhost;
1432: }
1433:
1434: sub spare_can_host {
1435: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1436: my $canhost=1;
1437: my $try_server_hostname = &hostname($try_server);
1438: my $serverhomeID = &get_server_homeID($try_server_hostname);
1439: my $serverhomedom = &host_domain($serverhomeID);
1440: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1441: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1442: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1443: $canhost = 0;
1444: }
1445: }
1446: if (($canhost) && ($uint_dom)) {
1447: my @intdoms;
1448: my $internet_names = &get_internet_names($try_server);
1449: if (ref($internet_names) eq 'ARRAY') {
1450: @intdoms = @{$internet_names};
1451: }
1452: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1453: my $remoterev = &get_server_loncaparev(undef,$try_server);
1454: $canhost = &can_host_session($udom,$try_server,$remoterev,
1455: $remotesessions,
1456: $defdomdefaults{'hostedsessions'});
1457: }
1458: }
1459: return $canhost;
1460: }
1461:
1462: sub this_host_spares {
1463: my ($dom) = @_;
1464: my ($dom_in_use,$lonhost_in_use,$result);
1465: my @hosts = ¤t_machine_ids();
1466: foreach my $lonhost (@hosts) {
1467: if (&host_domain($lonhost) eq $dom) {
1468: $dom_in_use = $dom;
1469: $lonhost_in_use = $lonhost;
1470: last;
1471: }
1472: }
1473: if ($dom_in_use ne '') {
1474: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1475: }
1476: if (ref($result) ne 'HASH') {
1477: $lonhost_in_use = $perlvar{'lonHostID'};
1478: $dom_in_use = &host_domain($lonhost_in_use);
1479: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1480: if (ref($result) ne 'HASH') {
1481: $result = \%spareid;
1482: }
1483: }
1484: return $result;
1485: }
1486:
1487: sub spares_for_offload {
1488: my ($dom_in_use,$lonhost_in_use) = @_;
1489: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1490: if (defined($cached)) {
1491: return $result;
1492: } else {
1493: my $cachetime = 60*60*24;
1494: my %domconfig =
1495: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1496: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1497: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1498: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1499: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1500: }
1501: }
1502: }
1503: }
1504: return;
1505: }
1506:
1507: sub get_lonbalancer_config {
1508: my ($servers) = @_;
1509: my ($currbalancer,$currtargets);
1510: if (ref($servers) eq 'HASH') {
1511: foreach my $server (keys(%{$servers})) {
1512: my %what = (
1513: spareid => 1,
1514: perlvar => 1,
1515: );
1516: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1517: if ($result eq 'ok') {
1518: if (ref($returnhash) eq 'HASH') {
1519: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1520: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1521: $currbalancer = $server;
1522: $currtargets = {};
1523: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1524: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1525: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1526: }
1527: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1528: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1529: }
1530: }
1531: last;
1532: }
1533: }
1534: }
1535: }
1536: }
1537: }
1538: return ($currbalancer,$currtargets);
1539: }
1540:
1541: sub check_loadbalancing {
1542: my ($uname,$udom,$caller) = @_;
1543: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1544: $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1545: my $lonhost = $perlvar{'lonHostID'};
1546: my @hosts = ¤t_machine_ids();
1547: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1548: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1549: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1550: my $serverhomedom = &host_domain($lonhost);
1551: my $domneedscache;
1552: my $cachetime = 60*60*24;
1553:
1554: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1555: $dom_in_use = $udom;
1556: $homeintdom = 1;
1557: } else {
1558: $dom_in_use = $serverhomedom;
1559: }
1560: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1561: unless (defined($cached)) {
1562: my %domconfig =
1563: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1564: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1565: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1566: } else {
1567: $domneedscache = $dom_in_use;
1568: }
1569: }
1570: if (ref($result) eq 'HASH') {
1571: ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1572: &check_balancer_result($result,@hosts);
1573: if ($is_balancer) {
1574: if (ref($currrules) eq 'HASH') {
1575: if ($homeintdom) {
1576: if ($uname ne '') {
1577: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1578: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1579: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1580: $rule_in_effect = $currrules->{'_LC_author'};
1581: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1582: $rule_in_effect = $currrules->{'_LC_adv'}
1583: }
1584: }
1585: if ($rule_in_effect eq '') {
1586: my %userenv = &userenvironment($udom,$uname,'inststatus');
1587: if ($userenv{'inststatus'} ne '') {
1588: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1589: my ($othertitle,$usertypes,$types) =
1590: &Apache::loncommon::sorted_inst_types($udom);
1591: if (ref($types) eq 'ARRAY') {
1592: foreach my $type (@{$types}) {
1593: if (grep(/^\Q$type\E$/,@statuses)) {
1594: if (exists($currrules->{$type})) {
1595: $rule_in_effect = $currrules->{$type};
1596: }
1597: }
1598: }
1599: }
1600: } else {
1601: if (exists($currrules->{'default'})) {
1602: $rule_in_effect = $currrules->{'default'};
1603: }
1604: }
1605: }
1606: } else {
1607: if (exists($currrules->{'default'})) {
1608: $rule_in_effect = $currrules->{'default'};
1609: }
1610: }
1611: } else {
1612: if ($currrules->{'_LC_external'} ne '') {
1613: $rule_in_effect = $currrules->{'_LC_external'};
1614: }
1615: }
1616: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1617: $uname,$udom);
1618: }
1619: }
1620: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1621: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1622: unless (defined($cached)) {
1623: my %domconfig =
1624: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1625: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1626: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1627: } else {
1628: $domneedscache = $serverhomedom;
1629: }
1630: }
1631: if (ref($result) eq 'HASH') {
1632: ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1633: &check_balancer_result($result,@hosts);
1634: if ($is_balancer) {
1635: if (ref($currrules) eq 'HASH') {
1636: if ($currrules->{'_LC_internetdom'} ne '') {
1637: $rule_in_effect = $currrules->{'_LC_internetdom'};
1638: }
1639: }
1640: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1641: $uname,$udom);
1642: }
1643: } else {
1644: if ($perlvar{'lonBalancer'} eq 'yes') {
1645: $is_balancer = 1;
1646: $offloadto = &this_host_spares($dom_in_use);
1647: }
1648: unless (defined($cached)) {
1649: $domneedscache = $serverhomedom;
1650: }
1651: }
1652: } else {
1653: if ($perlvar{'lonBalancer'} eq 'yes') {
1654: $is_balancer = 1;
1655: $offloadto = &this_host_spares($dom_in_use);
1656: }
1657: unless (defined($cached)) {
1658: $domneedscache = $serverhomedom;
1659: }
1660: }
1661: if ($domneedscache) {
1662: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1663: }
1664: if (($is_balancer) && ($caller ne 'switchserver')) {
1665: my $lowest_load = 30000;
1666: if (ref($offloadto) eq 'HASH') {
1667: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1668: foreach my $try_server (@{$offloadto->{'primary'}}) {
1669: ($otherserver,$lowest_load) =
1670: &compare_server_load($try_server,$otherserver,$lowest_load);
1671: }
1672: }
1673: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1674:
1675: if (!$found_server) {
1676: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1677: foreach my $try_server (@{$offloadto->{'default'}}) {
1678: ($otherserver,$lowest_load) =
1679: &compare_server_load($try_server,$otherserver,$lowest_load);
1680: }
1681: }
1682: }
1683: } elsif (ref($offloadto) eq 'ARRAY') {
1684: if (@{$offloadto} == 1) {
1685: $otherserver = $offloadto->[0];
1686: } elsif (@{$offloadto} > 1) {
1687: foreach my $try_server (@{$offloadto}) {
1688: ($otherserver,$lowest_load) =
1689: &compare_server_load($try_server,$otherserver,$lowest_load);
1690: }
1691: }
1692: }
1693: unless ($caller eq 'login') {
1694: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1695: $is_balancer = 0;
1696: if ($uname ne '' && $udom ne '') {
1697: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1698: &appenv({'user.loadbalexempt' => $lonhost,
1699: 'user.loadbalcheck.time' => time});
1700: }
1701: }
1702: }
1703: }
1704: }
1705: if (($is_balancer) && (!$homeintdom)) {
1706: undef($setcookie);
1707: }
1708: return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1709: }
1710:
1711: sub check_balancer_result {
1712: my ($result,@hosts) = @_;
1713: my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1714: if (ref($result) eq 'HASH') {
1715: if ($result->{'lonhost'} ne '') {
1716: my $currbalancer = $result->{'lonhost'};
1717: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1718: $is_balancer = 1;
1719: $currtargets = $result->{'targets'};
1720: $currrules = $result->{'rules'};
1721: }
1722: $dom_balancers = $currbalancer;
1723: } else {
1724: if (keys(%{$result})) {
1725: foreach my $key (keys(%{$result})) {
1726: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1727: (ref($result->{$key}) eq 'HASH')) {
1728: $is_balancer = 1;
1729: $currrules = $result->{$key}{'rules'};
1730: $currtargets = $result->{$key}{'targets'};
1731: $setcookie = $result->{$key}{'cookie'};
1732: last;
1733: }
1734: }
1735: $dom_balancers = join(',',sort(keys(%{$result})));
1736: }
1737: }
1738: }
1739: return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1740: }
1741:
1742: sub get_loadbalancer_targets {
1743: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1744: my $offloadto;
1745: if ($rule_in_effect eq 'none') {
1746: return [$perlvar{'lonHostID'}];
1747: } elsif ($rule_in_effect eq '') {
1748: $offloadto = $currtargets;
1749: } else {
1750: if ($rule_in_effect eq 'homeserver') {
1751: my $homeserver = &homeserver($uname,$udom);
1752: if ($homeserver ne 'no_host') {
1753: $offloadto = [$homeserver];
1754: }
1755: } elsif ($rule_in_effect eq 'externalbalancer') {
1756: my %domconfig =
1757: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1758: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1759: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1760: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1761: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1762: }
1763: }
1764: } else {
1765: my %servers = &internet_dom_servers($udom);
1766: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1767: if (&hostname($remotebalancer) ne '') {
1768: $offloadto = [$remotebalancer];
1769: }
1770: }
1771: } elsif (&hostname($rule_in_effect) ne '') {
1772: $offloadto = [$rule_in_effect];
1773: }
1774: }
1775: return $offloadto;
1776: }
1777:
1778: sub internet_dom_servers {
1779: my ($dom) = @_;
1780: my (%uniqservers,%servers);
1781: my $primaryserver = &hostname(&domain($dom,'primary'));
1782: my @machinedoms = &machine_domains($primaryserver);
1783: foreach my $mdom (@machinedoms) {
1784: my %currservers = %servers;
1785: my %server = &get_servers($mdom);
1786: %servers = (%currservers,%server);
1787: }
1788: my %by_hostname;
1789: foreach my $id (keys(%servers)) {
1790: push(@{$by_hostname{$servers{$id}}},$id);
1791: }
1792: foreach my $hostname (sort(keys(%by_hostname))) {
1793: if (@{$by_hostname{$hostname}} > 1) {
1794: my $match = 0;
1795: foreach my $id (@{$by_hostname{$hostname}}) {
1796: if (&host_domain($id) eq $dom) {
1797: $uniqservers{$id} = $hostname;
1798: $match = 1;
1799: }
1800: }
1801: unless ($match) {
1802: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1803: }
1804: } else {
1805: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1806: }
1807: }
1808: return %uniqservers;
1809: }
1810:
1811: sub trusted_domains {
1812: my ($cmdtype,$calldom) = @_;
1813: my ($trusted,$untrusted);
1814: if (&domain($calldom) eq '') {
1815: return ($trusted,$untrusted);
1816: }
1817: unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
1818: return ($trusted,$untrusted);
1819: }
1820: my $callprimary = &domain($calldom,'primary');
1821: my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
1822: if ($intcalldom eq '') {
1823: return ($trusted,$untrusted);
1824: }
1825:
1826: my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
1827: unless (defined($cached)) {
1828: my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
1829: &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
1830: $trustconfig = $domconfig{'trust'};
1831: }
1832: if (ref($trustconfig)) {
1833: my (%possexc,%possinc,@allexc,@allinc);
1834: if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
1835: if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
1836: map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}};
1837: }
1838: if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1839: $possinc{$intcalldom} = 1;
1840: map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
1841: }
1842: }
1843: if (keys(%possexc)) {
1844: if (keys(%possinc)) {
1845: foreach my $key (sort(keys(%possexc))) {
1846: next if ($key eq $intcalldom);
1847: unless ($possinc{$key}) {
1848: push(@allexc,$key);
1849: }
1850: }
1851: } else {
1852: @allexc = sort(keys(%possexc));
1853: }
1854: }
1855: if (keys(%possinc)) {
1856: $possinc{$intcalldom} = 1;
1857: @allinc = sort(keys(%possinc));
1858: }
1859: if ((@allexc > 0) || (@allinc > 0)) {
1860: my %doms_by_intdom;
1861: my %allintdoms = &all_host_intdom();
1862: my %alldoms = &all_host_domain();
1863: foreach my $key (%allintdoms) {
1864: if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
1865: unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
1866: push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
1867: }
1868: } else {
1869: $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}];
1870: }
1871: }
1872: foreach my $exc (@allexc) {
1873: if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1874: push(@{$untrusted},@{$doms_by_intdom{$exc}});
1875: }
1876: }
1877: foreach my $inc (@allinc) {
1878: if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1879: push(@{$trusted},@{$doms_by_intdom{$inc}});
1880: }
1881: }
1882: }
1883: }
1884: return ($trusted,$untrusted);
1885: }
1886:
1887: sub will_trust {
1888: my ($cmdtype,$domain,$possdom) = @_;
1889: return 1 if ($domain eq $possdom);
1890: my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
1891: my $willtrust;
1892: if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
1893: if (grep(/^\Q$domain\E$/,@{$trustedref})) {
1894: $willtrust = 1;
1895: }
1896: } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
1897: unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
1898: $willtrust = 1;
1899: }
1900: } else {
1901: $willtrust = 1;
1902: }
1903: return $willtrust;
1904: }
1905:
1906: # ---------------------- Find the homebase for a user from domain's lib servers
1907:
1908: my %homecache;
1909: sub homeserver {
1910: my ($uname,$udom,$ignoreBadCache)=@_;
1911: my $index="$uname:$udom";
1912:
1913: if (exists($homecache{$index})) { return $homecache{$index}; }
1914:
1915: my %servers = &get_servers($udom,'library');
1916: foreach my $tryserver (keys(%servers)) {
1917: next if ($ignoreBadCache ne 'true' &&
1918: exists($badServerCache{$tryserver}));
1919:
1920: my $answer=reply("home:$udom:$uname",$tryserver);
1921: if ($answer eq 'found') {
1922: delete($badServerCache{$tryserver});
1923: return $homecache{$index}=$tryserver;
1924: } elsif ($answer eq 'no_host') {
1925: $badServerCache{$tryserver}=1;
1926: }
1927: }
1928: return 'no_host';
1929: }
1930:
1931: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1932:
1933: sub idget {
1934: my ($udom,$idsref,$namespace)=@_;
1935: my %returnhash=();
1936: my @ids=();
1937: if (ref($idsref) eq 'ARRAY') {
1938: @ids = @{$idsref};
1939: } else {
1940: return %returnhash;
1941: }
1942: if ($namespace eq '') {
1943: $namespace = 'ids';
1944: }
1945:
1946: my %servers = &get_servers($udom,'library');
1947: foreach my $tryserver (keys(%servers)) {
1948: my $idlist=join('&', map { &escape($_); } @ids);
1949: if ($namespace eq 'ids') {
1950: $idlist=~tr/A-Z/a-z/;
1951: }
1952: my $reply;
1953: if ($namespace eq 'ids') {
1954: $reply=&reply("idget:$udom:".$idlist,$tryserver);
1955: } else {
1956: $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
1957: }
1958: my @answer=();
1959: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1960: @answer=split(/\&/,$reply);
1961: } ;
1962: my $i;
1963: for ($i=0;$i<=$#ids;$i++) {
1964: if ($answer[$i]) {
1965: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1966: }
1967: }
1968: }
1969: return %returnhash;
1970: }
1971:
1972: # ------------------------------------- Find the IDs behind a list of usernames
1973:
1974: sub idrget {
1975: my ($udom,@unames)=@_;
1976: my %returnhash=();
1977: foreach my $uname (@unames) {
1978: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1979: }
1980: return %returnhash;
1981: }
1982:
1983: # Store away a list of names and associated student/employee IDs or clicker IDs
1984:
1985: sub idput {
1986: my ($udom,$idsref,$uhom,$namespace)=@_;
1987: my %servers=();
1988: my %ids=();
1989: my %byid = ();
1990: if (ref($idsref) eq 'HASH') {
1991: %ids=%{$idsref};
1992: }
1993: if ($namespace eq '') {
1994: $namespace = 'ids';
1995: }
1996: foreach my $uname (keys(%ids)) {
1997: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1998: if ($uhom eq '') {
1999: $uhom=&homeserver($uname,$udom);
2000: }
2001: if ($uhom ne 'no_host') {
2002: my $esc_unam=&escape($uname);
2003: if ($namespace eq 'ids') {
2004: my $id=&escape($ids{$uname});
2005: $id=~tr/A-Z/a-z/;
2006: my $esc_unam=&escape($uname);
2007: $servers{$uhom}.=$id.'='.$esc_unam.'&';
2008: } else {
2009: my @currids = split(/,/,$ids{$uname});
2010: foreach my $id (@currids) {
2011: $byid{$uhom}{$id} .= $uname.',';
2012: }
2013: }
2014: }
2015: }
2016: if ($namespace eq 'clickers') {
2017: foreach my $server (keys(%byid)) {
2018: if (ref($byid{$server}) eq 'HASH') {
2019: foreach my $id (keys(%{$byid{$server}})) {
2020: $byid{$server} =~ s/,$//;
2021: $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&';
2022: }
2023: }
2024: }
2025: }
2026: foreach my $server (keys(%servers)) {
2027: $servers{$server} =~ s/\&$//;
2028: if ($namespace eq 'ids') {
2029: &critical('idput:'.$udom.':'.$servers{$server},$server);
2030: } else {
2031: &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
2032: }
2033: }
2034: }
2035:
2036: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
2037:
2038: sub iddel {
2039: my ($udom,$idshashref,$uhome,$namespace)=@_;
2040: my %result=();
2041: my %ids=();
2042: my %byid = ();
2043: if (ref($idshashref) eq 'HASH') {
2044: %ids=%{$idshashref};
2045: } else {
2046: return %result;
2047: }
2048: if ($namespace eq '') {
2049: $namespace = 'ids';
2050: }
2051: my %servers=();
2052: while (my ($id,$unamestr) = each(%ids)) {
2053: if ($namespace eq 'ids') {
2054: my $uhom = $uhome;
2055: if ($uhom eq '') {
2056: $uhom=&homeserver($unamestr,$udom);
2057: }
2058: if ($uhom ne 'no_host') {
2059: $servers{$uhom}.='&'.&escape($id);
2060: }
2061: } else {
2062: my @curritems = split(/,/,$ids{$id});
2063: foreach my $uname (@curritems) {
2064: my $uhom = $uhome;
2065: if ($uhom eq '') {
2066: $uhom=&homeserver($uname,$udom);
2067: }
2068: if ($uhom ne 'no_host') {
2069: $byid{$uhom}{$id} .= $uname.',';
2070: }
2071: }
2072: }
2073: }
2074: if ($namespace eq 'clickers') {
2075: foreach my $server (keys(%byid)) {
2076: if (ref($byid{$server}) eq 'HASH') {
2077: foreach my $id (keys(%{$byid{$server}})) {
2078: $byid{$server}{$id} =~ s/,$//;
2079: $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
2080: }
2081: }
2082: }
2083: }
2084: foreach my $server (keys(%servers)) {
2085: $servers{$server} =~ s/\&$//;
2086: if ($namespace eq 'ids') {
2087: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
2088: } elsif ($namespace eq 'clickers') {
2089: $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
2090: }
2091: }
2092: return %result;
2093: }
2094:
2095: # ----- Update clicker ID-to-username look-ups in clickers.db on library server
2096:
2097: sub updateclickers {
2098: my ($udom,$action,$idshashref,$uhome,$critical) = @_;
2099: my %clickers;
2100: if (ref($idshashref) eq 'HASH') {
2101: %clickers=%{$idshashref};
2102: } else {
2103: return;
2104: }
2105: my $items='';
2106: foreach my $item (keys(%clickers)) {
2107: $items.=&escape($item).'='.&escape($clickers{$item}).'&';
2108: }
2109: $items=~s/\&$//;
2110: my $request = "updateclickers:$udom:$action:$items";
2111: if ($critical) {
2112: return &critical($request,$uhome);
2113: } else {
2114: return &reply($request,$uhome);
2115: }
2116: }
2117:
2118: # ------------------------------dump from db file owned by domainconfig user
2119: sub dump_dom {
2120: my ($namespace, $udom, $regexp) = @_;
2121:
2122: $udom ||= $env{'user.domain'};
2123:
2124: return () unless $udom;
2125:
2126: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
2127: }
2128:
2129: # ------------------------------------------ get items from domain db files
2130:
2131: sub get_dom {
2132: my ($namespace,$storearr,$udom,$uhome)=@_;
2133: return if ($udom eq 'public');
2134: my $items='';
2135: foreach my $item (@$storearr) {
2136: $items.=&escape($item).'&';
2137: }
2138: $items=~s/\&$//;
2139: if (!$udom) {
2140: $udom=$env{'user.domain'};
2141: return if ($udom eq 'public');
2142: if (defined(&domain($udom,'primary'))) {
2143: $uhome=&domain($udom,'primary');
2144: } else {
2145: undef($uhome);
2146: }
2147: } else {
2148: if (!$uhome) {
2149: if (defined(&domain($udom,'primary'))) {
2150: $uhome=&domain($udom,'primary');
2151: }
2152: }
2153: }
2154: if ($udom && $uhome && ($uhome ne 'no_host')) {
2155: my $rep;
2156: if ($namespace =~ /^enc/) {
2157: $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
2158: } else {
2159: $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
2160: }
2161: my %returnhash;
2162: if ($rep eq '' || $rep =~ /^error: 2 /) {
2163: return %returnhash;
2164: }
2165: my @pairs=split(/\&/,$rep);
2166: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
2167: return @pairs;
2168: }
2169: my $i=0;
2170: foreach my $item (@$storearr) {
2171: $returnhash{$item}=&thaw_unescape($pairs[$i]);
2172: $i++;
2173: }
2174: return %returnhash;
2175: } else {
2176: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
2177: }
2178: }
2179:
2180: # -------------------------------------------- put items in domain db files
2181:
2182: sub put_dom {
2183: my ($namespace,$storehash,$udom,$uhome)=@_;
2184: if (!$udom) {
2185: $udom=$env{'user.domain'};
2186: if (defined(&domain($udom,'primary'))) {
2187: $uhome=&domain($udom,'primary');
2188: } else {
2189: undef($uhome);
2190: }
2191: } else {
2192: if (!$uhome) {
2193: if (defined(&domain($udom,'primary'))) {
2194: $uhome=&domain($udom,'primary');
2195: }
2196: }
2197: }
2198: if ($udom && $uhome && ($uhome ne 'no_host')) {
2199: my $items='';
2200: foreach my $item (keys(%$storehash)) {
2201: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
2202: }
2203: $items=~s/\&$//;
2204: if ($namespace =~ /^enc/) {
2205: return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
2206: } else {
2207: return &reply("putdom:$udom:$namespace:$items",$uhome);
2208: }
2209: } else {
2210: &logthis("put_dom failed - no homeserver and/or domain");
2211: }
2212: }
2213:
2214: # --------------------- newput for items in db file owned by domainconfig user
2215: sub newput_dom {
2216: my ($namespace,$storehash,$udom) = @_;
2217: my $result;
2218: if (!$udom) {
2219: $udom=$env{'user.domain'};
2220: }
2221: if ($udom) {
2222: my $uname = &get_domainconfiguser($udom);
2223: $result = &newput($namespace,$storehash,$udom,$uname);
2224: }
2225: return $result;
2226: }
2227:
2228: # --------------------- delete for items in db file owned by domainconfig user
2229: sub del_dom {
2230: my ($namespace,$storearr,$udom)=@_;
2231: if (ref($storearr) eq 'ARRAY') {
2232: if (!$udom) {
2233: $udom=$env{'user.domain'};
2234: }
2235: if ($udom) {
2236: my $uname = &get_domainconfiguser($udom);
2237: return &del($namespace,$storearr,$udom,$uname);
2238: }
2239: }
2240: }
2241:
2242: # ----------------------------------construct domainconfig user for a domain
2243: sub get_domainconfiguser {
2244: my ($udom) = @_;
2245: return $udom.'-domainconfig';
2246: }
2247:
2248: sub retrieve_inst_usertypes {
2249: my ($udom) = @_;
2250: my (%returnhash,@order);
2251: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
2252: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
2253: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
2254: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
2255: } else {
2256: if (defined(&domain($udom,'primary'))) {
2257: my $uhome=&domain($udom,'primary');
2258: my $rep=&reply("inst_usertypes:$udom",$uhome);
2259: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
2260: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
2261: return (\%returnhash,\@order);
2262: }
2263: my ($hashitems,$orderitems) = split(/:/,$rep);
2264: my @pairs=split(/\&/,$hashitems);
2265: foreach my $item (@pairs) {
2266: my ($key,$value)=split(/=/,$item,2);
2267: $key = &unescape($key);
2268: next if ($key =~ /^error: 2 /);
2269: $returnhash{$key}=&thaw_unescape($value);
2270: }
2271: my @esc_order = split(/\&/,$orderitems);
2272: foreach my $item (@esc_order) {
2273: push(@order,&unescape($item));
2274: }
2275: } else {
2276: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
2277: }
2278: return (\%returnhash,\@order);
2279: }
2280: }
2281:
2282: sub is_domainimage {
2283: my ($url) = @_;
2284: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
2285: if (&domain($1) ne '') {
2286: return '1';
2287: }
2288: }
2289: return;
2290: }
2291:
2292: sub inst_directory_query {
2293: my ($srch) = @_;
2294: my $udom = $srch->{'srchdomain'};
2295: my %results;
2296: my $homeserver = &domain($udom,'primary');
2297: my $outcome;
2298: if ($homeserver ne '') {
2299: unless ($homeserver eq $perlvar{'lonHostID'}) {
2300: if ($srch->{'srchby'} eq 'email') {
2301: my $lcrev = &get_server_loncaparev($udom,$homeserver);
2302: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2303: if (($major eq '' && $minor eq '') || ($major < 2) ||
2304: (($major == 2) && ($minor < 12))) {
2305: return;
2306: }
2307: }
2308: }
2309: my $queryid=&reply("querysend:instdirsearch:".
2310: &escape($srch->{'srchby'}).':'.
2311: &escape($srch->{'srchterm'}).':'.
2312: &escape($srch->{'srchtype'}),$homeserver);
2313: my $host=&hostname($homeserver);
2314: if ($queryid !~/^\Q$host\E\_/) {
2315: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
2316: return;
2317: }
2318: my $response = &get_query_reply($queryid);
2319: my $maxtries = 5;
2320: my $tries = 1;
2321: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2322: $response = &get_query_reply($queryid);
2323: $tries ++;
2324: }
2325:
2326: if (!&error($response) && $response ne 'refused') {
2327: if ($response eq 'unavailable') {
2328: $outcome = $response;
2329: } else {
2330: $outcome = 'ok';
2331: my @matches = split(/\n/,$response);
2332: foreach my $match (@matches) {
2333: my ($key,$value) = split(/=/,$match);
2334: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2335: }
2336: }
2337: }
2338: }
2339: return ($outcome,%results);
2340: }
2341:
2342: sub usersearch {
2343: my ($srch) = @_;
2344: my $dom = $srch->{'srchdomain'};
2345: my %results;
2346: my %libserv = &all_library();
2347: my $query = 'usersearch';
2348: foreach my $tryserver (keys(%libserv)) {
2349: if (&host_domain($tryserver) eq $dom) {
2350: unless ($tryserver eq $perlvar{'lonHostID'}) {
2351: if ($srch->{'srchby'} eq 'email') {
2352: my $lcrev = &get_server_loncaparev($dom,$tryserver);
2353: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2354: next if (($major eq '' && $minor eq '') || ($major < 2) ||
2355: (($major == 2) && ($minor < 12)));
2356: }
2357: }
2358: my $host=&hostname($tryserver);
2359: my $queryid=
2360: &reply("querysend:".&escape($query).':'.
2361: &escape($srch->{'srchby'}).':'.
2362: &escape($srch->{'srchtype'}).':'.
2363: &escape($srch->{'srchterm'}),$tryserver);
2364: if ($queryid !~/^\Q$host\E\_/) {
2365: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
2366: next;
2367: }
2368: my $reply = &get_query_reply($queryid);
2369: my $maxtries = 1;
2370: my $tries = 1;
2371: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2372: $reply = &get_query_reply($queryid);
2373: $tries ++;
2374: }
2375: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2376: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2377: } else {
2378: my @matches;
2379: if ($reply =~ /\n/) {
2380: @matches = split(/\n/,$reply);
2381: } else {
2382: @matches = split(/\&/,$reply);
2383: }
2384: foreach my $match (@matches) {
2385: my ($uname,$udom,%userhash);
2386: foreach my $entry (split(/:/,$match)) {
2387: my ($key,$value) =
2388: map {&unescape($_);} split(/=/,$entry);
2389: $userhash{$key} = $value;
2390: if ($key eq 'username') {
2391: $uname = $value;
2392: } elsif ($key eq 'domain') {
2393: $udom = $value;
2394: }
2395: }
2396: $results{$uname.':'.$udom} = \%userhash;
2397: }
2398: }
2399: }
2400: }
2401: return %results;
2402: }
2403:
2404: sub get_instuser {
2405: my ($udom,$uname,$id) = @_;
2406: my $homeserver = &domain($udom,'primary');
2407: my ($outcome,%results);
2408: if ($homeserver ne '') {
2409: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2410: &escape($id).':'.&escape($udom),$homeserver);
2411: my $host=&hostname($homeserver);
2412: if ($queryid !~/^\Q$host\E\_/) {
2413: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2414: return;
2415: }
2416: my $response = &get_query_reply($queryid);
2417: my $maxtries = 5;
2418: my $tries = 1;
2419: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2420: $response = &get_query_reply($queryid);
2421: $tries ++;
2422: }
2423: if (!&error($response) && $response ne 'refused') {
2424: if ($response eq 'unavailable') {
2425: $outcome = $response;
2426: } else {
2427: $outcome = 'ok';
2428: my @matches = split(/\n/,$response);
2429: foreach my $match (@matches) {
2430: my ($key,$value) = split(/=/,$match);
2431: $results{&unescape($key)} = &thaw_unescape($value);
2432: }
2433: }
2434: }
2435: }
2436: my %userinfo;
2437: if (ref($results{$uname}) eq 'HASH') {
2438: %userinfo = %{$results{$uname}};
2439: }
2440: return ($outcome,%userinfo);
2441: }
2442:
2443: sub get_multiple_instusers {
2444: my ($udom,$users,$caller) = @_;
2445: my ($outcome,$results);
2446: if (ref($users) eq 'HASH') {
2447: my $count = keys(%{$users});
2448: my $requested = &freeze_escape($users);
2449: my $homeserver = &domain($udom,'primary');
2450: if ($homeserver ne '') {
2451: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2452: my $host=&hostname($homeserver);
2453: if ($queryid !~/^\Q$host\E\_/) {
2454: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2455: ' for host: '.$homeserver.'in domain '.$udom);
2456: return ($outcome,$results);
2457: }
2458: my $response = &get_query_reply($queryid);
2459: my $maxtries = 5;
2460: if ($count > 100) {
2461: $maxtries = 1+int($count/20);
2462: }
2463: my $tries = 1;
2464: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2465: $response = &get_query_reply($queryid);
2466: $tries ++;
2467: }
2468: if ($response eq '') {
2469: $results = {};
2470: foreach my $key (keys(%{$users})) {
2471: my ($uname,$id);
2472: if ($caller eq 'id') {
2473: $id = $key;
2474: } else {
2475: $uname = $key;
2476: }
2477: my ($resp,%info) = &get_instuser($udom,$uname,$id);
2478: $outcome = $resp;
2479: if ($resp eq 'ok') {
2480: %{$results} = (%{$results}, %info);
2481: } else {
2482: last;
2483: }
2484: }
2485: } elsif(!&error($response) && ($response ne 'refused')) {
2486: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2487: $outcome = $response;
2488: } else {
2489: ($outcome,my $userdata) = split(/=/,$response,2);
2490: if ($outcome eq 'ok') {
2491: $results = &thaw_unescape($userdata);
2492: }
2493: }
2494: }
2495: }
2496: }
2497: return ($outcome,$results);
2498: }
2499:
2500: sub inst_rulecheck {
2501: my ($udom,$uname,$id,$item,$rules) = @_;
2502: my %returnhash;
2503: if ($udom ne '') {
2504: if (ref($rules) eq 'ARRAY') {
2505: @{$rules} = map {&escape($_);} (@{$rules});
2506: my $rulestr = join(':',@{$rules});
2507: my $homeserver=&domain($udom,'primary');
2508: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
2509: my $response;
2510: if ($item eq 'username') {
2511: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2512: ':'.&escape($uname).':'.$rulestr,
2513: $homeserver));
2514: } elsif ($item eq 'id') {
2515: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2516: ':'.&escape($id).':'.$rulestr,
2517: $homeserver));
2518: } elsif ($item eq 'selfcreate') {
2519: $response=&unescape(&reply('instselfcreatecheck:'.
2520: &escape($udom).':'.&escape($uname).
2521: ':'.$rulestr,$homeserver));
2522: }
2523: if ($response ne 'refused') {
2524: my @pairs=split(/\&/,$response);
2525: foreach my $item (@pairs) {
2526: my ($key,$value)=split(/=/,$item,2);
2527: $key = &unescape($key);
2528: next if ($key =~ /^error: 2 /);
2529: $returnhash{$key}=&thaw_unescape($value);
2530: }
2531: }
2532: }
2533: }
2534: }
2535: return %returnhash;
2536: }
2537:
2538: sub inst_userrules {
2539: my ($udom,$check) = @_;
2540: my (%ruleshash,@ruleorder);
2541: if ($udom ne '') {
2542: my $homeserver=&domain($udom,'primary');
2543: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
2544: my $response;
2545: if ($check eq 'id') {
2546: $response=&reply('instidrules:'.&escape($udom),
2547: $homeserver);
2548: } elsif ($check eq 'email') {
2549: $response=&reply('instemailrules:'.&escape($udom),
2550: $homeserver);
2551: } else {
2552: $response=&reply('instuserrules:'.&escape($udom),
2553: $homeserver);
2554: }
2555: if (($response ne 'refused') && ($response ne 'error') &&
2556: ($response ne 'unknown_cmd') &&
2557: ($response ne 'no_such_host')) {
2558: my ($hashitems,$orderitems) = split(/:/,$response);
2559: my @pairs=split(/\&/,$hashitems);
2560: foreach my $item (@pairs) {
2561: my ($key,$value)=split(/=/,$item,2);
2562: $key = &unescape($key);
2563: next if ($key =~ /^error: 2 /);
2564: $ruleshash{$key}=&thaw_unescape($value);
2565: }
2566: my @esc_order = split(/\&/,$orderitems);
2567: foreach my $item (@esc_order) {
2568: push(@ruleorder,&unescape($item));
2569: }
2570: }
2571: }
2572: }
2573: return (\%ruleshash,\@ruleorder);
2574: }
2575:
2576: # ------------- Get Authentication, Language and User Tools Defaults for Domain
2577:
2578: sub get_domain_defaults {
2579: my ($domain,$ignore_cache) = @_;
2580: return if (($domain eq '') || ($domain eq 'public'));
2581: my $cachetime = 60*60*24;
2582: unless ($ignore_cache) {
2583: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2584: if (defined($cached)) {
2585: if (ref($result) eq 'HASH') {
2586: return %{$result};
2587: }
2588: }
2589: }
2590: my %domdefaults;
2591: my %domconfig =
2592: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
2593: 'requestcourses','inststatus',
2594: 'coursedefaults','usersessions',
2595: 'requestauthor','selfenrollment',
2596: 'coursecategories','ssl','autoenroll',
2597: 'trust','helpsettings'],$domain);
2598: my @coursetypes = ('official','unofficial','community','textbook','placement');
2599: if (ref($domconfig{'defaults'}) eq 'HASH') {
2600: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2601: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2602: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
2603: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
2604: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
2605: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
2606: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2607: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2608: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
2609: } else {
2610: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2611: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2612: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2613: }
2614: if (ref($domconfig{'quotas'}) eq 'HASH') {
2615: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2616: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2617: } else {
2618: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
2619: }
2620: my @usertools = ('aboutme','blog','webdav','portfolio');
2621: foreach my $item (@usertools) {
2622: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2623: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2624: }
2625: }
2626: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2627: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2628: }
2629: }
2630: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
2631: foreach my $item ('official','unofficial','community','textbook','placement') {
2632: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2633: }
2634: }
2635: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2636: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2637: }
2638: if (ref($domconfig{'inststatus'}) eq 'HASH') {
2639: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
2640: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2641: }
2642: }
2643: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
2644: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
2645: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2646: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2647: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2648: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2649: }
2650: foreach my $type (@coursetypes) {
2651: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2652: unless ($type eq 'community') {
2653: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2654: }
2655: }
2656: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2657: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2658: }
2659: if ($domdefaults{'postsubmit'} eq 'on') {
2660: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2661: $domdefaults{$type.'postsubtimeout'} =
2662: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2663: }
2664: }
2665: }
2666: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2667: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2668: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2669: if (@clonecodes) {
2670: $domdefaults{'canclone'} = join('+',@clonecodes);
2671: }
2672: }
2673: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2674: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2675: }
2676: if ($domconfig{'coursedefaults'}{'texengine'}) {
2677: $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
2678: }
2679: }
2680: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2681: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2682: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2683: }
2684: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2685: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2686: }
2687: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2688: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2689: }
2690: }
2691: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2692: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2693: my @settings = ('types','registered','enroll_dates','access_dates','section',
2694: 'approval','limit');
2695: foreach my $type (@coursetypes) {
2696: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2697: my @mgrdc = ();
2698: foreach my $item (@settings) {
2699: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2700: push(@mgrdc,$item);
2701: }
2702: }
2703: if (@mgrdc) {
2704: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2705: }
2706: }
2707: }
2708: }
2709: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2710: foreach my $type (@coursetypes) {
2711: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2712: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2713: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2714: }
2715: }
2716: }
2717: }
2718: }
2719: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2720: $domdefaults{'catauth'} = 'std';
2721: $domdefaults{'catunauth'} = 'std';
2722: if ($domconfig{'coursecategories'}{'auth'}) {
2723: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2724: }
2725: if ($domconfig{'coursecategories'}{'unauth'}) {
2726: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2727: }
2728: }
2729: if (ref($domconfig{'ssl'}) eq 'HASH') {
2730: if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
2731: $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
2732: }
2733: if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
2734: $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
2735: }
2736: if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
2737: $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
2738: }
2739: }
2740: if (ref($domconfig{'trust'}) eq 'HASH') {
2741: my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
2742: foreach my $prefix (@prefixes) {
2743: if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
2744: $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
2745: }
2746: }
2747: }
2748: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2749: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2750: }
2751: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2752: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2753: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2754: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2755: }
2756: }
2757: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
2758: return %domdefaults;
2759: }
2760:
2761: sub get_dom_cats {
2762: my ($dom) = @_;
2763: return unless (&domain($dom));
2764: my ($cats,$cached)=&is_cached_new('cats',$dom);
2765: unless (defined($cached)) {
2766: my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
2767: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2768: if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
2769: %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
2770: } else {
2771: $cats = {};
2772: }
2773: } else {
2774: $cats = {};
2775: }
2776: &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
2777: }
2778: return $cats;
2779: }
2780:
2781: sub get_dom_instcats {
2782: my ($dom) = @_;
2783: return unless (&domain($dom));
2784: my ($instcats,$cached)=&is_cached_new('instcats',$dom);
2785: unless (defined($cached)) {
2786: my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
2787: my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
2788: if ($totcodes > 0) {
2789: my $caller = 'global';
2790: if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
2791: \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
2792: $instcats = {
2793: codes => \%codes,
2794: codetitles => \@codetitles,
2795: cat_titles => \%cat_titles,
2796: cat_order => \%cat_order,
2797: };
2798: &do_cache_new('instcats',$dom,$instcats,3600);
2799: }
2800: }
2801: }
2802: return $instcats;
2803: }
2804:
2805: sub retrieve_instcodes {
2806: my ($coursecodes,$dom) = @_;
2807: my $totcodes;
2808: my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
2809: foreach my $course (keys(%courses)) {
2810: if (ref($courses{$course}) eq 'HASH') {
2811: if ($courses{$course}{'inst_code'} ne '') {
2812: $$coursecodes{$course} = $courses{$course}{'inst_code'};
2813: $totcodes ++;
2814: }
2815: }
2816: }
2817: return $totcodes;
2818: }
2819:
2820: sub course_portal_url {
2821: my ($cnum,$cdom) = @_;
2822: my $chome = &homeserver($cnum,$cdom);
2823: my $hostname = &hostname($chome);
2824: my $protocol = $protocol{$chome};
2825: $protocol = 'http' if ($protocol ne 'https');
2826: my %domdefaults = &get_domain_defaults($cdom);
2827: my $firsturl;
2828: if ($domdefaults{'portal_def'}) {
2829: $firsturl = $domdefaults{'portal_def'};
2830: } else {
2831: $firsturl = $protocol.'://'.$hostname;
2832: }
2833: return $firsturl;
2834: }
2835:
2836: # --------------------------------------------- Get domain config for passwords
2837:
2838: sub get_passwdconf {
2839: my ($dom) = @_;
2840: my (%passwdconf,$gotconf,$lookup);
2841: my ($result,$cached)=&is_cached_new('passwdconf',$dom);
2842: if (defined($cached)) {
2843: if (ref($result) eq 'HASH') {
2844: %passwdconf = %{$result};
2845: $gotconf = 1;
2846: }
2847: }
2848: unless ($gotconf) {
2849: my %domconfig = &get_dom('configuration',['passwords'],$dom);
2850: if (ref($domconfig{'passwords'}) eq 'HASH') {
2851: %passwdconf = %{$domconfig{'passwords'}};
2852: }
2853: my $cachetime = 24*60*60;
2854: &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
2855: }
2856: return %passwdconf;
2857: }
2858:
2859: # --------------------------------------------------- Assign a key to a student
2860:
2861: sub assign_access_key {
2862: #
2863: # a valid key looks like uname:udom#comments
2864: # comments are being appended
2865: #
2866: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2867: $kdom=
2868: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
2869: $knum=
2870: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
2871: $cdom=
2872: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2873: $cnum=
2874: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2875: $udom=$env{'user.name'} unless (defined($udom));
2876: $uname=$env{'user.domain'} unless (defined($uname));
2877: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
2878: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
2879: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
2880: # assigned to this person
2881: # - this should not happen,
2882: # unless something went wrong
2883: # the first time around
2884: # ready to assign
2885: $logentry=$1.'; '.$logentry;
2886: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
2887: $kdom,$knum) eq 'ok') {
2888: # key now belongs to user
2889: my $envkey='key.'.$cdom.'_'.$cnum;
2890: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
2891: &appenv({'environment.'.$envkey => $ckey});
2892: return 'ok';
2893: } else {
2894: return
2895: 'error: Count not permanently assign key, will need to be re-entered later.';
2896: }
2897: } else {
2898: return 'error: Could not assign key, try again later.';
2899: }
2900: } elsif (!$existing{$ckey}) {
2901: # the key does not exist
2902: return 'error: The key does not exist';
2903: } else {
2904: # the key is somebody else's
2905: return 'error: The key is already in use';
2906: }
2907: }
2908:
2909: # ------------------------------------------ put an additional comment on a key
2910:
2911: sub comment_access_key {
2912: #
2913: # a valid key looks like uname:udom#comments
2914: # comments are being appended
2915: #
2916: my ($ckey,$cdom,$cnum,$logentry)=@_;
2917: $cdom=
2918: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2919: $cnum=
2920: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2921: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2922: if ($existing{$ckey}) {
2923: $existing{$ckey}.='; '.$logentry;
2924: # ready to assign
2925: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
2926: $cdom,$cnum) eq 'ok') {
2927: return 'ok';
2928: } else {
2929: return 'error: Count not store comment.';
2930: }
2931: } else {
2932: # the key does not exist
2933: return 'error: The key does not exist';
2934: }
2935: }
2936:
2937: # ------------------------------------------------------ Generate a set of keys
2938:
2939: sub generate_access_keys {
2940: my ($number,$cdom,$cnum,$logentry)=@_;
2941: $cdom=
2942: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2943: $cnum=
2944: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2945: unless (&allowed('mky',$cdom)) { return 0; }
2946: unless (($cdom) && ($cnum)) { return 0; }
2947: if ($number>10000) { return 0; }
2948: sleep(2); # make sure don't get same seed twice
2949: srand(time()^($$+($$<<15))); # from "Programming Perl"
2950: my $total=0;
2951: for (my $i=1;$i<=$number;$i++) {
2952: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2953: sprintf("%lx",int(100000*rand)).'-'.
2954: sprintf("%lx",int(100000*rand));
2955: $newkey=~s/1/g/g; # folks mix up 1 and l
2956: $newkey=~s/0/h/g; # and also 0 and O
2957: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2958: if ($existing{$newkey}) {
2959: $i--;
2960: } else {
2961: if (&put('accesskeys',
2962: { $newkey => '# generated '.localtime().
2963: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
2964: '; '.$logentry },
2965: $cdom,$cnum) eq 'ok') {
2966: $total++;
2967: }
2968: }
2969: }
2970: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
2971: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2972: return $total;
2973: }
2974:
2975: # ------------------------------------------------------- Validate an accesskey
2976:
2977: sub validate_access_key {
2978: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2979: $cdom=
2980: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2981: $cnum=
2982: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2983: $udom=$env{'user.domain'} unless (defined($udom));
2984: $uname=$env{'user.name'} unless (defined($uname));
2985: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2986: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
2987: }
2988:
2989: # ------------------------------------- Find the section of student in a course
2990: sub devalidate_getsection_cache {
2991: my ($udom,$unam,$courseid)=@_;
2992: my $hashid="$udom:$unam:$courseid";
2993: &devalidate_cache_new('getsection',$hashid);
2994: }
2995:
2996: sub courseid_to_courseurl {
2997: my ($courseid) = @_;
2998: #already url style courseid
2999: return $courseid if ($courseid =~ m{^/});
3000:
3001: if (exists($env{'course.'.$courseid.'.num'})) {
3002: my $cnum = $env{'course.'.$courseid.'.num'};
3003: my $cdom = $env{'course.'.$courseid.'.domain'};
3004: return "/$cdom/$cnum";
3005: }
3006:
3007: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
3008: if (exists($courseinfo{'num'})) {
3009: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
3010: }
3011:
3012: return undef;
3013: }
3014:
3015: sub getsection {
3016: my ($udom,$unam,$courseid)=@_;
3017: my $cachetime=1800;
3018:
3019: my $hashid="$udom:$unam:$courseid";
3020: my ($result,$cached)=&is_cached_new('getsection',$hashid);
3021: if (defined($cached)) { return $result; }
3022:
3023: my %Pending;
3024: my %Expired;
3025: #
3026: # Each role can either have not started yet (pending), be active,
3027: # or have expired.
3028: #
3029: # If there is an active role, we are done.
3030: #
3031: # If there is more than one role which has not started yet,
3032: # choose the one which will start sooner
3033: # If there is one role which has not started yet, return it.
3034: #
3035: # If there is more than one expired role, choose the one which ended last.
3036: # If there is a role which has expired, return it.
3037: #
3038: $courseid = &courseid_to_courseurl($courseid);
3039: my %roleshash = &dump('roles',$udom,$unam,$courseid);
3040: foreach my $key (keys(%roleshash)) {
3041: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
3042: my $section=$1;
3043: if ($key eq $courseid.'_st') { $section=''; }
3044: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
3045: my $now=time;
3046: if (defined($end) && $end && ($now > $end)) {
3047: $Expired{$end}=$section;
3048: next;
3049: }
3050: if (defined($start) && $start && ($now < $start)) {
3051: $Pending{$start}=$section;
3052: next;
3053: }
3054: return &do_cache_new('getsection',$hashid,$section,$cachetime);
3055: }
3056: #
3057: # Presumedly there will be few matching roles from the above
3058: # loop and the sorting time will be negligible.
3059: if (scalar(keys(%Pending))) {
3060: my ($time) = sort {$a <=> $b} keys(%Pending);
3061: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
3062: }
3063: if (scalar(keys(%Expired))) {
3064: my @sorted = sort {$a <=> $b} keys(%Expired);
3065: my $time = pop(@sorted);
3066: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
3067: }
3068: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
3069: }
3070:
3071: sub save_cache {
3072: &purge_remembered();
3073: #&Apache::loncommon::validate_page();
3074: undef(%env);
3075: undef($env_loaded);
3076: }
3077:
3078: my $to_remember=-1;
3079: my %remembered;
3080: my %accessed;
3081: my $kicks=0;
3082: my $hits=0;
3083: sub make_key {
3084: my ($name,$id) = @_;
3085: if (length($id) > 65
3086: && length(&escape($id)) > 200) {
3087: $id=length($id).':'.&Digest::MD5::md5_hex($id);
3088: }
3089: return &escape($name.':'.$id);
3090: }
3091:
3092: sub devalidate_cache_new {
3093: my ($name,$id,$debug) = @_;
3094: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
3095: my $remembered_id=$name.':'.$id;
3096: $id=&make_key($name,$id);
3097: $memcache->delete($id);
3098: delete($remembered{$remembered_id});
3099: delete($accessed{$remembered_id});
3100: }
3101:
3102: sub is_cached_new {
3103: my ($name,$id,$debug) = @_;
3104: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
3105: if (exists($remembered{$remembered_id})) {
3106: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
3107: $accessed{$remembered_id}=[&gettimeofday()];
3108: $hits++;
3109: return ($remembered{$remembered_id},1);
3110: }
3111: $id=&make_key($name,$id);
3112: my $value = $memcache->get($id);
3113: if (!(defined($value))) {
3114: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
3115: return (undef,undef);
3116: }
3117: if ($value eq '__undef__') {
3118: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
3119: $value=undef;
3120: }
3121: &make_room($remembered_id,$value,$debug);
3122: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
3123: return ($value,1);
3124: }
3125:
3126: sub do_cache_new {
3127: my ($name,$id,$value,$time,$debug) = @_;
3128: my $remembered_id=$name.':'.$id;
3129: $id=&make_key($name,$id);
3130: my $setvalue=$value;
3131: if (!defined($setvalue)) {
3132: $setvalue='__undef__';
3133: }
3134: if (!defined($time) ) {
3135: $time=600;
3136: }
3137: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
3138: my $result = $memcache->set($id,$setvalue,$time);
3139: if (! $result) {
3140: &logthis("caching of id -> $id failed");
3141: $memcache->disconnect_all();
3142: }
3143: # need to make a copy of $value
3144: &make_room($remembered_id,$value,$debug);
3145: return $value;
3146: }
3147:
3148: sub make_room {
3149: my ($remembered_id,$value,$debug)=@_;
3150:
3151: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
3152: : $value;
3153: if ($to_remember<0) { return; }
3154: $accessed{$remembered_id}=[&gettimeofday()];
3155: if (scalar(keys(%remembered)) <= $to_remember) { return; }
3156: my $to_kick;
3157: my $max_time=0;
3158: foreach my $other (keys(%accessed)) {
3159: if (&tv_interval($accessed{$other}) > $max_time) {
3160: $to_kick=$other;
3161: $max_time=&tv_interval($accessed{$other});
3162: }
3163: }
3164: delete($remembered{$to_kick});
3165: delete($accessed{$to_kick});
3166: $kicks++;
3167: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
3168: return;
3169: }
3170:
3171: sub purge_remembered {
3172: #&logthis("Tossing ".scalar(keys(%remembered)));
3173: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
3174: undef(%remembered);
3175: undef(%accessed);
3176: }
3177: # ------------------------------------- Read an entry from a user's environment
3178:
3179: sub userenvironment {
3180: my ($udom,$unam,@what)=@_;
3181: my $items;
3182: foreach my $item (@what) {
3183: $items.=&escape($item).'&';
3184: }
3185: $items=~s/\&$//;
3186: my %returnhash=();
3187: my $uhome = &homeserver($unam,$udom);
3188: unless ($uhome eq 'no_host') {
3189: my @answer=split(/\&/,
3190: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
3191: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
3192: return %returnhash;
3193: }
3194: my $i;
3195: for ($i=0;$i<=$#what;$i++) {
3196: $returnhash{$what[$i]}=&unescape($answer[$i]);
3197: }
3198: }
3199: return %returnhash;
3200: }
3201:
3202: # ---------------------------------------------------------- Get a studentphoto
3203: sub studentphoto {
3204: my ($udom,$unam,$ext) = @_;
3205: my $home=&Apache::lonnet::homeserver($unam,$udom);
3206: if (defined($env{'request.course.id'})) {
3207: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
3208: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
3209: return(&retrievestudentphoto($udom,$unam,$ext));
3210: } else {
3211: my ($result,$perm_reqd)=
3212: &Apache::lonnet::auto_photo_permission($unam,$udom);
3213: if ($result eq 'ok') {
3214: if (!($perm_reqd eq 'yes')) {
3215: return(&retrievestudentphoto($udom,$unam,$ext));
3216: }
3217: }
3218: }
3219: }
3220: } else {
3221: my ($result,$perm_reqd) =
3222: &Apache::lonnet::auto_photo_permission($unam,$udom);
3223: if ($result eq 'ok') {
3224: if (!($perm_reqd eq 'yes')) {
3225: return(&retrievestudentphoto($udom,$unam,$ext));
3226: }
3227: }
3228: }
3229: return '/adm/lonKaputt/lonlogo_broken.gif';
3230: }
3231:
3232: sub retrievestudentphoto {
3233: my ($udom,$unam,$ext,$type) = @_;
3234: my $home=&Apache::lonnet::homeserver($unam,$udom);
3235: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
3236: if ($ret eq 'ok') {
3237: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
3238: if ($type eq 'thumbnail') {
3239: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
3240: }
3241: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
3242: return $tokenurl;
3243: } else {
3244: if ($type eq 'thumbnail') {
3245: return '/adm/lonKaputt/genericstudent_tn.gif';
3246: } else {
3247: return '/adm/lonKaputt/lonlogo_broken.gif';
3248: }
3249: }
3250: }
3251:
3252: # -------------------------------------------------------------------- New chat
3253:
3254: sub chatsend {
3255: my ($newentry,$anon,$group)=@_;
3256: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
3257: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3258: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
3259: &reply('chatsend:'.$cdom.':'.$cnum.':'.
3260: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
3261: &escape($newentry)).':'.$group,$chome);
3262: }
3263:
3264: # ------------------------------------------ Find current version of a resource
3265:
3266: sub getversion {
3267: my $fname=&clutter(shift);
3268: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
3269: return ¤tversion(&filelocation('',$fname));
3270: }
3271:
3272: sub currentversion {
3273: my $fname=shift;
3274: my $author=$fname;
3275: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3276: my ($udom,$uname)=split(/\//,$author);
3277: my $home=&homeserver($uname,$udom);
3278: if ($home eq 'no_host') {
3279: return -1;
3280: }
3281: my $answer=&reply("currentversion:$fname",$home);
3282: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3283: return -1;
3284: }
3285: return $answer;
3286: }
3287:
3288: #
3289: # Return special version number of resource if set by override, empty otherwise
3290: #
3291: sub usedversion {
3292: my $fname=shift;
3293: unless ($fname) { $fname=$env{'request.uri'}; }
3294: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
3295: if ($urlversion) { return $urlversion; }
3296: return '';
3297: }
3298:
3299: # ----------------------------- Subscribe to a resource, return URL if possible
3300:
3301: sub subscribe {
3302: my $fname=shift;
3303: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
3304: $fname=~s/[\n\r]//g;
3305: my $author=$fname;
3306: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3307: my ($udom,$uname)=split(/\//,$author);
3308: my $home=homeserver($uname,$udom);
3309: if ($home eq 'no_host') {
3310: return 'not_found';
3311: }
3312: my $answer=reply("sub:$fname",$home);
3313: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3314: $answer.=' by '.$home;
3315: }
3316: return $answer;
3317: }
3318:
3319: # -------------------------------------------------------------- Replicate file
3320:
3321: sub repcopy {
3322: my $filename=shift;
3323: $filename=~s/\/+/\//g;
3324: my $londocroot = $perlvar{'lonDocRoot'};
3325: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
3326: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
3327: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3328: $filename=~m{^/*(uploaded|editupload)/}) {
3329: return &repcopy_userfile($filename);
3330: }
3331: $filename=~s/[\n\r]//g;
3332: my $transname="$filename.in.transfer";
3333: # FIXME: this should flock
3334: if ((-e $filename) || (-e $transname)) { return 'ok'; }
3335: my $remoteurl=subscribe($filename);
3336: if ($remoteurl =~ /^con_lost by/) {
3337: &logthis("Subscribe returned $remoteurl: $filename");
3338: return 'unavailable';
3339: } elsif ($remoteurl eq 'not_found') {
3340: #&logthis("Subscribe returned not_found: $filename");
3341: return 'not_found';
3342: } elsif ($remoteurl =~ /^rejected by/) {
3343: &logthis("Subscribe returned $remoteurl: $filename");
3344: return 'forbidden';
3345: } elsif ($remoteurl eq 'directory') {
3346: return 'ok';
3347: } else {
3348: my $author=$filename;
3349: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3350: my ($udom,$uname)=split(/\//,$author);
3351: my $home=homeserver($uname,$udom);
3352: unless ($home eq $perlvar{'lonHostID'}) {
3353: my @parts=split(/\//,$filename);
3354: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
3355: if ($path ne "$londocroot/res") {
3356: &logthis("Malconfiguration for replication: $filename");
3357: return 'bad_request';
3358: }
3359: my $count;
3360: for ($count=5;$count<$#parts;$count++) {
3361: $path.="/$parts[$count]";
3362: if ((-e $path)!=1) {
3363: mkdir($path,0777);
3364: }
3365: }
3366: my $request=new HTTP::Request('GET',"$remoteurl");
3367: my $response;
3368: if ($remoteurl =~ m{/raw/}) {
3369: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
3370: } else {
3371: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
3372: }
3373: if ($response->is_error()) {
3374: unlink($transname);
3375: my $message=$response->status_line;
3376: &logthis("<font color=\"blue\">WARNING:"
3377: ." LWP get: $message: $filename</font>");
3378: return 'unavailable';
3379: } else {
3380: if ($remoteurl!~/\.meta$/) {
3381: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
3382: my $mresponse;
3383: if ($remoteurl =~ m{/raw/}) {
3384: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
3385: } else {
3386: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
3387: }
3388: if ($mresponse->is_error()) {
3389: unlink($filename.'.meta');
3390: &logthis(
3391: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
3392: }
3393: }
3394: rename($transname,$filename);
3395: return 'ok';
3396: }
3397: }
3398: }
3399: }
3400:
3401: # ------------------------------------------------- Unsubscribe from a resource
3402:
3403: sub unsubscribe {
3404: my ($fname) = @_;
3405: my $answer;
3406: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
3407: $fname=~s/[\n\r]//g;
3408: my $author=$fname;
3409: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3410: my ($udom,$uname)=split(/\//,$author);
3411: my $home=homeserver($uname,$udom);
3412: if ($home eq 'no_host') {
3413: $answer = 'no_host';
3414: } elsif (grep { $_ eq $home } ¤t_machine_ids()) {
3415: $answer = 'home';
3416: } else {
3417: my $defdom = $perlvar{'lonDefDomain'};
3418: if (&will_trust('content',$defdom,$udom)) {
3419: $answer = reply("unsub:$fname",$home);
3420: } else {
3421: $answer = 'untrusted';
3422: }
3423: }
3424: return $answer;
3425: }
3426:
3427: # ------------------------------------------------ Get server side include body
3428: sub ssi_body {
3429: my ($filelink,%form)=@_;
3430: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3431: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3432: }
3433: my $output='';
3434: my $response;
3435: if ($filelink=~/^https?\:/) {
3436: ($output,$response)=&externalssi($filelink);
3437: } else {
3438: $filelink .= $filelink=~/\?/ ? '&' : '?';
3439: $filelink .= 'inhibitmenu=yes';
3440: ($output,$response)=&ssi($filelink,%form);
3441: }
3442: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
3443: $output=~s/^.*?\<body[^\>]*\>//si;
3444: $output=~s/\<\/body\s*\>.*?$//si;
3445: if (wantarray) {
3446: return ($output, $response);
3447: } else {
3448: return $output;
3449: }
3450: }
3451:
3452: # --------------------------------------------------------- Server Side Include
3453:
3454: sub absolute_url {
3455: my ($host_name) = @_;
3456: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3457: if ($host_name eq '') {
3458: $host_name = $ENV{'SERVER_NAME'};
3459: }
3460: return $protocol.$host_name;
3461: }
3462:
3463: #
3464: # Server side include.
3465: # Parameters:
3466: # fn Possibly encrypted resource name/id.
3467: # form Hash that describes how the rendering should be done
3468: # and other things.
3469: # Returns:
3470: # Scalar context: The content of the response.
3471: # Array context: 2 element list of the content and the full response object.
3472: #
3473: sub ssi {
3474:
3475: my ($fn,%form)=@_;
3476: my $request;
3477:
3478: $form{'no_update_last_known'}=1;
3479: &Apache::lonenc::check_encrypt(\$fn);
3480: if (%form) {
3481: $request=new HTTP::Request('POST',&absolute_url().$fn);
3482: $request->content(join('&',map {
3483: my $name = escape($_);
3484: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3485: ? join("&$name=", map {escape($_) } @{$form{$_}})
3486: : &escape($form{$_}) );
3487: } keys(%form)));
3488: } else {
3489: $request=new HTTP::Request('GET',&absolute_url().$fn);
3490: }
3491:
3492: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
3493: my $lonhost = $perlvar{'lonHostID'};
3494: my $islocal;
3495: if (($env{'request.course.id'}) &&
3496: ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
3497: ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
3498: ($form{'grade_symb'} ne '') &&
3499: (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
3500: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
3501: $islocal = 1;
3502: }
3503: my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
3504: '','','',$islocal);
3505:
3506: if (wantarray) {
3507: return ($response->content, $response);
3508: } else {
3509: return $response->content;
3510: }
3511: }
3512:
3513: sub externalssi {
3514: my ($url)=@_;
3515: my $request=new HTTP::Request('GET',$url);
3516: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
3517: if (wantarray) {
3518: return ($response->content, $response);
3519: } else {
3520: return $response->content;
3521: }
3522: }
3523:
3524:
3525: # If the local copy of a replicated resource is outdated, trigger a
3526: # connection from the homeserver to flush the delayed queue. If no update
3527: # happens, remove local copies of outdated resource (and corresponding
3528: # metadata file).
3529:
3530: sub remove_stale_resfile {
3531: my ($url) = @_;
3532: my $removed;
3533: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3534: my $audom = $1;
3535: my $auname = $2;
3536: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
3537: my $homeserver = &homeserver($auname,$audom);
3538: unless (($homeserver eq 'no_host') ||
3539: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3540: my $fname = &filelocation('',$url);
3541: if (-e $fname) {
3542: my $hostname = &hostname($homeserver);
3543: if ($hostname) {
3544: my $protocol = $protocol{$homeserver};
3545: $protocol = 'http' if ($protocol ne 'https');
3546: my $uri = &declutter($url);
3547: my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
3548: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
3549: if ($response->is_success()) {
3550: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3551: my $locmodtime = (stat($fname))[9];
3552: if ($locmodtime < $remmodtime) {
3553: my $stale;
3554: my $answer = &reply('pong',$homeserver);
3555: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3556: sleep(0.2);
3557: $locmodtime = (stat($fname))[9];
3558: if ($locmodtime < $remmodtime) {
3559: my $posstransfer = $fname.'.in.transfer';
3560: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3561: $removed = 1;
3562: } else {
3563: $stale = 1;
3564: }
3565: } else {
3566: $removed = 1;
3567: }
3568: } else {
3569: $stale = 1;
3570: }
3571: if ($stale) {
3572: if (unlink($fname)) {
3573: if ($uri!~/\.meta$/) {
3574: if (-e $fname.'.meta') {
3575: unlink($fname.'.meta');
3576: }
3577: }
3578: my $unsubresult = &unsubscribe($fname);
3579: unless ($unsubresult eq 'ok') {
3580: &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
3581: }
3582: $removed = 1;
3583: }
3584: }
3585: }
3586: }
3587: }
3588: }
3589: }
3590: }
3591: }
3592: return $removed;
3593: }
3594:
3595: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3596:
3597: sub allowuploaded {
3598: my ($srcurl,$url)=@_;
3599: $url=&clutter(&declutter($url));
3600: my $dir=$url;
3601: $dir=~s/\/[^\/]+$//;
3602: my %httpref=();
3603: my $httpurl=&hreflocation('',$url);
3604: $httpref{'httpref.'.$httpurl}=$srcurl;
3605: &Apache::lonnet::appenv(\%httpref);
3606: }
3607:
3608: #
3609: # Determine if the current user should be able to edit a particular resource,
3610: # when viewing in course context.
3611: # (a) When viewing resource used to determine if "Edit" item is included in
3612: # Functions.
3613: # (b) When displaying folder contents in course editor, used to determine if
3614: # "Edit" link will be displayed alongside resource.
3615: #
3616: # input: six args -- filename (decluttered), course number, course domain,
3617: # url, symb (if registered) and group (if this is a group
3618: # item -- e.g., bulletin board, group page etc.).
3619: # output: array of five scalars --
3620: # $cfile -- url for file editing if editable on current server
3621: # $home -- homeserver of resource (i.e., for author if published,
3622: # or course if uploaded.).
3623: # $switchserver -- 1 if server switch will be needed.
3624: # $forceedit -- 1 if icon/link should be to go to edit mode
3625: # $forceview -- 1 if icon/link should be to go to view mode
3626: #
3627:
3628: sub can_edit_resource {
3629: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3630: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3631: #
3632: # For aboutme pages user can only edit his/her own.
3633: #
3634: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
3635: my ($sdom,$sname) = ($1,$2);
3636: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3637: $home = $env{'user.home'};
3638: $cfile = $resurl;
3639: if ($env{'form.forceedit'}) {
3640: $forceview = 1;
3641: } else {
3642: $forceedit = 1;
3643: }
3644: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3645: } else {
3646: return;
3647: }
3648: }
3649:
3650: if ($env{'request.course.id'}) {
3651: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3652: if ($group ne '') {
3653: # if this is a group homepage or group bulletin board, check group privs
3654: my $allowed = 0;
3655: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3656: if ((&allowed('mdg',$env{'request.course.id'}.
3657: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3658: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3659: $allowed = 1;
3660: }
3661: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3662: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3663: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3664: $allowed = 1;
3665: }
3666: }
3667: if ($allowed) {
3668: $home=&homeserver($cnum,$cdom);
3669: if ($env{'form.forceedit'}) {
3670: $forceview = 1;
3671: } else {
3672: $forceedit = 1;
3673: }
3674: $cfile = $resurl;
3675: } else {
3676: return;
3677: }
3678: } else {
3679: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3680: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3681: return;
3682: }
3683: } elsif (!$crsedit) {
3684: #
3685: # No edit allowed where CC has switched to student role.
3686: #
3687: return;
3688: }
3689: }
3690: }
3691:
3692: if ($file ne '') {
3693: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
3694: if (&is_course_upload($file,$cnum,$cdom)) {
3695: $uploaded = 1;
3696: $incourse = 1;
3697: if ($file =~/\.(htm|html|css|js|txt)$/) {
3698: $cfile = &hreflocation('',$file);
3699: if ($env{'form.forceedit'}) {
3700: $forceview = 1;
3701: } else {
3702: $forceedit = 1;
3703: }
3704: }
3705: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3706: $incourse = 1;
3707: if ($env{'form.forceedit'}) {
3708: $forceview = 1;
3709: } else {
3710: $forceedit = 1;
3711: }
3712: $cfile = $resurl;
3713: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3714: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3715: $incourse = 1;
3716: if ($env{'form.forceedit'}) {
3717: $forceview = 1;
3718: } else {
3719: $forceedit = 1;
3720: }
3721: $cfile = $resurl;
3722: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
3723: $incourse = 1;
3724: $cfile = $resurl.'/smpedit';
3725: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
3726: $incourse = 1;
3727: if ($env{'form.forceedit'}) {
3728: $forceview = 1;
3729: } else {
3730: $forceedit = 1;
3731: }
3732: $cfile = $resurl;
3733: } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
3734: my ($map,$id,$res) = &decode_symb($symb);
3735: if ($map =~ /\.page$/) {
3736: $incourse = 1;
3737: if ($env{'form.forceedit'}) {
3738: $forceview = 1;
3739: $cfile = $map;
3740: } else {
3741: $forceedit = 1;
3742: $cfile = '/adm/wrapper'.$resurl;
3743: }
3744: }
3745: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
3746: $incourse = 1;
3747: if ($env{'form.forceedit'}) {
3748: $forceview = 1;
3749: } else {
3750: $forceedit = 1;
3751: }
3752: $cfile = $resurl;
3753: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3754: $incourse = 1;
3755: if ($env{'form.forceedit'}) {
3756: $forceview = 1;
3757: } else {
3758: $forceedit = 1;
3759: }
3760: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
3761: }
3762: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3763: my $template = '/res/lib/templates/simpleproblem.problem';
3764: if (&is_on_map($template)) {
3765: $incourse = 1;
3766: $forceview = 1;
3767: $cfile = $template;
3768: }
3769: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3770: $incourse = 1;
3771: if ($env{'form.forceedit'}) {
3772: $forceview = 1;
3773: } else {
3774: $forceedit = 1;
3775: }
3776: $cfile = $resurl;
3777: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3778: $incourse = 1;
3779: if ($env{'form.forceedit'}) {
3780: $forceview = 1;
3781: } else {
3782: $forceedit = 1;
3783: }
3784: $cfile = $resurl;
3785: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3786: $incourse = 1;
3787: $forceview = 1;
3788: if ($symb) {
3789: my ($map,$id,$res)=&decode_symb($symb);
3790: $env{'request.symb'} = $symb;
3791: $cfile = &clutter($res);
3792: } else {
3793: $cfile = $env{'form.suppurl'};
3794: my $escfile = &unescape($cfile);
3795: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
3796: $cfile = '/adm/wrapper'.$escfile;
3797: } else {
3798: $escfile =~ s{^http://}{};
3799: $cfile = &escape("/adm/wrapper/ext/$escfile");
3800: }
3801: }
3802: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3803: if ($env{'form.forceedit'}) {
3804: $forceview = 1;
3805: } else {
3806: $forceedit = 1;
3807: }
3808: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
3809: }
3810: }
3811: if ($uploaded || $incourse) {
3812: $home=&homeserver($cnum,$cdom);
3813: } elsif ($file !~ m{/$}) {
3814: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3815: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3816: # Check that the user has permission to edit this resource
3817: my $setpriv = 1;
3818: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3819: if (defined($cfudom)) {
3820: $home=&homeserver($cfuname,$cfudom);
3821: $cfile=$file;
3822: }
3823: }
3824: if (($cfile ne '') && (!$incourse || $uploaded) &&
3825: (($home ne '') && ($home ne 'no_host'))) {
3826: my @ids=¤t_machine_ids();
3827: unless (grep(/^\Q$home\E$/,@ids)) {
3828: $switchserver=1;
3829: }
3830: }
3831: }
3832: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3833: }
3834:
3835: sub is_course_upload {
3836: my ($file,$cnum,$cdom) = @_;
3837: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3838: $uploadpath =~ s{^\/}{};
3839: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3840: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3841: return 1;
3842: }
3843: return;
3844: }
3845:
3846: sub in_course {
3847: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3848: if ($hideprivileged) {
3849: my $skipuser;
3850: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3851: my @possdoms = ($cdom);
3852: if ($coursehash{'checkforpriv'}) {
3853: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3854: }
3855: if (&privileged($uname,$udom,\@possdoms)) {
3856: $skipuser = 1;
3857: if ($coursehash{'nothideprivileged'}) {
3858: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3859: my $user;
3860: if ($item =~ /:/) {
3861: $user = $item;
3862: } else {
3863: $user = join(':',split(/[\@]/,$item));
3864: }
3865: if ($user eq $uname.':'.$udom) {
3866: undef($skipuser);
3867: last;
3868: }
3869: }
3870: }
3871: if ($skipuser) {
3872: return 0;
3873: }
3874: }
3875: }
3876: $type ||= 'any';
3877: if (!defined($cdom) || !defined($cnum)) {
3878: my $cid = $env{'request.course.id'};
3879: $cdom = $env{'course.'.$cid.'.domain'};
3880: $cnum = $env{'course.'.$cid.'.num'};
3881: }
3882: my $typesref;
3883: if (($type eq 'any') || ($type eq 'all')) {
3884: $typesref = ['active','previous','future'];
3885: } elsif ($type eq 'previous' || $type eq 'future') {
3886: $typesref = [$type];
3887: }
3888: my %roles = &get_my_roles($uname,$udom,'userroles',
3889: $typesref,undef,[$cdom]);
3890: my ($tmp) = keys(%roles);
3891: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3892: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3893: if (@course_roles > 0) {
3894: return 1;
3895: }
3896: return 0;
3897: }
3898:
3899: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
3900: # input: action, courseID, current domain, intended
3901: # path to file, source of file, instruction to parse file for objects,
3902: # ref to hash for embedded objects,
3903: # ref to hash for codebase of java objects.
3904: # reference to scalar to accommodate mime type determined
3905: # from File::MMagic if $parser = parse.
3906: #
3907: # output: url to file (if action was uploaddoc),
3908: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
3909: #
3910: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3911: # course.
3912: #
3913: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3914: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3915: # course's home server.
3916: #
3917: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3918: # be copied from $source (current location) to
3919: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3920: # and will then be copied to
3921: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3922: # course's home server.
3923: #
3924: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3925: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
3926: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3927: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3928: # in course's home server.
3929: #
3930:
3931: sub process_coursefile {
3932: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3933: $mimetype)=@_;
3934: my $fetchresult;
3935: my $home=&homeserver($docuname,$docudom);
3936: if ($action eq 'propagate') {
3937: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3938: $home);
3939: } else {
3940: my $fpath = '';
3941: my $fname = $file;
3942: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3943: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3944: my $filepath = &build_filepath($fpath);
3945: if ($action eq 'copy') {
3946: if ($source eq '') {
3947: $fetchresult = 'no source file';
3948: return $fetchresult;
3949: } else {
3950: my $destination = $filepath.'/'.$fname;
3951: rename($source,$destination);
3952: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3953: $home);
3954: }
3955: } elsif ($action eq 'uploaddoc') {
3956: open(my $fh,'>',$filepath.'/'.$fname);
3957: print $fh $env{'form.'.$source};
3958: close($fh);
3959: if ($parser eq 'parse') {
3960: my $mm = new File::MMagic;
3961: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3962: if ($type eq 'text/html') {
3963: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3964: unless ($parse_result eq 'ok') {
3965: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3966: }
3967: }
3968: if (ref($mimetype)) {
3969: $$mimetype = $type;
3970: }
3971: }
3972: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3973: $home);
3974: if ($fetchresult eq 'ok') {
3975: return '/uploaded/'.$fpath.'/'.$fname;
3976: } else {
3977: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3978: ' to host '.$home.': '.$fetchresult);
3979: return '/adm/notfound.html';
3980: }
3981: }
3982: }
3983: unless ( $fetchresult eq 'ok') {
3984: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3985: ' to host '.$home.': '.$fetchresult);
3986: }
3987: return $fetchresult;
3988: }
3989:
3990: sub build_filepath {
3991: my ($fpath) = @_;
3992: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3993: unless ($fpath eq '') {
3994: my @parts=split('/',$fpath);
3995: foreach my $part (@parts) {
3996: $filepath.= '/'.$part;
3997: if ((-e $filepath)!=1) {
3998: mkdir($filepath,0777);
3999: }
4000: }
4001: }
4002: return $filepath;
4003: }
4004:
4005: sub store_edited_file {
4006: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
4007: my $file = $primary_url;
4008: $file =~ s#^/uploaded/$docudom/$docuname/##;
4009: my $fpath = '';
4010: my $fname = $file;
4011: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
4012: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
4013: my $filepath = &build_filepath($fpath);
4014: open(my $fh,'>',$filepath.'/'.$fname);
4015: print $fh $content;
4016: close($fh);
4017: my $home=&homeserver($docuname,$docudom);
4018: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
4019: $home);
4020: if ($$fetchresult eq 'ok') {
4021: return '/uploaded/'.$fpath.'/'.$fname;
4022: } else {
4023: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
4024: ' to host '.$home.': '.$$fetchresult);
4025: return '/adm/notfound.html';
4026: }
4027: }
4028:
4029: sub clean_filename {
4030: my ($fname,$args)=@_;
4031: # Replace Windows backslashes by forward slashes
4032: $fname=~s/\\/\//g;
4033: if (!$args->{'keep_path'}) {
4034: # Get rid of everything but the actual filename
4035: $fname=~s/^.*\/([^\/]+)$/$1/;
4036: }
4037: # Replace spaces by underscores
4038: $fname=~s/\s+/\_/g;
4039: # Transliterate non-ascii text to ascii
4040: my $lang = &Apache::lonlocal::current_language();
4041: $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
4042: # Replace all other weird characters by nothing
4043: $fname=~s{[^/\w\.\-]}{}g;
4044: # Replace all .\d. sequences with _\d. so they no longer look like version
4045: # numbers
4046: $fname=~s/\.(\d+)(?=\.)/_$1/g;
4047: return $fname;
4048: }
4049:
4050: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
4051: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
4052: # image with the same aspect ratio as the original, but with dimensions which do
4053: # not exceed $resizewidth and $resizeheight.
4054:
4055: sub resizeImage {
4056: my ($img_path,$resizewidth,$resizeheight) = @_;
4057: my $ima = Image::Magick->new;
4058: my $resized;
4059: if (-e $img_path) {
4060: $ima->Read($img_path);
4061: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
4062: my $width = $ima->Get('width');
4063: my $height = $ima->Get('height');
4064: if ($width > $resizewidth) {
4065: my $factor = $width/$resizewidth;
4066: my $newheight = $height/$factor;
4067: $ima->Scale(width=>$resizewidth,height=>$newheight);
4068: $resized = 1;
4069: }
4070: }
4071: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
4072: my $width = $ima->Get('width');
4073: my $height = $ima->Get('height');
4074: if ($height > $resizeheight) {
4075: my $factor = $height/$resizeheight;
4076: my $newwidth = $width/$factor;
4077: $ima->Scale(width=>$newwidth,height=>$resizeheight);
4078: $resized = 1;
4079: }
4080: }
4081: if ($resized) {
4082: $ima->Write($img_path);
4083: }
4084: }
4085: return;
4086: }
4087:
4088: # --------------- Take an uploaded file and put it into the userfiles directory
4089: # input: $formname - the contents of the file are in $env{"form.$formname"}
4090: # the desired filename is in $env{"form.$formname.filename"}
4091: # $context - possible values: coursedoc, existingfile, overwrite,
4092: # canceloverwrite, scantron or ''.
4093: # if 'coursedoc': upload to the current course
4094: # if 'existingfile': write file to tmp/overwrites directory
4095: # if 'canceloverwrite': delete file written to tmp/overwrites directory
4096: # $context is passed as argument to &finishuserfileupload
4097: # $subdir - directory in userfile to store the file into
4098: # $parser - instruction to parse file for objects ($parser = parse) or
4099: # if context is 'scantron', $parser is hashref of csv column mapping
4100: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
4101: # Section => 4, CODE => 5, FirstQuestion => 9 }).
4102: # $allfiles - reference to hash for embedded objects
4103: # $codebase - reference to hash for codebase of java objects
4104: # $desuname - username for permanent storage of uploaded file
4105: # $dsetudom - domain for permanaent storage of uploaded file
4106: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
4107: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
4108: # $resizewidth - width (pixels) to which to resize uploaded image
4109: # $resizeheight - height (pixels) to which to resize uploaded image
4110: # $mimetype - reference to scalar to accommodate mime type determined
4111: # from File::MMagic.
4112: #
4113: # output: url of file in userspace, or error: <message>
4114: # or /adm/notfound.html if failure to upload occurse
4115:
4116: sub userfileupload {
4117: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
4118: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
4119: if (!defined($subdir)) { $subdir='unknown'; }
4120: my $fname=$env{'form.'.$formname.'.filename'};
4121: $fname=&clean_filename($fname);
4122: # See if there is anything left
4123: unless ($fname) { return 'error: no uploaded file'; }
4124: # If filename now begins with a . prepend unix timestamp _ milliseconds
4125: if ($fname =~ /^\./) {
4126: my ($s,$usec) = &gettimeofday();
4127: while (length($usec) < 6) {
4128: $usec = '0'.$usec;
4129: }
4130: $fname = $s.'_'.substr($usec,0,3).$fname;
4131: }
4132: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
4133: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
4134: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
4135: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
4136: my $now = time;
4137: my $filepath;
4138: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
4139: $filepath = 'tmp/helprequests/'.$now;
4140: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
4141: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
4142: '_'.$env{'user.domain'}.'/pending';
4143: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
4144: my ($docuname,$docudom);
4145: if ($destudom =~ /^$match_domain$/) {
4146: $docudom = $destudom;
4147: } else {
4148: $docudom = $env{'user.domain'};
4149: }
4150: if ($destuname =~ /^$match_username$/) {
4151: $docuname = $destuname;
4152: } else {
4153: $docuname = $env{'user.name'};
4154: }
4155: if (exists($env{'form.group'})) {
4156: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4157: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4158: }
4159: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
4160: if ($context eq 'canceloverwrite') {
4161: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
4162: if (-e $tempfile) {
4163: my @info = stat($tempfile);
4164: if ($info[9] eq $env{'form.timestamp'}) {
4165: unlink($tempfile);
4166: }
4167: }
4168: return;
4169: }
4170: }
4171: # Create the directory if not present
4172: my @parts=split(/\//,$filepath);
4173: my $fullpath = $perlvar{'lonDaemons'};
4174: for (my $i=0;$i<@parts;$i++) {
4175: $fullpath .= '/'.$parts[$i];
4176: if ((-e $fullpath)!=1) {
4177: mkdir($fullpath,0777);
4178: }
4179: }
4180: open(my $fh,'>',$fullpath.'/'.$fname);
4181: print $fh $env{'form.'.$formname};
4182: close($fh);
4183: if ($context eq 'existingfile') {
4184: my @info = stat($fullpath.'/'.$fname);
4185: return ($fullpath.'/'.$fname,$info[9]);
4186: } else {
4187: return $fullpath.'/'.$fname;
4188: }
4189: }
4190: if ($subdir eq 'scantron') {
4191: $fname = 'scantron_orig_'.$fname;
4192: } else {
4193: $fname="$subdir/$fname";
4194: }
4195: if ($context eq 'coursedoc') {
4196: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4197: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4198: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
4199: return &finishuserfileupload($docuname,$docudom,
4200: $formname,$fname,$parser,$allfiles,
4201: $codebase,$thumbwidth,$thumbheight,
4202: $resizewidth,$resizeheight,$context,$mimetype);
4203: } else {
4204: if ($env{'form.folder'}) {
4205: $fname=$env{'form.folder'}.'/'.$fname;
4206: }
4207: return &process_coursefile('uploaddoc',$docuname,$docudom,
4208: $fname,$formname,$parser,
4209: $allfiles,$codebase,$mimetype);
4210: }
4211: } elsif (defined($destuname)) {
4212: my $docuname=$destuname;
4213: my $docudom=$destudom;
4214: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4215: $parser,$allfiles,$codebase,
4216: $thumbwidth,$thumbheight,
4217: $resizewidth,$resizeheight,$context,$mimetype);
4218: } else {
4219: my $docuname=$env{'user.name'};
4220: my $docudom=$env{'user.domain'};
4221: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
4222: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4223: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4224: }
4225: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4226: $parser,$allfiles,$codebase,
4227: $thumbwidth,$thumbheight,
4228: $resizewidth,$resizeheight,$context,$mimetype);
4229: }
4230: }
4231:
4232: sub finishuserfileupload {
4233: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
4234: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
4235: my $path=$docudom.'/'.$docuname.'/';
4236: my $filepath=$perlvar{'lonDocRoot'};
4237:
4238: my ($fnamepath,$file,$fetchthumb);
4239: $file=$fname;
4240: if ($fname=~m|/|) {
4241: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
4242: $path.=$fnamepath.'/';
4243: }
4244: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
4245: my $count;
4246: for ($count=4;$count<=$#parts;$count++) {
4247: $filepath.="/$parts[$count]";
4248: if ((-e $filepath)!=1) {
4249: mkdir($filepath,0777);
4250: }
4251: }
4252:
4253: # Save the file
4254: {
4255: if (!open(FH,'>',$filepath.'/'.$file)) {
4256: &logthis('Failed to create '.$filepath.'/'.$file);
4257: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
4258: return '/adm/notfound.html';
4259: }
4260: if ($context eq 'overwrite') {
4261: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
4262: my $target = $filepath.'/'.$file;
4263: if (-e $source) {
4264: my @info = stat($source);
4265: if ($info[9] eq $env{'form.timestamp'}) {
4266: unless (&File::Copy::move($source,$target)) {
4267: &logthis('Failed to overwrite '.$filepath.'/'.$file);
4268: return "Moving from $source failed";
4269: }
4270: } else {
4271: return "Temporary file: $source had unexpected date/time for last modification";
4272: }
4273: } else {
4274: return "Temporary file: $source missing";
4275: }
4276: } elsif (!print FH ($env{'form.'.$formname})) {
4277: &logthis('Failed to write to '.$filepath.'/'.$file);
4278: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
4279: return '/adm/notfound.html';
4280: }
4281: close(FH);
4282: if ($resizewidth && $resizeheight) {
4283: my $mm = new File::MMagic;
4284: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
4285: if ($mime_type =~ m{^image/}) {
4286: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
4287: }
4288: }
4289: }
4290: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
4291: if (ref($mimetype)) {
4292: if ($$mimetype eq '') {
4293: my $mm = new File::MMagic;
4294: my $type = $mm->checktype_filename($filepath.'/'.$file);
4295: $$mimetype = $type;
4296: }
4297: }
4298: }
4299: if (($context ne 'scantron') && ($parser eq 'parse')) {
4300: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
4301: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
4302: $allfiles,$codebase);
4303: unless ($parse_result eq 'ok') {
4304: &logthis('Failed to parse '.$filepath.$file.
4305: ' for embedded media: '.$parse_result);
4306: }
4307: }
4308: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
4309: my $format = $env{'form.scantron_format'};
4310: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
4311: }
4312: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
4313: my $input = $filepath.'/'.$file;
4314: my $output = $filepath.'/'.'tn-'.$file;
4315: my $thumbsize = $thumbwidth.'x'.$thumbheight;
4316: my @args = ('convert','-sample',$thumbsize,$input,$output);
4317: system({$args[0]} @args);
4318: if (-e $filepath.'/'.'tn-'.$file) {
4319: $fetchthumb = 1;
4320: }
4321: }
4322:
4323: # Notify homeserver to grep it
4324: #
4325: my $docuhome=&homeserver($docuname,$docudom);
4326: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
4327: if ($fetchresult eq 'ok') {
4328: if ($fetchthumb) {
4329: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
4330: if ($thumbresult ne 'ok') {
4331: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
4332: $docuhome.': '.$thumbresult);
4333: }
4334: }
4335: #
4336: # Return the URL to it
4337: return '/uploaded/'.$path.$file;
4338: } else {
4339: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
4340: ': '.$fetchresult);
4341: return '/adm/notfound.html';
4342: }
4343: }
4344:
4345: sub extract_embedded_items {
4346: my ($fullpath,$allfiles,$codebase,$content) = @_;
4347: my @state = ();
4348: my (%lastids,%related,%shockwave,%flashvars);
4349: my %javafiles = (
4350: codebase => '',
4351: code => '',
4352: archive => ''
4353: );
4354: my %mediafiles = (
4355: src => '',
4356: movie => '',
4357: );
4358: my $p;
4359: if ($content) {
4360: $p = HTML::LCParser->new($content);
4361: } else {
4362: $p = HTML::LCParser->new($fullpath);
4363: }
4364: while (my $t=$p->get_token()) {
4365: if ($t->[0] eq 'S') {
4366: my ($tagname, $attr) = ($t->[1],$t->[2]);
4367: push(@state, $tagname);
4368: if (lc($tagname) eq 'allow') {
4369: &add_filetype($allfiles,$attr->{'src'},'src');
4370: }
4371: if (lc($tagname) eq 'img') {
4372: &add_filetype($allfiles,$attr->{'src'},'src');
4373: }
4374: if (lc($tagname) eq 'a') {
4375: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
4376: &add_filetype($allfiles,$attr->{'href'},'href');
4377: }
4378: }
4379: if (lc($tagname) eq 'script') {
4380: my $src;
4381: if ($attr->{'archive'} =~ /\.jar$/i) {
4382: &add_filetype($allfiles,$attr->{'archive'},'archive');
4383: } else {
4384: if ($attr->{'src'} ne '') {
4385: $src = $attr->{'src'};
4386: &add_filetype($allfiles,$src,'src');
4387: }
4388: }
4389: my $text = $p->get_trimmed_text();
4390: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4391: my @swfargs = split(/,/,$1);
4392: foreach my $item (@swfargs) {
4393: $item =~ s/["']//g;
4394: $item =~ s/^\s+//;
4395: $item =~ s/\s+$//;
4396: }
4397: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4398: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4399: push(@{$related{$swfargs[0]}},$swfargs[2]);
4400: } else {
4401: $related{$swfargs[0]} = [$swfargs[2]];
4402: }
4403: }
4404: }
4405: }
4406: if (lc($tagname) eq 'link') {
4407: if (lc($attr->{'rel'}) eq 'stylesheet') {
4408: &add_filetype($allfiles,$attr->{'href'},'href');
4409: }
4410: }
4411: if (lc($tagname) eq 'object' ||
4412: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4413: foreach my $item (keys(%javafiles)) {
4414: $javafiles{$item} = '';
4415: }
4416: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4417: $lastids{lc($tagname)} = $attr->{'id'};
4418: }
4419: }
4420: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4421: my $name = lc($attr->{'name'});
4422: foreach my $item (keys(%javafiles)) {
4423: if ($name eq $item) {
4424: $javafiles{$item} = $attr->{'value'};
4425: last;
4426: }
4427: }
4428: my $pathfrom;
4429: foreach my $item (keys(%mediafiles)) {
4430: if ($name eq $item) {
4431: $pathfrom = $attr->{'value'};
4432: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4433: &add_filetype($allfiles,$pathfrom,$name);
4434: last;
4435: }
4436: }
4437: if ($name eq 'flashvars') {
4438: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4439: }
4440: if ($pathfrom ne '') {
4441: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4442: $pathfrom);
4443: }
4444: }
4445: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4446: foreach my $item (keys(%javafiles)) {
4447: if ($attr->{$item}) {
4448: $javafiles{$item} = $attr->{$item};
4449: last;
4450: }
4451: }
4452: foreach my $item (keys(%mediafiles)) {
4453: if ($attr->{$item}) {
4454: &add_filetype($allfiles,$attr->{$item},$item);
4455: last;
4456: }
4457: }
4458: if (lc($tagname) eq 'embed') {
4459: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4460: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4461: $attr->{'src'});
4462: }
4463: }
4464: }
4465: if (lc($tagname) eq 'iframe') {
4466: my $src = $attr->{'src'} ;
4467: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4468: &add_filetype($allfiles,$src,'src');
4469: } elsif ($src =~ m{^/}) {
4470: if ($env{'request.course.id'}) {
4471: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4472: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4473: my $url = &hreflocation('',$fullpath);
4474: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4475: my $relpath = $1;
4476: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4477: &add_filetype($allfiles,$1,'src');
4478: }
4479: }
4480: }
4481: }
4482: }
4483: if ($t->[4] =~ m{/>$}) {
4484: pop(@state);
4485: }
4486: } elsif ($t->[0] eq 'E') {
4487: my ($tagname) = ($t->[1]);
4488: if ($javafiles{'codebase'} ne '') {
4489: $javafiles{'codebase'} .= '/';
4490: }
4491: if (lc($tagname) eq 'applet' ||
4492: lc($tagname) eq 'object' ||
4493: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4494: ) {
4495: foreach my $item (keys(%javafiles)) {
4496: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4497: my $file=$javafiles{'codebase'}.$javafiles{$item};
4498: &add_filetype($allfiles,$file,$item);
4499: }
4500: }
4501: }
4502: pop @state;
4503: }
4504: }
4505: foreach my $id (sort(keys(%flashvars))) {
4506: if ($shockwave{$id} ne '') {
4507: my @pairs = split(/\&/,$flashvars{$id});
4508: foreach my $pair (@pairs) {
4509: my ($key,$value) = split(/\=/,$pair);
4510: if ($key eq 'thumb') {
4511: &add_filetype($allfiles,$value,$key);
4512: } elsif ($key eq 'content') {
4513: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4514: my ($ext) = ($value =~ /\.([^.]+)$/);
4515: if ($ext ne '') {
4516: &add_filetype($allfiles,$path.$value,$ext);
4517: }
4518: }
4519: }
4520: }
4521: }
4522: return 'ok';
4523: }
4524:
4525: sub add_filetype {
4526: my ($allfiles,$file,$type)=@_;
4527: if (exists($allfiles->{$file})) {
4528: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4529: push(@{$allfiles->{$file}}, &escape($type));
4530: }
4531: } else {
4532: @{$allfiles->{$file}} = (&escape($type));
4533: }
4534: }
4535:
4536: sub embedded_dependency {
4537: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4538: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4539: if (($identifier ne '') &&
4540: (ref($related->{$identifier}) eq 'ARRAY') &&
4541: ($pathfrom ne '')) {
4542: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4543: foreach my $dep (@{$related->{$identifier}}) {
4544: &add_filetype($allfiles,$path.$dep,'object');
4545: }
4546: }
4547: }
4548: return;
4549: }
4550:
4551: sub bubblesheet_converter {
4552: my ($cdom,$fullpath,$config,$format) = @_;
4553: if ((&domain($cdom) ne '') &&
4554: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
4555: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
4556: my (%csvcols,%csvoptions);
4557: if (ref($config->{'fields'}) eq 'HASH') {
4558: %csvcols = %{$config->{'fields'}};
4559: }
4560: if (ref($config->{'options'}) eq 'HASH') {
4561: %csvoptions = %{$config->{'options'}};
4562: }
4563: my %csvbynum = reverse(%csvcols);
4564: my %scantronconf = &get_scantron_config($format,$cdom);
4565: if (keys(%scantronconf)) {
4566: my %bynum = (
4567: $scantronconf{CODEstart} => 'CODEstart',
4568: $scantronconf{IDstart} => 'IDstart',
4569: $scantronconf{PaperID} => 'PaperID',
4570: $scantronconf{FirstName} => 'FirstName',
4571: $scantronconf{LastName} => 'LastName',
4572: $scantronconf{Qstart} => 'Qstart',
4573: );
4574: my @ordered;
4575: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
4576: push(@ordered,$bynum{$item});
4577: }
4578: my %mapstart = (
4579: CODEstart => 'CODE',
4580: IDstart => 'ID',
4581: PaperID => 'PaperID',
4582: FirstName => 'FirstName',
4583: LastName => 'LastName',
4584: Qstart => 'FirstQuestion',
4585: );
4586: my %maplength = (
4587: CODEstart => 'CODElength',
4588: IDstart => 'IDlength',
4589: PaperID => 'PaperIDlength',
4590: FirstName => 'FirstNamelength',
4591: LastName => 'LastNamelength',
4592: );
4593: if (open(my $fh,'<',$fullpath)) {
4594: my $output;
4595: my %lettdig = &letter_to_digits();
4596: my %diglett = reverse(%lettdig);
4597: my $numletts = scalar(keys(%lettdig));
4598: my $num = 0;
4599: while (my $line=<$fh>) {
4600: $num ++;
4601: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
4602: $line =~ s{[\r\n]+$}{};
4603: my %found;
4604: my @values = split(/,/,$line);
4605: my ($qstart,$record);
4606: for (my $i=0; $i<@values; $i++) {
4607: if ((($qstart ne '') && ($i > $qstart)) ||
4608: ($csvbynum{$i} eq 'FirstQuestion')) {
4609: if ($values[$i] eq '') {
4610: $values[$i] = $scantronconf{'Qoff'};
4611: } elsif ($scantronconf{'Qon'} eq 'number') {
4612: if ($values[$i] =~ /^[A-Ja-j]$/) {
4613: $values[$i] = $lettdig{uc($values[$i])};
4614: }
4615: } elsif ($scantronconf{'Qon'} eq 'letter') {
4616: if ($values[$i] =~ /^[0-9]$/) {
4617: $values[$i] = $diglett{$values[$i]};
4618: }
4619: } else {
4620: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4621: my $digit;
4622: if ($values[$i] =~ /^[A-Ja-j]$/) {
4623: $digit = $lettdig{uc($values[$i])}-1;
4624: if ($values[$i] eq 'J') {
4625: $digit += $numletts;
4626: }
4627: } elsif ($values[$i] =~ /^[0-9]$/) {
4628: $digit = $values[$i]-1;
4629: if ($values[$i] eq '0') {
4630: $digit += $numletts;
4631: }
4632: }
4633: my $qval='';
4634: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
4635: if ($j == $digit) {
4636: $qval .= $scantronconf{'Qon'};
4637: } else {
4638: $qval .= $scantronconf{'Qoff'};
4639: }
4640: }
4641: $values[$i] = $qval;
4642: }
4643: }
4644: if (length($values[$i]) > $scantronconf{'Qlength'}) {
4645: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
4646: }
4647: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
4648: if ($numblank > 0) {
4649: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
4650: }
4651: if ($csvbynum{$i} eq 'FirstQuestion') {
4652: $qstart = $i;
4653: $found{$csvbynum{$i}} = $values[$i];
4654: } else {
4655: $found{'FirstQuestion'} .= $values[$i];
4656: }
4657: } elsif (exists($csvbynum{$i})) {
4658: if ($csvoptions{'rem'}) {
4659: $values[$i] =~ s/^\s+//;
4660: }
4661: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
4662: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
4663: $values[$i] = '0'.$values[$i];
4664: }
4665: }
4666: $found{$csvbynum{$i}} = $values[$i];
4667: }
4668: }
4669: foreach my $item (@ordered) {
4670: my $currlength = 1+length($record);
4671: my $numspaces = $scantronconf{$item} - $currlength;
4672: if ($numspaces > 0) {
4673: $record .= (' ' x $numspaces);
4674: }
4675: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
4676: unless ($item eq 'Qstart') {
4677: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
4678: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
4679: }
4680: }
4681: $record .= $found{$mapstart{$item}};
4682: }
4683: }
4684: $output .= "$record\n";
4685: }
4686: close($fh);
4687: if ($output) {
4688: if (open(my $fh,'>',$fullpath)) {
4689: print $fh $output;
4690: close($fh);
4691: }
4692: }
4693: }
4694: }
4695: return;
4696: }
4697: }
4698:
4699: sub letter_to_digits {
4700: my %lettdig = (
4701: A => 1,
4702: B => 2,
4703: C => 3,
4704: D => 4,
4705: E => 5,
4706: F => 6,
4707: G => 7,
4708: H => 8,
4709: I => 9,
4710: J => 0,
4711: );
4712: return %lettdig;
4713: }
4714:
4715: sub get_scantron_config {
4716: my ($which,$cdom) = @_;
4717: my @lines = &get_scantronformat_file($cdom);
4718: my %config;
4719: #FIXME probably should move to XML it has already gotten a bit much now
4720: foreach my $line (@lines) {
4721: my ($name,$descrip)=split(/:/,$line);
4722: if ($name ne $which ) { next; }
4723: chomp($line);
4724: my @config=split(/:/,$line);
4725: $config{'name'}=$config[0];
4726: $config{'description'}=$config[1];
4727: $config{'CODElocation'}=$config[2];
4728: $config{'CODEstart'}=$config[3];
4729: $config{'CODElength'}=$config[4];
4730: $config{'IDstart'}=$config[5];
4731: $config{'IDlength'}=$config[6];
4732: $config{'Qstart'}=$config[7];
4733: $config{'Qlength'}=$config[8];
4734: $config{'Qoff'}=$config[9];
4735: $config{'Qon'}=$config[10];
4736: $config{'PaperID'}=$config[11];
4737: $config{'PaperIDlength'}=$config[12];
4738: $config{'FirstName'}=$config[13];
4739: $config{'FirstNamelength'}=$config[14];
4740: $config{'LastName'}=$config[15];
4741: $config{'LastNamelength'}=$config[16];
4742: $config{'BubblesPerRow'}=$config[17];
4743: last;
4744: }
4745: return %config;
4746: }
4747:
4748: sub get_scantronformat_file {
4749: my ($cdom) = @_;
4750: if ($cdom eq '') {
4751: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4752: }
4753: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4754: my $gottab = 0;
4755: my @lines;
4756: if (ref($domconfig{'scantron'}) eq 'HASH') {
4757: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4758: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4759: if ($formatfile ne '-1') {
4760: @lines = split("\n",$formatfile,-1);
4761: $gottab = 1;
4762: }
4763: }
4764: }
4765: if (!$gottab) {
4766: my $confname = $cdom.'-domainconfig';
4767: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4768: my $formatfile = &getfile($default);
4769: if ($formatfile ne '-1') {
4770: @lines = split("\n",$formatfile,-1);
4771: $gottab = 1;
4772: }
4773: }
4774: if (!$gottab) {
4775: my @domains = ¤t_machine_domains();
4776: if (grep(/^\Q$cdom\E$/,@domains)) {
4777: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
4778: @lines = <$fh>;
4779: close($fh);
4780: }
4781: } else {
4782: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
4783: @lines = <$fh>;
4784: close($fh);
4785: }
4786: }
4787: }
4788: return @lines;
4789: }
4790:
4791: sub removeuploadedurl {
4792: my ($url)=@_;
4793: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
4794: return &removeuserfile($uname,$udom,$fname);
4795: }
4796:
4797: sub removeuserfile {
4798: my ($docuname,$docudom,$fname)=@_;
4799: my $home=&homeserver($docuname,$docudom);
4800: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
4801: if ($result eq 'ok') {
4802: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4803: my $metafile = $fname.'.meta';
4804: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
4805: my $url = "/uploaded/$docudom/$docuname/$fname";
4806: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
4807: my $sqlresult =
4808: &update_portfolio_table($docuname,$docudom,$file,
4809: 'portfolio_metadata',$group,
4810: 'delete');
4811: }
4812: }
4813: return $result;
4814: }
4815:
4816: sub mkdiruserfile {
4817: my ($docuname,$docudom,$dir)=@_;
4818: my $home=&homeserver($docuname,$docudom);
4819: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4820: }
4821:
4822: sub renameuserfile {
4823: my ($docuname,$docudom,$old,$new)=@_;
4824: my $home=&homeserver($docuname,$docudom);
4825: my $result = &reply("renameuserfile:$docudom:$docuname:".
4826: &escape("$old").':'.&escape("$new"),$home);
4827: if ($result eq 'ok') {
4828: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4829: my $oldmeta = $old.'.meta';
4830: my $newmeta = $new.'.meta';
4831: my $metaresult =
4832: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
4833: my $url = "/uploaded/$docudom/$docuname/$old";
4834: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
4835: my $sqlresult =
4836: &update_portfolio_table($docuname,$docudom,$file,
4837: 'portfolio_metadata',$group,
4838: 'delete');
4839: }
4840: }
4841: return $result;
4842: }
4843:
4844: # ------------------------------------------------------------------------- Log
4845:
4846: sub log {
4847: my ($dom,$nam,$hom,$what)=@_;
4848: return critical("log:$dom:$nam:$what",$hom);
4849: }
4850:
4851: # ------------------------------------------------------------------ Course Log
4852: #
4853: # This routine flushes several buffers of non-mission-critical nature
4854: #
4855:
4856: sub flushcourselogs {
4857: &logthis('Flushing log buffers');
4858: #
4859: # course logs
4860: # This is a log of all transactions in a course, which can be used
4861: # for data mining purposes
4862: #
4863: # It also collects the courseid database, which lists last transaction
4864: # times and course titles for all courseids
4865: #
4866: my %courseidbuffer=();
4867: foreach my $crsid (keys(%courselogs)) {
4868: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
4869: &escape($courselogs{$crsid}),
4870: $coursehombuf{$crsid}) eq 'ok') {
4871: delete $courselogs{$crsid};
4872: } else {
4873: &logthis('Failed to flush log buffer for '.$crsid);
4874: if (length($courselogs{$crsid})>40000) {
4875: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
4876: " exceeded maximum size, deleting.</font>");
4877: delete $courselogs{$crsid};
4878: }
4879: }
4880: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
4881: 'description' => $coursedescrbuf{$crsid},
4882: 'inst_code' => $courseinstcodebuf{$crsid},
4883: 'type' => $coursetypebuf{$crsid},
4884: 'owner' => $courseownerbuf{$crsid},
4885: };
4886: }
4887: #
4888: # Write course id database (reverse lookup) to homeserver of courses
4889: # Is used in pickcourse
4890: #
4891: foreach my $crs_home (keys(%courseidbuffer)) {
4892: my $response = &courseidput(&host_domain($crs_home),
4893: $courseidbuffer{$crs_home},
4894: $crs_home,'timeonly');
4895: }
4896: #
4897: # File accesses
4898: # Writes to the dynamic metadata of resources to get hit counts, etc.
4899: #
4900: foreach my $entry (keys(%accesshash)) {
4901: if ($entry =~ /___count$/) {
4902: my ($dom,$name);
4903: ($dom,$name,undef)=
4904: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
4905: if (! defined($dom) || $dom eq '' ||
4906: ! defined($name) || $name eq '') {
4907: my $cid = $env{'request.course.id'};
4908: $dom = $env{'request.'.$cid.'.domain'};
4909: $name = $env{'request.'.$cid.'.num'};
4910: }
4911: my $value = $accesshash{$entry};
4912: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4913: my %temphash=($url => $value);
4914: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4915: if ($result eq 'ok') {
4916: delete $accesshash{$entry};
4917: }
4918: } else {
4919: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
4920: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
4921: my %temphash=($entry => $accesshash{$entry});
4922: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4923: delete $accesshash{$entry};
4924: }
4925: }
4926: }
4927: #
4928: # Roles
4929: # Reverse lookup of user roles for course faculty/staff and co-authorship
4930: #
4931: foreach my $entry (keys(%userrolehash)) {
4932: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
4933: split(/\:/,$entry);
4934: if (&Apache::lonnet::put('nohist_userroles',
4935: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
4936: $rudom,$runame) eq 'ok') {
4937: delete $userrolehash{$entry};
4938: }
4939: }
4940: #
4941: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
4942: #
4943: my %domrolebuffer = ();
4944: foreach my $entry (keys(%domainrolehash)) {
4945: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
4946: if ($domrolebuffer{$rudom}) {
4947: $domrolebuffer{$rudom}.='&'.&escape($entry).
4948: '='.&escape($domainrolehash{$entry});
4949: } else {
4950: $domrolebuffer{$rudom}.=&escape($entry).
4951: '='.&escape($domainrolehash{$entry});
4952: }
4953: delete $domainrolehash{$entry};
4954: }
4955: foreach my $dom (keys(%domrolebuffer)) {
4956: my %servers;
4957: if (defined(&domain($dom,'primary'))) {
4958: my $primary=&domain($dom,'primary');
4959: my $hostname=&hostname($primary);
4960: $servers{$primary} = $hostname;
4961: } else {
4962: %servers = &get_servers($dom,'library');
4963: }
4964: foreach my $tryserver (keys(%servers)) {
4965: if (&reply('domroleput:'.$dom.':'.
4966: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4967: last;
4968: } else {
4969: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4970: }
4971: }
4972: }
4973: $dumpcount++;
4974: }
4975:
4976: sub courselog {
4977: my $what=shift;
4978: $what=time.':'.$what;
4979: unless ($env{'request.course.id'}) { return ''; }
4980: $coursedombuf{$env{'request.course.id'}}=
4981: $env{'course.'.$env{'request.course.id'}.'.domain'};
4982: $coursenumbuf{$env{'request.course.id'}}=
4983: $env{'course.'.$env{'request.course.id'}.'.num'};
4984: $coursehombuf{$env{'request.course.id'}}=
4985: $env{'course.'.$env{'request.course.id'}.'.home'};
4986: $coursedescrbuf{$env{'request.course.id'}}=
4987: $env{'course.'.$env{'request.course.id'}.'.description'};
4988: $courseinstcodebuf{$env{'request.course.id'}}=
4989: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4990: $courseownerbuf{$env{'request.course.id'}}=
4991: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
4992: $coursetypebuf{$env{'request.course.id'}}=
4993: $env{'course.'.$env{'request.course.id'}.'.type'};
4994: if (defined $courselogs{$env{'request.course.id'}}) {
4995: $courselogs{$env{'request.course.id'}}.='&'.$what;
4996: } else {
4997: $courselogs{$env{'request.course.id'}}.=$what;
4998: }
4999: if (length($courselogs{$env{'request.course.id'}})>4048) {
5000: &flushcourselogs();
5001: }
5002: }
5003:
5004: sub courseacclog {
5005: my $fnsymb=shift;
5006: unless ($env{'request.course.id'}) { return ''; }
5007: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
5008: if ($fnsymb=~/$LONCAPA::assess_re/) {
5009: $what.=':POST';
5010: # FIXME: Probably ought to escape things....
5011: foreach my $key (keys(%env)) {
5012: if ($key=~/^form\.(.*)/) {
5013: my $formitem = $1;
5014: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
5015: $what.=':'.$formitem.'='.$env{$key};
5016: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
5017: $what.=':'.$formitem.'='.$env{$key};
5018: }
5019: }
5020: }
5021: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
5022: # FIXME: We should not be depending on a form parameter that someone
5023: # editing lonsearchcat.pm might change in the future.
5024: if ($env{'form.phase'} eq 'course_search') {
5025: $what.= ':POST';
5026: # FIXME: Probably ought to escape things....
5027: foreach my $element ('courseexp','crsfulltext','crsrelated',
5028: 'crsdiscuss') {
5029: $what.=':'.$element.'='.$env{'form.'.$element};
5030: }
5031: }
5032: }
5033: &courselog($what);
5034: }
5035:
5036: sub countacc {
5037: my $url=&declutter(shift);
5038: return if (! defined($url) || $url eq '');
5039: unless ($env{'request.course.id'}) { return ''; }
5040: #
5041: # Mark that this url was used in this course
5042: #
5043: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
5044: #
5045: # Increase the access count for this resource in this child process
5046: #
5047: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
5048: $accesshash{$key}++;
5049: }
5050:
5051: sub linklog {
5052: my ($from,$to)=@_;
5053: $from=&declutter($from);
5054: $to=&declutter($to);
5055: $accesshash{$from.'___'.$to.'___comefrom'}=1;
5056: $accesshash{$to.'___'.$from.'___goto'}=1;
5057: }
5058:
5059: sub statslog {
5060: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
5061: if ($users<2) { return; }
5062: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
5063: 'course' => $env{'request.course.id'},
5064: 'sections' => '"all"',
5065: 'num_students' => $users,
5066: 'part' => $part,
5067: 'symb' => $symb,
5068: 'mean_tries' => $av_attempts,
5069: 'deg_of_diff' => $degdiff});
5070: foreach my $key (keys(%dynstore)) {
5071: $accesshash{$key}=$dynstore{$key};
5072: }
5073: }
5074:
5075: sub userrolelog {
5076: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
5077: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
5078: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5079: $userrolehash
5080: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
5081: =$tend.':'.$tstart;
5082: }
5083: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
5084: $userrolehash
5085: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
5086: =$tend.':'.$tstart;
5087: }
5088: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
5089: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5090: $domainrolehash
5091: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
5092: = $tend.':'.$tstart;
5093: }
5094: }
5095:
5096: sub courserolelog {
5097: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
5098: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
5099: my $cdom = $1;
5100: my $cnum = $2;
5101: my $sec = $3;
5102: my $namespace = 'rolelog';
5103: my %storehash = (
5104: role => $trole,
5105: start => $tstart,
5106: end => $tend,
5107: selfenroll => $selfenroll,
5108: context => $context,
5109: );
5110: if ($trole eq 'gr') {
5111: $namespace = 'groupslog';
5112: $storehash{'group'} = $sec;
5113: } else {
5114: $storehash{'section'} = $sec;
5115: }
5116: &write_log('course',$namespace,\%storehash,$delflag,$username,
5117: $domain,$cnum,$cdom);
5118: if (($trole ne 'st') || ($sec ne '')) {
5119: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
5120: }
5121: }
5122: return;
5123: }
5124:
5125: sub domainrolelog {
5126: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5127: if ($area =~ m{^/($match_domain)/$}) {
5128: my $cdom = $1;
5129: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
5130: my $namespace = 'rolelog';
5131: my %storehash = (
5132: role => $trole,
5133: start => $tstart,
5134: end => $tend,
5135: context => $context,
5136: );
5137: &write_log('domain',$namespace,\%storehash,$delflag,$username,
5138: $domain,$domconfiguser,$cdom);
5139: }
5140: return;
5141:
5142: }
5143:
5144: sub coauthorrolelog {
5145: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5146: if ($area =~ m{^/($match_domain)/($match_username)$}) {
5147: my $audom = $1;
5148: my $auname = $2;
5149: my $namespace = 'rolelog';
5150: my %storehash = (
5151: role => $trole,
5152: start => $tstart,
5153: end => $tend,
5154: context => $context,
5155: );
5156: &write_log('author',$namespace,\%storehash,$delflag,$username,
5157: $domain,$auname,$audom);
5158: }
5159: return;
5160: }
5161:
5162: sub get_course_adv_roles {
5163: my ($cid,$codes) = @_;
5164: $cid=$env{'request.course.id'} unless (defined($cid));
5165: my %coursehash=&coursedescription($cid);
5166: my $crstype = &Apache::loncommon::course_type($cid);
5167: my %nothide=();
5168: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
5169: if ($user !~ /:/) {
5170: $nothide{join(':',split(/[\@]/,$user))}=1;
5171: } else {
5172: $nothide{$user}=1;
5173: }
5174: }
5175: my @possdoms = ($coursehash{'domain'});
5176: if ($coursehash{'checkforpriv'}) {
5177: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
5178: }
5179: my %returnhash=();
5180: my %dumphash=
5181: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
5182: my $now=time;
5183: my %privileged;
5184: foreach my $entry (keys(%dumphash)) {
5185: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
5186: if (($tstart) && ($tstart<0)) { next; }
5187: if (($tend) && ($tend<$now)) { next; }
5188: if (($tstart) && ($now<$tstart)) { next; }
5189: my ($role,$username,$domain,$section)=split(/\:/,$entry);
5190: if ($username eq '' || $domain eq '') { next; }
5191: if ((&privileged($username,$domain,\@possdoms)) &&
5192: (!$nothide{$username.':'.$domain})) { next; }
5193: if ($role eq 'cr') { next; }
5194: if ($codes) {
5195: if ($section) { $role .= ':'.$section; }
5196: if ($returnhash{$role}) {
5197: $returnhash{$role}.=','.$username.':'.$domain;
5198: } else {
5199: $returnhash{$role}=$username.':'.$domain;
5200: }
5201: } else {
5202: my $key=&plaintext($role,$crstype);
5203: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
5204: if ($returnhash{$key}) {
5205: $returnhash{$key}.=','.$username.':'.$domain;
5206: } else {
5207: $returnhash{$key}=$username.':'.$domain;
5208: }
5209: }
5210: }
5211: return %returnhash;
5212: }
5213:
5214: sub get_my_roles {
5215: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
5216: unless (defined($uname)) { $uname=$env{'user.name'}; }
5217: unless (defined($udom)) { $udom=$env{'user.domain'}; }
5218: my (%dumphash,%nothide);
5219: if ($context eq 'userroles') {
5220: %dumphash = &dump('roles',$udom,$uname);
5221: } else {
5222: %dumphash = &dump('nohist_userroles',$udom,$uname);
5223: if ($hidepriv) {
5224: my %coursehash=&coursedescription($udom.'_'.$uname);
5225: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
5226: if ($user !~ /:/) {
5227: $nothide{join(':',split(/[\@]/,$user))} = 1;
5228: } else {
5229: $nothide{$user} = 1;
5230: }
5231: }
5232: }
5233: }
5234: my %returnhash=();
5235: my $now=time;
5236: my %privileged;
5237: foreach my $entry (keys(%dumphash)) {
5238: my ($role,$tend,$tstart);
5239: if ($context eq 'userroles') {
5240: next if ($entry =~ /^rolesdef/);
5241: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
5242: } else {
5243: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
5244: }
5245: if (($tstart) && ($tstart<0)) { next; }
5246: my $status = 'active';
5247: if (($tend) && ($tend<=$now)) {
5248: $status = 'previous';
5249: }
5250: if (($tstart) && ($now<$tstart)) {
5251: $status = 'future';
5252: }
5253: if (ref($types) eq 'ARRAY') {
5254: if (!grep(/^\Q$status\E$/,@{$types})) {
5255: next;
5256: }
5257: } else {
5258: if ($status ne 'active') {
5259: next;
5260: }
5261: }
5262: my ($rolecode,$username,$domain,$section,$area);
5263: if ($context eq 'userroles') {
5264: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
5265: (undef,$domain,$username,$section) = split(/\//,$area);
5266: } else {
5267: ($role,$username,$domain,$section) = split(/\:/,$entry);
5268: }
5269: if (ref($roledoms) eq 'ARRAY') {
5270: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
5271: next;
5272: }
5273: }
5274: if (ref($roles) eq 'ARRAY') {
5275: if (!grep(/^\Q$role\E$/,@{$roles})) {
5276: if ($role =~ /^cr\//) {
5277: if (!grep(/^cr$/,@{$roles})) {
5278: next;
5279: }
5280: } elsif ($role =~ /^gr\//) {
5281: if (!grep(/^gr$/,@{$roles})) {
5282: next;
5283: }
5284: } else {
5285: next;
5286: }
5287: }
5288: }
5289: if ($hidepriv) {
5290: my @privroles = ('dc','su');
5291: if ($context eq 'userroles') {
5292: next if (grep(/^\Q$role\E$/,@privroles));
5293: } else {
5294: my $possdoms = [$domain];
5295: if (ref($roledoms) eq 'ARRAY') {
5296: push(@{$possdoms},@{$roledoms});
5297: }
5298: if (&privileged($username,$domain,$possdoms,\@privroles)) {
5299: if (!$nothide{$username.':'.$domain}) {
5300: next;
5301: }
5302: }
5303: }
5304: }
5305: if ($withsec) {
5306: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
5307: $tstart.':'.$tend;
5308: } else {
5309: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
5310: }
5311: }
5312: return %returnhash;
5313: }
5314:
5315: sub get_all_adhocroles {
5316: my ($dom) = @_;
5317: my @roles_by_num = ();
5318: my %domdefaults = &get_domain_defaults($dom);
5319: my (%description,%access_in_dom,%access_info);
5320: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
5321: my $count = 0;
5322: my %domcurrent = %{$domdefaults{'adhocroles'}};
5323: my %ordered;
5324: foreach my $role (sort(keys(%domcurrent))) {
5325: my ($order,$desc,$access_in_dom);
5326: if (ref($domcurrent{$role}) eq 'HASH') {
5327: $order = $domcurrent{$role}{'order'};
5328: $desc = $domcurrent{$role}{'desc'};
5329: $access_in_dom{$role} = $domcurrent{$role}{'access'};
5330: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
5331: }
5332: if ($order eq '') {
5333: $order = $count;
5334: }
5335: $ordered{$order} = $role;
5336: if ($desc ne '') {
5337: $description{$role} = $desc;
5338: } else {
5339: $description{$role}= $role;
5340: }
5341: $count++;
5342: }
5343: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
5344: push(@roles_by_num,$ordered{$item});
5345: }
5346: }
5347: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
5348: }
5349:
5350: sub get_my_adhocroles {
5351: my ($cid,$checkreg) = @_;
5352: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
5353: if ($env{'request.course.id'} eq $cid) {
5354: $cdom = $env{'course.'.$cid.'.domain'};
5355: $cnum = $env{'course.'.$cid.'.num'};
5356: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
5357: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
5358: $cdom = $1;
5359: $cnum = $2;
5360: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
5361: $cdom,$cnum);
5362: }
5363: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
5364: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5365: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
5366: if ($rosterhash{$user} ne '') {
5367: my $type = (split(/:/,$rosterhash{$user}))[5];
5368: return ([],{}) if ($type eq 'auto');
5369: }
5370: }
5371: if (($cdom ne '') && ($cnum ne '')) {
5372: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
5373: my $then=$env{'user.login.time'};
5374: my $update=$env{'user.update.time'};
5375: if (!$update) {
5376: $update = $then;
5377: }
5378: my @liveroles;
5379: foreach my $role ('dh','da') {
5380: if ($env{"user.role.$role./$cdom/"}) {
5381: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
5382: my $limit = $update;
5383: if ($env{'request.role'} eq "$role./$cdom/") {
5384: $limit = $then;
5385: }
5386: my $activerole = 1;
5387: if ($tstart && $tstart>$limit) { $activerole = 0; }
5388: if ($tend && $tend <$limit) { $activerole = 0; }
5389: if ($activerole) {
5390: push(@liveroles,$role);
5391: }
5392: }
5393: }
5394: if (@liveroles) {
5395: if (&homeserver($cnum,$cdom) ne 'no_host') {
5396: my ($accessref,$accessinfo,%access_in_dom);
5397: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5398: if (ref($roles_by_num) eq 'ARRAY') {
5399: if (@{$roles_by_num}) {
5400: my %settings;
5401: if ($env{'request.course.id'} eq $cid) {
5402: foreach my $envkey (keys(%env)) {
5403: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5404: $settings{$1} = $env{$envkey};
5405: }
5406: }
5407: } else {
5408: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5409: }
5410: my %setincrs;
5411: if ($settings{'internal.adhocaccess'}) {
5412: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5413: }
5414: my @statuses;
5415: if ($env{'environment.inststatus'}) {
5416: @statuses = split(/,/,$env{'environment.inststatus'});
5417: }
5418: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5419: if (ref($accessref) eq 'HASH') {
5420: %access_in_dom = %{$accessref};
5421: }
5422: foreach my $role (@{$roles_by_num}) {
5423: my ($curraccess,@okstatus,@personnel);
5424: if ($setincrs{$role}) {
5425: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5426: if ($curraccess eq 'status') {
5427: @okstatus = split(/\&/,$rest);
5428: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5429: @personnel = split(/\&/,$rest);
5430: }
5431: } else {
5432: $curraccess = $access_in_dom{$role};
5433: if (ref($accessinfo) eq 'HASH') {
5434: if ($curraccess eq 'status') {
5435: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5436: @okstatus = @{$accessinfo->{$role}};
5437: }
5438: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5439: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5440: @personnel = @{$accessinfo->{$role}};
5441: }
5442: }
5443: }
5444: }
5445: if ($curraccess eq 'none') {
5446: next;
5447: } elsif ($curraccess eq 'all') {
5448: push(@possroles,$role);
5449: } elsif ($curraccess eq 'dh') {
5450: if (grep(/^dh$/,@liveroles)) {
5451: push(@possroles,$role);
5452: } else {
5453: next;
5454: }
5455: } elsif ($curraccess eq 'da') {
5456: if (grep(/^da$/,@liveroles)) {
5457: push(@possroles,$role);
5458: } else {
5459: next;
5460: }
5461: } elsif ($curraccess eq 'status') {
5462: if (@okstatus) {
5463: if (!@statuses) {
5464: if (grep(/^default$/,@okstatus)) {
5465: push(@possroles,$role);
5466: }
5467: } else {
5468: foreach my $status (@okstatus) {
5469: if (grep(/^\Q$status\E$/,@statuses)) {
5470: push(@possroles,$role);
5471: last;
5472: }
5473: }
5474: }
5475: }
5476: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5477: if (grep(/^\Q$user\E$/,@personnel)) {
5478: if ($curraccess eq 'exc') {
5479: push(@possroles,$role);
5480: }
5481: } elsif ($curraccess eq 'inc') {
5482: push(@possroles,$role);
5483: }
5484: }
5485: }
5486: }
5487: }
5488: }
5489: }
5490: }
5491: }
5492: unless (ref($description) eq 'HASH') {
5493: if (ref($roles_by_num) eq 'ARRAY') {
5494: my %desc;
5495: map { $desc{$_} = $_; } (@{$roles_by_num});
5496: $description = \%desc;
5497: } else {
5498: $description = {};
5499: }
5500: }
5501: return (\@possroles,$description);
5502: }
5503:
5504: # ----------------------------------------------------- Frontpage Announcements
5505: #
5506: #
5507:
5508: sub postannounce {
5509: my ($server,$text)=@_;
5510: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
5511: unless ($text=~/\w/) { $text=''; }
5512: return &reply('setannounce:'.&escape($text),$server);
5513: }
5514:
5515: sub getannounce {
5516:
5517: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
5518: my $announcement='';
5519: while (my $line = <$fh>) { $announcement .= $line; }
5520: close($fh);
5521: if ($announcement=~/\w/) {
5522: return
5523: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
5524: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
5525: } else {
5526: return '';
5527: }
5528: } else {
5529: return '';
5530: }
5531: }
5532:
5533: # ---------------------------------------------------------- Course ID routines
5534: # Deal with domain's nohist_courseid.db files
5535: #
5536:
5537: sub courseidput {
5538: my ($domain,$storehash,$coursehome,$caller) = @_;
5539: return unless (ref($storehash) eq 'HASH');
5540: my $outcome;
5541: if ($caller eq 'timeonly') {
5542: my $cids = '';
5543: foreach my $item (keys(%$storehash)) {
5544: $cids.=&escape($item).'&';
5545: }
5546: $cids=~s/\&$//;
5547: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5548: $coursehome);
5549: } else {
5550: my $items = '';
5551: foreach my $item (keys(%$storehash)) {
5552: $items.= &escape($item).'='.
5553: &freeze_escape($$storehash{$item}).'&';
5554: }
5555: $items=~s/\&$//;
5556: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5557: $coursehome);
5558: }
5559: if ($outcome eq 'unknown_cmd') {
5560: my $what;
5561: foreach my $cid (keys(%$storehash)) {
5562: $what .= &escape($cid).'=';
5563: foreach my $item ('description','inst_code','owner','type') {
5564: $what .= &escape($storehash->{$cid}{$item}).':';
5565: }
5566: $what =~ s/\:$/&/;
5567: }
5568: $what =~ s/\&$//;
5569: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5570: } else {
5571: return $outcome;
5572: }
5573: }
5574:
5575: sub courseiddump {
5576: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
5577: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
5578: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
5579: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
5580: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
5581: my $as_hash = 1;
5582: my %returnhash;
5583: if (!$domfilter) { $domfilter=''; }
5584: my %libserv = &all_library();
5585: foreach my $tryserver (keys(%libserv)) {
5586: if ( ( $hostidflag == 1
5587: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5588: || (!defined($hostidflag)) ) {
5589:
5590: if (($domfilter eq '') ||
5591: (&host_domain($tryserver) eq $domfilter)) {
5592: my $rep;
5593: if (grep { $_ eq $tryserver } current_machine_ids()) {
5594: $rep = LONCAPA::Lond::dump_course_id_handler(
5595: join(":", (&host_domain($tryserver), $sincefilter,
5596: &escape($descfilter), &escape($instcodefilter),
5597: &escape($ownerfilter), &escape($coursefilter),
5598: &escape($typefilter), &escape($regexp_ok),
5599: $as_hash, &escape($selfenrollonly),
5600: &escape($catfilter), $showhidden, $caller,
5601: &escape($cloner), &escape($cc_clone), $cloneonly,
5602: &escape($createdbefore), &escape($createdafter),
5603: &escape($creationcontext),$domcloner,$hasuniquecode,
5604: $reqcrsdom,&escape($reqinstcode))));
5605: } else {
5606: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5607: $sincefilter.':'.&escape($descfilter).':'.
5608: &escape($instcodefilter).':'.&escape($ownerfilter).
5609: ':'.&escape($coursefilter).':'.&escape($typefilter).
5610: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5611: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5612: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5613: &escape($cc_clone).':'.$cloneonly.':'.
5614: &escape($createdbefore).':'.&escape($createdafter).':'.
5615: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5616: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
5617: }
5618:
5619: my @pairs=split(/\&/,$rep);
5620: foreach my $item (@pairs) {
5621: my ($key,$value)=split(/\=/,$item,2);
5622: $key = &unescape($key);
5623: next if ($key =~ /^error: 2 /);
5624: my $result = &thaw_unescape($value);
5625: if (ref($result) eq 'HASH') {
5626: $returnhash{$key}=$result;
5627: } else {
5628: my @responses = split(/:/,$value);
5629: my @items = ('description','inst_code','owner','type');
5630: for (my $i=0; $i<@responses; $i++) {
5631: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
5632: }
5633: }
5634: }
5635: }
5636: }
5637: }
5638: return %returnhash;
5639: }
5640:
5641: sub courselastaccess {
5642: my ($cdom,$cnum,$hostidref) = @_;
5643: my %returnhash;
5644: if ($cdom && $cnum) {
5645: my $chome = &homeserver($cnum,$cdom);
5646: if ($chome ne 'no_host') {
5647: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5648: &extract_lastaccess(\%returnhash,$rep);
5649: }
5650: } else {
5651: if (!$cdom) { $cdom=''; }
5652: my %libserv = &all_library();
5653: foreach my $tryserver (keys(%libserv)) {
5654: if (ref($hostidref) eq 'ARRAY') {
5655: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5656: }
5657: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5658: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5659: &extract_lastaccess(\%returnhash,$rep);
5660: }
5661: }
5662: }
5663: return %returnhash;
5664: }
5665:
5666: sub extract_lastaccess {
5667: my ($returnhash,$rep) = @_;
5668: if (ref($returnhash) eq 'HASH') {
5669: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5670: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5671: $rep eq '') {
5672: my @pairs=split(/\&/,$rep);
5673: foreach my $item (@pairs) {
5674: my ($key,$value)=split(/\=/,$item,2);
5675: $key = &unescape($key);
5676: next if ($key =~ /^error: 2 /);
5677: $returnhash->{$key} = &thaw_unescape($value);
5678: }
5679: }
5680: }
5681: return;
5682: }
5683:
5684: # ---------------------------------------------------------- DC e-mail
5685:
5686: sub dcmailput {
5687: my ($domain,$msgid,$message,$server)=@_;
5688: my $status = &Apache::lonnet::critical(
5689: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5690: &escape($message),$server);
5691: return $status;
5692: }
5693:
5694: sub dcmaildump {
5695: my ($dom,$startdate,$enddate,$senders) = @_;
5696: my %returnhash=();
5697:
5698: if (defined(&domain($dom,'primary'))) {
5699: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5700: &escape($enddate).':';
5701: my @esc_senders=map { &escape($_)} @$senders;
5702: $cmd.=&escape(join('&',@esc_senders));
5703: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
5704: my ($key,$value) = split(/\=/,$line,2);
5705: if (($key) && ($value)) {
5706: $returnhash{&unescape($key)} = &unescape($value);
5707: }
5708: }
5709: }
5710: return %returnhash;
5711: }
5712: # ---------------------------------------------------------- Domain roles
5713:
5714: sub get_domain_roles {
5715: my ($dom,$roles,$startdate,$enddate)=@_;
5716: if ((!defined($startdate)) || ($startdate eq '')) {
5717: $startdate = '.';
5718: }
5719: if ((!defined($enddate)) || ($enddate eq '')) {
5720: $enddate = '.';
5721: }
5722: my $rolelist;
5723: if (ref($roles) eq 'ARRAY') {
5724: $rolelist = join('&',@{$roles});
5725: }
5726: my %personnel = ();
5727:
5728: my %servers = &get_servers($dom,'library');
5729: foreach my $tryserver (keys(%servers)) {
5730: %{$personnel{$tryserver}}=();
5731: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5732: &escape($startdate).':'.
5733: &escape($enddate).':'.
5734: &escape($rolelist), $tryserver))) {
5735: my ($key,$value) = split(/\=/,$line,2);
5736: if (($key) && ($value)) {
5737: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5738: }
5739: }
5740: }
5741: return %personnel;
5742: }
5743:
5744: sub get_active_domroles {
5745: my ($dom,$roles) = @_;
5746: return () unless (ref($roles) eq 'ARRAY');
5747: my $now = time;
5748: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5749: my %domroles;
5750: foreach my $server (keys(%dompersonnel)) {
5751: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5752: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5753: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5754: }
5755: }
5756: return %domroles;
5757: }
5758:
5759: # ----------------------------------------------------------- Interval timing
5760:
5761: {
5762: # Caches needed for speedup of navmaps
5763: # We don't want to cache this for very long at all (5 seconds at most)
5764: #
5765: # The user for whom we cache
5766: my $cachedkey='';
5767: # The cached times for this user
5768: my %cachedtimes=();
5769: # When this was last done
5770: my $cachedtime='';
5771:
5772: sub load_all_first_access {
5773: my ($uname,$udom,$ignorecache)=@_;
5774: if (($cachedkey eq $uname.':'.$udom) &&
5775: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
5776: (!$ignorecache)) {
5777: return;
5778: }
5779: $cachedtime=time;
5780: $cachedkey=$uname.':'.$udom;
5781: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
5782: }
5783:
5784: sub get_first_access {
5785: my ($type,$argsymb,$argmap,$ignorecache)=@_;
5786: my ($symb,$courseid,$udom,$uname)=&whichuser();
5787: if ($argsymb) { $symb=$argsymb; }
5788: my ($map,$id,$res)=&decode_symb($symb);
5789: if ($argmap) { $map = $argmap; }
5790: if ($type eq 'course') {
5791: $res='course';
5792: } elsif ($type eq 'map') {
5793: $res=&symbread($map);
5794: } else {
5795: $res=$symb;
5796: }
5797: &load_all_first_access($uname,$udom,$ignorecache);
5798: return $cachedtimes{"$courseid\0$res"};
5799: }
5800:
5801: sub set_first_access {
5802: my ($type,$interval)=@_;
5803: my ($symb,$courseid,$udom,$uname)=&whichuser();
5804: my ($map,$id,$res)=&decode_symb($symb);
5805: if ($type eq 'course') {
5806: $res='course';
5807: } elsif ($type eq 'map') {
5808: $res=&symbread($map);
5809: } else {
5810: $res=$symb;
5811: }
5812: $cachedkey='';
5813: my $firstaccess=&get_first_access($type,$symb,$map);
5814: if ($firstaccess) {
5815: &logthis("First access time already set ($firstaccess) when attempting ".
5816: "to set new value (type: $type, extent: $res) for $uname:$udom ".
5817: "in $courseid");
5818: return 'already_set';
5819: } else {
5820: my $start = time;
5821: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5822: $udom,$uname);
5823: if ($putres eq 'ok') {
5824: &put('timerinterval',{"$courseid\0$res"=>$interval},
5825: $udom,$uname);
5826: &appenv(
5827: {
5828: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5829: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5830: }
5831: );
5832: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
5833: $cachedtimes{"$courseid\0$res"} = $start;
5834: }
5835: } elsif ($putres ne 'refused') {
5836: &logthis("Result: $putres when attempting to set first access time ".
5837: "(type: $type, extent: $res) for $uname:$udom in $courseid");
5838: }
5839: return $putres;
5840: }
5841: return 'already_set';
5842: }
5843: }
5844:
5845: # --------------------------------------------- Set Expire Date for Spreadsheet
5846:
5847: sub expirespread {
5848: my ($uname,$udom,$stype,$usymb)=@_;
5849: my $cid=$env{'request.course.id'};
5850: if ($cid) {
5851: my $now=time;
5852: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
5853: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5854: $env{'course.'.$cid.'.num'}.
5855: ':nohist_expirationdates:'.
5856: &escape($key).'='.$now,
5857: $env{'course.'.$cid.'.home'})
5858: }
5859: return 'ok';
5860: }
5861:
5862: # ----------------------------------------------------- Devalidate Spreadsheets
5863:
5864: sub devalidate {
5865: my ($symb,$uname,$udom)=@_;
5866: my $cid=$env{'request.course.id'};
5867: if ($cid) {
5868: # delete the stored spreadsheets for
5869: # - the student level sheet of this user in course's homespace
5870: # - the assessment level sheet for this resource
5871: # for this user in user's homespace
5872: # - current conditional state info
5873: my $key=$uname.':'.$udom.':';
5874: my $status=
5875: &del('nohist_calculatedsheets',
5876: [$key.'studentcalc:'],
5877: $env{'course.'.$cid.'.domain'},
5878: $env{'course.'.$cid.'.num'})
5879: .' '.
5880: &del('nohist_calculatedsheets_'.$cid,
5881: [$key.'assesscalc:'.$symb],$udom,$uname);
5882: unless ($status eq 'ok ok') {
5883: &logthis('Could not devalidate spreadsheet '.
5884: $uname.' at '.$udom.' for '.
5885: $symb.': '.$status);
5886: }
5887: &delenv('user.state.'.$cid);
5888: }
5889: }
5890:
5891: sub get_scalar {
5892: my ($string,$end) = @_;
5893: my $value;
5894: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5895: $value = $1;
5896: } elsif ($$string =~ s/^([^&]*?)&//) {
5897: $value = $1;
5898: }
5899: return &unescape($value);
5900: }
5901:
5902: sub array2str {
5903: my (@array) = @_;
5904: my $result=&arrayref2str(\@array);
5905: $result=~s/^__ARRAY_REF__//;
5906: $result=~s/__END_ARRAY_REF__$//;
5907: return $result;
5908: }
5909:
5910: sub arrayref2str {
5911: my ($arrayref) = @_;
5912: my $result='__ARRAY_REF__';
5913: foreach my $elem (@$arrayref) {
5914: if(ref($elem) eq 'ARRAY') {
5915: $result.=&arrayref2str($elem).'&';
5916: } elsif(ref($elem) eq 'HASH') {
5917: $result.=&hashref2str($elem).'&';
5918: } elsif(ref($elem)) {
5919: #print("Got a ref of ".(ref($elem))." skipping.");
5920: } else {
5921: $result.=&escape($elem).'&';
5922: }
5923: }
5924: $result=~s/\&$//;
5925: $result .= '__END_ARRAY_REF__';
5926: return $result;
5927: }
5928:
5929: sub hash2str {
5930: my (%hash) = @_;
5931: my $result=&hashref2str(\%hash);
5932: $result=~s/^__HASH_REF__//;
5933: $result=~s/__END_HASH_REF__$//;
5934: return $result;
5935: }
5936:
5937: sub hashref2str {
5938: my ($hashref)=@_;
5939: my $result='__HASH_REF__';
5940: foreach my $key (sort(keys(%$hashref))) {
5941: if (ref($key) eq 'ARRAY') {
5942: $result.=&arrayref2str($key).'=';
5943: } elsif (ref($key) eq 'HASH') {
5944: $result.=&hashref2str($key).'=';
5945: } elsif (ref($key)) {
5946: $result.='=';
5947: #print("Got a ref of ".(ref($key))." skipping.");
5948: } else {
5949: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
5950: }
5951:
5952: if(ref($hashref->{$key}) eq 'ARRAY') {
5953: $result.=&arrayref2str($hashref->{$key}).'&';
5954: } elsif(ref($hashref->{$key}) eq 'HASH') {
5955: $result.=&hashref2str($hashref->{$key}).'&';
5956: } elsif(ref($hashref->{$key})) {
5957: $result.='&';
5958: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
5959: } else {
5960: $result.=&escape($hashref->{$key}).'&';
5961: }
5962: }
5963: $result=~s/\&$//;
5964: $result .= '__END_HASH_REF__';
5965: return $result;
5966: }
5967:
5968: sub str2hash {
5969: my ($string)=@_;
5970: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5971: return %$hash;
5972: }
5973:
5974: sub str2hashref {
5975: my ($string) = @_;
5976:
5977: my %hash;
5978:
5979: if($string !~ /^__HASH_REF__/) {
5980: if (! ($string eq '' || !defined($string))) {
5981: $hash{'error'}='Not hash reference';
5982: }
5983: return (\%hash, $string);
5984: }
5985:
5986: $string =~ s/^__HASH_REF__//;
5987:
5988: while($string !~ /^__END_HASH_REF__/) {
5989: #key
5990: my $key='';
5991: if($string =~ /^__HASH_REF__/) {
5992: ($key, $string)=&str2hashref($string);
5993: if(defined($key->{'error'})) {
5994: $hash{'error'}='Bad data';
5995: return (\%hash, $string);
5996: }
5997: } elsif($string =~ /^__ARRAY_REF__/) {
5998: ($key, $string)=&str2arrayref($string);
5999: if($key->[0] eq 'Array reference error') {
6000: $hash{'error'}='Bad data';
6001: return (\%hash, $string);
6002: }
6003: } else {
6004: $string =~ s/^(.*?)=//;
6005: $key=&unescape($1);
6006: }
6007: $string =~ s/^=//;
6008:
6009: #value
6010: my $value='';
6011: if($string =~ /^__HASH_REF__/) {
6012: ($value, $string)=&str2hashref($string);
6013: if(defined($value->{'error'})) {
6014: $hash{'error'}='Bad data';
6015: return (\%hash, $string);
6016: }
6017: } elsif($string =~ /^__ARRAY_REF__/) {
6018: ($value, $string)=&str2arrayref($string);
6019: if($value->[0] eq 'Array reference error') {
6020: $hash{'error'}='Bad data';
6021: return (\%hash, $string);
6022: }
6023: } else {
6024: $value=&get_scalar(\$string,'__END_HASH_REF__');
6025: }
6026: $string =~ s/^&//;
6027:
6028: $hash{$key}=$value;
6029: }
6030:
6031: $string =~ s/^__END_HASH_REF__//;
6032:
6033: return (\%hash, $string);
6034: }
6035:
6036: sub str2array {
6037: my ($string)=@_;
6038: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
6039: return @$array;
6040: }
6041:
6042: sub str2arrayref {
6043: my ($string) = @_;
6044: my @array;
6045:
6046: if($string !~ /^__ARRAY_REF__/) {
6047: if (! ($string eq '' || !defined($string))) {
6048: $array[0]='Array reference error';
6049: }
6050: return (\@array, $string);
6051: }
6052:
6053: $string =~ s/^__ARRAY_REF__//;
6054:
6055: while($string !~ /^__END_ARRAY_REF__/) {
6056: my $value='';
6057: if($string =~ /^__HASH_REF__/) {
6058: ($value, $string)=&str2hashref($string);
6059: if(defined($value->{'error'})) {
6060: $array[0] ='Array reference error';
6061: return (\@array, $string);
6062: }
6063: } elsif($string =~ /^__ARRAY_REF__/) {
6064: ($value, $string)=&str2arrayref($string);
6065: if($value->[0] eq 'Array reference error') {
6066: $array[0] ='Array reference error';
6067: return (\@array, $string);
6068: }
6069: } else {
6070: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
6071: }
6072: $string =~ s/^&//;
6073:
6074: push(@array, $value);
6075: }
6076:
6077: $string =~ s/^__END_ARRAY_REF__//;
6078:
6079: return (\@array, $string);
6080: }
6081:
6082: # -------------------------------------------------------------------Temp Store
6083:
6084: sub tmpreset {
6085: my ($symb,$namespace,$domain,$stuname) = @_;
6086: if (!$symb) {
6087: $symb=&symbread();
6088: if (!$symb) { $symb= $env{'request.url'}; }
6089: }
6090: $symb=escape($symb);
6091:
6092: if (!$namespace) { $namespace=$env{'request.state'}; }
6093: $namespace=~s/\//\_/g;
6094: $namespace=~s/\W//g;
6095:
6096: if (!$domain) { $domain=$env{'user.domain'}; }
6097: if (!$stuname) { $stuname=$env{'user.name'}; }
6098: if ($domain eq 'public' && $stuname eq 'public') {
6099: $stuname=$ENV{'REMOTE_ADDR'};
6100: }
6101: my $path=LONCAPA::tempdir();
6102: my %hash;
6103: if (tie(%hash,'GDBM_File',
6104: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
6105: &GDBM_WRCREAT(),0640)) {
6106: foreach my $key (keys(%hash)) {
6107: if ($key=~ /:$symb/) {
6108: delete($hash{$key});
6109: }
6110: }
6111: }
6112: }
6113:
6114: sub tmpstore {
6115: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
6116:
6117: if (!$symb) {
6118: $symb=&symbread();
6119: if (!$symb) { $symb= $env{'request.url'}; }
6120: }
6121: $symb=escape($symb);
6122:
6123: if (!$namespace) {
6124: # I don't think we would ever want to store this for a course.
6125: # it seems this will only be used if we don't have a course.
6126: #$namespace=$env{'request.course.id'};
6127: #if (!$namespace) {
6128: $namespace=$env{'request.state'};
6129: #}
6130: }
6131: $namespace=~s/\//\_/g;
6132: $namespace=~s/\W//g;
6133: if (!$domain) { $domain=$env{'user.domain'}; }
6134: if (!$stuname) { $stuname=$env{'user.name'}; }
6135: if ($domain eq 'public' && $stuname eq 'public') {
6136: $stuname=$ENV{'REMOTE_ADDR'};
6137: }
6138: my $now=time;
6139: my %hash;
6140: my $path=LONCAPA::tempdir();
6141: if (tie(%hash,'GDBM_File',
6142: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
6143: &GDBM_WRCREAT(),0640)) {
6144: $hash{"version:$symb"}++;
6145: my $version=$hash{"version:$symb"};
6146: my $allkeys='';
6147: foreach my $key (keys(%$storehash)) {
6148: $allkeys.=$key.':';
6149: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
6150: }
6151: $hash{"$version:$symb:timestamp"}=$now;
6152: $allkeys.='timestamp';
6153: $hash{"$version:keys:$symb"}=$allkeys;
6154: if (untie(%hash)) {
6155: return 'ok';
6156: } else {
6157: return "error:$!";
6158: }
6159: } else {
6160: return "error:$!";
6161: }
6162: }
6163:
6164: # -----------------------------------------------------------------Temp Restore
6165:
6166: sub tmprestore {
6167: my ($symb,$namespace,$domain,$stuname) = @_;
6168:
6169: if (!$symb) {
6170: $symb=&symbread();
6171: if (!$symb) { $symb= $env{'request.url'}; }
6172: }
6173: $symb=escape($symb);
6174:
6175: if (!$namespace) { $namespace=$env{'request.state'}; }
6176:
6177: if (!$domain) { $domain=$env{'user.domain'}; }
6178: if (!$stuname) { $stuname=$env{'user.name'}; }
6179: if ($domain eq 'public' && $stuname eq 'public') {
6180: $stuname=$ENV{'REMOTE_ADDR'};
6181: }
6182: my %returnhash;
6183: $namespace=~s/\//\_/g;
6184: $namespace=~s/\W//g;
6185: my %hash;
6186: my $path=LONCAPA::tempdir();
6187: if (tie(%hash,'GDBM_File',
6188: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
6189: &GDBM_READER(),0640)) {
6190: my $version=$hash{"version:$symb"};
6191: $returnhash{'version'}=$version;
6192: my $scope;
6193: for ($scope=1;$scope<=$version;$scope++) {
6194: my $vkeys=$hash{"$scope:keys:$symb"};
6195: my @keys=split(/:/,$vkeys);
6196: my $key;
6197: $returnhash{"$scope:keys"}=$vkeys;
6198: foreach $key (@keys) {
6199: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
6200: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
6201: }
6202: }
6203: if (!(untie(%hash))) {
6204: return "error:$!";
6205: }
6206: } else {
6207: return "error:$!";
6208: }
6209: return %returnhash;
6210: }
6211:
6212: # ----------------------------------------------------------------------- Store
6213:
6214: sub store {
6215: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
6216: my $home='';
6217:
6218: if ($stuname) { $home=&homeserver($stuname,$domain); }
6219:
6220: $symb=&symbclean($symb);
6221: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
6222:
6223: if (!$domain) { $domain=$env{'user.domain'}; }
6224: if (!$stuname) { $stuname=$env{'user.name'}; }
6225:
6226: &devalidate($symb,$stuname,$domain);
6227:
6228: $symb=escape($symb);
6229: if (!$namespace) {
6230: unless ($namespace=$env{'request.course.id'}) {
6231: return '';
6232: }
6233: }
6234: if (!$home) { $home=$env{'user.home'}; }
6235:
6236: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
6237: $$storehash{'host'}=$perlvar{'lonHostID'};
6238:
6239: my $namevalue='';
6240: foreach my $key (keys(%$storehash)) {
6241: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6242: }
6243: $namevalue=~s/\&$//;
6244: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
6245: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
6246: }
6247:
6248: # -------------------------------------------------------------- Critical Store
6249:
6250: sub cstore {
6251: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
6252: my $home='';
6253:
6254: if ($stuname) { $home=&homeserver($stuname,$domain); }
6255:
6256: $symb=&symbclean($symb);
6257: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
6258:
6259: if (!$domain) { $domain=$env{'user.domain'}; }
6260: if (!$stuname) { $stuname=$env{'user.name'}; }
6261:
6262: &devalidate($symb,$stuname,$domain);
6263:
6264: $symb=escape($symb);
6265: if (!$namespace) {
6266: unless ($namespace=$env{'request.course.id'}) {
6267: return '';
6268: }
6269: }
6270: if (!$home) { $home=$env{'user.home'}; }
6271:
6272: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
6273: $$storehash{'host'}=$perlvar{'lonHostID'};
6274:
6275: my $namevalue='';
6276: foreach my $key (keys(%$storehash)) {
6277: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6278: }
6279: $namevalue=~s/\&$//;
6280: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
6281: return critical
6282: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
6283: }
6284:
6285: # --------------------------------------------------------------------- Restore
6286:
6287: sub restore {
6288: my ($symb,$namespace,$domain,$stuname) = @_;
6289: my $home='';
6290:
6291: if ($stuname) { $home=&homeserver($stuname,$domain); }
6292:
6293: if (!$symb) {
6294: return if ($namespace eq 'courserequests');
6295: unless ($symb=escape(&symbread())) { return ''; }
6296: } else {
6297: unless ($namespace eq 'courserequests') {
6298: $symb=&escape(&symbclean($symb));
6299: }
6300: }
6301: if (!$namespace) {
6302: unless ($namespace=$env{'request.course.id'}) {
6303: return '';
6304: }
6305: }
6306: if (!$domain) { $domain=$env{'user.domain'}; }
6307: if (!$stuname) { $stuname=$env{'user.name'}; }
6308: if (!$home) { $home=$env{'user.home'}; }
6309: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6310:
6311: my %returnhash=();
6312: foreach my $line (split(/\&/,$answer)) {
6313: my ($name,$value)=split(/\=/,$line);
6314: $returnhash{&unescape($name)}=&thaw_unescape($value);
6315: }
6316: my $version;
6317: for ($version=1;$version<=$returnhash{'version'};$version++) {
6318: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6319: $returnhash{$item}=$returnhash{$version.':'.$item};
6320: }
6321: }
6322: return %returnhash;
6323: }
6324:
6325: # ---------------------------------------------------------- Course Description
6326: #
6327: #
6328:
6329: sub coursedescription {
6330: my ($courseid,$args)=@_;
6331: $courseid=~s/^\///;
6332: $courseid=~s/\_/\//g;
6333: my ($cdomain,$cnum)=split(/\//,$courseid);
6334: my $chome=&homeserver($cnum,$cdomain);
6335: my $normalid=$cdomain.'_'.$cnum;
6336: # need to always cache even if we get errors otherwise we keep
6337: # trying and trying and trying to get the course description.
6338: my %envhash=();
6339: my %returnhash=();
6340:
6341: my $expiretime=600;
6342: if ($env{'request.course.id'} eq $normalid) {
6343: $expiretime=120;
6344: }
6345:
6346: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6347: if (!$args->{'freshen_cache'}
6348: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6349: foreach my $key (keys(%env)) {
6350: next if ($key !~ /^\Q$prefix\E(.*)/);
6351: my ($setting) = $1;
6352: $returnhash{$setting} = $env{$key};
6353: }
6354: return %returnhash;
6355: }
6356:
6357: # get the data again
6358:
6359: if (!$args->{'one_time'}) {
6360: $envhash{'course.'.$normalid.'.last_cache'}=time;
6361: }
6362:
6363: if ($chome ne 'no_host') {
6364: %returnhash=&dump('environment',$cdomain,$cnum);
6365: if (!exists($returnhash{'con_lost'})) {
6366: my $username = $env{'user.name'}; # Defult username
6367: if(defined $args->{'user'}) {
6368: $username = $args->{'user'};
6369: }
6370: $returnhash{'home'}= $chome;
6371: $returnhash{'domain'} = $cdomain;
6372: $returnhash{'num'} = $cnum;
6373: if (!defined($returnhash{'type'})) {
6374: $returnhash{'type'} = 'Course';
6375: }
6376: while (my ($name,$value) = each %returnhash) {
6377: $envhash{'course.'.$normalid.'.'.$name}=$value;
6378: }
6379: $returnhash{'url'}=&clutter($returnhash{'url'});
6380: $returnhash{'fn'}=LONCAPA::tempdir() .
6381: $username.'_'.$cdomain.'_'.$cnum;
6382: $envhash{'course.'.$normalid.'.home'}=$chome;
6383: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6384: $envhash{'course.'.$normalid.'.num'}=$cnum;
6385: }
6386: }
6387: if (!$args->{'one_time'}) {
6388: &appenv(\%envhash);
6389: }
6390: return %returnhash;
6391: }
6392:
6393: sub update_released_required {
6394: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6395: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6396: $cid = $env{'request.course.id'};
6397: $cdom = $env{'course.'.$cid.'.domain'};
6398: $cnum = $env{'course.'.$cid.'.num'};
6399: $chome = $env{'course.'.$cid.'.home'};
6400: }
6401: if ($needsrelease) {
6402: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6403: my $needsupdate;
6404: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6405: $needsupdate = 1;
6406: } else {
6407: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6408: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6409: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6410: $needsupdate = 1;
6411: }
6412: }
6413: if ($needsupdate) {
6414: my %needshash = (
6415: 'internal.releaserequired' => $needsrelease,
6416: );
6417: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6418: if ($putresult eq 'ok') {
6419: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6420: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6421: if (ref($crsinfo{$cid}) eq 'HASH') {
6422: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6423: &courseidput($cdom,\%crsinfo,$chome,'notime');
6424: }
6425: }
6426: }
6427: }
6428: return;
6429: }
6430:
6431: # -------------------------------------------------See if a user is privileged
6432:
6433: sub privileged {
6434: my ($username,$domain,$possdomains,$possroles)=@_;
6435: my $now = time;
6436: my $roles;
6437: if (ref($possroles) eq 'ARRAY') {
6438: $roles = $possroles;
6439: } else {
6440: $roles = ['dc','su'];
6441: }
6442: if (ref($possdomains) eq 'ARRAY') {
6443: my %privileged = &privileged_by_domain($possdomains,$roles);
6444: foreach my $dom (@{$possdomains}) {
6445: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6446: (ref($privileged{$dom}) eq 'HASH')) {
6447: foreach my $role (@{$roles}) {
6448: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6449: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6450: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6451: return 1 unless (($end && $end < $now) ||
6452: ($start && $start > $now));
6453: }
6454: }
6455: }
6456: }
6457: }
6458: } else {
6459: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6460: my $now = time;
6461:
6462: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
6463: my ($trole, $tend, $tstart) = split(/_/, $role);
6464: if (grep(/^\Q$trole\E$/,@{$roles})) {
6465: return 1 unless ($tend && $tend < $now)
6466: or ($tstart && $tstart > $now);
6467: }
6468: }
6469: }
6470: return 0;
6471: }
6472:
6473: sub privileged_by_domain {
6474: my ($domains,$roles) = @_;
6475: my %privileged = ();
6476: my $cachetime = 60*60*24;
6477: my $now = time;
6478: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6479: return %privileged;
6480: }
6481: foreach my $dom (@{$domains}) {
6482: next if (ref($privileged{$dom}) eq 'HASH');
6483: my $needroles;
6484: foreach my $role (@{$roles}) {
6485: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6486: if (defined($cached)) {
6487: if (ref($result) eq 'HASH') {
6488: $privileged{$dom}{$role} = $result;
6489: }
6490: } else {
6491: $needroles = 1;
6492: }
6493: }
6494: if ($needroles) {
6495: my %dompersonnel = &get_domain_roles($dom,$roles);
6496: $privileged{$dom} = {};
6497: foreach my $server (keys(%dompersonnel)) {
6498: if (ref($dompersonnel{$server}) eq 'HASH') {
6499: foreach my $item (keys(%{$dompersonnel{$server}})) {
6500: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6501: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6502: next if ($end && $end < $now);
6503: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6504: $dompersonnel{$server}{$item};
6505: }
6506: }
6507: }
6508: if (ref($privileged{$dom}) eq 'HASH') {
6509: foreach my $role (@{$roles}) {
6510: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6511: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6512: } else {
6513: my %hash = ();
6514: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6515: }
6516: }
6517: }
6518: }
6519: }
6520: return %privileged;
6521: }
6522:
6523: # -------------------------------------------------------- Get user privileges
6524:
6525: sub rolesinit {
6526: my ($domain, $username) = @_;
6527: my %userroles = ('user.login.time' => time);
6528: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6529:
6530: # firstaccess and timerinterval are related to timed maps/resources.
6531: # also, blocking can be triggered by an activating timer
6532: # it's saved in the user's %env.
6533: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6534: my %timerinterval = &dump('timerinterval', $domain, $username);
6535: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
6536: %timerintchk, %timerintenv);
6537:
6538: foreach my $key (keys(%firstaccess)) {
6539: my ($cid, $rest) = split(/\0/, $key);
6540: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6541: }
6542:
6543: foreach my $key (keys(%timerinterval)) {
6544: my ($cid,$rest) = split(/\0/,$key);
6545: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6546: }
6547:
6548: my %allroles=();
6549: my %allgroups=();
6550:
6551: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
6552: my $role = $rolesdump{$area};
6553: $area =~ s/\_\w\w$//;
6554:
6555: my ($trole, $tend, $tstart, $group_privs);
6556:
6557: if ($role =~ /^cr/) {
6558: # Custom role, defined by a user
6559: # e.g., user.role.cr/msu/smith/mynewrole
6560: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6561: $trole = $1;
6562: ($tend, $tstart) = split('_', $2);
6563: } else {
6564: $trole = $role;
6565: }
6566: } elsif ($role =~ m|^gr/|) {
6567: # Role of member in a group, defined within a course/community
6568: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6569: ($trole, $tend, $tstart) = split(/_/, $role);
6570: next if $tstart eq '-1';
6571: ($trole, $group_privs) = split(/\//, $trole);
6572: $group_privs = &unescape($group_privs);
6573: } else {
6574: # Just a normal role, defined in roles.tab
6575: ($trole, $tend, $tstart) = split(/_/,$role);
6576: }
6577:
6578: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6579: $username);
6580: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6581:
6582: # role expired or not available yet?
6583: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6584: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6585:
6586: next if $area eq '' or $trole eq '';
6587:
6588: my $spec = "$trole.$area";
6589: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6590:
6591: if ($trole =~ /^cr\//) {
6592: # Custom role, defined by a user
6593: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6594: } elsif ($trole eq 'gr') {
6595: # Role of a member in a group, defined within a course/community
6596: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6597: next;
6598: } else {
6599: # Normal role, defined in roles.tab
6600: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6601: }
6602:
6603: my $cid = $tdomain.'_'.$trest;
6604: unless ($firstaccchk{$cid}) {
6605: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6606: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6607: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6608: $coursetimerstarts{$cid}{$item};
6609: }
6610: }
6611: $firstaccchk{$cid} = 1;
6612: }
6613: unless ($timerintchk{$cid}) {
6614: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6615: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6616: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6617: $coursetimerintervals{$cid}{$item};
6618: }
6619: }
6620: $timerintchk{$cid} = 1;
6621: }
6622: }
6623:
6624: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6625: \%allroles, \%allgroups);
6626: $env{'user.adv'} = $userroles{'user.adv'};
6627: $env{'user.rar'} = $userroles{'user.rar'};
6628:
6629: return (\%userroles,\%firstaccenv,\%timerintenv);
6630: }
6631:
6632: sub set_arearole {
6633: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6634: unless ($nolog) {
6635: # log the associated role with the area
6636: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6637: }
6638: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
6639: }
6640:
6641: sub custom_roleprivs {
6642: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6643: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
6644: my $homsvr = &homeserver($rauthor,$rdomain);
6645: if (&hostname($homsvr) ne '') {
6646: my ($rdummy,$roledef)=
6647: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6648: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6649: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6650: if (defined($syspriv)) {
6651: if ($trest =~ /^$match_community$/) {
6652: $syspriv =~ s/bre\&S//;
6653: }
6654: $$allroles{'cm./'}.=':'.$syspriv;
6655: $$allroles{$spec.'./'}.=':'.$syspriv;
6656: }
6657: if ($tdomain ne '') {
6658: if (defined($dompriv)) {
6659: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6660: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6661: }
6662: if (($trest ne '') && (defined($coursepriv))) {
6663: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6664: my $rolename = $1;
6665: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6666: }
6667: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6668: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6669: }
6670: }
6671: }
6672: }
6673: }
6674:
6675: sub course_adhocrole_privs {
6676: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6677: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6678: if ($overrides{"internal.adhocpriv.$rolename"}) {
6679: my (%currprivs,%storeprivs);
6680: foreach my $item (split(/:/,$coursepriv)) {
6681: my ($priv,$restrict) = split(/\&/,$item);
6682: $currprivs{$priv} = $restrict;
6683: }
6684: my (%possadd,%possremove,%full);
6685: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6686: my ($priv,$restrict)=split(/\&/,$item);
6687: $full{$priv} = $restrict;
6688: }
6689: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6690: next if ($item eq '');
6691: my ($rule,$rest) = split(/=/,$item);
6692: next unless (($rule eq 'off') || ($rule eq 'on'));
6693: foreach my $priv (split(/:/,$rest)) {
6694: if ($priv ne '') {
6695: if ($rule eq 'off') {
6696: $possremove{$priv} = 1;
6697: } else {
6698: $possadd{$priv} = 1;
6699: }
6700: }
6701: }
6702: }
6703: foreach my $priv (sort(keys(%full))) {
6704: if (exists($currprivs{$priv})) {
6705: unless (exists($possremove{$priv})) {
6706: $storeprivs{$priv} = $currprivs{$priv};
6707: }
6708: } elsif (exists($possadd{$priv})) {
6709: $storeprivs{$priv} = $full{$priv};
6710: }
6711: }
6712: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6713: }
6714: return $coursepriv;
6715: }
6716:
6717: sub group_roleprivs {
6718: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6719: my $access = 1;
6720: my $now = time;
6721: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6722: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6723: if ($access) {
6724: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
6725: $$allgroups{$course}{$group} .=':'.$group_privs;
6726: }
6727: }
6728:
6729: sub standard_roleprivs {
6730: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6731: if (defined($pr{$trole.':s'})) {
6732: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6733: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6734: }
6735: if ($tdomain ne '') {
6736: if (defined($pr{$trole.':d'})) {
6737: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6738: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6739: }
6740: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6741: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6742: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6743: }
6744: }
6745: }
6746:
6747: sub set_userprivs {
6748: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
6749: my $author=0;
6750: my $adv=0;
6751: my $rar=0;
6752: my %grouproles = ();
6753: if (keys(%{$allgroups}) > 0) {
6754: my @groupkeys;
6755: foreach my $role (keys(%{$allroles})) {
6756: push(@groupkeys,$role);
6757: }
6758: if (ref($groups_roles) eq 'HASH') {
6759: foreach my $key (keys(%{$groups_roles})) {
6760: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6761: push(@groupkeys,$key);
6762: }
6763: }
6764: }
6765: if (@groupkeys > 0) {
6766: foreach my $role (@groupkeys) {
6767: my ($trole,$area,$sec,$extendedarea);
6768: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6769: $trole = $1;
6770: $area = $2;
6771: $sec = $3;
6772: $extendedarea = $area.$sec;
6773: if (exists($$allgroups{$area})) {
6774: foreach my $group (keys(%{$$allgroups{$area}})) {
6775: my $spec = $trole.'.'.$extendedarea;
6776: $grouproles{$spec.'.'.$area.'/'.$group} =
6777: $$allgroups{$area}{$group};
6778: }
6779: }
6780: }
6781: }
6782: }
6783: }
6784: foreach my $group (keys(%grouproles)) {
6785: $$allroles{$group} = $grouproles{$group};
6786: }
6787: foreach my $role (keys(%{$allroles})) {
6788: my %thesepriv;
6789: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
6790: foreach my $item (split(/:/,$$allroles{$role})) {
6791: if ($item ne '') {
6792: my ($privilege,$restrictions)=split(/&/,$item);
6793: if ($restrictions eq '') {
6794: $thesepriv{$privilege}='F';
6795: } elsif ($thesepriv{$privilege} ne 'F') {
6796: $thesepriv{$privilege}.=$restrictions;
6797: }
6798: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
6799: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
6800: }
6801: }
6802: my $thesestr='';
6803: foreach my $priv (sort(keys(%thesepriv))) {
6804: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6805: }
6806: $userroles->{'user.priv.'.$role} = $thesestr;
6807: }
6808: return ($author,$adv,$rar);
6809: }
6810:
6811: sub role_status {
6812: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
6813: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
6814: my ($one,$two) = split(m{\./},$rolekey,2);
6815: (undef,undef,$$role) = split(/\./,$one,3);
6816: unless (!defined($$role) || $$role eq '') {
6817: $$where = '/'.$two;
6818: $$trolecode=$$role.'.'.$$where;
6819: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6820: $$tstatus='is';
6821: if ($$tstart && $$tstart>$update) {
6822: $$tstatus='future';
6823: if ($$tstart<$now) {
6824: if ($$tstart && $$tstart>$refresh) {
6825: if (($$where ne '') && ($$role ne '')) {
6826: my (%allroles,%allgroups,$group_privs,
6827: %groups_roles,@rolecodes);
6828: my %userroles = (
6829: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6830: );
6831: @rolecodes = ('cm');
6832: my $spec=$$role.'.'.$$where;
6833: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6834: if ($$role =~ /^cr\//) {
6835: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
6836: push(@rolecodes,'cr');
6837: } elsif ($$role eq 'gr') {
6838: push(@rolecodes,$$role);
6839: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6840: $env{'user.name'});
6841: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
6842: (undef,my $group_privs) = split(/\//,$trole);
6843: $group_privs = &unescape($group_privs);
6844: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
6845: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
6846: &get_groups_roles($tdomain,$trest,
6847: \%course_roles,\@rolecodes,
6848: \%groups_roles);
6849: } else {
6850: push(@rolecodes,$$role);
6851: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6852: }
6853: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6854: \%groups_roles);
6855: &appenv(\%userroles,\@rolecodes);
6856: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
6857: }
6858: }
6859: $$tstatus = 'is';
6860: }
6861: }
6862: if ($$tend) {
6863: if ($$tend<$update) {
6864: $$tstatus='expired';
6865: } elsif ($$tend<$now) {
6866: $$tstatus='will_not';
6867: }
6868: }
6869: }
6870: }
6871: }
6872:
6873: sub get_groups_roles {
6874: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6875: return unless((ref($cdom_courseroles) eq 'HASH') &&
6876: (ref($rolecodes) eq 'ARRAY') &&
6877: (ref($groups_roles) eq 'HASH'));
6878: if (keys(%{$cdom_courseroles}) > 0) {
6879: my ($cnum) = ($rest =~ /^($match_courseid)/);
6880: if ($cdom ne '' && $cnum ne '') {
6881: foreach my $key (keys(%{$cdom_courseroles})) {
6882: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6883: my $crsrole = $1;
6884: my $crssec = $2;
6885: if ($crsrole =~ /^cr/) {
6886: unless (grep(/^cr$/,@{$rolecodes})) {
6887: push(@{$rolecodes},'cr');
6888: }
6889: } else {
6890: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6891: push(@{$rolecodes},$crsrole);
6892: }
6893: }
6894: my $rolekey = "$crsrole./$cdom/$cnum";
6895: if ($crssec ne '') {
6896: $rolekey .= "/$crssec";
6897: }
6898: $rolekey .= './';
6899: $groups_roles->{$rolekey} = $rolecodes;
6900: }
6901: }
6902: }
6903: }
6904: return;
6905: }
6906:
6907: sub delete_env_groupprivs {
6908: my ($where,$courseroles,$possroles) = @_;
6909: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6910: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6911: unless (ref($courseroles->{$udom}) eq 'HASH') {
6912: %{$courseroles->{$udom}} =
6913: &get_my_roles('','','userroles',['active'],
6914: $possroles,[$udom],1);
6915: }
6916: if (ref($courseroles->{$udom}) eq 'HASH') {
6917: foreach my $item (keys(%{$courseroles->{$udom}})) {
6918: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6919: my $area = '/'.$cdom.'/'.$cnum;
6920: my $privkey = "user.priv.$crsrole.$area";
6921: if ($crssec ne '') {
6922: $privkey .= '/'.$crssec;
6923: }
6924: $privkey .= ".$area/$group";
6925: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6926: }
6927: }
6928: return;
6929: }
6930:
6931: sub check_adhoc_privs {
6932: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
6933: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
6934: if ($sec) {
6935: $cckey .= '/'.$sec;
6936: }
6937: my $setprivs;
6938: if ($env{$cckey}) {
6939: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
6940: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
6941: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
6942: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
6943: $setprivs = 1;
6944: }
6945: } else {
6946: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
6947: $setprivs = 1;
6948: }
6949: return $setprivs;
6950: }
6951:
6952: sub set_adhoc_privileges {
6953: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
6954: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
6955: my $area = '/'.$dcdom.'/'.$pickedcourse;
6956: if ($sec ne '') {
6957: $area .= '/'.$sec;
6958: }
6959: my $spec = $role.'.'.$area;
6960: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
6961: $env{'user.name'},1);
6962: my %rolehash = ();
6963: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6964: my $rolename = $1;
6965: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
6966: my %domdef = &get_domain_defaults($dcdom);
6967: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6968: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6969: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6970: }
6971: }
6972: } else {
6973: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6974: }
6975: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
6976: &appenv(\%userroles,[$role,'cm']);
6977: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
6978: unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
6979: ($caller eq 'tiny')) {
6980: &appenv( {'request.role' => $spec,
6981: 'request.role.domain' => $dcdom,
6982: 'request.course.sec' => $sec,
6983: }
6984: );
6985: my $tadv=0;
6986: if (&allowed('adv') eq 'F') { $tadv=1; }
6987: &appenv({'request.role.adv' => $tadv});
6988: }
6989: }
6990:
6991: # --------------------------------------------------------------- get interface
6992:
6993: sub get {
6994: my ($namespace,$storearr,$udomain,$uname)=@_;
6995: my $items='';
6996: foreach my $item (@$storearr) {
6997: $items.=&escape($item).'&';
6998: }
6999: $items=~s/\&$//;
7000: if (!$udomain) { $udomain=$env{'user.domain'}; }
7001: if (!$uname) { $uname=$env{'user.name'}; }
7002: my $uhome=&homeserver($uname,$udomain);
7003:
7004: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
7005: my @pairs=split(/\&/,$rep);
7006: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
7007: return @pairs;
7008: }
7009: my %returnhash=();
7010: my $i=0;
7011: foreach my $item (@$storearr) {
7012: $returnhash{$item}=&thaw_unescape($pairs[$i]);
7013: $i++;
7014: }
7015: return %returnhash;
7016: }
7017:
7018: # --------------------------------------------------------------- del interface
7019:
7020: sub del {
7021: my ($namespace,$storearr,$udomain,$uname)=@_;
7022: my $items='';
7023: foreach my $item (@$storearr) {
7024: $items.=&escape($item).'&';
7025: }
7026:
7027: $items=~s/\&$//;
7028: if (!$udomain) { $udomain=$env{'user.domain'}; }
7029: if (!$uname) { $uname=$env{'user.name'}; }
7030: my $uhome=&homeserver($uname,$udomain);
7031: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
7032: }
7033:
7034: # -------------------------------------------------------------- dump interface
7035:
7036: sub unserialize {
7037: my ($rep, $escapedkeys) = @_;
7038:
7039: return {} if $rep =~ /^error/;
7040:
7041: my %returnhash=();
7042: foreach my $item (split(/\&/,$rep)) {
7043: my ($key, $value) = split(/=/, $item, 2);
7044: $key = unescape($key) unless $escapedkeys;
7045: next if $key =~ /^error: 2 /;
7046: $returnhash{$key} = &thaw_unescape($value);
7047: }
7048: #return %returnhash;
7049: return \%returnhash;
7050: }
7051:
7052: # see Lond::dump_with_regexp
7053: # if $escapedkeys hash keys won't get unescaped.
7054: sub dump {
7055: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
7056: if (!$udomain) { $udomain=$env{'user.domain'}; }
7057: if (!$uname) { $uname=$env{'user.name'}; }
7058: my $uhome=&homeserver($uname,$udomain);
7059:
7060: if ($regexp) {
7061: $regexp=&escape($regexp);
7062: } else {
7063: $regexp='.';
7064: }
7065: if (grep { $_ eq $uhome } current_machine_ids()) {
7066: # user is hosted on this machine
7067: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
7068: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
7069: return %{unserialize($reply, $escapedkeys)};
7070: }
7071: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
7072: my @pairs=split(/\&/,$rep);
7073: my %returnhash=();
7074: if (!($rep =~ /^error/ )) {
7075: foreach my $item (@pairs) {
7076: my ($key,$value)=split(/=/,$item,2);
7077: $key = unescape($key) unless $escapedkeys;
7078: #$key = &unescape($key);
7079: next if ($key =~ /^error: 2 /);
7080: $returnhash{$key}=&thaw_unescape($value);
7081: }
7082: }
7083: return %returnhash;
7084: }
7085:
7086:
7087: # --------------------------------------------------------- dumpstore interface
7088:
7089: sub dumpstore {
7090: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
7091: # same as dump but keys must be escaped. They may contain colon separated
7092: # lists of values that may themself contain colons (e.g. symbs).
7093: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
7094: }
7095:
7096: # -------------------------------------------------------------- keys interface
7097:
7098: sub getkeys {
7099: my ($namespace,$udomain,$uname)=@_;
7100: if (!$udomain) { $udomain=$env{'user.domain'}; }
7101: if (!$uname) { $uname=$env{'user.name'}; }
7102: my $uhome=&homeserver($uname,$udomain);
7103: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
7104: my @keyarray=();
7105: foreach my $key (split(/\&/,$rep)) {
7106: next if ($key =~ /^error: 2 /);
7107: push(@keyarray,&unescape($key));
7108: }
7109: return @keyarray;
7110: }
7111:
7112: # --------------------------------------------------------------- currentdump
7113: sub currentdump {
7114: my ($courseid,$sdom,$sname)=@_;
7115: $courseid = $env{'request.course.id'} if (! defined($courseid));
7116: $sdom = $env{'user.domain'} if (! defined($sdom));
7117: $sname = $env{'user.name'} if (! defined($sname));
7118: my $uhome = &homeserver($sname,$sdom);
7119: my $rep;
7120:
7121: if (grep { $_ eq $uhome } current_machine_ids()) {
7122: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
7123: $courseid)));
7124: } else {
7125: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
7126: }
7127:
7128: return if ($rep =~ /^(error:|no_such_host)/);
7129: #
7130: my %returnhash=();
7131: #
7132: if ($rep eq 'unknown_cmd') {
7133: # an old lond will not know currentdump
7134: # Do a dump and make it look like a currentdump
7135: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
7136: return if ($tmp[0] =~ /^(error:|no_such_host)/);
7137: my %hash = @tmp;
7138: @tmp=();
7139: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
7140: } else {
7141: my @pairs=split(/\&/,$rep);
7142: foreach my $pair (@pairs) {
7143: my ($key,$value)=split(/=/,$pair,2);
7144: my ($symb,$param) = split(/:/,$key);
7145: $returnhash{&unescape($symb)}->{&unescape($param)} =
7146: &thaw_unescape($value);
7147: }
7148: }
7149: return %returnhash;
7150: }
7151:
7152: sub convert_dump_to_currentdump{
7153: my %hash = %{shift()};
7154: my %returnhash;
7155: # Code ripped from lond, essentially. The only difference
7156: # here is the unescaping done by lonnet::dump(). Conceivably
7157: # we might run in to problems with parameter names =~ /^v\./
7158: while (my ($key,$value) = each(%hash)) {
7159: my ($v,$symb,$param) = split(/:/,$key);
7160: $symb = &unescape($symb);
7161: $param = &unescape($param);
7162: next if ($v eq 'version' || $symb eq 'keys');
7163: next if (exists($returnhash{$symb}) &&
7164: exists($returnhash{$symb}->{$param}) &&
7165: $returnhash{$symb}->{'v.'.$param} > $v);
7166: $returnhash{$symb}->{$param}=$value;
7167: $returnhash{$symb}->{'v.'.$param}=$v;
7168: }
7169: #
7170: # Remove all of the keys in the hashes which keep track of
7171: # the version of the parameter.
7172: while (my ($symb,$param_hash) = each(%returnhash)) {
7173: # use a foreach because we are going to delete from the hash.
7174: foreach my $key (keys(%$param_hash)) {
7175: delete($param_hash->{$key}) if ($key =~ /^v\./);
7176: }
7177: }
7178: return \%returnhash;
7179: }
7180:
7181: # ------------------------------------------------------ critical inc interface
7182:
7183: sub cinc {
7184: return &inc(@_,'critical');
7185: }
7186:
7187: # --------------------------------------------------------------- inc interface
7188:
7189: sub inc {
7190: my ($namespace,$store,$udomain,$uname,$critical) = @_;
7191: if (!$udomain) { $udomain=$env{'user.domain'}; }
7192: if (!$uname) { $uname=$env{'user.name'}; }
7193: my $uhome=&homeserver($uname,$udomain);
7194: my $items='';
7195: if (! ref($store)) {
7196: # got a single value, so use that instead
7197: $items = &escape($store).'=&';
7198: } elsif (ref($store) eq 'SCALAR') {
7199: $items = &escape($$store).'=&';
7200: } elsif (ref($store) eq 'ARRAY') {
7201: $items = join('=&',map {&escape($_);} @{$store});
7202: } elsif (ref($store) eq 'HASH') {
7203: while (my($key,$value) = each(%{$store})) {
7204: $items.= &escape($key).'='.&escape($value).'&';
7205: }
7206: }
7207: $items=~s/\&$//;
7208: if ($critical) {
7209: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
7210: } else {
7211: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
7212: }
7213: }
7214:
7215: # --------------------------------------------------------------- put interface
7216:
7217: sub put {
7218: my ($namespace,$storehash,$udomain,$uname)=@_;
7219: if (!$udomain) { $udomain=$env{'user.domain'}; }
7220: if (!$uname) { $uname=$env{'user.name'}; }
7221: my $uhome=&homeserver($uname,$udomain);
7222: my $items='';
7223: foreach my $item (keys(%$storehash)) {
7224: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
7225: }
7226: $items=~s/\&$//;
7227: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
7228: }
7229:
7230: # ------------------------------------------------------------ newput interface
7231:
7232: sub newput {
7233: my ($namespace,$storehash,$udomain,$uname)=@_;
7234: if (!$udomain) { $udomain=$env{'user.domain'}; }
7235: if (!$uname) { $uname=$env{'user.name'}; }
7236: my $uhome=&homeserver($uname,$udomain);
7237: my $items='';
7238: foreach my $key (keys(%$storehash)) {
7239: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7240: }
7241: $items=~s/\&$//;
7242: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
7243: }
7244:
7245: # --------------------------------------------------------- putstore interface
7246:
7247: sub putstore {
7248: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
7249: if (!$udomain) { $udomain=$env{'user.domain'}; }
7250: if (!$uname) { $uname=$env{'user.name'}; }
7251: my $uhome=&homeserver($uname,$udomain);
7252: my $items='';
7253: foreach my $key (keys(%$storehash)) {
7254: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7255: }
7256: $items=~s/\&$//;
7257: my $esc_symb=&escape($symb);
7258: my $esc_v=&escape($version);
7259: my $reply =
7260: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
7261: $uhome);
7262: if (($tolog) && ($reply eq 'ok')) {
7263: my $namevalue='';
7264: foreach my $key (keys(%{$storehash})) {
7265: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7266: }
7267: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
7268: '&host='.&escape($perlvar{'lonHostID'}).
7269: '&version='.$esc_v.
7270: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
7271: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
7272: }
7273: if ($reply eq 'unknown_cmd') {
7274: # gfall back to way things use to be done
7275: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7276: $uname);
7277: }
7278: return $reply;
7279: }
7280:
7281: sub old_putstore {
7282: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
7283: if (!$udomain) { $udomain=$env{'user.domain'}; }
7284: if (!$uname) { $uname=$env{'user.name'}; }
7285: my $uhome=&homeserver($uname,$udomain);
7286: my %newstorehash;
7287: foreach my $item (keys(%$storehash)) {
7288: my $key = $version.':'.&escape($symb).':'.$item;
7289: $newstorehash{$key} = $storehash->{$item};
7290: }
7291: my $items='';
7292: my %allitems = ();
7293: foreach my $item (keys(%newstorehash)) {
7294: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
7295: my $key = $1.':keys:'.$2;
7296: $allitems{$key} .= $3.':';
7297: }
7298: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
7299: }
7300: foreach my $item (keys(%allitems)) {
7301: $allitems{$item} =~ s/\:$//;
7302: $items.= $item.'='.$allitems{$item}.'&';
7303: }
7304: $items=~s/\&$//;
7305: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
7306: }
7307:
7308: # ------------------------------------------------------ critical put interface
7309:
7310: sub cput {
7311: my ($namespace,$storehash,$udomain,$uname)=@_;
7312: if (!$udomain) { $udomain=$env{'user.domain'}; }
7313: if (!$uname) { $uname=$env{'user.name'}; }
7314: my $uhome=&homeserver($uname,$udomain);
7315: my $items='';
7316: foreach my $item (keys(%$storehash)) {
7317: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
7318: }
7319: $items=~s/\&$//;
7320: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
7321: }
7322:
7323: # -------------------------------------------------------------- eget interface
7324:
7325: sub eget {
7326: my ($namespace,$storearr,$udomain,$uname)=@_;
7327: my $items='';
7328: foreach my $item (@$storearr) {
7329: $items.=&escape($item).'&';
7330: }
7331: $items=~s/\&$//;
7332: if (!$udomain) { $udomain=$env{'user.domain'}; }
7333: if (!$uname) { $uname=$env{'user.name'}; }
7334: my $uhome=&homeserver($uname,$udomain);
7335: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
7336: my @pairs=split(/\&/,$rep);
7337: my %returnhash=();
7338: my $i=0;
7339: foreach my $item (@$storearr) {
7340: $returnhash{$item}=&thaw_unescape($pairs[$i]);
7341: $i++;
7342: }
7343: return %returnhash;
7344: }
7345:
7346: # ------------------------------------------------------------ tmpput interface
7347: sub tmpput {
7348: my ($storehash,$server,$context)=@_;
7349: my $items='';
7350: foreach my $item (keys(%$storehash)) {
7351: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
7352: }
7353: $items=~s/\&$//;
7354: if (defined($context)) {
7355: $items .= ':'.&escape($context);
7356: }
7357: return &reply("tmpput:$items",$server);
7358: }
7359:
7360: # ------------------------------------------------------------ tmpget interface
7361: sub tmpget {
7362: my ($token,$server)=@_;
7363: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7364: my $rep=&reply("tmpget:$token",$server);
7365: my %returnhash;
7366: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7367: return %returnhash;
7368: }
7369: foreach my $item (split(/\&/,$rep)) {
7370: my ($key,$value)=split(/=/,$item);
7371: $returnhash{&unescape($key)}=&thaw_unescape($value);
7372: }
7373: return %returnhash;
7374: }
7375:
7376: # ------------------------------------------------------------ tmpdel interface
7377: sub tmpdel {
7378: my ($token,$server)=@_;
7379: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7380: return &reply("tmpdel:$token",$server);
7381: }
7382:
7383: # ------------------------------------------------------------ get_timebased_id
7384:
7385: sub get_timebased_id {
7386: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7387: $maxtries) = @_;
7388: my ($newid,$error,$dellock);
7389: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7390: return ('','ok','invalid call to get suffix');
7391: }
7392:
7393: # set defaults for any optional args for which values were not supplied
7394: if ($who eq '') {
7395: $who = $env{'user.name'}.':'.$env{'user.domain'};
7396: }
7397: if (!$locktries) {
7398: $locktries = 3;
7399: }
7400: if (!$maxtries) {
7401: $maxtries = 10;
7402: }
7403:
7404: if (($cdom eq '') || ($cnum eq '')) {
7405: if ($env{'request.course.id'}) {
7406: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7407: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7408: }
7409: if (($cdom eq '') || ($cnum eq '')) {
7410: return ('','ok','call to get suffix not in course context');
7411: }
7412: }
7413:
7414: # construct locking item
7415: my $lockhash = {
7416: $prefix."\0".'locked_'.$keyid => $who,
7417: };
7418: my $tries = 0;
7419:
7420: # attempt to get lock on nohist_$namespace file
7421: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7422: while (($gotlock ne 'ok') && $tries <$locktries) {
7423: $tries ++;
7424: sleep 1;
7425: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7426: }
7427:
7428: # attempt to get unique identifier, based on current timestamp
7429: if ($gotlock eq 'ok') {
7430: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
7431: my $id = time;
7432: $newid = $id;
7433: if ($idtype eq 'addcode') {
7434: $newid .= &sixnum_code();
7435: }
7436: my $idtries = 0;
7437: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7438: if ($idtype eq 'concat') {
7439: $newid = $id.$idtries;
7440: } elsif ($idtype eq 'addcode') {
7441: $newid = $newid.&sixnum_code();
7442: } else {
7443: $newid ++;
7444: }
7445: $idtries ++;
7446: }
7447: if (!exists($inuse{$prefix."\0".$newid})) {
7448: my %new_item = (
7449: $prefix."\0".$newid => $who,
7450: );
7451: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
7452: $cdom,$cnum);
7453: if ($putresult ne 'ok') {
7454: undef($newid);
7455: $error = 'error saving new item: '.$putresult;
7456: }
7457: } else {
7458: undef($newid);
7459: $error = ('error: no unique suffix available for the new item ');
7460: }
7461: # remove lock
7462: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7463: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7464: } else {
7465: $error = "error: could not obtain lockfile\n";
7466: $dellock = 'ok';
7467: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7468: $dellock = 'nolock';
7469: }
7470: }
7471: return ($newid,$dellock,$error);
7472: }
7473:
7474: sub sixnum_code {
7475: my $code;
7476: for (0..6) {
7477: $code .= int( rand(9) );
7478: }
7479: return $code;
7480: }
7481:
7482: # -------------------------------------------------- portfolio access checking
7483:
7484: sub portfolio_access {
7485: my ($requrl,$clientip) = @_;
7486: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
7487: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
7488: if ($result) {
7489: my %setters;
7490: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7491: my ($startblock,$endblock) =
7492: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
7493: if ($startblock && $endblock) {
7494: return 'B';
7495: }
7496: } else {
7497: my ($startblock,$endblock) =
7498: &Apache::loncommon::blockcheck(\%setters,'port');
7499: if ($startblock && $endblock) {
7500: return 'B';
7501: }
7502: }
7503: }
7504: if ($result eq 'ok') {
7505: return 'F';
7506: } elsif ($result =~ /^[^:]+:guest_/) {
7507: return 'A';
7508: }
7509: return '';
7510: }
7511:
7512: sub get_portfolio_access {
7513: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
7514:
7515: if (!ref($access_hash)) {
7516: my $current_perms = &get_portfile_permissions($udom,$unum);
7517: my %access_controls = &get_access_controls($current_perms,$group,
7518: $file_name);
7519: $access_hash = $access_controls{$file_name};
7520: }
7521:
7522: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
7523: my $now = time;
7524: if (ref($access_hash) eq 'HASH') {
7525: foreach my $key (keys(%{$access_hash})) {
7526: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7527: if ($start > $now) {
7528: next;
7529: }
7530: if ($end && $end<$now) {
7531: next;
7532: }
7533: if ($scope eq 'public') {
7534: $public = $key;
7535: last;
7536: } elsif ($scope eq 'guest') {
7537: $guest = $key;
7538: } elsif ($scope eq 'domains') {
7539: push(@domains,$key);
7540: } elsif ($scope eq 'users') {
7541: push(@users,$key);
7542: } elsif ($scope eq 'course') {
7543: push(@courses,$key);
7544: } elsif ($scope eq 'group') {
7545: push(@groups,$key);
7546: } elsif ($scope eq 'ip') {
7547: push(@ips,$key);
7548: }
7549: }
7550: if ($public) {
7551: return 'ok';
7552: } elsif (@ips > 0) {
7553: my $allowed;
7554: foreach my $ipkey (@ips) {
7555: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7556: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7557: $allowed = 1;
7558: last;
7559: }
7560: }
7561: }
7562: if ($allowed) {
7563: return 'ok';
7564: }
7565: }
7566: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7567: if ($guest) {
7568: return $guest;
7569: }
7570: } else {
7571: if (@domains > 0) {
7572: foreach my $domkey (@domains) {
7573: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7574: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7575: return 'ok';
7576: }
7577: }
7578: }
7579: }
7580: if (@users > 0) {
7581: foreach my $userkey (@users) {
7582: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7583: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7584: if (ref($item) eq 'HASH') {
7585: if (($item->{'uname'} eq $env{'user.name'}) &&
7586: ($item->{'udom'} eq $env{'user.domain'})) {
7587: return 'ok';
7588: }
7589: }
7590: }
7591: }
7592: }
7593: }
7594: my %roleshash;
7595: my @courses_and_groups = @courses;
7596: push(@courses_and_groups,@groups);
7597: if (@courses_and_groups > 0) {
7598: my (%allgroups,%allroles);
7599: my ($start,$end,$role,$sec,$group);
7600: foreach my $envkey (%env) {
7601: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
7602: my $cid = $2.'_'.$3;
7603: if ($1 eq 'gr') {
7604: $group = $4;
7605: $allgroups{$cid}{$group} = $env{$envkey};
7606: } else {
7607: if ($4 eq '') {
7608: $sec = 'none';
7609: } else {
7610: $sec = $4;
7611: }
7612: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7613: }
7614: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
7615: my $cid = $2.'_'.$3;
7616: if ($4 eq '') {
7617: $sec = 'none';
7618: } else {
7619: $sec = $4;
7620: }
7621: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7622: }
7623: }
7624: if (keys(%allroles) == 0) {
7625: return;
7626: }
7627: foreach my $key (@courses_and_groups) {
7628: my %content = %{$$access_hash{$key}};
7629: my $cnum = $content{'number'};
7630: my $cdom = $content{'domain'};
7631: my $cid = $cdom.'_'.$cnum;
7632: if (!exists($allroles{$cid})) {
7633: next;
7634: }
7635: foreach my $role_id (keys(%{$content{'roles'}})) {
7636: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7637: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7638: my @status = @{$content{'roles'}{$role_id}{'access'}};
7639: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7640: foreach my $role (keys(%{$allroles{$cid}})) {
7641: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7642: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7643: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7644: if (grep/^all$/,@sections) {
7645: return 'ok';
7646: } else {
7647: if (grep/^$sec$/,@sections) {
7648: return 'ok';
7649: }
7650: }
7651: }
7652: }
7653: if (keys(%{$allgroups{$cid}}) == 0) {
7654: if (grep/^none$/,@groups) {
7655: return 'ok';
7656: }
7657: } else {
7658: if (grep/^all$/,@groups) {
7659: return 'ok';
7660: }
7661: foreach my $group (keys(%{$allgroups{$cid}})) {
7662: if (grep/^$group$/,@groups) {
7663: return 'ok';
7664: }
7665: }
7666: }
7667: }
7668: }
7669: }
7670: }
7671: }
7672: if ($guest) {
7673: return $guest;
7674: }
7675: }
7676: }
7677: return;
7678: }
7679:
7680: sub course_group_datechecker {
7681: my ($dates,$now,$status) = @_;
7682: my ($start,$end) = split(/\./,$dates);
7683: if (!$start && !$end) {
7684: return 'ok';
7685: }
7686: if (grep/^active$/,@{$status}) {
7687: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7688: return 'ok';
7689: }
7690: }
7691: if (grep/^previous$/,@{$status}) {
7692: if ($end > $now ) {
7693: return 'ok';
7694: }
7695: }
7696: if (grep/^future$/,@{$status}) {
7697: if ($start > $now) {
7698: return 'ok';
7699: }
7700: }
7701: return;
7702: }
7703:
7704: sub parse_portfolio_url {
7705: my ($url) = @_;
7706:
7707: my ($type,$udom,$unum,$group,$file_name);
7708:
7709: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
7710: $type = 1;
7711: $udom = $1;
7712: $unum = $2;
7713: $file_name = $3;
7714: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
7715: $type = 2;
7716: $udom = $1;
7717: $unum = $2;
7718: $group = $3;
7719: $file_name = $3.'/'.$4;
7720: }
7721: if (wantarray) {
7722: return ($type,$udom,$unum,$file_name,$group);
7723: }
7724: return $type;
7725: }
7726:
7727: sub is_portfolio_url {
7728: my ($url) = @_;
7729: return scalar(&parse_portfolio_url($url));
7730: }
7731:
7732: sub is_portfolio_file {
7733: my ($file) = @_;
7734: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
7735: return 1;
7736: }
7737: return;
7738: }
7739:
7740: sub usertools_access {
7741: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
7742: my ($access,%tools);
7743: if ($context eq '') {
7744: $context = 'tools';
7745: }
7746: if ($context eq 'requestcourses') {
7747: %tools = (
7748: official => 1,
7749: unofficial => 1,
7750: community => 1,
7751: textbook => 1,
7752: placement => 1,
7753: lti => 1,
7754: );
7755: } elsif ($context eq 'requestauthor') {
7756: %tools = (
7757: requestauthor => 1,
7758: );
7759: } else {
7760: %tools = (
7761: aboutme => 1,
7762: blog => 1,
7763: webdav => 1,
7764: portfolio => 1,
7765: );
7766: }
7767: return if (!defined($tools{$tool}));
7768:
7769: if (($udom eq '') || ($uname eq '')) {
7770: $udom = $env{'user.domain'};
7771: $uname = $env{'user.name'};
7772: }
7773:
7774: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7775: if ($action ne 'reload') {
7776: if ($context eq 'requestcourses') {
7777: return $env{'environment.canrequest.'.$tool};
7778: } elsif ($context eq 'requestauthor') {
7779: return $env{'environment.canrequest.author'};
7780: } else {
7781: return $env{'environment.availabletools.'.$tool};
7782: }
7783: }
7784: }
7785:
7786: my ($toolstatus,$inststatus,$envkey);
7787: if ($context eq 'requestauthor') {
7788: $envkey = $context;
7789: } else {
7790: $envkey = $context.'.'.$tool;
7791: }
7792:
7793: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7794: ($action ne 'reload')) {
7795: $toolstatus = $env{'environment.'.$envkey};
7796: $inststatus = $env{'environment.inststatus'};
7797: } else {
7798: if (ref($userenvref) eq 'HASH') {
7799: $toolstatus = $userenvref->{$envkey};
7800: $inststatus = $userenvref->{'inststatus'};
7801: } else {
7802: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7803: $toolstatus = $userenv{$envkey};
7804: $inststatus = $userenv{'inststatus'};
7805: }
7806: }
7807:
7808: if ($toolstatus ne '') {
7809: if ($toolstatus) {
7810: $access = 1;
7811: } else {
7812: $access = 0;
7813: }
7814: return $access;
7815: }
7816:
7817: my ($is_adv,%domdef);
7818: if (ref($is_advref) eq 'HASH') {
7819: $is_adv = $is_advref->{'is_adv'};
7820: } else {
7821: $is_adv = &is_advanced_user($udom,$uname);
7822: }
7823: if (ref($domdefref) eq 'HASH') {
7824: %domdef = %{$domdefref};
7825: } else {
7826: %domdef = &get_domain_defaults($udom);
7827: }
7828: if (ref($domdef{$tool}) eq 'HASH') {
7829: if ($is_adv) {
7830: if ($domdef{$tool}{'_LC_adv'} ne '') {
7831: if ($domdef{$tool}{'_LC_adv'}) {
7832: $access = 1;
7833: } else {
7834: $access = 0;
7835: }
7836: return $access;
7837: }
7838: }
7839: if ($inststatus ne '') {
7840: my ($hasaccess,$hasnoaccess);
7841: foreach my $affiliation (split(/:/,$inststatus)) {
7842: if ($domdef{$tool}{$affiliation} ne '') {
7843: if ($domdef{$tool}{$affiliation}) {
7844: $hasaccess = 1;
7845: } else {
7846: $hasnoaccess = 1;
7847: }
7848: }
7849: }
7850: if ($hasaccess || $hasnoaccess) {
7851: if ($hasaccess) {
7852: $access = 1;
7853: } elsif ($hasnoaccess) {
7854: $access = 0;
7855: }
7856: return $access;
7857: }
7858: } else {
7859: if ($domdef{$tool}{'default'} ne '') {
7860: if ($domdef{$tool}{'default'}) {
7861: $access = 1;
7862: } elsif ($domdef{$tool}{'default'} == 0) {
7863: $access = 0;
7864: }
7865: return $access;
7866: }
7867: }
7868: } else {
7869: if (($context eq 'tools') && ($tool ne 'webdav')) {
7870: $access = 1;
7871: } else {
7872: $access = 0;
7873: }
7874: return $access;
7875: }
7876: }
7877:
7878: sub is_course_owner {
7879: my ($cdom,$cnum,$udom,$uname) = @_;
7880: if (($udom eq '') || ($uname eq '')) {
7881: $udom = $env{'user.domain'};
7882: $uname = $env{'user.name'};
7883: }
7884: unless (($udom eq '') || ($uname eq '')) {
7885: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7886: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7887: return 1;
7888: } else {
7889: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7890: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7891: return 1;
7892: }
7893: }
7894: }
7895: }
7896: return;
7897: }
7898:
7899: sub is_advanced_user {
7900: my ($udom,$uname) = @_;
7901: if ($udom ne '' && $uname ne '') {
7902: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7903: if (wantarray) {
7904: return ($env{'user.adv'},$env{'user.author'});
7905: } else {
7906: return $env{'user.adv'};
7907: }
7908: }
7909: }
7910: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7911: my %allroles;
7912: my ($is_adv,$is_author);
7913: foreach my $role (keys(%roleshash)) {
7914: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7915: my $area = '/'.$tdomain.'/'.$trest;
7916: if ($sec ne '') {
7917: $area .= '/'.$sec;
7918: }
7919: if (($area ne '') && ($trole ne '')) {
7920: my $spec=$trole.'.'.$area;
7921: if ($trole =~ /^cr\//) {
7922: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7923: } elsif ($trole ne 'gr') {
7924: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7925: }
7926: if ($trole eq 'au') {
7927: $is_author = 1;
7928: }
7929: }
7930: }
7931: foreach my $role (keys(%allroles)) {
7932: last if ($is_adv);
7933: foreach my $item (split(/:/,$allroles{$role})) {
7934: if ($item ne '') {
7935: my ($privilege,$restrictions)=split(/&/,$item);
7936: if ($privilege eq 'adv') {
7937: $is_adv = 1;
7938: last;
7939: }
7940: }
7941: }
7942: }
7943: if (wantarray) {
7944: return ($is_adv,$is_author);
7945: }
7946: return $is_adv;
7947: }
7948:
7949: sub check_can_request {
7950: my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
7951: my $canreq = 0;
7952: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7953: $uname = $env{'user.name'};
7954: $udom = $env{'user.domain'};
7955: }
7956: my ($types,$typename) = &Apache::loncommon::course_types();
7957: my @options = ('approval','validate','autolimit');
7958: my $optregex = join('|',@options);
7959: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7960: foreach my $type (@{$types}) {
7961: if (&usertools_access($uname,$udom,$type,undef,
7962: 'requestcourses')) {
7963: $canreq ++;
7964: if (ref($request_domains) eq 'HASH') {
7965: push(@{$request_domains->{$type}},$udom);
7966: }
7967: if ($dom eq $udom) {
7968: $can_request->{$type} = 1;
7969: }
7970: }
7971: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
7972: ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
7973: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7974: if (@curr > 0) {
7975: foreach my $item (@curr) {
7976: if (ref($request_domains) eq 'HASH') {
7977: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7978: if ($otherdom ne '') {
7979: if (ref($request_domains->{$type}) eq 'ARRAY') {
7980: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7981: push(@{$request_domains->{$type}},$otherdom);
7982: }
7983: } else {
7984: push(@{$request_domains->{$type}},$otherdom);
7985: }
7986: }
7987: }
7988: }
7989: unless ($dom eq $env{'user.domain'}) {
7990: $canreq ++;
7991: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7992: $can_request->{$type} = 1;
7993: }
7994: }
7995: }
7996: }
7997: }
7998: }
7999: return $canreq;
8000: }
8001:
8002: # ---------------------------------------------- Custom access rule evaluation
8003:
8004: sub customaccess {
8005: my ($priv,$uri)=@_;
8006: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
8007: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
8008: $udom = &LONCAPA::clean_domain($udom);
8009: $ucrs = &LONCAPA::clean_username($ucrs);
8010: my $access=0;
8011: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
8012: my ($effect,$realm,$role,$type)=split(/\:/,$right);
8013: if ($type eq 'user') {
8014: foreach my $scope (split(/\s*\,\s*/,$realm)) {
8015: my ($tdom,$tuname)=split(m{/},$scope);
8016: if ($tdom) {
8017: if ($tdom ne $env{'user.domain'}) { next; }
8018: }
8019: if ($tuname) {
8020: if ($tuname ne $env{'user.name'}) { next; }
8021: }
8022: $access=($effect eq 'allow');
8023: last;
8024: }
8025: } else {
8026: if ($role) {
8027: if ($role ne $urole) { next; }
8028: }
8029: foreach my $scope (split(/\s*\,\s*/,$realm)) {
8030: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
8031: if ($tdom) {
8032: if ($tdom ne $udom) { next; }
8033: }
8034: if ($tcrs) {
8035: if ($tcrs ne $ucrs) { next; }
8036: }
8037: if ($tsec) {
8038: if ($tsec ne $usec) { next; }
8039: }
8040: $access=($effect eq 'allow');
8041: last;
8042: }
8043: if ($realm eq '' && $role eq '') {
8044: $access=($effect eq 'allow');
8045: }
8046: }
8047: }
8048: return $access;
8049: }
8050:
8051: # ------------------------------------------------- Check for a user privilege
8052:
8053: sub allowed {
8054: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
8055: my $ver_orguri=$uri;
8056: $uri=&deversion($uri);
8057: my $orguri=$uri;
8058: $uri=&declutter($uri);
8059:
8060: if ($priv eq 'evb') {
8061: # Evade communication block restrictions for specified role in a course
8062: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
8063: return $1;
8064: } else {
8065: return;
8066: }
8067: }
8068:
8069: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
8070: # Free bre access to adm and meta resources
8071: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$}))
8072: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
8073: && ($priv eq 'bre')) {
8074: return 'F';
8075: }
8076:
8077: # Free bre access to user's own portfolio contents
8078: my ($space,$domain,$name,@dir)=split('/',$uri);
8079: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
8080: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
8081: my %setters;
8082: my ($startblock,$endblock) =
8083: &Apache::loncommon::blockcheck(\%setters,'port');
8084: if ($startblock && $endblock) {
8085: return 'B';
8086: } else {
8087: return 'F';
8088: }
8089: }
8090:
8091: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
8092: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
8093: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
8094: if (exists($env{'request.course.id'})) {
8095: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8096: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8097: if (($domain eq $cdom) && ($name eq $cnum)) {
8098: my $courseprivid=$env{'request.course.id'};
8099: $courseprivid=~s/\_/\//;
8100: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
8101: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
8102: return $1;
8103: } else {
8104: if ($env{'request.course.sec'}) {
8105: $courseprivid.='/'.$env{'request.course.sec'};
8106: }
8107: if ($env{'user.priv.'.$env{'request.role'}.'./'.
8108: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
8109: return $2;
8110: }
8111: }
8112: }
8113: }
8114: }
8115:
8116: # Free bre to public access
8117:
8118: if ($priv eq 'bre') {
8119: my $copyright;
8120: unless ($uri =~ /ext\.tool/) {
8121: $copyright=&metadata($uri,'copyright');
8122: }
8123: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
8124: return 'F';
8125: }
8126: if ($copyright eq 'priv') {
8127: $uri=~/([^\/]+)\/([^\/]+)\//;
8128: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
8129: return '';
8130: }
8131: }
8132: if ($copyright eq 'domain') {
8133: $uri=~/([^\/]+)\/([^\/]+)\//;
8134: unless (($env{'user.domain'} eq $1) ||
8135: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
8136: return '';
8137: }
8138: }
8139: if ($env{'request.role'}=~ /li\.\//) {
8140: # Library role, so allow browsing of resources in this domain.
8141: return 'F';
8142: }
8143: if ($copyright eq 'custom') {
8144: unless (&customaccess($priv,$uri)) { return ''; }
8145: }
8146: }
8147: # Domain coordinator is trying to create a course
8148: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
8149: # uri is the requested domain in this case.
8150: # comparison to 'request.role.domain' shows if the user has selected
8151: # a role of dc for the domain in question.
8152: return 'F' if ($uri eq $env{'request.role.domain'});
8153: }
8154:
8155: my $thisallowed='';
8156: my $statecond=0;
8157: my $courseprivid='';
8158:
8159: my $ownaccess;
8160: # Community Coordinator or Assistant Co-author browsing resource space.
8161: if (($priv eq 'bro') && ($env{'user.author'})) {
8162: if ($uri eq '') {
8163: $ownaccess = 1;
8164: } else {
8165: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
8166: my $udom = $env{'user.domain'};
8167: my $uname = $env{'user.name'};
8168: if ($uri =~ m{^\Q$udom\E/?$}) {
8169: $ownaccess = 1;
8170: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
8171: unless ($uri =~ m{\.\./}) {
8172: $ownaccess = 1;
8173: }
8174: } elsif (($udom ne 'public') && ($uname ne 'public')) {
8175: my $now = time;
8176: if ($uri =~ m{^([^/]+)/?$}) {
8177: my $adom = $1;
8178: foreach my $key (keys(%env)) {
8179: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
8180: my ($start,$end) = split('.',$env{$key});
8181: if (($now >= $start) && (!$end || $end < $now)) {
8182: $ownaccess = 1;
8183: last;
8184: }
8185: }
8186: }
8187: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
8188: my $adom = $1;
8189: my $aname = $2;
8190: foreach my $role ('ca','aa') {
8191: if ($env{"user.role.$role./$adom/$aname"}) {
8192: my ($start,$end) =
8193: split('.',$env{"user.role.$role./$adom/$aname"});
8194: if (($now >= $start) && (!$end || $end < $now)) {
8195: $ownaccess = 1;
8196: last;
8197: }
8198: }
8199: }
8200: }
8201: }
8202: }
8203: }
8204: }
8205:
8206: # Course
8207:
8208: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
8209: unless (($priv eq 'bro') && (!$ownaccess)) {
8210: $thisallowed.=$1;
8211: }
8212: }
8213:
8214: # Domain
8215:
8216: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
8217: =~/\Q$priv\E\&([^\:]*)/) {
8218: unless (($priv eq 'bro') && (!$ownaccess)) {
8219: $thisallowed.=$1;
8220: }
8221: }
8222:
8223: # User who is not author or co-author might still be able to edit
8224: # resource of an author in the domain (e.g., if Domain Coordinator).
8225: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
8226: (&allowed('mdc',$env{'request.course.id'}))) {
8227: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
8228: $thisallowed.=$1;
8229: }
8230: }
8231:
8232: # Course: uri itself is a course
8233: my $courseuri=$uri;
8234: $courseuri=~s/\_(\d)/\/$1/;
8235: $courseuri=~s/^([^\/])/\/$1/;
8236:
8237: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
8238: =~/\Q$priv\E\&([^\:]*)/) {
8239: if ($priv eq 'mip') {
8240: my $rem = $1;
8241: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
8242: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
8243: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8244: if ($cdom ne '') {
8245: my %passwdconf = &get_passwdconf($cdom);
8246: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
8247: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
8248: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
8249: my @inststatuses = split(':',$env{'environment.inststatus'});
8250: unless (@inststatuses) {
8251: @inststatuses = ('default');
8252: }
8253: foreach my $status (@inststatuses) {
8254: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
8255: $thisallowed.=$rem;
8256: }
8257: }
8258: }
8259: }
8260: }
8261: }
8262: }
8263: } else {
8264: unless (($priv eq 'bro') && (!$ownaccess)) {
8265: $thisallowed.=$1;
8266: }
8267: }
8268: }
8269:
8270: # URI is an uploaded document for this course, default permissions don't matter
8271: # not allowing 'edit' access (editupload) to uploaded course docs
8272: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
8273: $thisallowed='';
8274: my ($match)=&is_on_map($uri);
8275: if ($match) {
8276: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8277: =~/\Q$priv\E\&([^\:]*)/) {
8278: my $value = $1;
8279: my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
8280: if ($deeplinkblock) {
8281: $thisallowed='D';
8282: } elsif ($noblockcheck) {
8283: $thisallowed.=$value;
8284: } else {
8285: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
8286: if (@blockers > 0) {
8287: $thisallowed = 'B';
8288: } else {
8289: $thisallowed.=$value;
8290: }
8291: }
8292: }
8293: } else {
8294: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
8295: if ($refuri) {
8296: if ($refuri =~ m|^/adm/|) {
8297: $thisallowed='F';
8298: } else {
8299: $refuri=&declutter($refuri);
8300: my ($match) = &is_on_map($refuri);
8301: if ($match) {
8302: my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8303: if ($deeplinkblock) {
8304: $thisallowed='D';
8305: } elsif ($noblockcheck) {
8306: $thisallowed='F';
8307: } else {
8308: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
8309: if (@blockers > 0) {
8310: $thisallowed = 'B';
8311: } else {
8312: $thisallowed='F';
8313: }
8314: }
8315: }
8316: }
8317: }
8318: }
8319: }
8320:
8321: if ($priv eq 'bre'
8322: && $thisallowed ne 'F'
8323: && $thisallowed ne '2'
8324: && &is_portfolio_url($uri)) {
8325: $thisallowed = &portfolio_access($uri,$clientip);
8326: }
8327:
8328: # Full access at system, domain or course-wide level? Exit.
8329: if ($thisallowed=~/F/) {
8330: return 'F';
8331: }
8332:
8333: # If this is generating or modifying users, exit with special codes
8334:
8335: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
8336: if (($priv eq 'cca') || ($priv eq 'caa')) {
8337: my ($audom,$auname)=split('/',$uri);
8338: # no author name given, so this just checks on the general right to make a co-author in this domain
8339: unless ($auname) { return $thisallowed; }
8340: # an author name is given, so we are about to actually make a co-author for a certain account
8341: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8342: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8343: ($audom ne $env{'request.role.domain'}))) { return ''; }
8344: }
8345: return $thisallowed;
8346: }
8347: #
8348: # Gathered so far: system, domain and course wide privileges
8349: #
8350: # Course: See if uri or referer is an individual resource that is part of
8351: # the course
8352:
8353: if ($env{'request.course.id'}) {
8354:
8355: # If this is modifying password (internal auth) domains must match for user and user's role.
8356:
8357: if ($priv eq 'mip') {
8358: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
8359: return $thisallowed;
8360: } else {
8361: return '';
8362: }
8363: }
8364:
8365: $courseprivid=$env{'request.course.id'};
8366: if ($env{'request.course.sec'}) {
8367: $courseprivid.='/'.$env{'request.course.sec'};
8368: }
8369: $courseprivid=~s/\_/\//;
8370: my $checkreferer=1;
8371: my ($match,$cond)=&is_on_map($uri);
8372: if ($match) {
8373: $statecond=$cond;
8374: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
8375: =~/\Q$priv\E\&([^\:]*)/) {
8376: my $value = $1;
8377: if ($priv eq 'bre') {
8378: if ($noblockcheck) {
8379: $thisallowed.=$value;
8380: } else {
8381: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
8382: if (@blockers > 0) {
8383: $thisallowed = 'B';
8384: } else {
8385: $thisallowed.=$value;
8386: }
8387: }
8388: } else {
8389: $thisallowed.=$value;
8390: }
8391: $checkreferer=0;
8392: }
8393: }
8394:
8395: if ($checkreferer) {
8396: my $refuri=$env{'httpref.'.$orguri};
8397: unless ($refuri) {
8398: foreach my $key (keys(%env)) {
8399: if ($key=~/^httpref\..*\*/) {
8400: my $pattern=$key;
8401: $pattern=~s/^httpref\.\/res\///;
8402: $pattern=~s/\*/\[\^\/\]\+/g;
8403: $pattern=~s/\//\\\//g;
8404: if ($orguri=~/$pattern/) {
8405: $refuri=$env{$key};
8406: }
8407: }
8408: }
8409: }
8410:
8411: if ($refuri) {
8412: $refuri=&declutter($refuri);
8413: my ($match,$cond)=&is_on_map($refuri);
8414: if ($match) {
8415: my $refstatecond=$cond;
8416: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
8417: =~/\Q$priv\E\&([^\:]*)/) {
8418: my $value = $1;
8419: if ($priv eq 'bre') {
8420: my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8421: if ($deeplinkblock) {
8422: $thisallowed = 'D';
8423: } elsif ($noblockcheck) {
8424: $thisallowed.=$value;
8425: } else {
8426: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
8427: if (@blockers > 0) {
8428: $thisallowed = 'B';
8429: } else {
8430: $thisallowed.=$value;
8431: }
8432: }
8433: } else {
8434: $thisallowed.=$value;
8435: }
8436: $uri=$refuri;
8437: $statecond=$refstatecond;
8438: }
8439: }
8440: }
8441: }
8442: }
8443:
8444: #
8445: # Gathered now: all privileges that could apply, and condition number
8446: #
8447: #
8448: # Full or no access?
8449: #
8450:
8451: if ($thisallowed=~/F/) {
8452: return 'F';
8453: }
8454:
8455: unless ($thisallowed) {
8456: return '';
8457: }
8458:
8459: # Restrictions exist, deal with them
8460: #
8461: # C:according to course preferences
8462: # R:according to resource settings
8463: # L:unless locked
8464: # X:according to user session state
8465: #
8466:
8467: # Possibly locked functionality, check all courses
8468: # Locks might take effect only after 10 minutes cache expiration for other
8469: # courses, and 2 minutes for current course
8470:
8471: my $envkey;
8472: if ($thisallowed=~/L/) {
8473: foreach $envkey (keys(%env)) {
8474: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8475: my $courseid=$2;
8476: my $roleid=$1.'.'.$2;
8477: $courseid=~s/^\///;
8478: my $expiretime=600;
8479: if ($env{'request.role'} eq $roleid) {
8480: $expiretime=120;
8481: }
8482: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8483: my $prefix='course.'.$cdom.'_'.$cnum.'.';
8484: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
8485: &coursedescription($courseid,{'freshen_cache' => 1});
8486: }
8487: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8488: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8489: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8490: &log($env{'user.domain'},$env{'user.name'},
8491: $env{'user.home'},
8492: 'Locked by res: '.$priv.' for '.$uri.' due to '.
8493: $cdom.'/'.$cnum.'/'.$csec.' expire '.
8494: $env{$prefix.'priv.'.$priv.'.lock.expire'});
8495: return '';
8496: }
8497: }
8498: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8499: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
8500: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
8501: &log($env{'user.domain'},$env{'user.name'},
8502: $env{'user.home'},
8503: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
8504: $cdom.'/'.$cnum.'/'.$csec.' expire '.
8505: $env{$prefix.'priv.'.$priv.'.lock.expire'});
8506: return '';
8507: }
8508: }
8509: }
8510: }
8511: }
8512:
8513: #
8514: # Rest of the restrictions depend on selected course
8515: #
8516:
8517: unless ($env{'request.course.id'}) {
8518: if ($thisallowed eq 'A') {
8519: return 'A';
8520: } elsif ($thisallowed eq 'B') {
8521: return 'B';
8522: } else {
8523: return '1';
8524: }
8525: }
8526:
8527: #
8528: # Now user is definitely in a course
8529: #
8530:
8531:
8532: # Course preferences
8533:
8534: if ($thisallowed=~/C/) {
8535: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8536: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8537: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
8538: =~/\Q$rolecode\E/) {
8539: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
8540: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8541: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8542: $env{'request.course.id'});
8543: }
8544: return '';
8545: }
8546:
8547: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
8548: =~/\Q$unamedom\E/) {
8549: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
8550: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8551: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8552: $env{'request.course.id'});
8553: }
8554: return '';
8555: }
8556: }
8557:
8558: # Resource preferences
8559:
8560: if ($thisallowed=~/R/) {
8561: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8562: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
8563: if (($priv ne 'pch') && ($priv ne 'plc')) {
8564: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8565: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8566: }
8567: return '';
8568: }
8569: }
8570:
8571: # Restricted by state or randomout?
8572:
8573: if ($thisallowed=~/X/) {
8574: if ($env{'acc.randomout'}) {
8575: if (!$symb) { $symb=&symbread($uri,1); }
8576: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
8577: return '';
8578: }
8579: }
8580: if (&condval($statecond)) {
8581: return '2';
8582: } else {
8583: return '';
8584: }
8585: }
8586:
8587: if ($thisallowed eq 'A') {
8588: return 'A';
8589: } elsif ($thisallowed eq 'B') {
8590: return 'B';
8591: } elsif ($thisallowed eq 'D') {
8592: return 'D';
8593: }
8594: return 'F';
8595: }
8596:
8597: # ------------------------------------------- Check construction space access
8598:
8599: sub constructaccess {
8600: my ($url,$setpriv)=@_;
8601:
8602: # We do not allow editing of previous versions of files
8603: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8604:
8605: # Get username and domain from URL
8606: my ($ownername,$ownerdomain,$ownerhome);
8607:
8608: ($ownerdomain,$ownername) =
8609: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
8610:
8611: # The URL does not really point to any authorspace, forget it
8612: unless (($ownername) && ($ownerdomain)) { return ''; }
8613:
8614: # Now we need to see if the user has access to the authorspace of
8615: # $ownername at $ownerdomain
8616:
8617: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8618: # Real author for this?
8619: $ownerhome = $env{'user.home'};
8620: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8621: return ($ownername,$ownerdomain,$ownerhome);
8622: }
8623: } else {
8624: # Co-author for this?
8625: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
8626: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
8627: $ownerhome = &homeserver($ownername,$ownerdomain);
8628: return ($ownername,$ownerdomain,$ownerhome);
8629: }
8630: if ($env{'request.course.id'}) {
8631: if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
8632: ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
8633: if (&allowed('mdc',$env{'request.course.id'})) {
8634: $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
8635: return ($ownername,$ownerdomain,$ownerhome);
8636: }
8637: }
8638: }
8639: }
8640:
8641: # We don't have any access right now. If we are not possibly going to do anything about this,
8642: # we might as well leave
8643: unless ($setpriv) { return ''; }
8644:
8645: # Backdoor access?
8646: my $allowed=&allowed('eco',$ownerdomain);
8647: # Nope
8648: unless ($allowed) { return ''; }
8649: # Looks like we may have access, but could be locked by the owner of the construction space
8650: if ($allowed eq 'U') {
8651: my %blocked=&get('environment',['domcoord.author'],
8652: $ownerdomain,$ownername);
8653: # Is blocked by owner
8654: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
8655: }
8656: if (($allowed eq 'F') || ($allowed eq 'U')) {
8657: # Grant temporary access
8658: my $then=$env{'user.login.time'};
8659: my $update=$env{'user.update.time'};
8660: if (!$update) { $update = $then; }
8661: my $refresh=$env{'user.refresh.time'};
8662: if (!$refresh) { $refresh = $update; }
8663: my $now = time;
8664: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
8665: $now,'ca','constructaccess');
8666: $ownerhome = &homeserver($ownername,$ownerdomain);
8667: return($ownername,$ownerdomain,$ownerhome);
8668: }
8669: # No business here
8670: return '';
8671: }
8672:
8673: # ----------------------------------------------------------- Content Blocking
8674:
8675: {
8676: # Caches for faster Course Contents display where content blocking
8677: # is in operation (i.e., interval param set) for timed quiz.
8678: #
8679: # User for whom data are being temporarily cached.
8680: my $cacheduser='';
8681: # Course for which data are being temporarily cached.
8682: my $cachedcid='';
8683: # Cached blockers for this user (a hash of blocking items).
8684: my %cachedblockers=();
8685: # When the data were last cached.
8686: my $cachedlast='';
8687:
8688: sub load_all_blockers {
8689: my ($uname,$udom)=@_;
8690: if (($uname ne '') && ($udom ne '')) {
8691: if (($cacheduser eq $uname.':'.$udom) &&
8692: ($cachedcid eq $env{'request.course.id'}) &&
8693: (abs($cachedlast-time)<5)) {
8694: return;
8695: }
8696: }
8697: $cachedlast=time;
8698: $cacheduser=$uname.':'.$udom;
8699: $cachedcid=$env{'request.course.id'};
8700: %cachedblockers = &get_commblock_resources();
8701: return;
8702: }
8703:
8704: sub get_comm_blocks {
8705: my ($cdom,$cnum) = @_;
8706: if ($cdom eq '' || $cnum eq '') {
8707: return unless ($env{'request.course.id'});
8708: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8709: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8710: }
8711: my %commblocks;
8712: my $hashid=$cdom.'_'.$cnum;
8713: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8714: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8715: %commblocks = %{$blocksref};
8716: } else {
8717: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8718: my $cachetime = 600;
8719: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8720: }
8721: return %commblocks;
8722: }
8723:
8724: sub get_commblock_resources {
8725: my ($blocks) = @_;
8726: my %blockers = ();
8727: return %blockers unless ($env{'request.course.id'});
8728: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
8729: my %commblocks;
8730: if (ref($blocks) eq 'HASH') {
8731: %commblocks = %{$blocks};
8732: } else {
8733: %commblocks = &get_comm_blocks();
8734: }
8735: return %blockers unless (keys(%commblocks) > 0);
8736: my $navmap = Apache::lonnavmaps::navmap->new();
8737: return %blockers unless (ref($navmap));
8738: my $now = time;
8739: foreach my $block (keys(%commblocks)) {
8740: if ($block =~ /^(\d+)____(\d+)$/) {
8741: my ($start,$end) = ($1,$2);
8742: if ($start <= $now && $end >= $now) {
8743: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8744: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8745: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8746: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8747: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8748: }
8749: }
8750: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8751: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8752: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
8753: }
8754: }
8755: }
8756: }
8757: }
8758: } elsif ($block =~ /^firstaccess____(.+)$/) {
8759: my $item = $1;
8760: my @to_test;
8761: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8762: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8763: my @interval;
8764: my $type = 'map';
8765: if ($item eq 'course') {
8766: $type = 'course';
8767: @interval=&EXT("resource.0.interval");
8768: } else {
8769: if ($item =~ /___\d+___/) {
8770: $type = 'resource';
8771: @interval=&EXT("resource.0.interval",$item);
8772: if (ref($navmap)) {
8773: my $res = $navmap->getBySymb($item);
8774: push(@to_test,$res);
8775: }
8776: } else {
8777: my $mapsymb = &symbread($item,1);
8778: if ($mapsymb) {
8779: if (ref($navmap)) {
8780: my $mapres = $navmap->getBySymb($mapsymb);
8781: if (ref($mapres)) {
8782: my $first = $mapres->map_start();
8783: my $finish = $mapres->map_finish();
8784: my $it = $navmap->getIterator($first,$finish,undef,0,0);
8785: if (ref($it)) {
8786: my $res;
8787: while ($res = $it->next(undef,1)) {
8788: next unless (ref($res));
8789: my $symb = $res->symb();
8790: next if (($symb eq $mapsymb) || ($symb eq ''));
8791: @interval=&EXT("resource.0.interval",$symb);
8792: if ($interval[1] eq 'map') {
8793: if ($res->answerable()) {
8794: push(@to_test,$res);
8795: last;
8796: }
8797: }
8798: }
8799: }
8800: }
8801: }
8802: }
8803: }
8804: }
8805: if ($interval[0] =~ /^(\d+)/) {
8806: my $timelimit = $1;
8807: my $first_access;
8808: if ($type eq 'resource') {
8809: $first_access=&get_first_access($interval[1],$item);
8810: } elsif ($type eq 'map') {
8811: $first_access=&get_first_access($interval[1],undef,$item);
8812: } else {
8813: $first_access=&get_first_access($interval[1]);
8814: }
8815: if ($first_access) {
8816: my $timesup = $first_access+$timelimit;
8817: if ($timesup > $now) {
8818: my $activeblock;
8819: foreach my $res (@to_test) {
8820: if ($res->answerable()) {
8821: $activeblock = 1;
8822: last;
8823: }
8824: }
8825: if ($activeblock) {
8826: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8827: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8828: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8829: }
8830: }
8831: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8832: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8833: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
8834: }
8835: }
8836: }
8837: }
8838: }
8839: }
8840: }
8841: }
8842: }
8843: }
8844: return %blockers;
8845: }
8846:
8847: sub has_comm_blocking {
8848: my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
8849: my @blockers;
8850: return unless ($env{'request.course.id'});
8851: return unless ($priv eq 'bre');
8852: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
8853: return if ($env{'request.state'} eq 'construct');
8854: my %blockinfo;
8855: if (ref($blocks) eq 'HASH') {
8856: %blockinfo = &get_commblock_resources($blocks);
8857: } else {
8858: &load_all_blockers($env{'user.name'},$env{'user.domain'});
8859: %blockinfo = %cachedblockers;
8860: }
8861: return unless (keys(%blockinfo) > 0);
8862: my (%possibles,@symbs);
8863: if (!$symb) {
8864: $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
8865: }
8866: if ($symb) {
8867: @symbs = ($symb);
8868: } elsif (keys(%possibles)) {
8869: @symbs = keys(%possibles);
8870: }
8871: my $noblock;
8872: foreach my $symb (@symbs) {
8873: last if ($noblock);
8874: my ($map,$resid,$resurl)=&decode_symb($symb);
8875: foreach my $block (keys(%blockinfo)) {
8876: if ($block =~ /^firstaccess____(.+)$/) {
8877: my $item = $1;
8878: unless ($blocked) {
8879: if (($item eq $map) || ($item eq $symb)) {
8880: $noblock = 1;
8881: last;
8882: }
8883: }
8884: }
8885: if (ref($blockinfo{$block}) eq 'HASH') {
8886: if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
8887: if ($blockinfo{$block}{'resources'}{$symb}) {
8888: unless (grep(/^\Q$block\E$/,@blockers)) {
8889: push(@blockers,$block);
8890: }
8891: }
8892: }
8893: if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
8894: if ($blockinfo{$block}{'maps'}{$map}) {
8895: unless (grep(/^\Q$block\E$/,@blockers)) {
8896: push(@blockers,$block);
8897: }
8898: }
8899: }
8900: }
8901: }
8902: }
8903: unless ($noblock) {
8904: return @blockers;
8905: }
8906: return;
8907: }
8908: }
8909:
8910: sub deeplink_check {
8911: my ($priv,$symb,$uri) = @_;
8912: return unless ($env{'request.course.id'});
8913: return unless ($priv eq 'bre');
8914: return if ($env{'request.state'} eq 'construct');
8915: return if ($env{'request.role.adv'});
8916: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8917: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8918: my (%possibles,@symbs);
8919: if (!$symb) {
8920: $symb = &symbread($uri,1,1,1,\%possibles);
8921: }
8922: if ($symb) {
8923: @symbs = ($symb);
8924: } elsif (keys(%possibles)) {
8925: @symbs = keys(%possibles);
8926: }
8927:
8928: my ($login,$switchrole,$allow);
8929: if ($env{'request.deeplink.login'} =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
8930: my $key = $1;
8931: my $tinyurl;
8932: my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
8933: if (defined($cached)) {
8934: $tinyurl = $result;
8935: } else {
8936: my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
8937: my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
8938: if ($currtiny{$key} ne '') {
8939: $tinyurl = $currtiny{$key};
8940: &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
8941: }
8942: }
8943: if ($tinyurl ne '') {
8944: my ($cnumreq,$posslogin) = split(/\&/,$tinyurl);
8945: if ($cnumreq eq $cnum) {
8946: $login = $posslogin;
8947: } else {
8948: $switchrole = 1;
8949: }
8950: }
8951: }
8952: foreach my $symb (@symbs) {
8953: last if ($allow);
8954: my $deeplink = &EXT("resource.0.deeplink",$symb);
8955: if ($deeplink eq '') {
8956: $allow = 1;
8957: } else {
8958: my ($listed,$scope,$access) = split(/,/,$deeplink);
8959: if ($access eq 'any') {
8960: $allow = 1;
8961: } elsif ($login) {
8962: if ($access eq 'only') {
8963: if ($scope eq 'res') {
8964: if ($symb eq $login) {
8965: $allow = 1;
8966: }
8967: } elsif ($scope eq 'map') {
8968: #FIXME Compare map for $env{'request.deeplink.login'} with map for $symb
8969: } elsif ($scope eq 'rec') {
8970: #FIXME Recurse up for $env{'request.deeplink.login'} with map for $symb
8971: }
8972: } else {
8973: my ($acctype,$item) = split(/:/,$access);
8974: if (($acctype eq 'lti') && ($env{'user.linkprotector'})) {
8975: if (grep(/^\Q$item\E$/,split(/,/,$env{'user.linkprotector'}))) {
8976: my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
8977: if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.linkproturis'}))) {
8978: $allow = 1;
8979: }
8980: }
8981: } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
8982: if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
8983: my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
8984: if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.keyedlinkuri'}))) {
8985: $allow = 1;
8986: }
8987: }
8988: }
8989: }
8990: }
8991: }
8992: }
8993: return if ($allow);
8994: return 1;
8995: }
8996:
8997: # -------------------------------- Deversion and split uri into path an filename
8998:
8999: #
9000: # Removes the version from a URI and
9001: # splits it in to its filename and path to the filename.
9002: # Seems like File::Basename could have done this more clearly.
9003: # Parameters:
9004: # $uri - input URI
9005: # Returns:
9006: # Two element list consisting of
9007: # $pathname - the URI up to and excluding the trailing /
9008: # $filename - The part of the URI following the last /
9009: # NOTE:
9010: # Another realization of this is simply:
9011: # use File::Basename;
9012: # ...
9013: # $uri = shift;
9014: # $filename = basename($uri);
9015: # $path = dirname($uri);
9016: # return ($filename, $path);
9017: #
9018: # The implementation below is probably faster however.
9019: #
9020: sub split_uri_for_cond {
9021: my $uri=&deversion(&declutter(shift));
9022: my @uriparts=split(/\//,$uri);
9023: my $filename=pop(@uriparts);
9024: my $pathname=join('/',@uriparts);
9025: return ($pathname,$filename);
9026: }
9027: # --------------------------------------------------- Is a resource on the map?
9028:
9029: sub is_on_map {
9030: my ($pathname,$filename) = &split_uri_for_cond(shift);
9031: #Trying to find the conditional for the file
9032: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
9033: /\&\Q$filename\E\:([\d\|]+)\&/);
9034: if ($match) {
9035: return (1,$1);
9036: } else {
9037: return (0,0);
9038: }
9039: }
9040:
9041: # --------------------------------------------------------- Get symb from alias
9042:
9043: sub get_symb_from_alias {
9044: my $symb=shift;
9045: my ($map,$resid,$url)=&decode_symb($symb);
9046: # Already is a symb
9047: if ($url) { return $symb; }
9048: # Must be an alias
9049: my $aliassymb='';
9050: my %bighash;
9051: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9052: &GDBM_READER(),0640)) {
9053: my $rid=$bighash{'mapalias_'.$symb};
9054: if ($rid) {
9055: my ($mapid,$resid)=split(/\./,$rid);
9056: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
9057: $resid,$bighash{'src_'.$rid});
9058: }
9059: untie %bighash;
9060: }
9061: return $aliassymb;
9062: }
9063:
9064: # ----------------------------------------------------------------- Define Role
9065:
9066: sub definerole {
9067: if (allowed('mcr','/')) {
9068: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
9069: foreach my $role (split(':',$sysrole)) {
9070: my ($crole,$cqual)=split(/\&/,$role);
9071: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
9072: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
9073: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
9074: return "refused:s:$crole&$cqual";
9075: }
9076: }
9077: }
9078: foreach my $role (split(':',$domrole)) {
9079: my ($crole,$cqual)=split(/\&/,$role);
9080: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
9081: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
9082: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
9083: return "refused:d:$crole&$cqual";
9084: }
9085: }
9086: }
9087: foreach my $role (split(':',$courole)) {
9088: my ($crole,$cqual)=split(/\&/,$role);
9089: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
9090: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
9091: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
9092: return "refused:c:$crole&$cqual";
9093: }
9094: }
9095: }
9096: my $uhome;
9097: if (($uname ne '') && ($udom ne '')) {
9098: $uhome = &homeserver($uname,$udom);
9099: return $uhome if ($uhome eq 'no_host');
9100: } else {
9101: $uname = $env{'user.name'};
9102: $udom = $env{'user.domain'};
9103: $uhome = $env{'user.home'};
9104: }
9105: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
9106: "$udom:$uname:rolesdef_$rolename=".
9107: escape($sysrole.'_'.$domrole.'_'.$courole);
9108: return reply($command,$uhome);
9109: } else {
9110: return 'refused';
9111: }
9112: }
9113:
9114: # ---------------- Make a metadata query against the network of library servers
9115:
9116: sub metadata_query {
9117: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
9118: my %rhash;
9119: my %libserv = &all_library();
9120: my @server_list = (defined($server_array) ? @$server_array
9121: : keys(%libserv) );
9122: for my $server (@server_list) {
9123: my $domains = '';
9124: if (ref($domains_hash) eq 'HASH') {
9125: $domains = $domains_hash->{$server};
9126: }
9127: unless ($custom or $customshow) {
9128: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
9129: $rhash{$server}=$reply;
9130: }
9131: else {
9132: my $reply=&reply("querysend:".&escape($query).':'.
9133: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
9134: $server);
9135: $rhash{$server}=$reply;
9136: }
9137: }
9138: return \%rhash;
9139: }
9140:
9141: # ----------------------------------------- Send log queries and wait for reply
9142:
9143: sub log_query {
9144: my ($uname,$udom,$query,%filters)=@_;
9145: my $uhome=&homeserver($uname,$udom);
9146: if ($uhome eq 'no_host') { return 'error: no_host'; }
9147: my $uhost=&hostname($uhome);
9148: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
9149: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
9150: $uhome);
9151: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
9152: return get_query_reply($queryid);
9153: }
9154:
9155: # -------------------------- Update MySQL table for portfolio file
9156:
9157: sub update_portfolio_table {
9158: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
9159: if ($group ne '') {
9160: $file_name =~s /^\Q$group\E//;
9161: }
9162: my $homeserver = &homeserver($uname,$udom);
9163: my $queryid=
9164: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
9165: ':'.&escape($file_name).':'.$action,$homeserver);
9166: my $reply = &get_query_reply($queryid);
9167: return $reply;
9168: }
9169:
9170: # -------------------------- Update MySQL allusers table
9171:
9172: sub update_allusers_table {
9173: my ($uname,$udom,$names) = @_;
9174: my $homeserver = &homeserver($uname,$udom);
9175: my $queryid=
9176: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
9177: 'lastname='.&escape($names->{'lastname'}).'%%'.
9178: 'firstname='.&escape($names->{'firstname'}).'%%'.
9179: 'middlename='.&escape($names->{'middlename'}).'%%'.
9180: 'generation='.&escape($names->{'generation'}).'%%'.
9181: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
9182: 'id='.&escape($names->{'id'}),$homeserver);
9183: return;
9184: }
9185:
9186: # ------- Request retrieval of institutional classlists for course(s)
9187:
9188: sub fetch_enrollment_query {
9189: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
9190: my ($homeserver,$sleep,$loopmax);
9191: my $maxtries = 1;
9192: if ($context eq 'automated') {
9193: $homeserver = $perlvar{'lonHostID'};
9194: $sleep = 2;
9195: $loopmax = 100;
9196: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
9197: } else {
9198: $homeserver = &homeserver($cnum,$dom);
9199: }
9200: my $host=&hostname($homeserver);
9201: my $cmd = '';
9202: foreach my $affiliate (keys(%{$affiliatesref})) {
9203: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
9204: }
9205: $cmd =~ s/%%$//;
9206: $cmd = &escape($cmd);
9207: my $query = 'fetchenrollment';
9208: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
9209: unless ($queryid=~/^\Q$host\E\_/) {
9210: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
9211: return 'error: '.$queryid;
9212: }
9213: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
9214: my $tries = 1;
9215: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9216: $reply = &get_query_reply($queryid,$sleep,$loopmax);
9217: $tries ++;
9218: }
9219: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9220: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9221: } else {
9222: my @responses = split(/:/,$reply);
9223: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
9224: foreach my $line (@responses) {
9225: my ($key,$value) = split(/=/,$line,2);
9226: $$replyref{$key} = $value;
9227: }
9228: } else {
9229: my $pathname = LONCAPA::tempdir();
9230: foreach my $line (@responses) {
9231: my ($key,$value) = split(/=/,$line);
9232: $$replyref{$key} = $value;
9233: if ($value > 0) {
9234: foreach my $item (@{$$affiliatesref{$key}}) {
9235: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
9236: my $destname = $pathname.'/'.$filename;
9237: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
9238: if ($xml_classlist =~ /^error/) {
9239: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
9240: } else {
9241: if ( open(FILE,">",$destname) ) {
9242: print FILE &unescape($xml_classlist);
9243: close(FILE);
9244: } else {
9245: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
9246: }
9247: }
9248: }
9249: }
9250: }
9251: }
9252: return 'ok';
9253: }
9254: return 'error';
9255: }
9256:
9257: sub get_query_reply {
9258: my ($queryid,$sleep,$loopmax) = @_;;
9259: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
9260: $sleep = 0.2;
9261: }
9262: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
9263: $loopmax = 100;
9264: }
9265: my $replyfile=LONCAPA::tempdir().$queryid;
9266: my $reply='';
9267: for (1..$loopmax) {
9268: sleep($sleep);
9269: if (-e $replyfile.'.end') {
9270: if (open(my $fh,"<",$replyfile)) {
9271: $reply = join('',<$fh>);
9272: close($fh);
9273: } else { return 'error: reply_file_error'; }
9274: return &unescape($reply);
9275: }
9276: }
9277: return 'timeout:'.$queryid;
9278: }
9279:
9280: sub courselog_query {
9281: #
9282: # possible filters:
9283: # url: url or symb
9284: # username
9285: # domain
9286: # action: view, submit, grade
9287: # start: timestamp
9288: # end: timestamp
9289: #
9290: my (%filters)=@_;
9291: unless ($env{'request.course.id'}) { return 'no_course'; }
9292: if ($filters{'url'}) {
9293: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
9294: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
9295: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
9296: }
9297: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
9298: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
9299: return &log_query($cname,$cdom,'courselog',%filters);
9300: }
9301:
9302: sub userlog_query {
9303: #
9304: # possible filters:
9305: # action: log check role
9306: # start: timestamp
9307: # end: timestamp
9308: #
9309: my ($uname,$udom,%filters)=@_;
9310: return &log_query($uname,$udom,'userlog',%filters);
9311: }
9312:
9313: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
9314:
9315: sub auto_run {
9316: my ($cnum,$cdom) = @_;
9317: my $response = 0;
9318: my $settings;
9319: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
9320: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
9321: $settings = $domconfig{'autoenroll'};
9322: if ($settings->{'run'} eq '1') {
9323: $response = 1;
9324: }
9325: } else {
9326: my $homeserver;
9327: if (&is_course($cdom,$cnum)) {
9328: $homeserver = &homeserver($cnum,$cdom);
9329: } else {
9330: $homeserver = &domain($cdom,'primary');
9331: }
9332: if ($homeserver ne 'no_host') {
9333: $response = &reply('autorun:'.$cdom,$homeserver);
9334: }
9335: }
9336: return $response;
9337: }
9338:
9339: sub auto_get_sections {
9340: my ($cnum,$cdom,$inst_coursecode) = @_;
9341: my $homeserver;
9342: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9343: $homeserver = &homeserver($cnum,$cdom);
9344: }
9345: if (!defined($homeserver)) {
9346: if ($cdom =~ /^$match_domain$/) {
9347: $homeserver = &domain($cdom,'primary');
9348: }
9349: }
9350: my @secs;
9351: if (defined($homeserver)) {
9352: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
9353: unless ($response eq 'refused') {
9354: @secs = split(/:/,$response);
9355: }
9356: }
9357: return @secs;
9358: }
9359:
9360: sub auto_new_course {
9361: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
9362: my $homeserver = &homeserver($cnum,$cdom);
9363: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
9364: return $response;
9365: }
9366:
9367: sub auto_validate_courseID {
9368: my ($cnum,$cdom,$inst_course_id) = @_;
9369: my $homeserver = &homeserver($cnum,$cdom);
9370: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
9371: return $response;
9372: }
9373:
9374: sub auto_validate_instcode {
9375: my ($cnum,$cdom,$instcode,$owner) = @_;
9376: my ($homeserver,$response);
9377: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9378: $homeserver = &homeserver($cnum,$cdom);
9379: }
9380: if (!defined($homeserver)) {
9381: if ($cdom =~ /^$match_domain$/) {
9382: $homeserver = &domain($cdom,'primary');
9383: }
9384: }
9385: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
9386: &escape($instcode).':'.&escape($owner),$homeserver));
9387: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
9388: return ($outcome,$description,$defaultcredits);
9389: }
9390:
9391: sub auto_create_password {
9392: my ($cnum,$cdom,$authparam,$udom) = @_;
9393: my ($homeserver,$response);
9394: my $create_passwd = 0;
9395: my $authchk = '';
9396: if ($udom =~ /^$match_domain$/) {
9397: $homeserver = &domain($udom,'primary');
9398: }
9399: if ($homeserver eq '') {
9400: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9401: $homeserver = &homeserver($cnum,$cdom);
9402: }
9403: }
9404: if ($homeserver eq '') {
9405: $authchk = 'nodomain';
9406: } else {
9407: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
9408: if ($response eq 'refused') {
9409: $authchk = 'refused';
9410: } else {
9411: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
9412: }
9413: }
9414: return ($authparam,$create_passwd,$authchk);
9415: }
9416:
9417: sub auto_photo_permission {
9418: my ($cnum,$cdom,$students) = @_;
9419: my $homeserver = &homeserver($cnum,$cdom);
9420: my ($outcome,$perm_reqd,$conditions) =
9421: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
9422: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9423: return (undef,undef);
9424: }
9425: return ($outcome,$perm_reqd,$conditions);
9426: }
9427:
9428: sub auto_checkphotos {
9429: my ($uname,$udom,$pid) = @_;
9430: my $homeserver = &homeserver($uname,$udom);
9431: my ($result,$resulttype);
9432: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
9433: &escape($uname).':'.&escape($pid),
9434: $homeserver));
9435: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9436: return (undef,undef);
9437: }
9438: if ($outcome) {
9439: ($result,$resulttype) = split(/:/,$outcome);
9440: }
9441: return ($result,$resulttype);
9442: }
9443:
9444: sub auto_photochoice {
9445: my ($cnum,$cdom) = @_;
9446: my $homeserver = &homeserver($cnum,$cdom);
9447: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
9448: &escape($cdom),
9449: $homeserver)));
9450: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9451: return (undef,undef);
9452: }
9453: return ($update,$comment);
9454: }
9455:
9456: sub auto_photoupdate {
9457: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9458: my $homeserver = &homeserver($cnum,$dom);
9459: my $host=&hostname($homeserver);
9460: my $cmd = '';
9461: my $maxtries = 1;
9462: foreach my $affiliate (keys(%{$affiliatesref})) {
9463: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
9464: }
9465: $cmd =~ s/%%$//;
9466: $cmd = &escape($cmd);
9467: my $query = 'institutionalphotos';
9468: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9469: unless ($queryid=~/^\Q$host\E\_/) {
9470: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9471: return 'error: '.$queryid;
9472: }
9473: my $reply = &get_query_reply($queryid);
9474: my $tries = 1;
9475: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9476: $reply = &get_query_reply($queryid);
9477: $tries ++;
9478: }
9479: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9480: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9481: } else {
9482: my @responses = split(/:/,$reply);
9483: my $outcome = shift(@responses);
9484: foreach my $item (@responses) {
9485: my ($key,$value) = split(/=/,$item);
9486: $$photo{$key} = $value;
9487: }
9488: return $outcome;
9489: }
9490: return 'error';
9491: }
9492:
9493: sub auto_instcode_format {
9494: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9495: $cat_order) = @_;
9496: my $courses = '';
9497: my @homeservers;
9498: if ($caller eq 'global') {
9499: my %servers = &get_servers($codedom,'library');
9500: foreach my $tryserver (keys(%servers)) {
9501: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9502: push(@homeservers,$tryserver);
9503: }
9504: }
9505: } elsif ($caller eq 'requests') {
9506: if ($codedom =~ /^$match_domain$/) {
9507: my $chome = &domain($codedom,'primary');
9508: unless ($chome eq 'no_host') {
9509: push(@homeservers,$chome);
9510: }
9511: }
9512: } else {
9513: push(@homeservers,&homeserver($caller,$codedom));
9514: }
9515: foreach my $code (keys(%{$instcodes})) {
9516: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
9517: }
9518: chop($courses);
9519: my $ok_response = 0;
9520: my $response;
9521: while (@homeservers > 0 && $ok_response == 0) {
9522: my $server = shift(@homeservers);
9523: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9524: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9525: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
9526: split(/:/,$response);
9527: %{$codes} = (%{$codes},&str2hash($codes_str));
9528: push(@{$codetitles},&str2array($codetitles_str));
9529: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9530: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9531: $ok_response = 1;
9532: }
9533: }
9534: if ($ok_response) {
9535: return 'ok';
9536: } else {
9537: return $response;
9538: }
9539: }
9540:
9541: sub auto_instcode_defaults {
9542: my ($domain,$returnhash,$code_order) = @_;
9543: my @homeservers;
9544:
9545: my %servers = &get_servers($domain,'library');
9546: foreach my $tryserver (keys(%servers)) {
9547: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9548: push(@homeservers,$tryserver);
9549: }
9550: }
9551:
9552: my $response;
9553: foreach my $server (@homeservers) {
9554: $response=&reply('autoinstcodedefaults:'.$domain,$server);
9555: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9556:
9557: foreach my $pair (split(/\&/,$response)) {
9558: my ($name,$value)=split(/\=/,$pair);
9559: if ($name eq 'code_order') {
9560: @{$code_order} = split(/\&/,&unescape($value));
9561: } else {
9562: $returnhash->{&unescape($name)}=&unescape($value);
9563: }
9564: }
9565: return 'ok';
9566: }
9567:
9568: return $response;
9569: }
9570:
9571: sub auto_possible_instcodes {
9572: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9573: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9574: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9575: return;
9576: }
9577: my (@homeservers,$uhome);
9578: if (defined(&domain($domain,'primary'))) {
9579: $uhome=&domain($domain,'primary');
9580: push(@homeservers,&domain($domain,'primary'));
9581: } else {
9582: my %servers = &get_servers($domain,'library');
9583: foreach my $tryserver (keys(%servers)) {
9584: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9585: push(@homeservers,$tryserver);
9586: }
9587: }
9588: }
9589: my $response;
9590: foreach my $server (@homeservers) {
9591: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9592: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9593: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9594: split(':',$response);
9595: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9596: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
9597: foreach my $item (split('&',$cat_title)) {
9598: my ($name,$value)=split('=',$item);
9599: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
9600: }
9601: foreach my $item (split('&',$cat_order)) {
9602: my ($name,$value)=split('=',$item);
9603: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
9604: }
9605: return 'ok';
9606: }
9607: return $response;
9608: }
9609:
9610: sub auto_courserequest_checks {
9611: my ($dom) = @_;
9612: my ($homeserver,%validations);
9613: if ($dom =~ /^$match_domain$/) {
9614: $homeserver = &domain($dom,'primary');
9615: }
9616: unless ($homeserver eq 'no_host') {
9617: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9618: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9619: my @items = split(/&/,$response);
9620: foreach my $item (@items) {
9621: my ($key,$value) = split('=',$item);
9622: $validations{&unescape($key)} = &thaw_unescape($value);
9623: }
9624: }
9625: }
9626: return %validations;
9627: }
9628:
9629: sub auto_courserequest_validation {
9630: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
9631: my ($homeserver,$response);
9632: if ($dom =~ /^$match_domain$/) {
9633: $homeserver = &domain($dom,'primary');
9634: }
9635: unless ($homeserver eq 'no_host') {
9636: my $customdata;
9637: if (ref($custominfo) eq 'HASH') {
9638: $customdata = &freeze_escape($custominfo);
9639: }
9640: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
9641: ':'.&escape($crstype).':'.&escape($inststatuslist).
9642: ':'.&escape($instcode).':'.&escape($instseclist).':'.
9643: $customdata,$homeserver));
9644: }
9645: return $response;
9646: }
9647:
9648: sub auto_validate_class_sec {
9649: my ($cdom,$cnum,$owners,$inst_class) = @_;
9650: my $homeserver = &homeserver($cnum,$cdom);
9651: my $ownerlist;
9652: if (ref($owners) eq 'ARRAY') {
9653: $ownerlist = join(',',@{$owners});
9654: } else {
9655: $ownerlist = $owners;
9656: }
9657: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
9658: &escape($ownerlist).':'.$cdom,$homeserver);
9659: return $response;
9660: }
9661:
9662: sub auto_validate_instclasses {
9663: my ($cdom,$cnum,$owners,$classesref) = @_;
9664: my ($homeserver,%validations);
9665: $homeserver = &homeserver($cnum,$cdom);
9666: unless ($homeserver eq 'no_host') {
9667: my $ownerlist;
9668: if (ref($owners) eq 'ARRAY') {
9669: $ownerlist = join(',',@{$owners});
9670: } else {
9671: $ownerlist = $owners;
9672: }
9673: if (ref($classesref) eq 'HASH') {
9674: my $classes = &freeze_escape($classesref);
9675: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
9676: ':'.$cdom.':'.$classes,$homeserver);
9677: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9678: my @items = split(/&/,$response);
9679: foreach my $item (@items) {
9680: my ($key,$value) = split('=',$item);
9681: $validations{&unescape($key)} = &thaw_unescape($value);
9682: }
9683: }
9684: }
9685: }
9686: return %validations;
9687: }
9688:
9689: sub auto_crsreq_update {
9690: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
9691: $code,$accessstart,$accessend,$inbound) = @_;
9692: my ($homeserver,%crsreqresponse);
9693: if ($cdom =~ /^$match_domain$/) {
9694: $homeserver = &domain($cdom,'primary');
9695: }
9696: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9697: my $info;
9698: if (ref($inbound) eq 'HASH') {
9699: $info = &freeze_escape($inbound);
9700: }
9701: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
9702: ':'.&escape($action).':'.&escape($ownername).':'.
9703: &escape($ownerdomain).':'.&escape($fullname).':'.
9704: &escape($title).':'.&escape($code).':'.
9705: &escape($accessstart).':'.&escape($accessend).':'.$info,
9706: $homeserver);
9707: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9708: my @items = split(/&/,$response);
9709: foreach my $item (@items) {
9710: my ($key,$value) = split('=',$item);
9711: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
9712: }
9713: }
9714: }
9715: return \%crsreqresponse;
9716: }
9717:
9718: sub auto_export_grades {
9719: my ($cdom,$cnum,$inforef,$gradesref) = @_;
9720: my ($homeserver,%exportresponse);
9721: if ($cdom =~ /^$match_domain$/) {
9722: $homeserver = &domain($cdom,'primary');
9723: }
9724: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9725: my $info;
9726: if (ref($inforef) eq 'HASH') {
9727: $info = &freeze_escape($inforef);
9728: }
9729: if (ref($gradesref) eq 'HASH') {
9730: my $grades = &freeze_escape($gradesref);
9731: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
9732: $info.':'.$grades,$homeserver);
9733: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
9734: my @items = split(/&/,$response);
9735: foreach my $item (@items) {
9736: my ($key,$value) = split('=',$item);
9737: $exportresponse{&unescape($key)} = &thaw_unescape($value);
9738: }
9739: }
9740: }
9741: }
9742: return \%exportresponse;
9743: }
9744:
9745: sub check_instcode_cloning {
9746: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
9747: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9748: return;
9749: }
9750: my $canclone;
9751: if (@{$code_order} > 0) {
9752: my $instcoderegexp ='^';
9753: my @clonecodes = split(/\&/,$cloner);
9754: foreach my $item (@{$code_order}) {
9755: if (grep(/^\Q$item\E=/,@clonecodes)) {
9756: foreach my $pair (@clonecodes) {
9757: my ($key,$val) = split(/\=/,$pair,2);
9758: $val = &unescape($val);
9759: if ($key eq $item) {
9760: $instcoderegexp .= '('.$val.')';
9761: last;
9762: }
9763: }
9764: } else {
9765: $instcoderegexp .= $codedefaults->{$item};
9766: }
9767: }
9768: $instcoderegexp .= '$';
9769: my (@from,@to);
9770: eval {
9771: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9772: (@to) = ($clonetocode =~ /$instcoderegexp/);
9773: };
9774: if ((@from > 0) && (@to > 0)) {
9775: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9776: if (!@diffs) {
9777: $canclone = 1;
9778: }
9779: }
9780: }
9781: return $canclone;
9782: }
9783:
9784: sub default_instcode_cloning {
9785: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
9786: my (%codedefaults,@code_order,$canclone);
9787: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
9788: %codedefaults = %{$codedefaultsref};
9789: @code_order = @{$codeorderref};
9790: } elsif ($clonedom) {
9791: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
9792: }
9793: if (($domdefclone) && (@code_order)) {
9794: my @clonecodes = split(/\+/,$domdefclone);
9795: my $instcoderegexp ='^';
9796: foreach my $item (@code_order) {
9797: if (grep(/^\Q$item\E$/,@clonecodes)) {
9798: $instcoderegexp .= '('.$codedefaults{$item}.')';
9799: } else {
9800: $instcoderegexp .= $codedefaults{$item};
9801: }
9802: }
9803: $instcoderegexp .= '$';
9804: my (@from,@to);
9805: eval {
9806: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9807: (@to) = ($clonetocode =~ /$instcoderegexp/);
9808: };
9809: if ((@from > 0) && (@to > 0)) {
9810: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9811: if (!@diffs) {
9812: $canclone = 1;
9813: }
9814: }
9815: }
9816: return $canclone;
9817: }
9818:
9819: # ------------------------------------------------------- Course Group routines
9820:
9821: sub get_coursegroups {
9822: my ($cdom,$cnum,$group,$namespace) = @_;
9823: return(&dump($namespace,$cdom,$cnum,$group));
9824: }
9825:
9826: sub modify_coursegroup {
9827: my ($cdom,$cnum,$groupsettings) = @_;
9828: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
9829: }
9830:
9831: sub toggle_coursegroup_status {
9832: my ($cdom,$cnum,$group,$action) = @_;
9833: my ($from_namespace,$to_namespace);
9834: if ($action eq 'delete') {
9835: $from_namespace = 'coursegroups';
9836: $to_namespace = 'deleted_groups';
9837: } else {
9838: $from_namespace = 'deleted_groups';
9839: $to_namespace = 'coursegroups';
9840: }
9841: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
9842: if (my $tmp = &error(%curr_group)) {
9843: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
9844: return ('read error',$tmp);
9845: } else {
9846: my %savedsettings = %curr_group;
9847: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
9848: my $deloutcome;
9849: if ($result eq 'ok') {
9850: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
9851: } else {
9852: return ('write error',$result);
9853: }
9854: if ($deloutcome eq 'ok') {
9855: return 'ok';
9856: } else {
9857: return ('delete error',$deloutcome);
9858: }
9859: }
9860: }
9861:
9862: sub modify_group_roles {
9863: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
9864: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
9865: my $role = 'gr/'.&escape($userprivs);
9866: my ($uname,$udom) = split(/:/,$user);
9867: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
9868: if ($result eq 'ok') {
9869: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
9870: }
9871: return $result;
9872: }
9873:
9874: sub modify_coursegroup_membership {
9875: my ($cdom,$cnum,$membership) = @_;
9876: my $result = &put('groupmembership',$membership,$cdom,$cnum);
9877: return $result;
9878: }
9879:
9880: sub get_active_groups {
9881: my ($udom,$uname,$cdom,$cnum) = @_;
9882: my $now = time;
9883: my %groups = ();
9884: foreach my $key (keys(%env)) {
9885: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
9886: my ($start,$end) = split(/\./,$env{$key});
9887: if (($end!=0) && ($end<$now)) { next; }
9888: if (($start!=0) && ($start>$now)) { next; }
9889: if ($1 eq $cdom && $2 eq $cnum) {
9890: $groups{$3} = $env{$key} ;
9891: }
9892: }
9893: }
9894: return %groups;
9895: }
9896:
9897: sub get_group_membership {
9898: my ($cdom,$cnum,$group) = @_;
9899: return(&dump('groupmembership',$cdom,$cnum,$group));
9900: }
9901:
9902: sub get_users_groups {
9903: my ($udom,$uname,$courseid) = @_;
9904: my @usersgroups;
9905: my $cachetime=1800;
9906:
9907: my $hashid="$udom:$uname:$courseid";
9908: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
9909: if (defined($cached)) {
9910: @usersgroups = split(/:/,$grouplist);
9911: } else {
9912: $grouplist = '';
9913: my $courseurl = &courseid_to_courseurl($courseid);
9914: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
9915: my $access_end = $env{'course.'.$courseid.
9916: '.default_enrollment_end_date'};
9917: my $now = time;
9918: foreach my $key (keys(%roleshash)) {
9919: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
9920: my $group = $1;
9921: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
9922: my $start = $2;
9923: my $end = $1;
9924: if ($start == -1) { next; } # deleted from group
9925: if (($start!=0) && ($start>$now)) { next; }
9926: if (($end!=0) && ($end<$now)) {
9927: if ($access_end && $access_end < $now) {
9928: if ($access_end - $end < 86400) {
9929: push(@usersgroups,$group);
9930: }
9931: }
9932: next;
9933: }
9934: push(@usersgroups,$group);
9935: }
9936: }
9937: }
9938: @usersgroups = &sort_course_groups($courseid,@usersgroups);
9939: $grouplist = join(':',@usersgroups);
9940: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
9941: }
9942: return @usersgroups;
9943: }
9944:
9945: sub devalidate_getgroups_cache {
9946: my ($udom,$uname,$cdom,$cnum)=@_;
9947: my $courseid = $cdom.'_'.$cnum;
9948:
9949: my $hashid="$udom:$uname:$courseid";
9950: &devalidate_cache_new('getgroups',$hashid);
9951: }
9952:
9953: # ------------------------------------------------------------------ Plain Text
9954:
9955: sub plaintext {
9956: my ($short,$type,$cid,$forcedefault) = @_;
9957: if ($short =~ m{^cr/}) {
9958: return (split('/',$short))[-1];
9959: }
9960: if (!defined($cid)) {
9961: $cid = $env{'request.course.id'};
9962: }
9963: my %rolenames = (
9964: Course => 'std',
9965: Community => 'alt1',
9966: Placement => 'std',
9967: );
9968: if ($cid ne '') {
9969: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
9970: unless ($forcedefault) {
9971: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
9972: &Apache::lonlocal::mt_escape(\$roletext);
9973: return &Apache::lonlocal::mt($roletext);
9974: }
9975: }
9976: }
9977: if ((defined($type)) && (defined($rolenames{$type})) &&
9978: (defined($rolenames{$type})) &&
9979: (defined($prp{$short}{$rolenames{$type}}))) {
9980: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
9981: } elsif ($cid ne '') {
9982: my $crstype = $env{'course.'.$cid.'.type'};
9983: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
9984: (defined($prp{$short}{$rolenames{$crstype}}))) {
9985: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
9986: }
9987: }
9988: return &Apache::lonlocal::mt($prp{$short}{'std'});
9989: }
9990:
9991: # ----------------------------------------------------------------- Assign Role
9992:
9993: sub assignrole {
9994: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
9995: $context)=@_;
9996: my $mrole;
9997: if ($role =~ /^cr\//) {
9998: my $cwosec=$url;
9999: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10000: unless (&allowed('ccr',$cwosec)) {
10001: my $refused = 1;
10002: if ($context eq 'requestcourses') {
10003: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10004: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10005: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10006: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10007: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10008: if ($crsenv{'internal.courseowner'} eq
10009: $env{'user.name'}.':'.$env{'user.domain'}) {
10010: $refused = '';
10011: }
10012: }
10013: }
10014: }
10015: }
10016: if ($refused) {
10017: &logthis('Refused custom assignrole: '.
10018: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10019: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10020: return 'refused';
10021: }
10022: }
10023: $mrole='cr';
10024: } elsif ($role =~ /^gr\//) {
10025: my $cwogrp=$url;
10026: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
10027: unless (&allowed('mdg',$cwogrp)) {
10028: &logthis('Refused group assignrole: '.
10029: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10030: $env{'user.name'}.' at '.$env{'user.domain'});
10031: return 'refused';
10032: }
10033: $mrole='gr';
10034: } else {
10035: my $cwosec=$url;
10036: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10037: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10038: my $refused;
10039: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
10040: if (!(&allowed('c'.$role,$url))) {
10041: $refused = 1;
10042: }
10043: } else {
10044: $refused = 1;
10045: }
10046: if ($refused) {
10047: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10048: if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
10049: my %crsenv;
10050: if ($role eq 'cc' || $role eq 'co') {
10051: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10052: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10053: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10054: if ($crsenv{'internal.courseowner'} eq
10055: $env{'user.name'}.':'.$env{'user.domain'}) {
10056: $refused = '';
10057: }
10058: }
10059: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
10060: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10061: if ($crsenv{'internal.courseowner'} eq
10062: $env{'user.name'}.':'.$env{'user.domain'}) {
10063: $refused = '';
10064: }
10065: }
10066: }
10067: }
10068: } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10069: if ($role eq 'st') {
10070: $refused = '';
10071: } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10072: $refused = '';
10073: }
10074: } elsif ($context eq 'requestcourses') {
10075: my @possroles = ('st','ta','ep','in','cc','co');
10076: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
10077: my $wrongcc;
10078: if ($cnum =~ /^$match_community$/) {
10079: $wrongcc = 1 if ($role eq 'cc');
10080: } else {
10081: $wrongcc = 1 if ($role eq 'co');
10082: }
10083: unless ($wrongcc) {
10084: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10085: if ($crsenv{'internal.courseowner'} eq
10086: $env{'user.name'}.':'.$env{'user.domain'}) {
10087: $refused = '';
10088: }
10089: }
10090: }
10091: } elsif ($context eq 'requestauthor') {
10092: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
10093: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10094: if ($env{'environment.requestauthor'} eq 'automatic') {
10095: $refused = '';
10096: } else {
10097: my %domdefaults = &get_domain_defaults($udom);
10098: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10099: my $checkbystatus;
10100: if ($env{'user.adv'}) {
10101: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10102: if ($disposition eq 'automatic') {
10103: $refused = '';
10104: } elsif ($disposition eq '') {
10105: $checkbystatus = 1;
10106: }
10107: } else {
10108: $checkbystatus = 1;
10109: }
10110: if ($checkbystatus) {
10111: if ($env{'environment.inststatus'}) {
10112: my @inststatuses = split(/,/,$env{'environment.inststatus'});
10113: foreach my $type (@inststatuses) {
10114: if (($type ne '') &&
10115: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10116: $refused = '';
10117: }
10118: }
10119: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10120: $refused = '';
10121: }
10122: }
10123: }
10124: }
10125: }
10126: }
10127: if ($refused) {
10128: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10129: ' '.$role.' '.$end.' '.$start.' by '.
10130: $env{'user.name'}.' at '.$env{'user.domain'});
10131: return 'refused';
10132: }
10133: }
10134: } elsif ($role eq 'au') {
10135: if ($url ne '/'.$udom.'/') {
10136: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10137: ' to assign author role for '.$uname.':'.$udom.
10138: ' in domain: '.$url.' refused (wrong domain).');
10139: return 'refused';
10140: }
10141: }
10142: $mrole=$role;
10143: }
10144: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
10145: "$udom:$uname:$url".'_'."$mrole=$role";
10146: if ($end) { $command.='_'.$end; }
10147: if ($start) {
10148: if ($end) {
10149: $command.='_'.$start;
10150: } else {
10151: $command.='_0_'.$start;
10152: }
10153: }
10154: my $origstart = $start;
10155: my $origend = $end;
10156: my $delflag;
10157: # actually delete
10158: if ($deleteflag) {
10159: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
10160: # modify command to delete the role
10161: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
10162: "$udom:$uname:$url".'_'."$mrole";
10163: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
10164: # set start and finish to negative values for userrolelog
10165: $start=-1;
10166: $end=-1;
10167: $delflag = 1;
10168: }
10169: }
10170: # send command
10171: my $answer=&reply($command,&homeserver($uname,$udom));
10172: # log new user role if status is ok
10173: if ($answer eq 'ok') {
10174: &userrolelog($role,$uname,$udom,$url,$start,$end);
10175: if (($role eq 'cc') || ($role eq 'in') ||
10176: ($role eq 'ep') || ($role eq 'ad') ||
10177: ($role eq 'ta') || ($role eq 'st') ||
10178: ($role=~/^cr/) || ($role eq 'gr') ||
10179: ($role eq 'co')) {
10180: # for course roles, perform group memberships changes triggered by role change.
10181: unless ($role =~ /^gr/) {
10182: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10183: $origstart,$selfenroll,$context);
10184: }
10185: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10186: $selfenroll,$context);
10187: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10188: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10189: ($role eq 'da')) {
10190: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10191: $context);
10192: } elsif (($role eq 'ca') || ($role eq 'aa')) {
10193: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10194: $context);
10195: }
10196: if ($role eq 'cc') {
10197: &autoupdate_coowners($url,$end,$start,$uname,$udom);
10198: }
10199: }
10200: return $answer;
10201: }
10202:
10203: sub autoupdate_coowners {
10204: my ($url,$end,$start,$uname,$udom) = @_;
10205: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10206: if (($cdom ne '') && ($cnum ne '')) {
10207: my $now = time;
10208: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10209: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10210: my %coursehash = &coursedescription($cdom.'_'.$cnum);
10211: my $instcode = $coursehash{'internal.coursecode'};
10212: if ($instcode ne '') {
10213: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10214: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10215: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10216: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10217: if ($result eq 'valid') {
10218: if ($coursehash{'internal.co-owners'}) {
10219: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10220: push(@newcoowners,$coowner);
10221: }
10222: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10223: push(@newcoowners,$uname.':'.$udom);
10224: }
10225: @newcoowners = sort(@newcoowners);
10226: } else {
10227: push(@newcoowners,$uname.':'.$udom);
10228: }
10229: } else {
10230: if ($coursehash{'internal.co-owners'}) {
10231: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10232: unless ($coowner eq $uname.':'.$udom) {
10233: push(@newcoowners,$coowner);
10234: }
10235: }
10236: unless (@newcoowners > 0) {
10237: $delcoowners = 1;
10238: $coowners = '';
10239: }
10240: }
10241: }
10242: if (@newcoowners || $delcoowners) {
10243: &store_coowners($cdom,$cnum,$coursehash{'home'},
10244: $delcoowners,@newcoowners);
10245: }
10246: }
10247: }
10248: }
10249: }
10250: }
10251: }
10252:
10253: sub store_coowners {
10254: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10255: my $cid = $cdom.'_'.$cnum;
10256: my ($coowners,$delresult,$putresult);
10257: if (@newcoowners) {
10258: $coowners = join(',',@newcoowners);
10259: my %coownershash = (
10260: 'internal.co-owners' => $coowners,
10261: );
10262: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10263: if ($putresult eq 'ok') {
10264: if ($env{'course.'.$cid.'.num'} eq $cnum) {
10265: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10266: }
10267: }
10268: }
10269: if ($delcoowners) {
10270: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10271: if ($delresult eq 'ok') {
10272: if ($env{'course.'.$cid.'.internal.co-owners'}) {
10273: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10274: }
10275: }
10276: }
10277: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10278: my %crsinfo =
10279: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10280: if (ref($crsinfo{$cid}) eq 'HASH') {
10281: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10282: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10283: }
10284: }
10285: }
10286:
10287: # -------------------------------------------------- Modify user authentication
10288: # Overrides without validation
10289:
10290: sub modifyuserauth {
10291: my ($udom,$uname,$umode,$upass)=@_;
10292: my $uhome=&homeserver($uname,$udom);
10293: my $allowed;
10294: if (&allowed('mau',$udom)) {
10295: $allowed = 1;
10296: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10297: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10298: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10299: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10300: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10301: if (($cdom ne '') && ($cnum ne '')) {
10302: my $is_owner = &is_course_owner($cdom,$cnum);
10303: if ($is_owner) {
10304: $allowed = 1;
10305: }
10306: }
10307: }
10308: unless ($allowed) { return 'refused'; }
10309: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
10310: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10311: ' in domain '.$env{'request.role.domain'});
10312: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10313: &escape($upass),$uhome);
10314: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
10315: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10316: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
10317: &log($udom,,$uname,$uhome,
10318: 'Authentication changed by '.$env{'user.domain'}.', '.
10319: $env{'user.name'}.', '.$umode.
10320: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
10321: unless ($reply eq 'ok') {
10322: &logthis('Authentication mode error: '.$reply);
10323: return 'error: '.$reply;
10324: }
10325: return 'ok';
10326: }
10327:
10328: # --------------------------------------------------------------- Modify a user
10329:
10330: sub modifyuser {
10331: my ($udom, $uname, $uid,
10332: $umode, $upass, $first,
10333: $middle, $last, $gene,
10334: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10335: $udom= &LONCAPA::clean_domain($udom);
10336: $uname=&LONCAPA::clean_username($uname);
10337: my $showcandelete = 'none';
10338: if (ref($candelete) eq 'ARRAY') {
10339: if (@{$candelete} > 0) {
10340: $showcandelete = join(', ',@{$candelete});
10341: }
10342: }
10343: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10344: $umode.', '.$first.', '.$middle.', '.
10345: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10346: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10347: ' desiredhome not specified').
10348: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10349: ' in domain '.$env{'request.role.domain'});
10350: my $uhome=&homeserver($uname,$udom,'true');
10351: my $newuser;
10352: if ($uhome eq 'no_host') {
10353: $newuser = 1;
10354: unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10355: ($umode eq 'lti')) {
10356: return 'error: more information needed to create new user';
10357: }
10358: }
10359: # ----------------------------------------------------------------- Create User
10360: if (($uhome eq 'no_host') &&
10361: (($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
10362: my $unhome='';
10363: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
10364: $unhome = $desiredhome;
10365: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10366: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10367: } else { # load balancing routine for determining $unhome
10368: my $loadm=10000000;
10369: my %servers = &get_servers($udom,'library');
10370: foreach my $tryserver (keys(%servers)) {
10371: my $answer=reply('load',$tryserver);
10372: if (($answer=~/\d+/) && ($answer<$loadm)) {
10373: $loadm=$answer;
10374: $unhome=$tryserver;
10375: }
10376: }
10377: }
10378: if (($unhome eq '') || ($unhome eq 'no_host')) {
10379: return 'error: unable to find a home server for '.$uname.
10380: ' in domain '.$udom;
10381: }
10382: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10383: &escape($upass),$unhome);
10384: unless ($reply eq 'ok') {
10385: return 'error: '.$reply;
10386: }
10387: $uhome=&homeserver($uname,$udom,'true');
10388: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10389: return 'error: unable verify users home machine.';
10390: }
10391: } # End of creation of new user
10392: # ---------------------------------------------------------------------- Add ID
10393: if ($uid) {
10394: $uid=~tr/A-Z/a-z/;
10395: my %uidhash=&idrget($udom,$uname);
10396: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
10397: && (!$forceid)) {
10398: unless ($uid eq $uidhash{$uname}) {
10399: return 'error: user id "'.$uid.'" does not match '.
10400: 'current user id "'.$uidhash{$uname}.'".';
10401: }
10402: } else {
10403: &idput($udom,{$uname => $uid},$uhome,'ids');
10404: }
10405: }
10406: # -------------------------------------------------------------- Add names, etc
10407: my @tmp=&get('environment',
10408: ['firstname','middlename','lastname','generation','id',
10409: 'permanentemail','inststatus'],
10410: $udom,$uname);
10411: my (%names,%oldnames);
10412: if ($tmp[0] =~ m/^error:.*/) {
10413: %names=();
10414: } else {
10415: %names = @tmp;
10416: %oldnames = %names;
10417: }
10418: #
10419: # If name, email and/or uid are blank (e.g., because an uploaded file
10420: # of users did not contain them), do not overwrite existing values
10421: # unless field is in $candelete array ref.
10422: #
10423:
10424: my @fields = ('firstname','middlename','lastname','generation',
10425: 'permanentemail','id');
10426: my %newvalues;
10427: if (ref($candelete) eq 'ARRAY') {
10428: foreach my $field (@fields) {
10429: if (grep(/^\Q$field\E$/,@{$candelete})) {
10430: if ($field eq 'firstname') {
10431: $names{$field} = $first;
10432: } elsif ($field eq 'middlename') {
10433: $names{$field} = $middle;
10434: } elsif ($field eq 'lastname') {
10435: $names{$field} = $last;
10436: } elsif ($field eq 'generation') {
10437: $names{$field} = $gene;
10438: } elsif ($field eq 'permanentemail') {
10439: $names{$field} = $email;
10440: } elsif ($field eq 'id') {
10441: $names{$field} = $uid;
10442: }
10443: }
10444: }
10445: }
10446: if ($first) { $names{'firstname'} = $first; }
10447: if (defined($middle)) { $names{'middlename'} = $middle; }
10448: if ($last) { $names{'lastname'} = $last; }
10449: if (defined($gene)) { $names{'generation'} = $gene; }
10450: if ($email) {
10451: $email=~s/[^\w\@\.\-\,]//gs;
10452: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10453: }
10454: if ($uid) { $names{'id'} = $uid; }
10455: if (defined($inststatus)) {
10456: $names{'inststatus'} = '';
10457: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10458: if (ref($usertypes) eq 'HASH') {
10459: my @okstatuses;
10460: foreach my $item (split(/:/,$inststatus)) {
10461: if (defined($usertypes->{$item})) {
10462: push(@okstatuses,$item);
10463: }
10464: }
10465: if (@okstatuses) {
10466: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10467: }
10468: }
10469: }
10470: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10471: $umode.', '.$first.', '.$middle.', '.
10472: $last.', '.$gene.', '.$email.', '.$inststatus;
10473: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10474: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10475: } else {
10476: $logmsg .= ' during self creation';
10477: }
10478: my $changed;
10479: if ($newuser) {
10480: $changed = 1;
10481: } else {
10482: foreach my $field (@fields) {
10483: if ($names{$field} ne $oldnames{$field}) {
10484: $changed = 1;
10485: last;
10486: }
10487: }
10488: }
10489: unless ($changed) {
10490: $logmsg = 'No changes in user information needed for: '.$logmsg;
10491: &logthis($logmsg);
10492: return 'ok';
10493: }
10494: my $reply = &put('environment', \%names, $udom,$uname);
10495: if ($reply ne 'ok') {
10496: return 'error: '.$reply;
10497: }
10498: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10499: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10500: }
10501: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10502: &devalidate_cache_new('namescache',$uname.':'.$udom);
10503: $logmsg = 'Success modifying user '.$logmsg;
10504: &logthis($logmsg);
10505: return 'ok';
10506: }
10507:
10508: # -------------------------------------------------------------- Modify student
10509:
10510: sub modifystudent {
10511: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10512: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10513: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10514: if (!$cid) {
10515: unless ($cid=$env{'request.course.id'}) {
10516: return 'not_in_class';
10517: }
10518: }
10519: # --------------------------------------------------------------- Make the user
10520: my $reply=&modifyuser
10521: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10522: $desiredhome,$email,$inststatus);
10523: unless ($reply eq 'ok') { return $reply; }
10524: # This will cause &modify_student_enrollment to get the uid from the
10525: # student's environment
10526: $uid = undef if (!$forceid);
10527: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10528: $gene,$usec,$end,$start,$type,$locktype,
10529: $cid,$selfenroll,$context,$credits,$instsec);
10530: return $reply;
10531: }
10532:
10533: sub modify_student_enrollment {
10534: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10535: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10536: my ($cdom,$cnum,$chome);
10537: if (!$cid) {
10538: unless ($cid=$env{'request.course.id'}) {
10539: return 'not_in_class';
10540: }
10541: $cdom=$env{'course.'.$cid.'.domain'};
10542: $cnum=$env{'course.'.$cid.'.num'};
10543: } else {
10544: ($cdom,$cnum)=split(/_/,$cid);
10545: }
10546: $chome=$env{'course.'.$cid.'.home'};
10547: if (!$chome) {
10548: $chome=&homeserver($cnum,$cdom);
10549: }
10550: if (!$chome) { return 'unknown_course'; }
10551: # Make sure the user exists
10552: my $uhome=&homeserver($uname,$udom);
10553: if (($uhome eq '') || ($uhome eq 'no_host')) {
10554: return 'error: no such user';
10555: }
10556: # Get student data if we were not given enough information
10557: if (!defined($first) || $first eq '' ||
10558: !defined($last) || $last eq '' ||
10559: !defined($uid) || $uid eq '' ||
10560: !defined($middle) || $middle eq '' ||
10561: !defined($gene) || $gene eq '') {
10562: # They did not supply us with enough data to enroll the student, so
10563: # we need to pick up more information.
10564: my %tmp = &get('environment',
10565: ['firstname','middlename','lastname', 'generation','id']
10566: ,$udom,$uname);
10567:
10568: #foreach my $key (keys(%tmp)) {
10569: # &logthis("key $key = ".$tmp{$key});
10570: #}
10571: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10572: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10573: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
10574: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
10575: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10576: }
10577: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10578: my $user = "$uname:$udom";
10579: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10580: my $reply=cput('classlist',
10581: {$user =>
10582: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10583: $cdom,$cnum);
10584: if (($reply eq 'ok') || ($reply eq 'delayed')) {
10585: &devalidate_getsection_cache($udom,$uname,$cid);
10586: } else {
10587: return 'error: '.$reply;
10588: }
10589: # Add student role to user
10590: my $uurl='/'.$cid;
10591: $uurl=~s/\_/\//g;
10592: if ($usec) {
10593: $uurl.='/'.$usec;
10594: }
10595: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10596: $selfenroll,$context);
10597: if ($result ne 'ok') {
10598: if ($old_entry{$user} ne '') {
10599: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10600: } else {
10601: $reply = &del('classlist',[$user],$cdom,$cnum);
10602: }
10603: }
10604: return $result;
10605: }
10606:
10607: sub format_name {
10608: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10609: my $name;
10610: if ($first ne 'lastname') {
10611: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10612: } else {
10613: if ($lastname=~/\S/) {
10614: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10615: $name=~s/\s+,/,/;
10616: } else {
10617: $name.= $firstname.' '.$middlename.' '.$generation;
10618: }
10619: }
10620: $name=~s/^\s+//;
10621: $name=~s/\s+$//;
10622: $name=~s/\s+/ /g;
10623: return $name;
10624: }
10625:
10626: # ------------------------------------------------- Write to course preferences
10627:
10628: sub writecoursepref {
10629: my ($courseid,%prefs)=@_;
10630: $courseid=~s/^\///;
10631: $courseid=~s/\_/\//g;
10632: my ($cdomain,$cnum)=split(/\//,$courseid);
10633: my $chome=homeserver($cnum,$cdomain);
10634: if (($chome eq '') || ($chome eq 'no_host')) {
10635: return 'error: no such course';
10636: }
10637: my $cstring='';
10638: foreach my $pref (keys(%prefs)) {
10639: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10640: }
10641: $cstring=~s/\&$//;
10642: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10643: }
10644:
10645: # ---------------------------------------------------------- Make/modify course
10646:
10647: sub createcourse {
10648: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10649: $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
10650: $url=&declutter($url);
10651: my $cid='';
10652: if ($context eq 'requestcourses') {
10653: my $can_create = 0;
10654: my ($ownername,$ownerdom) = split(':',$course_owner);
10655: if ($udom eq $ownerdom) {
10656: my $reload;
10657: if (($callercontext eq 'auto') &&
10658: ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
10659: $reload = 'reload';
10660: }
10661: if (&usertools_access($ownername,$ownerdom,$category,$reload,
10662: $context)) {
10663: $can_create = 1;
10664: }
10665: } else {
10666: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10667: $category);
10668: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10669: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10670: if (@curr > 0) {
10671: my @options = qw(approval validate autolimit);
10672: my $optregex = join('|',@options);
10673: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10674: $can_create = 1;
10675: }
10676: }
10677: }
10678: }
10679: if ($can_create) {
10680: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10681: unless (&allowed('ccc',$udom)) {
10682: return 'refused';
10683: }
10684: }
10685: } else {
10686: return 'refused';
10687: }
10688: } elsif (!&allowed('ccc',$udom)) {
10689: return 'refused';
10690: }
10691: # --------------------------------------------------------------- Get Unique ID
10692: my $uname;
10693: if ($cnum =~ /^$match_courseid$/) {
10694: my $chome=&homeserver($cnum,$udom,'true');
10695: if (($chome eq '') || ($chome eq 'no_host')) {
10696: $uname = $cnum;
10697: } else {
10698: $uname = &generate_coursenum($udom,$crstype);
10699: }
10700: } else {
10701: $uname = &generate_coursenum($udom,$crstype);
10702: }
10703: return $uname if ($uname =~ /^error/);
10704: # -------------------------------------------------- Check supplied server name
10705: if (!defined($course_server)) {
10706: if (defined(&domain($udom,'primary'))) {
10707: $course_server = &domain($udom,'primary');
10708: } else {
10709: $course_server = $env{'user.home'};
10710: }
10711: }
10712: my %host_servers =
10713: &Apache::lonnet::get_servers($udom,'library');
10714: unless ($host_servers{$course_server}) {
10715: return 'error: invalid home server for course: '.$course_server;
10716: }
10717: # ------------------------------------------------------------- Make the course
10718: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10719: $course_server);
10720: unless ($reply eq 'ok') { return 'error: '.$reply; }
10721: my $uhome=&homeserver($uname,$udom,'true');
10722: if (($uhome eq '') || ($uhome eq 'no_host')) {
10723: return 'error: no such course';
10724: }
10725: # ----------------------------------------------------------------- Course made
10726: # log existence
10727: my $now = time;
10728: my $newcourse = {
10729: $udom.'_'.$uname => {
10730: description => $description,
10731: inst_code => $inst_code,
10732: owner => $course_owner,
10733: type => $crstype,
10734: creator => $env{'user.name'}.':'.
10735: $env{'user.domain'},
10736: created => $now,
10737: context => $context,
10738: },
10739: };
10740: &courseidput($udom,$newcourse,$uhome,'notime');
10741: # set toplevel url
10742: my $topurl=$url;
10743: unless ($nonstandard) {
10744: # ------------------------------------------ For standard courses, make top url
10745: my $mapurl=&clutter($url);
10746: if ($mapurl eq '/res/') { $mapurl=''; }
10747: $env{'form.initmap'}=(<<ENDINITMAP);
10748: <map>
10749: <resource id="1" type="start"></resource>
10750: <resource id="2" src="$mapurl"></resource>
10751: <resource id="3" type="finish"></resource>
10752: <link index="1" from="1" to="2"></link>
10753: <link index="2" from="2" to="3"></link>
10754: </map>
10755: ENDINITMAP
10756: $topurl=&declutter(
10757: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10758: );
10759: }
10760: # ----------------------------------------------------------- Write preferences
10761: &writecoursepref($udom.'_'.$uname,
10762: ('description' => $description,
10763: 'url' => $topurl,
10764: 'internal.creator' => $env{'user.name'}.':'.
10765: $env{'user.domain'},
10766: 'internal.created' => $now,
10767: 'internal.creationcontext' => $context)
10768: );
10769: return '/'.$udom.'/'.$uname;
10770: }
10771:
10772: # ------------------------------------------------------------------- Create ID
10773: sub generate_coursenum {
10774: my ($udom,$crstype) = @_;
10775: my $domdesc = &domain($udom);
10776: return 'error: invalid domain' if ($domdesc eq '');
10777: my $first;
10778: if ($crstype eq 'Community') {
10779: $first = '0';
10780: } else {
10781: $first = int(1+rand(9));
10782: }
10783: my $uname=$first.
10784: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10785: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10786: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10787: # ----------------------------------------------- Make sure that does not exist
10788: my $uhome=&homeserver($uname,$udom,'true');
10789: unless (($uhome eq '') || ($uhome eq 'no_host')) {
10790: if ($crstype eq 'Community') {
10791: $first = '0';
10792: } else {
10793: $first = int(1+rand(9));
10794: }
10795: $uname=$first.
10796: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10797: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10798: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10799: $uhome=&homeserver($uname,$udom,'true');
10800: unless (($uhome eq '') || ($uhome eq 'no_host')) {
10801: return 'error: unable to generate unique course-ID';
10802: }
10803: }
10804: return $uname;
10805: }
10806:
10807: sub is_course {
10808: my ($cdom, $cnum) = scalar(@_) == 1 ?
10809: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
10810:
10811: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10812: my $uhome=&homeserver($cnum,$cdom);
10813: my $iscourse;
10814: if (grep { $_ eq $uhome } current_machine_ids()) {
10815: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10816: } else {
10817: my $hashid = $cdom.':'.$cnum;
10818: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10819: unless (defined($cached)) {
10820: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10821: $cnum,undef,undef,'.');
10822: $iscourse = 0;
10823: if (exists($courses{$cdom.'_'.$cnum})) {
10824: $iscourse = 1;
10825: }
10826: &do_cache_new('iscourse',$hashid,$iscourse,3600);
10827: }
10828: }
10829: return unless ($iscourse);
10830: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10831: }
10832:
10833: sub store_userdata {
10834: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10835: my $result;
10836: if ($datakey ne '') {
10837: if (ref($storehash) eq 'HASH') {
10838: if ($udom eq '' || $uname eq '') {
10839: $udom = $env{'user.domain'};
10840: $uname = $env{'user.name'};
10841: }
10842: my $uhome=&homeserver($uname,$udom);
10843: if (($uhome eq '') || ($uhome eq 'no_host')) {
10844: $result = 'error: no_host';
10845: } else {
10846: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10847: $storehash->{'host'} = $perlvar{'lonHostID'};
10848:
10849: my $namevalue='';
10850: foreach my $key (keys(%{$storehash})) {
10851: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10852: }
10853: $namevalue=~s/\&$//;
10854: unless ($namespace eq 'courserequests') {
10855: $datakey = &escape($datakey);
10856: }
10857: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
10858: $namevalue,$uhome);
10859: }
10860: } else {
10861: $result = 'error: data to store was not a hash reference';
10862: }
10863: } else {
10864: $result= 'error: invalid requestkey';
10865: }
10866: return $result;
10867: }
10868:
10869: # ---------------------------------------------------------- Assign Custom Role
10870:
10871: sub assigncustomrole {
10872: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10873: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10874: $end,$start,$deleteflag,$selfenroll,$context);
10875: }
10876:
10877: # ----------------------------------------------------------------- Revoke Role
10878:
10879: sub revokerole {
10880: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10881: my $now=time;
10882: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10883: }
10884:
10885: # ---------------------------------------------------------- Revoke Custom Role
10886:
10887: sub revokecustomrole {
10888: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10889: my $now=time;
10890: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10891: $deleteflag,$selfenroll,$context);
10892: }
10893:
10894: # ------------------------------------------------------------ Disk usage
10895: sub diskusage {
10896: my ($udom,$uname,$directorypath,$getpropath)=@_;
10897: $directorypath =~ s/\/$//;
10898: my $listing=&reply('du2:'.&escape($directorypath).':'
10899: .&escape($getpropath).':'.&escape($uname).':'
10900: .&escape($udom),homeserver($uname,$udom));
10901: if ($listing eq 'unknown_cmd') {
10902: if ($getpropath) {
10903: $directorypath = &propath($udom,$uname).'/'.$directorypath;
10904: }
10905: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10906: }
10907: return $listing;
10908: }
10909:
10910: sub is_locked {
10911: my ($file_name, $domain, $user, $which) = @_;
10912: my @check;
10913: my $is_locked;
10914: push (@check,$file_name);
10915: my %locked = &get('file_permissions',\@check,
10916: $env{'user.domain'},$env{'user.name'});
10917: my ($tmp)=keys(%locked);
10918: if ($tmp=~/^error:/) { undef(%locked); }
10919:
10920: if (ref($locked{$file_name}) eq 'ARRAY') {
10921: $is_locked = 'false';
10922: foreach my $entry (@{$locked{$file_name}}) {
10923: if (ref($entry) eq 'ARRAY') {
10924: $is_locked = 'true';
10925: if (ref($which) eq 'ARRAY') {
10926: push(@{$which},$entry);
10927: } else {
10928: last;
10929: }
10930: }
10931: }
10932: } else {
10933: $is_locked = 'false';
10934: }
10935: return $is_locked;
10936: }
10937:
10938: sub declutter_portfile {
10939: my ($file) = @_;
10940: $file =~ s{^(/portfolio/|portfolio/)}{/};
10941: return $file;
10942: }
10943:
10944: # ------------------------------------------------------------- Mark as Read Only
10945:
10946: sub mark_as_readonly {
10947: my ($domain,$user,$files,$what) = @_;
10948: my %current_permissions = &dump('file_permissions',$domain,$user);
10949: my ($tmp)=keys(%current_permissions);
10950: if ($tmp=~/^error:/) { undef(%current_permissions); }
10951: foreach my $file (@{$files}) {
10952: $file = &declutter_portfile($file);
10953: push(@{$current_permissions{$file}},$what);
10954: }
10955: &put('file_permissions',\%current_permissions,$domain,$user);
10956: return;
10957: }
10958:
10959: # ------------------------------------------------------------Save Selected Files
10960:
10961: sub save_selected_files {
10962: my ($user, $path, @files) = @_;
10963: my $filename = $user."savedfiles";
10964: my @other_files = &files_not_in_path($user, $path);
10965: open (OUT,'>',LONCAPA::tempdir().$filename);
10966: foreach my $file (@files) {
10967: print (OUT $env{'form.currentpath'}.$file."\n");
10968: }
10969: foreach my $file (@other_files) {
10970: print (OUT $file."\n");
10971: }
10972: close (OUT);
10973: return 'ok';
10974: }
10975:
10976: sub clear_selected_files {
10977: my ($user) = @_;
10978: my $filename = $user."savedfiles";
10979: open (OUT,'>',LONCAPA::tempdir().$filename);
10980: print (OUT undef);
10981: close (OUT);
10982: return ("ok");
10983: }
10984:
10985: sub files_in_path {
10986: my ($user, $path) = @_;
10987: my $filename = $user."savedfiles";
10988: my %return_files;
10989: open (IN,'<',LONCAPA::tempdir().$filename);
10990: while (my $line_in = <IN>) {
10991: chomp ($line_in);
10992: my @paths_and_file = split (m!/!, $line_in);
10993: my $file_part = pop (@paths_and_file);
10994: my $path_part = join ('/', @paths_and_file);
10995: $path_part.='/';
10996: my $path_and_file = $path_part.$file_part;
10997: if ($path_part eq $path) {
10998: $return_files{$file_part}= 'selected';
10999: }
11000: }
11001: close (IN);
11002: return (\%return_files);
11003: }
11004:
11005: # called in portfolio select mode, to show files selected NOT in current directory
11006: sub files_not_in_path {
11007: my ($user, $path) = @_;
11008: my $filename = $user."savedfiles";
11009: my @return_files;
11010: my $path_part;
11011: open(IN, '<',LONCAPA::tempdir().$filename);
11012: while (my $line = <IN>) {
11013: #ok, I know it's clunky, but I want it to work
11014: my @paths_and_file = split(m|/|, $line);
11015: my $file_part = pop(@paths_and_file);
11016: chomp($file_part);
11017: my $path_part = join('/', @paths_and_file);
11018: $path_part .= '/';
11019: my $path_and_file = $path_part.$file_part;
11020: if ($path_part ne $path) {
11021: push(@return_files, ($path_and_file));
11022: }
11023: }
11024: close(OUT);
11025: return (@return_files);
11026: }
11027:
11028: #------------------------------Submitted/Handedback Portfolio Files Versioning
11029:
11030: sub portfiles_versioning {
11031: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11032: my $portfolio_root = '/userfiles/portfolio';
11033: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11034: foreach my $file (@{$portfiles}) {
11035: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11036: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11037: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11038: my $getpropath = 1;
11039: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11040: $stu_name,$getpropath);
11041: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11042: my $new_answer =
11043: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11044: if ($new_answer ne 'problem getting file') {
11045: push(@{$versioned_portfiles}, $directory.$new_answer);
11046: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11047: [$symb,$env{'request.course.id'},'graded']);
11048: }
11049: }
11050: }
11051:
11052: sub get_next_version {
11053: my ($answer_name, $answer_ext, $dir_list) = @_;
11054: my $version;
11055: if (ref($dir_list) eq 'ARRAY') {
11056: foreach my $row (@{$dir_list}) {
11057: my ($file) = split(/\&/,$row,2);
11058: my ($file_name,$file_version,$file_ext) =
11059: &file_name_version_ext($file);
11060: if (($file_name eq $answer_name) &&
11061: ($file_ext eq $answer_ext)) {
11062: # gets here if filename and extension match,
11063: # regardless of version
11064: if ($file_version ne '') {
11065: # a versioned file is found so save it for later
11066: if ($file_version > $version) {
11067: $version = $file_version;
11068: }
11069: }
11070: }
11071: }
11072: }
11073: $version ++;
11074: return($version);
11075: }
11076:
11077: sub version_selected_portfile {
11078: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11079: my ($answer_name,$answer_ver,$answer_ext) =
11080: &file_name_version_ext($file_name);
11081: my $new_answer;
11082: $env{'form.copy'} =
11083: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11084: if($env{'form.copy'} eq '-1') {
11085: $new_answer = 'problem getting file';
11086: } else {
11087: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11088: my $copy_result =
11089: &finishuserfileupload($stu_name,$domain,'copy',
11090: '/portfolio'.$directory.$new_answer);
11091: }
11092: undef($env{'form.copy'});
11093: return ($new_answer);
11094: }
11095:
11096: sub file_name_version_ext {
11097: my ($file)=@_;
11098: my @file_parts = split(/\./, $file);
11099: my ($name,$version,$ext);
11100: if (@file_parts > 1) {
11101: $ext=pop(@file_parts);
11102: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11103: $version=pop(@file_parts);
11104: }
11105: $name=join('.',@file_parts);
11106: } else {
11107: $name=join('.',@file_parts);
11108: }
11109: return($name,$version,$ext);
11110: }
11111:
11112: #----------------------------------------------Get portfolio file permissions
11113:
11114: sub get_portfile_permissions {
11115: my ($domain,$user) = @_;
11116: my %current_permissions = &dump('file_permissions',$domain,$user);
11117: my ($tmp)=keys(%current_permissions);
11118: if ($tmp=~/^error:/) { undef(%current_permissions); }
11119: return \%current_permissions;
11120: }
11121:
11122: #---------------------------------------------Get portfolio file access controls
11123:
11124: sub get_access_controls {
11125: my ($current_permissions,$group,$file) = @_;
11126: my %access;
11127: my $real_file = $file;
11128: $file =~ s/\.meta$//;
11129: if (defined($file)) {
11130: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11131: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
11132: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
11133: }
11134: }
11135: } else {
11136: foreach my $key (keys(%{$current_permissions})) {
11137: if ($key =~ /\0accesscontrol$/) {
11138: if (defined($group)) {
11139: if ($key !~ m-^\Q$group\E/-) {
11140: next;
11141: }
11142: }
11143: my ($fullpath) = split(/\0/,$key);
11144: if (ref($$current_permissions{$key}) eq 'HASH') {
11145: foreach my $control (keys(%{$$current_permissions{$key}})) {
11146: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11147: }
11148: }
11149: }
11150: }
11151: }
11152: return %access;
11153: }
11154:
11155: sub modify_access_controls {
11156: my ($file_name,$changes,$domain,$user)=@_;
11157: my ($outcome,$deloutcome);
11158: my %store_permissions;
11159: my %new_values;
11160: my %new_control;
11161: my %translation;
11162: my @deletions = ();
11163: my $now = time;
11164: if (exists($$changes{'activate'})) {
11165: if (ref($$changes{'activate'}) eq 'HASH') {
11166: my @newitems = sort(keys(%{$$changes{'activate'}}));
11167: my $numnew = scalar(@newitems);
11168: for (my $i=0; $i<$numnew; $i++) {
11169: my $newkey = $newitems[$i];
11170: my $newid = &Apache::loncommon::get_cgi_id();
11171: if ($newkey =~ /^\d+:/) {
11172: $newkey =~ s/^(\d+)/$newid/;
11173: $translation{$1} = $newid;
11174: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11175: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11176: $translation{$1} = $newid;
11177: }
11178: $new_values{$file_name."\0".$newkey} =
11179: $$changes{'activate'}{$newitems[$i]};
11180: $new_control{$newkey} = $now;
11181: }
11182: }
11183: }
11184: my %todelete;
11185: my %changed_items;
11186: foreach my $action ('delete','update') {
11187: if (exists($$changes{$action})) {
11188: if (ref($$changes{$action}) eq 'HASH') {
11189: foreach my $key (keys(%{$$changes{$action}})) {
11190: my ($itemnum) = ($key =~ /^([^:]+):/);
11191: if ($action eq 'delete') {
11192: $todelete{$itemnum} = 1;
11193: } else {
11194: $changed_items{$itemnum} = $key;
11195: }
11196: }
11197: }
11198: }
11199: }
11200: # get lock on access controls for file.
11201: my $lockhash = {
11202: $file_name."\0".'locked_access_records' => $env{'user.name'}.
11203: ':'.$env{'user.domain'},
11204: };
11205: my $tries = 0;
11206: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11207:
11208: while (($gotlock ne 'ok') && $tries < 10) {
11209: $tries ++;
11210: sleep(0.1);
11211: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11212: }
11213: if ($gotlock eq 'ok') {
11214: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11215: my ($tmp)=keys(%curr_permissions);
11216: if ($tmp=~/^error:/) { undef(%curr_permissions); }
11217: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11218: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11219: if (ref($curr_controls) eq 'HASH') {
11220: foreach my $control_item (keys(%{$curr_controls})) {
11221: my ($itemnum) = ($control_item =~ /^([^:]+):/);
11222: if (defined($todelete{$itemnum})) {
11223: push(@deletions,$file_name."\0".$control_item);
11224: } else {
11225: if (defined($changed_items{$itemnum})) {
11226: $new_control{$changed_items{$itemnum}} = $now;
11227: push(@deletions,$file_name."\0".$control_item);
11228: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11229: } else {
11230: $new_control{$control_item} = $$curr_controls{$control_item};
11231: }
11232: }
11233: }
11234: }
11235: }
11236: my ($group);
11237: if (&is_course($domain,$user)) {
11238: ($group,my $file) = split(/\//,$file_name,2);
11239: }
11240: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11241: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11242: $outcome = &put('file_permissions',\%new_values,$domain,$user);
11243: # remove lock
11244: my @del_lock = ($file_name."\0".'locked_access_records');
11245: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
11246: my $sqlresult =
11247: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
11248: $group);
11249: } else {
11250: $outcome = "error: could not obtain lockfile\n";
11251: }
11252: return ($outcome,$deloutcome,\%new_values,\%translation);
11253: }
11254:
11255: sub make_public_indefinitely {
11256: my (@requrl) = @_;
11257: return &automated_portfile_access('public',\@requrl);
11258: }
11259:
11260: sub automated_portfile_access {
11261: my ($accesstype,$addsref,$delsref,$info) = @_;
11262: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11263: return 'invalid';
11264: }
11265: my %urls;
11266: if (ref($addsref) eq 'ARRAY') {
11267: foreach my $requrl (@{$addsref}) {
11268: if (&is_portfolio_url($requrl)) {
11269: unless (exists($urls{$requrl})) {
11270: $urls{$requrl} = 'add';
11271: }
11272: }
11273: }
11274: }
11275: if (ref($delsref) eq 'ARRAY') {
11276: foreach my $requrl (@{$delsref}) {
11277: if (&is_portfolio_url($requrl)) {
11278: unless (exists($urls{$requrl})) {
11279: $urls{$requrl} = 'delete';
11280: }
11281: }
11282: }
11283: }
11284: unless (keys(%urls)) {
11285: return 'invalid';
11286: }
11287: my $ip;
11288: if ($accesstype eq 'ip') {
11289: if (ref($info) eq 'HASH') {
11290: if ($info->{'ip'} ne '') {
11291: $ip = $info->{'ip'};
11292: }
11293: }
11294: if ($ip eq '') {
11295: return 'invalid';
11296: }
11297: }
11298: my $errors;
11299: my $now = time;
11300: my %current_perms;
11301: foreach my $requrl (sort(keys(%urls))) {
11302: my $action;
11303: if ($urls{$requrl} eq 'add') {
11304: $action = 'activate';
11305: } else {
11306: $action = 'none';
11307: }
11308: my $aclnum = 0;
11309: my (undef,$udom,$unum,$file_name,$group) =
11310: &parse_portfolio_url($requrl);
11311: unless (exists($current_perms{$unum.':'.$udom})) {
11312: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11313: }
11314: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
11315: $group,$file_name);
11316: foreach my $key (keys(%{$access_controls{$file_name}})) {
11317: my ($num,$scope,$end,$start) =
11318: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11319: if ($scope eq $accesstype) {
11320: if (($start <= $now) && ($end == 0)) {
11321: if ($accesstype eq 'ip') {
11322: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11323: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11324: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11325: if ($urls{$requrl} eq 'add') {
11326: $action = 'none';
11327: last;
11328: } else {
11329: $action = 'delete';
11330: $aclnum = $num;
11331: last;
11332: }
11333: }
11334: }
11335: }
11336: } elsif ($accesstype eq 'public') {
11337: if ($urls{$requrl} eq 'add') {
11338: $action = 'none';
11339: last;
11340: } else {
11341: $action = 'delete';
11342: $aclnum = $num;
11343: last;
11344: }
11345: }
11346: } elsif ($accesstype eq 'public') {
11347: $action = 'update';
11348: $aclnum = $num;
11349: last;
11350: }
11351: }
11352: }
11353: if ($action eq 'none') {
11354: next;
11355: } else {
11356: my %changes;
11357: my $newend = 0;
11358: my $newstart = $now;
11359: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
11360: $changes{$action}{$newkey} = {
11361: type => $accesstype,
11362: time => {
11363: start => $newstart,
11364: end => $newend,
11365: },
11366: };
11367: if ($accesstype eq 'ip') {
11368: $changes{$action}{$newkey}{'ip'} = [$ip];
11369: }
11370: my ($outcome,$deloutcome,$new_values,$translation) =
11371: &modify_access_controls($file_name,\%changes,$udom,$unum);
11372: unless ($outcome eq 'ok') {
11373: $errors .= $outcome.' ';
11374: }
11375: }
11376: }
11377: if ($errors) {
11378: $errors =~ s/\s$//;
11379: return $errors;
11380: } else {
11381: return 'ok';
11382: }
11383: }
11384:
11385: #------------------------------------------------------Get Marked as Read Only
11386:
11387: sub get_marked_as_readonly {
11388: my ($domain,$user,$what,$group) = @_;
11389: my $current_permissions = &get_portfile_permissions($domain,$user);
11390: my @readonly_files;
11391: my $cmp1=$what;
11392: if (ref($what)) { $cmp1=join('',@{$what}) };
11393: while (my ($file_name,$value) = each(%{$current_permissions})) {
11394: if (defined($group)) {
11395: if ($file_name !~ m-^\Q$group\E/-) {
11396: next;
11397: }
11398: }
11399: if (ref($value) eq "ARRAY"){
11400: foreach my $stored_what (@{$value}) {
11401: my $cmp2=$stored_what;
11402: if (ref($stored_what) eq 'ARRAY') {
11403: $cmp2=join('',@{$stored_what});
11404: }
11405: if ($cmp1 eq $cmp2) {
11406: push(@readonly_files, $file_name);
11407: last;
11408: } elsif (!defined($what)) {
11409: push(@readonly_files, $file_name);
11410: last;
11411: }
11412: }
11413: }
11414: }
11415: return @readonly_files;
11416: }
11417: #-----------------------------------------------------------Get Marked as Read Only Hash
11418:
11419: sub get_marked_as_readonly_hash {
11420: my ($current_permissions,$group,$what) = @_;
11421: my %readonly_files;
11422: while (my ($file_name,$value) = each(%{$current_permissions})) {
11423: if (defined($group)) {
11424: if ($file_name !~ m-^\Q$group\E/-) {
11425: next;
11426: }
11427: }
11428: if (ref($value) eq "ARRAY"){
11429: foreach my $stored_what (@{$value}) {
11430: if (ref($stored_what) eq 'ARRAY') {
11431: foreach my $lock_descriptor(@{$stored_what}) {
11432: if ($lock_descriptor eq 'graded') {
11433: $readonly_files{$file_name} = 'graded';
11434: } elsif ($lock_descriptor eq 'handback') {
11435: $readonly_files{$file_name} = 'handback';
11436: } else {
11437: if (!exists($readonly_files{$file_name})) {
11438: $readonly_files{$file_name} = 'locked';
11439: }
11440: }
11441: }
11442: }
11443: }
11444: }
11445: }
11446: return %readonly_files;
11447: }
11448: # ------------------------------------------------------------ Unmark as Read Only
11449:
11450: sub unmark_as_readonly {
11451: # unmarks $file_name (if $file_name is defined), or all files locked by $what
11452: # for portfolio submissions, $what contains [$symb,$crsid]
11453: my ($domain,$user,$what,$file_name,$group) = @_;
11454: $file_name = &declutter_portfile($file_name);
11455: my $symb_crs = $what;
11456: if (ref($what)) { $symb_crs=join('',@$what); }
11457: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
11458: my ($tmp)=keys(%current_permissions);
11459: if ($tmp=~/^error:/) { undef(%current_permissions); }
11460: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
11461: foreach my $file (@readonly_files) {
11462: my $clean_file = &declutter_portfile($file);
11463: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
11464: my $current_locks = $current_permissions{$file};
11465: my @new_locks;
11466: my @del_keys;
11467: if (ref($current_locks) eq "ARRAY"){
11468: foreach my $locker (@{$current_locks}) {
11469: my $compare=$locker;
11470: if (ref($locker) eq 'ARRAY') {
11471: $compare=join('',@{$locker});
11472: if ($compare ne $symb_crs) {
11473: push(@new_locks, $locker);
11474: }
11475: }
11476: }
11477: if (scalar(@new_locks) > 0) {
11478: $current_permissions{$file} = \@new_locks;
11479: } else {
11480: push(@del_keys, $file);
11481: &del('file_permissions',\@del_keys, $domain, $user);
11482: delete($current_permissions{$file});
11483: }
11484: }
11485: }
11486: &put('file_permissions',\%current_permissions,$domain,$user);
11487: return;
11488: }
11489:
11490: # ------------------------------------------------------------ Directory lister
11491:
11492: sub dirlist {
11493: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
11494: $uri=~s/^\///;
11495: $uri=~s/\/$//;
11496: my ($udom, $uname);
11497: if ($getuserdir) {
11498: $udom = $userdomain;
11499: $uname = $username;
11500: } else {
11501: (undef,$udom,$uname)=split(/\//,$uri);
11502: if(defined($userdomain)) {
11503: $udom = $userdomain;
11504: }
11505: if(defined($username)) {
11506: $uname = $username;
11507: }
11508: }
11509: my ($dirRoot,$listing,@listing_results);
11510:
11511: $dirRoot = $perlvar{'lonDocRoot'};
11512: if (defined($getpropath)) {
11513: $dirRoot = &propath($udom,$uname);
11514: $dirRoot =~ s/\/$//;
11515: } elsif (defined($getuserdir)) {
11516: my $subdir=$uname.'__';
11517: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11518: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11519: ."/$udom/$subdir/$uname";
11520: } elsif (defined($alternateRoot)) {
11521: $dirRoot = $alternateRoot;
11522: }
11523:
11524: if($udom) {
11525: if($uname) {
11526: my $uhome = &homeserver($uname,$udom);
11527: if ($uhome eq 'no_host') {
11528: return ([],'no_host');
11529: }
11530: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11531: .$getuserdir.':'.&escape($dirRoot)
11532: .':'.&escape($uname).':'.&escape($udom),$uhome);
11533: if ($listing eq 'unknown_cmd') {
11534: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11535: } else {
11536: @listing_results = map { &unescape($_); } split(/:/,$listing);
11537: }
11538: if ($listing eq 'unknown_cmd') {
11539: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11540: @listing_results = split(/:/,$listing);
11541: } else {
11542: @listing_results = map { &unescape($_); } split(/:/,$listing);
11543: }
11544: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11545: ($listing eq 'rejected') || ($listing eq 'refused') ||
11546: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11547: return ([],$listing);
11548: } else {
11549: return (\@listing_results);
11550: }
11551: } elsif(!$alternateRoot) {
11552: my (%allusers,%listerror);
11553: my %servers = &get_servers($udom,'library');
11554: foreach my $tryserver (keys(%servers)) {
11555: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11556: &escape($udom),$tryserver);
11557: if ($listing eq 'unknown_cmd') {
11558: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11559: $udom, $tryserver);
11560: } else {
11561: @listing_results = map { &unescape($_); } split(/:/,$listing);
11562: }
11563: if ($listing eq 'unknown_cmd') {
11564: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11565: $udom, $tryserver);
11566: @listing_results = split(/:/,$listing);
11567: } else {
11568: @listing_results =
11569: map { &unescape($_); } split(/:/,$listing);
11570: }
11571: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11572: ($listing eq 'rejected') || ($listing eq 'refused') ||
11573: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11574: $listerror{$tryserver} = $listing;
11575: } else {
11576: foreach my $line (@listing_results) {
11577: my ($entry) = split(/&/,$line,2);
11578: $allusers{$entry} = 1;
11579: }
11580: }
11581: }
11582: my @alluserslist=();
11583: foreach my $user (sort(keys(%allusers))) {
11584: push(@alluserslist,$user.'&user');
11585: }
11586:
11587: if (!%listerror) {
11588: # no errors
11589: return (\@alluserslist);
11590: } elsif (scalar(keys(%servers)) == 1) {
11591: # one library server, one error
11592: my ($key) = keys(%listerror);
11593: return (\@alluserslist, $listerror{$key});
11594: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11595: # con_lost indicates that we might miss data from at least one
11596: # library server
11597: return (\@alluserslist, 'con_lost');
11598: } else {
11599: # multiple library servers and no con_lost -> data should be
11600: # complete.
11601: return (\@alluserslist);
11602: }
11603:
11604: } else {
11605: return ([],'missing username');
11606: }
11607: } elsif(!defined($getpropath)) {
11608: my $path = $perlvar{'lonDocRoot'}.'/res/';
11609: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11610: return (\@all_domains);
11611: } else {
11612: return ([],'missing domain');
11613: }
11614: }
11615:
11616: # --------------------------------------------- GetFileTimestamp
11617: # This function utilizes dirlist and returns the date stamp for
11618: # when it was last modified. It will also return an error of -1
11619: # if an error occurs
11620:
11621: sub GetFileTimestamp {
11622: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11623: $studentDomain = &LONCAPA::clean_domain($studentDomain);
11624: $studentName = &LONCAPA::clean_username($studentName);
11625: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11626: undef,$getuserdir);
11627: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11628: return -1;
11629: }
11630: if (ref($fileref) eq 'ARRAY') {
11631: my @stats = split('&',$fileref->[0]);
11632: # @stats contains first the filename, then the stat output
11633: return $stats[10]; # so this is 10 instead of 9.
11634: } else {
11635: return -1;
11636: }
11637: }
11638:
11639: sub stat_file {
11640: my ($uri) = @_;
11641: $uri = &clutter_with_no_wrapper($uri);
11642:
11643: my ($udom,$uname,$file);
11644: if ($uri =~ m-^/(uploaded|editupload)/-) {
11645: ($udom,$uname,$file) =
11646: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11647: $file = 'userfiles/'.$file;
11648: }
11649: if ($uri =~ m-^/res/-) {
11650: ($udom,$uname) =
11651: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11652: $file = $uri;
11653: }
11654:
11655: if (!$udom || !$uname || !$file) {
11656: # unable to handle the uri
11657: return ();
11658: }
11659: my $getpropath;
11660: if ($file =~ /^userfiles\//) {
11661: $getpropath = 1;
11662: }
11663: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11664: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11665: return ();
11666: } else {
11667: if (ref($listref) eq 'ARRAY') {
11668: my @stats = split('&',$listref->[0]);
11669: shift(@stats); #filename is first
11670: return @stats;
11671: }
11672: }
11673: return ();
11674: }
11675:
11676: # --------------------------------------------------------- recursedirs
11677: # Recursive function to traverse either a specific user's Authoring Space
11678: # or corresponding Published Resource Space, and populate the hash ref:
11679: # $dirhashref with URLs of all directories, and if $filehashref hash
11680: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11681: # or .rights files in resource space, and .meta, .save, .log, and .bak
11682: # files in Authoring Space.
11683: #
11684: # Inputs:
11685: #
11686: # $is_home - true if current server is home server for user's space
11687: # $context - either: priv, or res respectively for Authoring or Resource Space.
11688: # $docroot - Document root (i.e., /home/httpd/html
11689: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11690: # $relpath - Current path (relative to top level).
11691: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11692: # $filehashref - reference to hash to populate with URLs of files (Optional)
11693: #
11694: # Returns: nothing
11695: #
11696: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11697: #
11698: # Currently used by interface/londocs.pm to create linked select boxes for
11699: # directory and filename to import a Course "Author" resource into a course, and
11700: # also to create linked select boxes for Authoring Space and Directory to choose
11701: # save location for creation of a new "standard" problem from the Course Editor.
11702: #
11703:
11704: sub recursedirs {
11705: my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11706: return unless (ref($dirhashref) eq 'HASH');
11707: my $currpath = $docroot.$toppath;
11708: if ($relpath) {
11709: $currpath .= "/$relpath";
11710: }
11711: my $savefile;
11712: if (ref($filehashref)) {
11713: $savefile = 1;
11714: }
11715: if ($is_home) {
11716: if (opendir(my $dirh,$currpath)) {
11717: foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11718: next if ($item eq '');
11719: if (-d "$currpath/$item") {
11720: my $newpath;
11721: if ($relpath) {
11722: $newpath = "$relpath/$item";
11723: } else {
11724: $newpath = $item;
11725: }
11726: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11727: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11728: } elsif ($savefile) {
11729: if ($context eq 'priv') {
11730: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11731: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11732: }
11733: } else {
11734: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11735: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11736: }
11737: }
11738: }
11739: }
11740: closedir($dirh);
11741: }
11742: } else {
11743: my ($dirlistref,$listerror) =
11744: &dirlist($toppath.$relpath);
11745: my @dir_lines;
11746: my $dirptr=16384;
11747: if (ref($dirlistref) eq 'ARRAY') {
11748: foreach my $dir_line (sort
11749: {
11750: my ($afile)=split('&',$a,2);
11751: my ($bfile)=split('&',$b,2);
11752: return (lc($afile) cmp lc($bfile));
11753: } (@{$dirlistref})) {
11754: my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11755: split(/\&/,$dir_line,16);
11756: $item =~ s/\s+$//;
11757: next if (($item =~ /^\.\.?$/) || ($obs));
11758: if ($dirptr&$testdir) {
11759: my $newpath;
11760: if ($relpath) {
11761: $newpath = "$relpath/$item";
11762: } else {
11763: $relpath = '/';
11764: $newpath = $item;
11765: }
11766: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11767: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11768: } elsif ($savefile) {
11769: if ($context eq 'priv') {
11770: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11771: $filehashref->{$relpath}{$item} = 1;
11772: }
11773: } else {
11774: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11775: $filehashref->{$relpath}{$item} = 1;
11776: }
11777: }
11778: }
11779: }
11780: }
11781: }
11782: return;
11783: }
11784:
11785: # -------------------------------------------------------- Value of a Condition
11786:
11787: # gets the value of a specific preevaluated condition
11788: # stored in the string $env{user.state.<cid>}
11789: # or looks up a condition reference in the bighash and if if hasn't
11790: # already been evaluated recurses into docondval to get the value of
11791: # the condition, then memoizing it to
11792: # $env{user.state.<cid>.<condition>}
11793: sub directcondval {
11794: my $number=shift;
11795: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11796: &Apache::lonuserstate::evalstate();
11797: }
11798: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11799: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11800: } elsif ($number =~ /^_/) {
11801: my $sub_condition;
11802: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11803: &GDBM_READER(),0640)) {
11804: $sub_condition=$bighash{'conditions'.$number};
11805: untie(%bighash);
11806: }
11807: my $value = &docondval($sub_condition);
11808: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11809: return $value;
11810: }
11811: if ($env{'user.state.'.$env{'request.course.id'}}) {
11812: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11813: } else {
11814: return 2;
11815: }
11816: }
11817:
11818: # get the collection of conditions for this resource
11819: sub condval {
11820: my $condidx=shift;
11821: my $allpathcond='';
11822: foreach my $cond (split(/\|/,$condidx)) {
11823: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11824: $allpathcond.=
11825: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11826: }
11827: }
11828: $allpathcond=~s/\|$//;
11829: return &docondval($allpathcond);
11830: }
11831:
11832: #evaluates an expression of conditions
11833: sub docondval {
11834: my ($allpathcond) = @_;
11835: my $result=0;
11836: if ($env{'request.course.id'}
11837: && defined($allpathcond)) {
11838: my $operand='|';
11839: my @stack;
11840: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11841: if ($chunk eq '(') {
11842: push @stack,($operand,$result);
11843: } elsif ($chunk eq ')') {
11844: my $before=pop @stack;
11845: if (pop @stack eq '&') {
11846: $result=$result>$before?$before:$result;
11847: } else {
11848: $result=$result>$before?$result:$before;
11849: }
11850: } elsif (($chunk eq '&') || ($chunk eq '|')) {
11851: $operand=$chunk;
11852: } else {
11853: my $new=directcondval($chunk);
11854: if ($operand eq '&') {
11855: $result=$result>$new?$new:$result;
11856: } else {
11857: $result=$result>$new?$result:$new;
11858: }
11859: }
11860: }
11861: }
11862: return $result;
11863: }
11864:
11865: # ---------------------------------------------------- Devalidate courseresdata
11866:
11867: sub devalidatecourseresdata {
11868: my ($coursenum,$coursedomain)=@_;
11869: my $hashid=$coursenum.':'.$coursedomain;
11870: &devalidate_cache_new('courseres',$hashid);
11871: }
11872:
11873:
11874: # --------------------------------------------------- Course Resourcedata Query
11875: #
11876: # Parameters:
11877: # $coursenum - Number of the course.
11878: # $coursedomain - Domain at which the course was created.
11879: # Returns:
11880: # A hash of the course parameters along (I think) with timestamps
11881: # and version info.
11882:
11883: sub get_courseresdata {
11884: my ($coursenum,$coursedomain)=@_;
11885: my $coursehom=&homeserver($coursenum,$coursedomain);
11886: my $hashid=$coursenum.':'.$coursedomain;
11887: my ($result,$cached)=&is_cached_new('courseres',$hashid);
11888: my %dumpreply;
11889: unless (defined($cached)) {
11890: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11891: $result=\%dumpreply;
11892: my ($tmp) = keys(%dumpreply);
11893: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11894: &do_cache_new('courseres',$hashid,$result,600);
11895: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11896: return $tmp;
11897: } elsif ($tmp =~ /^(error)/) {
11898: $result=undef;
11899: &do_cache_new('courseres',$hashid,$result,600);
11900: }
11901: }
11902: return $result;
11903: }
11904:
11905: sub devalidateuserresdata {
11906: my ($uname,$udom)=@_;
11907: my $hashid="$udom:$uname";
11908: &devalidate_cache_new('userres',$hashid);
11909: }
11910:
11911: sub get_userresdata {
11912: my ($uname,$udom)=@_;
11913: #most student don\'t have any data set, check if there is some data
11914: if (&EXT_cache_status($udom,$uname)) { return undef; }
11915:
11916: my $hashid="$udom:$uname";
11917: my ($result,$cached)=&is_cached_new('userres',$hashid);
11918: if (!defined($cached)) {
11919: my %resourcedata=&dump('resourcedata',$udom,$uname);
11920: $result=\%resourcedata;
11921: &do_cache_new('userres',$hashid,$result,600);
11922: }
11923: my ($tmp)=keys(%$result);
11924: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11925: return $result;
11926: }
11927: #error 2 occurs when the .db doesn't exist
11928: if ($tmp!~/error: 2 /) {
11929: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11930: &logthis("<font color=\"blue\">WARNING:".
11931: " Trying to get resource data for ".
11932: $uname." at ".$udom.": ".
11933: $tmp."</font>");
11934: }
11935: } elsif ($tmp=~/error: 2 /) {
11936: #&EXT_cache_set($udom,$uname);
11937: &do_cache_new('userres',$hashid,undef,600);
11938: undef($tmp); # not really an error so don't send it back
11939: }
11940: return $tmp;
11941: }
11942: #----------------------------------------------- resdata - return resource data
11943: # Purpose:
11944: # Return resource data for either users or for a course.
11945: # Parameters:
11946: # $name - Course/user name.
11947: # $domain - Name of the domain the user/course is registered on.
11948: # $type - Type of thing $name is (must be 'course' or 'user')
11949: # $mapp - decluttered URL of enclosing map
11950: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
11951: # $recurseup - Ref to array of map URLs, starting with map containing
11952: # $mapp up through hierarchy of nested maps to top level map.
11953: # $courseid - CourseID (first part of param identifier).
11954: # $modifier - Middle part of param identifier.
11955: # $what - Last part of param identifier.
11956: # @which - Array of names of resources desired.
11957: # Returns:
11958: # The value of the first reasource in @which that is found in the
11959: # resource hash.
11960: # Exceptional Conditions:
11961: # If the $type passed in is not valid (not the string 'course' or
11962: # 'user', an undefined reference is returned.
11963: # If none of the resources are found, an undef is returned
11964: sub resdata {
11965: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11966: $modifier,$what,@which)=@_;
11967: my $result;
11968: if ($type eq 'course') {
11969: $result=&get_courseresdata($name,$domain);
11970: } elsif ($type eq 'user') {
11971: $result=&get_userresdata($name,$domain);
11972: }
11973: if (!ref($result)) { return $result; }
11974: foreach my $item (@which) {
11975: if ($item->[1] eq 'course') {
11976: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11977: unless ($$recursed) {
11978: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11979: $$recursed = 1;
11980: }
11981: foreach my $item (@${recurseup}) {
11982: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11983: last if (defined($result->{$norecursechk}));
11984: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11985: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11986: }
11987: }
11988: }
11989: if (defined($result->{$item->[0]})) {
11990: return [$result->{$item->[0]},$item->[1]];
11991: }
11992: }
11993: return undef;
11994: }
11995:
11996: sub get_domain_lti {
11997: my ($cdom,$context) = @_;
11998: my ($name,%lti);
11999: if ($context eq 'consumer') {
12000: $name = 'ltitools';
12001: } elsif ($context eq 'provider') {
12002: $name = 'lti';
12003: } else {
12004: return %lti;
12005: }
12006: my ($result,$cached)=&is_cached_new($name,$cdom);
12007: if (defined($cached)) {
12008: if (ref($result) eq 'HASH') {
12009: %lti = %{$result};
12010: }
12011: } else {
12012: my %domconfig = &get_dom('configuration',[$name],$cdom);
12013: if (ref($domconfig{$name}) eq 'HASH') {
12014: %lti = %{$domconfig{$name}};
12015: my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
12016: if (ref($encdomconfig{$name}) eq 'HASH') {
12017: foreach my $id (keys(%lti)) {
12018: if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
12019: foreach my $item ('key','secret') {
12020: $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
12021: }
12022: }
12023: }
12024: }
12025: }
12026: my $cachetime = 24*60*60;
12027: &do_cache_new($name,$cdom,\%lti,$cachetime);
12028: }
12029: return %lti;
12030: }
12031:
12032: sub get_numsuppfiles {
12033: my ($cnum,$cdom,$ignorecache)=@_;
12034: my $hashid=$cnum.':'.$cdom;
12035: my ($suppcount,$cached);
12036: unless ($ignorecache) {
12037: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
12038: }
12039: unless (defined($cached)) {
12040: my $chome=&homeserver($cnum,$cdom);
12041: unless ($chome eq 'no_host') {
12042: ($suppcount,my $supptools,my $errors) = (0,0,0);
12043: my $suppmap = 'supplemental.sequence';
12044: ($suppcount,$supptools,$errors) =
12045: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
12046: $supptools,$errors);
12047: }
12048: &do_cache_new('suppcount',$hashid,$suppcount,600);
12049: }
12050: return $suppcount;
12051: }
12052:
12053: #
12054: # EXT resource caching routines
12055: #
12056:
12057: {
12058: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12059: #
12060: # The course for which we cache
12061: my $cachedmapkey='';
12062: # The cached recursive maps for this course
12063: my %cachedmaps=();
12064: # When this was last done
12065: my $cachedmaptime='';
12066:
12067: sub clear_EXT_cache_status {
12068: &delenv('cache.EXT.');
12069: }
12070:
12071: sub EXT_cache_status {
12072: my ($target_domain,$target_user) = @_;
12073: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12074: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
12075: # We know already the user has no data
12076: return 1;
12077: } else {
12078: return 0;
12079: }
12080: }
12081:
12082: sub EXT_cache_set {
12083: my ($target_domain,$target_user) = @_;
12084: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12085: #&appenv({$cachename => time});
12086: }
12087:
12088: # --------------------------------------------------------- Value of a Variable
12089: sub EXT {
12090:
12091: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
12092: unless ($varname) { return ''; }
12093: #get real user name/domain, courseid and symb
12094: my $courseid;
12095: my $publicuser;
12096: if ($symbparm) {
12097: $symbparm=&get_symb_from_alias($symbparm);
12098: }
12099: if (!($uname && $udom)) {
12100: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
12101: if (!$symbparm) { $symbparm=$cursymb; }
12102: } else {
12103: $courseid=$env{'request.course.id'};
12104: }
12105: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12106: my $rest;
12107: if (defined($therest[0])) {
12108: $rest=join('.',@therest);
12109: } else {
12110: $rest='';
12111: }
12112:
12113: my $qualifierrest=$qualifier;
12114: if ($rest) { $qualifierrest.='.'.$rest; }
12115: my $spacequalifierrest=$space;
12116: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
12117: if ($realm eq 'user') {
12118: # --------------------------------------------------------------- user.resource
12119: if ($space eq 'resource') {
12120: if ( (defined($Apache::lonhomework::parsing_a_problem)
12121: || defined($Apache::lonhomework::parsing_a_task))
12122: &&
12123: ($symbparm eq &symbread()) ) {
12124: # if we are in the middle of processing the resource the
12125: # get the value we are planning on committing
12126: if (defined($Apache::lonhomework::results{$qualifierrest})) {
12127: return $Apache::lonhomework::results{$qualifierrest};
12128: } else {
12129: return $Apache::lonhomework::history{$qualifierrest};
12130: }
12131: } else {
12132: my %restored;
12133: if ($publicuser || $env{'request.state'} eq 'construct') {
12134: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12135: } else {
12136: %restored=&restore($symbparm,$courseid,$udom,$uname);
12137: }
12138: return $restored{$qualifierrest};
12139: }
12140: # ----------------------------------------------------------------- user.access
12141: } elsif ($space eq 'access') {
12142: # FIXME - not supporting calls for a specific user
12143: return &allowed($qualifier,$rest);
12144: # ------------------------------------------ user.preferences, user.environment
12145: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
12146: if (($uname eq $env{'user.name'}) &&
12147: ($udom eq $env{'user.domain'})) {
12148: return $env{join('.',('environment',$qualifierrest))};
12149: } else {
12150: my %returnhash;
12151: if (!$publicuser) {
12152: %returnhash=&userenvironment($udom,$uname,
12153: $qualifierrest);
12154: }
12155: return $returnhash{$qualifierrest};
12156: }
12157: # ----------------------------------------------------------------- user.course
12158: } elsif ($space eq 'course') {
12159: # FIXME - not supporting calls for a specific user
12160: return $env{join('.',('request.course',$qualifier))};
12161: # ------------------------------------------------------------------- user.role
12162: } elsif ($space eq 'role') {
12163: # FIXME - not supporting calls for a specific user
12164: my ($role,$where)=split(/\./,$env{'request.role'});
12165: if ($qualifier eq 'value') {
12166: return $role;
12167: } elsif ($qualifier eq 'extent') {
12168: return $where;
12169: }
12170: # ----------------------------------------------------------------- user.domain
12171: } elsif ($space eq 'domain') {
12172: return $udom;
12173: # ------------------------------------------------------------------- user.name
12174: } elsif ($space eq 'name') {
12175: return $uname;
12176: # ---------------------------------------------------- Any other user namespace
12177: } else {
12178: my %reply;
12179: if (!$publicuser) {
12180: %reply=&get($space,[$qualifierrest],$udom,$uname);
12181: }
12182: return $reply{$qualifierrest};
12183: }
12184: } elsif ($realm eq 'query') {
12185: # ---------------------------------------------- pull stuff out of query string
12186: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12187: [$spacequalifierrest]);
12188: return $env{'form.'.$spacequalifierrest};
12189: } elsif ($realm eq 'request') {
12190: # ------------------------------------------------------------- request.browser
12191: if ($space eq 'browser') {
12192: return $env{'browser.'.$qualifier};
12193: # ------------------------------------------------------------ request.filename
12194: } else {
12195: return $env{'request.'.$spacequalifierrest};
12196: }
12197: } elsif ($realm eq 'course') {
12198: # ---------------------------------------------------------- course.description
12199: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
12200: } elsif ($realm eq 'resource') {
12201:
12202: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
12203: if (!$symbparm) { $symbparm=&symbread(); }
12204: }
12205:
12206: if ($qualifier eq '') {
12207: if ($space eq 'title') {
12208: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12209: return &gettitle($symbparm);
12210: }
12211:
12212: if ($space eq 'map') {
12213: my ($map) = &decode_symb($symbparm);
12214: return &symbread($map);
12215: }
12216: if ($space eq 'maptitle') {
12217: my ($map) = &decode_symb($symbparm);
12218: return &gettitle($map);
12219: }
12220: if ($space eq 'filename') {
12221: if ($symbparm) {
12222: return &clutter((&decode_symb($symbparm))[2]);
12223: }
12224: return &hreflocation('',$env{'request.filename'});
12225: }
12226:
12227: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12228: if ($space eq 'visibleparts') {
12229: my $navmap = Apache::lonnavmaps::navmap->new();
12230: my $item;
12231: if (ref($navmap)) {
12232: my $res = $navmap->getBySymb($symbparm);
12233: my $parts = $res->parts();
12234: if (ref($parts) eq 'ARRAY') {
12235: $item = join(',',@{$parts});
12236: }
12237: undef($navmap);
12238: }
12239: return $item;
12240: }
12241: }
12242: }
12243:
12244: my ($section, $group, @groups, @recurseup, $recursed);
12245: my ($courselevelm,$courseleveli,$courselevel,$mapp);
12246: if (($courseid eq '') && ($cid)) {
12247: $courseid = $cid;
12248: }
12249: if (($symbparm && $courseid) &&
12250: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
12251:
12252: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
12253:
12254: # ----------------------------------------------------- Cascading lookup scheme
12255: my $symbp=$symbparm;
12256: $mapp=&deversion((&decode_symb($symbp))[0]);
12257: my $symbparm=$symbp.'.'.$spacequalifierrest;
12258: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
12259: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
12260: if (($env{'user.name'} eq $uname) &&
12261: ($env{'user.domain'} eq $udom)) {
12262: $section=$env{'request.course.sec'};
12263: @groups = split(/:/,$env{'request.course.groups'});
12264: @groups=&sort_course_groups($courseid,@groups);
12265: } else {
12266: if (! defined($usection)) {
12267: $section=&getsection($udom,$uname,$courseid);
12268: } else {
12269: $section = $usection;
12270: }
12271: @groups = &get_users_groups($udom,$uname,$courseid);
12272: }
12273:
12274: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12275: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
12276: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
12277: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12278:
12279: $courselevel=$courseid.'.'.$spacequalifierrest;
12280: my $courselevelr=$courseid.'.'.$symbparm;
12281: $courseleveli=$courseid.'.'.$recurseparm;
12282: $courselevelm=$courseid.'.'.$mapparm;
12283:
12284: # ----------------------------------------------------------- first, check user
12285:
12286: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12287: \@recurseup,$courseid,'.',$spacequalifierrest,
12288: ([$courselevelr,'resource'],
12289: [$courselevelm,'map' ],
12290: [$courseleveli,'map' ],
12291: [$courselevel, 'course' ]));
12292: if (defined($userreply)) { return &get_reply($userreply); }
12293:
12294: # ------------------------------------------------ second, check some of course
12295: my $coursereply;
12296: if (@groups > 0) {
12297: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
12298: $recurseparm,$mapparm,$spacequalifierrest,
12299: $mapp,\$recursed,\@recurseup);
12300: if (defined($coursereply)) { return &get_reply($coursereply); }
12301: }
12302:
12303: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12304: $env{'course.'.$courseid.'.domain'},
12305: 'course',$mapp,\$recursed,\@recurseup,
12306: $courseid,'.['.$section.'].',$spacequalifierrest,
12307: ([$seclevelr, 'resource'],
12308: [$seclevelm, 'map' ],
12309: [$secleveli, 'map' ],
12310: [$seclevel, 'course' ],
12311: [$courselevelr,'resource']));
12312: if (defined($coursereply)) { return &get_reply($coursereply); }
12313:
12314: # ------------------------------------------------------ third, check map parms
12315: my %parmhash=();
12316: my $thisparm='';
12317: if (tie(%parmhash,'GDBM_File',
12318: $env{'request.course.fn'}.'_parms.db',
12319: &GDBM_READER(),0640)) {
12320: $thisparm=$parmhash{$symbparm};
12321: untie(%parmhash);
12322: }
12323: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
12324: }
12325: # ------------------------------------------ fourth, look in resource metadata
12326:
12327: my $what = $spacequalifierrest;
12328: $what=~s/\./\_/;
12329: my $filename;
12330: if (!$symbparm) { $symbparm=&symbread(); }
12331: if ($symbparm) {
12332: $filename=(&decode_symb($symbparm))[2];
12333: } else {
12334: $filename=$env{'request.filename'};
12335: }
12336: my $toolsymb;
12337: if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12338: $toolsymb = $symbparm;
12339: }
12340: my $metadata=&metadata($filename,$what,$toolsymb);
12341: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12342: $metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
12343: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12344:
12345: # ----------------------------------------------- fifth, look in rest of course
12346: if ($symbparm && defined($courseid) &&
12347: $courseid eq $env{'request.course.id'}) {
12348: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12349: $env{'course.'.$courseid.'.domain'},
12350: 'course',$mapp,\$recursed,\@recurseup,
12351: $courseid,'.',$spacequalifierrest,
12352: ([$courselevelm,'map' ],
12353: [$courseleveli,'map' ],
12354: [$courselevel, 'course']));
12355: if (defined($coursereply)) { return &get_reply($coursereply); }
12356: }
12357: # ------------------------------------------------------------------ Cascade up
12358: unless ($space eq '0') {
12359: my @parts=split(/_/,$space);
12360: my $id=pop(@parts);
12361: my $part=join('_',@parts);
12362: if ($part eq '') { $part='0'; }
12363: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
12364: $symbparm,$udom,$uname,$section,1);
12365: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
12366: }
12367: if ($recurse) { return undef; }
12368: my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
12369: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
12370: # ---------------------------------------------------- Any other user namespace
12371: } elsif ($realm eq 'environment') {
12372: # ----------------------------------------------------------------- environment
12373: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12374: return $env{'environment.'.$spacequalifierrest};
12375: } else {
12376: if ($uname eq 'anonymous' && $udom eq '') {
12377: return '';
12378: }
12379: my %returnhash=&userenvironment($udom,$uname,
12380: $spacequalifierrest);
12381: return $returnhash{$spacequalifierrest};
12382: }
12383: } elsif ($realm eq 'system') {
12384: # ----------------------------------------------------------------- system.time
12385: if ($space eq 'time') {
12386: return time;
12387: }
12388: } elsif ($realm eq 'server') {
12389: # ----------------------------------------------------------------- system.time
12390: if ($space eq 'name') {
12391: return $ENV{'SERVER_NAME'};
12392: }
12393: } elsif ($realm eq 'client') {
12394: if ($space eq 'remote_addr') {
12395: return $ENV{'REMOTE_ADDR'};
12396: }
12397: }
12398: return '';
12399: }
12400:
12401: sub get_reply {
12402: my ($reply_value) = @_;
12403: if (ref($reply_value) eq 'ARRAY') {
12404: if (wantarray) {
12405: return @$reply_value;
12406: }
12407: return $reply_value->[0];
12408: } else {
12409: return $reply_value;
12410: }
12411: }
12412:
12413: sub check_group_parms {
12414: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12415: $recursed,$recurseupref) = @_;
12416: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12417: [$what,'course']);
12418: my $coursereply;
12419: foreach my $group (@{$groups}) {
12420: my @groupitems = ();
12421: foreach my $level (@levels) {
12422: my $item = $courseid.'.['.$group.'].'.$level->[0];
12423: push(@groupitems,[$item,$level->[1]]);
12424: }
12425: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12426: $env{'course.'.$courseid.'.domain'},
12427: 'course',$mapp,$recursed,$recurseupref,
12428: $courseid,'.['.$group.'].',$what,
12429: @groupitems);
12430: last if (defined($coursereply));
12431: }
12432: return $coursereply;
12433: }
12434:
12435: sub get_map_hierarchy {
12436: my ($mapname,$courseid) = @_;
12437: my @recurseup = ();
12438: if ($mapname) {
12439: if (($cachedmapkey eq $courseid) &&
12440: (abs($cachedmaptime-time)<5)) {
12441: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12442: return @{$cachedmaps{$mapname}};
12443: }
12444: }
12445: my $navmap = Apache::lonnavmaps::navmap->new();
12446: if (ref($navmap)) {
12447: @recurseup = $navmap->recurseup_maps($mapname);
12448: undef($navmap);
12449: $cachedmaps{$mapname} = \@recurseup;
12450: $cachedmaptime=time;
12451: $cachedmapkey=$courseid;
12452: }
12453: }
12454: return @recurseup;
12455: }
12456:
12457: }
12458:
12459: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
12460: my ($courseid,@groups) = @_;
12461: @groups = sort(@groups);
12462: return @groups;
12463: }
12464:
12465: sub packages_tab_default {
12466: my ($uri,$varname,$toolsymb)=@_;
12467: my (undef,$part,$name)=split(/\./,$varname);
12468:
12469: my (@extension,@specifics,$do_default);
12470: foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
12471: my ($pack_type,$pack_part)=split(/_/,$package,2);
12472: if ($pack_type eq 'default') {
12473: $do_default=1;
12474: } elsif ($pack_type eq 'extension') {
12475: push(@extension,[$package,$pack_type,$pack_part]);
12476: } elsif ($pack_part eq $part || $pack_type eq 'part') {
12477: # only look at packages defaults for packages that this id is
12478: push(@specifics,[$package,$pack_type,$pack_part]);
12479: }
12480: }
12481: # first look for a package that matches the requested part id
12482: foreach my $package (@specifics) {
12483: my (undef,$pack_type,$pack_part)=@{$package};
12484: next if ($pack_part ne $part);
12485: if (defined($packagetab{"$pack_type&$name&default"})) {
12486: return $packagetab{"$pack_type&$name&default"};
12487: }
12488: }
12489: # look for any possible matching non extension_ package
12490: foreach my $package (@specifics) {
12491: my (undef,$pack_type,$pack_part)=@{$package};
12492: if (defined($packagetab{"$pack_type&$name&default"})) {
12493: return $packagetab{"$pack_type&$name&default"};
12494: }
12495: if ($pack_type eq 'part') { $pack_part='0'; }
12496: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12497: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
12498: }
12499: }
12500: # look for any posible extension_ match
12501: foreach my $package (@extension) {
12502: my ($package,$pack_type)=@{$package};
12503: if (defined($packagetab{"$pack_type&$name&default"})) {
12504: return $packagetab{"$pack_type&$name&default"};
12505: }
12506: if (defined($packagetab{$package."&$name&default"})) {
12507: return $packagetab{$package."&$name&default"};
12508: }
12509: }
12510: # look for a global default setting
12511: if ($do_default && defined($packagetab{"default&$name&default"})) {
12512: return $packagetab{"default&$name&default"};
12513: }
12514: return undef;
12515: }
12516:
12517: sub add_prefix_and_part {
12518: my ($prefix,$part)=@_;
12519: my $keyroot;
12520: if (defined($prefix) && $prefix !~ /^__/) {
12521: # prefix that has a part already
12522: $keyroot=$prefix;
12523: } elsif (defined($prefix)) {
12524: # prefix that is missing a part
12525: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12526: } else {
12527: # no prefix at all
12528: if (defined($part)) { $keyroot='_'.$part; }
12529: }
12530: return $keyroot;
12531: }
12532:
12533: # ---------------------------------------------------------------- Get metadata
12534:
12535: my %metaentry;
12536: my %importedpartids;
12537: my %importedrespids;
12538: sub metadata {
12539: my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
12540: $uri=&declutter($uri);
12541: # if it is a non metadata possible uri return quickly
12542: if (($uri eq '') ||
12543: (($uri =~ m|^/*adm/|) &&
12544: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
12545: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
12546: return undef;
12547: }
12548: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
12549: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
12550: return undef;
12551: }
12552: my $filename=$uri;
12553: $uri=~s/\.meta$//;
12554: #
12555: # Is the metadata already cached?
12556: # Look at timestamp of caching
12557: # Everything is cached by the main uri, libraries are never directly cached
12558: #
12559: if (!defined($liburi)) {
12560: my ($result,$cached)=&is_cached_new('meta',$uri);
12561: if (defined($cached)) { return $result->{':'.$what}; }
12562: }
12563:
12564: #
12565: # If the uri is for an external tool the file from
12566: # which metadata should be retrieved depends on whether
12567: # the tool had been configured to be gradable (set in the Course
12568: # Editor or Resource Editor).
12569: #
12570: # If a valid symb has been included as the third arg in the call
12571: # to &metadata() that can be used to retrieve the value of
12572: # parameter_0_gradable set for the resource, and included in the
12573: # uploaded map containing the tool. The value is retrieved via
12574: # &EXT(), if a valid symb is available. Otherwise the value of
12575: # gradable in the exttool_$marker.db file for the tool instance
12576: # is retrieved via &get().
12577: #
12578: # When lonuserstate::traceroute() calls lonnet::EXT() for
12579: # hiddenresource and encrypturl (during course initialization)
12580: # the map-level parameter for resource.0.gradable included in the
12581: # uploaded map containing the tool will not yet have been stored
12582: # in the user_course_parms.db file for the user's session, so in
12583: # this case fall back to retrieving gradable status from the
12584: # exttool_$marker.db file.
12585: #
12586: # In order to avoid an infinite loop, &metadata() will return
12587: # before a call to &EXT(), if the uri is for an external tool
12588: # and the $what for which metadata is being requested is
12589: # parameter_0_gradable or 0_gradable.
12590: #
12591:
12592: if ($uri =~ /ext\.tool$/) {
12593: if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12594: return;
12595: } else {
12596: my ($checked,$use_passback);
12597: if ($toolsymb ne '') {
12598: (undef,undef,my $tooluri) = &decode_symb($toolsymb);
12599: if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
12600: $checked = 1;
12601: if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12602: $use_passback = 1;
12603: }
12604: }
12605: }
12606: unless ($checked) {
12607: my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12608: $marker=~s/\D//g;
12609: if ($marker) {
12610: my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12611: $use_passback = $toolsettings{'gradable'};
12612: }
12613: }
12614: if ($use_passback) {
12615: $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12616: } else {
12617: $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12618: }
12619: }
12620: }
12621:
12622: {
12623: # Imported parts would go here
12624: my @origfiletagids=();
12625: my $importedparts=0;
12626:
12627: # Imported responseids would go here
12628: my $importedresponses=0;
12629: #
12630: # Is this a recursive call for a library?
12631: #
12632: # if (! exists($metacache{$uri})) {
12633: # $metacache{$uri}={};
12634: # }
12635: my $cachetime = 60*60;
12636: if ($liburi) {
12637: $liburi=&declutter($liburi);
12638: $filename=$liburi;
12639: } else {
12640: &devalidate_cache_new('meta',$uri);
12641: undef(%metaentry);
12642: }
12643: my %metathesekeys=();
12644: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
12645: my $metastring;
12646: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
12647: my $which = &hreflocation('','/'.($liburi || $uri));
12648: $metastring =
12649: &Apache::lonnet::ssi_body($which,
12650: ('grade_target' => 'meta'));
12651: $cachetime = 1; # only want this cached in the child not long term
12652: } elsif (($uri !~ m -^(editupload)/-) &&
12653: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
12654: my $file=&filelocation('',&clutter($filename));
12655: #push(@{$metaentry{$uri.'.file'}},$file);
12656: $metastring=&getfile($file);
12657: }
12658: my $parser=HTML::LCParser->new(\$metastring);
12659: my $token;
12660: undef %metathesekeys;
12661: while ($token=$parser->get_token) {
12662: if ($token->[0] eq 'S') {
12663: if (defined($token->[2]->{'package'})) {
12664: #
12665: # This is a package - get package info
12666: #
12667: my $package=$token->[2]->{'package'};
12668: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12669: if (defined($token->[2]->{'id'})) {
12670: $keyroot.='_'.$token->[2]->{'id'};
12671: }
12672: if ($metaentry{':packages'}) {
12673: $metaentry{':packages'}.=','.$package.$keyroot;
12674: } else {
12675: $metaentry{':packages'}=$package.$keyroot;
12676: }
12677: foreach my $pack_entry (keys(%packagetab)) {
12678: my $part=$keyroot;
12679: $part=~s/^\_//;
12680: if ($pack_entry=~/^\Q$package\E\&/ ||
12681: $pack_entry=~/^\Q$package\E_0\&/) {
12682: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
12683: # ignore package.tab specified default values
12684: # here &package_tab_default() will fetch those
12685: if ($subp eq 'default') { next; }
12686: my $value=$packagetab{$pack_entry};
12687: my $unikey;
12688: if ($pack =~ /_0$/) {
12689: $unikey='parameter_0_'.$name;
12690: $part=0;
12691: } else {
12692: $unikey='parameter'.$keyroot.'_'.$name;
12693: }
12694: if ($subp eq 'display') {
12695: $value.=' [Part: '.$part.']';
12696: }
12697: $metaentry{':'.$unikey.'.part'}=$part;
12698: $metathesekeys{$unikey}=1;
12699: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12700: $metaentry{':'.$unikey.'.'.$subp}=$value;
12701: }
12702: if (defined($metaentry{':'.$unikey.'.default'})) {
12703: $metaentry{':'.$unikey}=
12704: $metaentry{':'.$unikey.'.default'};
12705: }
12706: }
12707: }
12708: } else {
12709: #
12710: # This is not a package - some other kind of start tag
12711: #
12712: my $entry=$token->[1];
12713: my $unikey='';
12714:
12715: if ($entry eq 'import') {
12716: #
12717: # Importing a library here
12718: #
12719: my $location=$parser->get_text('/import');
12720: my $dir=$filename;
12721: $dir=~s|[^/]*$||;
12722: $location=&filelocation($dir,$location);
12723:
12724: my $importid=$token->[2]->{'id'};
12725: my $importmode=$token->[2]->{'importmode'};
12726: #
12727: # Check metadata for imported file to
12728: # see if it contained response items
12729: #
12730: my ($origfile,@libfilekeys);
12731: my %currmetaentry = %metaentry;
12732: @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12733: $depthcount+1));
12734: if (grep(/^responseorder$/,@libfilekeys)) {
12735: my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12736: undef,$depthcount+1);
12737: if ($libresponseorder ne '') {
12738: if ($#origfiletagids<0) {
12739: undef(%importedrespids);
12740: undef(%importedpartids);
12741: }
12742: my @respids = split(/\s*,\s*/,$libresponseorder);
12743: if (@respids) {
12744: $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12745: }
12746: if ($importedrespids{$importid} ne '') {
12747: $importedresponses = 1;
12748: # We need to get the original file and the imported file to get the response order correct
12749: # Load and inspect original file
12750: if ($#origfiletagids<0) {
12751: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12752: $origfile=&getfile($origfilelocation);
12753: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12754: }
12755: }
12756: }
12757: }
12758: # Do not overwrite contents of %metaentry hash for resource itself with
12759: # hash populated for imported library file
12760: %metaentry = %currmetaentry;
12761: undef(%currmetaentry);
12762: if ($importmode eq 'part') {
12763: # Import as part(s)
12764: $importedparts=1;
12765: # We need to get the original file and the imported file to get the part order correct
12766: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
12767: # Load and inspect original file if we didn't do that already
12768: if ($#origfiletagids<0) {
12769: undef(%importedrespids);
12770: undef(%importedpartids);
12771: if ($origfile eq '') {
12772: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12773: $origfile=&getfile($origfilelocation);
12774: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12775: }
12776: }
12777: my @impfilepartids;
12778: # If <partorder> tag is included in metadata for the imported file
12779: # get the parts in the imported file from that.
12780: if (grep(/^partorder$/,@libfilekeys)) {
12781: %currmetaentry = %metaentry;
12782: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12783: $depthcount+1);
12784: %metaentry = %currmetaentry;
12785: undef(%currmetaentry);
12786: if ($libpartorder ne '') {
12787: @impfilepartids=split(/\s*,\s*/,$libpartorder);
12788: }
12789: } else {
12790: # If no <partorder> tag available, load and inspect imported file
12791: my $impfile=&getfile($location);
12792: @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12793: }
12794: if ($#impfilepartids>=0) {
12795: # This problem had parts
12796: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12797: } else {
12798: # Importing by turning a single problem into a problem part
12799: # It gets the import-tags ID as part-ID
12800: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12801: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12802: }
12803: } else {
12804: # Import as problem or as normal import
12805: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12806: unless ($importmode eq 'problem') {
12807: # Normal import
12808: if (defined($token->[2]->{'id'})) {
12809: $unikey.='_'.$token->[2]->{'id'};
12810: }
12811: }
12812: # Check metadata for imported file to
12813: # see if it contained parts
12814: if (grep(/^partorder$/,@libfilekeys)) {
12815: %currmetaentry = %metaentry;
12816: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12817: $depthcount+1);
12818: %metaentry = %currmetaentry;
12819: undef(%currmetaentry);
12820: if ($libpartorder ne '') {
12821: $importedparts = 1;
12822: $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12823: }
12824: }
12825: }
12826: if ($depthcount<20) {
12827: my $metadata =
12828: &metadata($uri,'keys',$toolsymb,$location,$unikey,
12829: $depthcount+1);
12830: foreach my $meta (split(',',$metadata)) {
12831: $metaentry{':'.$meta}=$metaentry{':'.$meta};
12832: $metathesekeys{$meta}=1;
12833: }
12834: }
12835: } else {
12836: #
12837: # Not importing, some other kind of non-package, non-library start tag
12838: #
12839: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12840: if (defined($token->[2]->{'id'})) {
12841: $unikey.='_'.$token->[2]->{'id'};
12842: }
12843: if (defined($token->[2]->{'name'})) {
12844: $unikey.='_'.$token->[2]->{'name'};
12845: }
12846: $metathesekeys{$unikey}=1;
12847: foreach my $param (@{$token->[3]}) {
12848: $metaentry{':'.$unikey.'.'.$param} =
12849: $token->[2]->{$param};
12850: }
12851: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12852: my $default=$metaentry{':'.$unikey.'.default'};
12853: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12854: # only ws inside the tag, and not in default, so use default
12855: # as value
12856: $metaentry{':'.$unikey}=$default;
12857: } elsif ( $internaltext =~ /\S/ ) {
12858: # something interesting inside the tag
12859: $metaentry{':'.$unikey}=$internaltext;
12860: } else {
12861: # no interesting values, don't set a default
12862: }
12863: # end of not-a-package not-a-library import
12864: }
12865: # end of not-a-package start tag
12866: }
12867: # the next is the end of "start tag"
12868: }
12869: }
12870: my ($extension) = ($uri =~ /\.(\w+)$/);
12871: $extension = lc($extension);
12872: if ($extension eq 'htm') { $extension='html'; }
12873:
12874: foreach my $key (keys(%packagetab)) {
12875: #no specific packages #how's our extension
12876: if ($key!~/^extension_\Q$extension\E&/) { next; }
12877: &metadata_create_package_def($uri,$key,'extension_'.$extension,
12878: \%metathesekeys);
12879: }
12880:
12881: if (!exists($metaentry{':packages'})
12882: || $packagetab{"import_defaults&extension_$extension"}) {
12883: foreach my $key (keys(%packagetab)) {
12884: #no specific packages well let's get default then
12885: if ($key!~/^default&/) { next; }
12886: &metadata_create_package_def($uri,$key,'default',
12887: \%metathesekeys);
12888: }
12889: }
12890: # are there custom rights to evaluate
12891: if ($metaentry{':copyright'} eq 'custom') {
12892:
12893: #
12894: # Importing a rights file here
12895: #
12896: unless ($depthcount) {
12897: my $location=$metaentry{':customdistributionfile'};
12898: my $dir=$filename;
12899: $dir=~s|[^/]*$||;
12900: $location=&filelocation($dir,$location);
12901: my $rights_metadata =
12902: &metadata($uri,'keys',$toolsymb,$location,'_rights',
12903: $depthcount+1);
12904: foreach my $rights (split(',',$rights_metadata)) {
12905: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12906: $metathesekeys{$rights}=1;
12907: }
12908: }
12909: }
12910: # uniqifiy package listing
12911: my %seen;
12912: my @uniq_packages =
12913: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12914: $metaentry{':packages'} = join(',',@uniq_packages);
12915:
12916: if (($importedresponses) || ($importedparts)) {
12917: if ($importedparts) {
12918: # We had imported parts and need to rebuild partorder
12919: $metaentry{':partorder'}='';
12920: $metathesekeys{'partorder'}=1;
12921: }
12922: if ($importedresponses) {
12923: # We had imported responses and need to rebuil responseorder
12924: $metaentry{':responseorder'}='';
12925: $metathesekeys{'responseorder'}=1;
12926: }
12927: for (my $index=0;$index<$#origfiletagids;$index+=2) {
12928: my $origid = $origfiletagids[$index+1];
12929: if ($origfiletagids[$index] eq 'part') {
12930: # Original part, part of the problem
12931: if ($importedparts) {
12932: $metaentry{':partorder'}.=','.$origid;
12933: }
12934: } elsif ($origfiletagids[$index] eq 'import') {
12935: if ($importedparts) {
12936: # We have imported parts at this position
12937: if ($importedpartids{$origid} ne '') {
12938: $metaentry{':partorder'}.=','.$importedpartids{$origid};
12939: }
12940: }
12941: if ($importedresponses) {
12942: # We have imported responses at this position
12943: if ($importedrespids{$origid} ne '') {
12944: $metaentry{':responseorder'}.=','.$importedrespids{$origid};
12945: }
12946: }
12947: } else {
12948: # Original response item, part of the problem
12949: if ($importedresponses) {
12950: $metaentry{':responseorder'}.=','.$origid;
12951: }
12952: }
12953: }
12954: if ($importedparts) {
12955: $metaentry{':partorder'}=~s/^\,//;
12956: }
12957: if ($importedresponses) {
12958: $metaentry{':responseorder'}=~s/^\,//;
12959: }
12960: }
12961: $metaentry{':keys'} = join(',',keys(%metathesekeys));
12962: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12963: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12964: unless ($liburi) {
12965: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12966: }
12967: # this is the end of "was not already recently cached
12968: }
12969: return $metaentry{':'.$what};
12970: }
12971:
12972: sub metadata_create_package_def {
12973: my ($uri,$key,$package,$metathesekeys)=@_;
12974: my ($pack,$name,$subp)=split(/\&/,$key);
12975: if ($subp eq 'default') { next; }
12976:
12977: if (defined($metaentry{':packages'})) {
12978: $metaentry{':packages'}.=','.$package;
12979: } else {
12980: $metaentry{':packages'}=$package;
12981: }
12982: my $value=$packagetab{$key};
12983: my $unikey;
12984: $unikey='parameter_0_'.$name;
12985: $metaentry{':'.$unikey.'.part'}=0;
12986: $$metathesekeys{$unikey}=1;
12987: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12988: $metaentry{':'.$unikey.'.'.$subp}=$value;
12989: }
12990: if (defined($metaentry{':'.$unikey.'.default'})) {
12991: $metaentry{':'.$unikey}=
12992: $metaentry{':'.$unikey.'.default'};
12993: }
12994: }
12995:
12996: sub metadata_generate_part0 {
12997: my ($metadata,$metacache,$uri) = @_;
12998: my %allnames;
12999: foreach my $metakey (keys(%$metadata)) {
13000: if ($metakey=~/^parameter\_(.*)/) {
13001: my $part=$$metacache{':'.$metakey.'.part'};
13002: my $name=$$metacache{':'.$metakey.'.name'};
13003: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
13004: $allnames{$name}=$part;
13005: }
13006: }
13007: }
13008: foreach my $name (keys(%allnames)) {
13009: $$metadata{"parameter_0_$name"}=1;
13010: my $key=":parameter_0_$name";
13011: $$metacache{"$key.part"}='0';
13012: $$metacache{"$key.name"}=$name;
13013: $$metacache{"$key.type"}=$$metacache{':parameter_'.
13014: $allnames{$name}.'_'.$name.
13015: '.type'};
13016: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
13017: '.display'};
13018: my $expr='[Part: '.$allnames{$name}.']';
13019: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
13020: $$metacache{"$key.display"}=$olddis;
13021: }
13022: }
13023:
13024: # ------------------------------------------------------ Devalidate title cache
13025:
13026: sub devalidate_title_cache {
13027: my ($url)=@_;
13028: if (!$env{'request.course.id'}) { return; }
13029: my $symb=&symbread($url);
13030: if (!$symb) { return; }
13031: my $key=$env{'request.course.id'}."\0".$symb;
13032: &devalidate_cache_new('title',$key);
13033: }
13034:
13035: # ------------------------------------------------- Get the title of a course
13036:
13037: sub current_course_title {
13038: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
13039: }
13040: # ------------------------------------------------- Get the title of a resource
13041:
13042: sub gettitle {
13043: my $urlsymb=shift;
13044: my $symb=&symbread($urlsymb);
13045: if ($symb) {
13046: my $key=$env{'request.course.id'}."\0".$symb;
13047: my ($result,$cached)=&is_cached_new('title',$key);
13048: if (defined($cached)) {
13049: return $result;
13050: }
13051: my ($map,$resid,$url)=&decode_symb($symb);
13052: my $title='';
13053: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13054: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13055: } else {
13056: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13057: &GDBM_READER(),0640)) {
13058: my $mapid=$bighash{'map_pc_'.&clutter($map)};
13059: $title=$bighash{'title_'.$mapid.'.'.$resid};
13060: untie(%bighash);
13061: }
13062: }
13063: $title=~s/\&colon\;/\:/gs;
13064: if ($title) {
13065: # Remember both $symb and $title for dynamic metadata
13066: $accesshash{$symb.'___crstitle'}=$title;
13067: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
13068: # Cache this title and then return it
13069: return &do_cache_new('title',$key,$title,600);
13070: }
13071: $urlsymb=$url;
13072: }
13073: my $title=&metadata($urlsymb,'title');
13074: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
13075: return $title;
13076: }
13077:
13078: sub get_slot {
13079: my ($which,$cnum,$cdom)=@_;
13080: if (!$cnum || !$cdom) {
13081: (undef,my $courseid)=&whichuser();
13082: $cdom=$env{'course.'.$courseid.'.domain'};
13083: $cnum=$env{'course.'.$courseid.'.num'};
13084: }
13085: my $key=join("\0",'slots',$cdom,$cnum,$which);
13086: my %slotinfo;
13087: if (exists($remembered{$key})) {
13088: $slotinfo{$which} = $remembered{$key};
13089: } else {
13090: %slotinfo=&get('slots',[$which],$cdom,$cnum);
13091: &Apache::lonhomework::showhash(%slotinfo);
13092: my ($tmp)=keys(%slotinfo);
13093: if ($tmp=~/^error:/) { return (); }
13094: $remembered{$key} = $slotinfo{$which};
13095: }
13096: if (ref($slotinfo{$which}) eq 'HASH') {
13097: return %{$slotinfo{$which}};
13098: }
13099: return $slotinfo{$which};
13100: }
13101:
13102: sub get_reservable_slots {
13103: my ($cnum,$cdom,$uname,$udom) = @_;
13104: my $now = time;
13105: my $reservable_info;
13106: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13107: if (exists($remembered{$key})) {
13108: $reservable_info = $remembered{$key};
13109: } else {
13110: my %resv;
13111: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13112: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13113: $reservable_info = \%resv;
13114: $remembered{$key} = $reservable_info;
13115: }
13116: return $reservable_info;
13117: }
13118:
13119: sub get_course_slots {
13120: my ($cnum,$cdom) = @_;
13121: my $hashid=$cnum.':'.$cdom;
13122: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
13123: if (defined($cached)) {
13124: if (ref($result) eq 'HASH') {
13125: return %{$result};
13126: }
13127: } else {
13128: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
13129: my ($tmp) = keys(%slots);
13130: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
13131: &do_cache_new('allslots',$hashid,\%slots,600);
13132: return %slots;
13133: }
13134: }
13135: return;
13136: }
13137:
13138: sub devalidate_slots_cache {
13139: my ($cnum,$cdom)=@_;
13140: my $hashid=$cnum.':'.$cdom;
13141: &devalidate_cache_new('allslots',$hashid);
13142: }
13143:
13144: sub get_coursechange {
13145: my ($cdom,$cnum) = @_;
13146: if ($cdom eq '' || $cnum eq '') {
13147: return unless ($env{'request.course.id'});
13148: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13149: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13150: }
13151: my $hashid=$cdom.'_'.$cnum;
13152: my ($change,$cached)=&is_cached_new('crschange',$hashid);
13153: if ((defined($cached)) && ($change ne '')) {
13154: return $change;
13155: } else {
13156: my %crshash;
13157: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13158: if ($crshash{'internal.contentchange'} eq '') {
13159: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13160: if ($change eq '') {
13161: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13162: $change = $crshash{'internal.created'};
13163: }
13164: } else {
13165: $change = $crshash{'internal.contentchange'};
13166: }
13167: my $cachetime = 600;
13168: &do_cache_new('crschange',$hashid,$change,$cachetime);
13169: }
13170: return $change;
13171: }
13172:
13173: sub devalidate_coursechange_cache {
13174: my ($cnum,$cdom)=@_;
13175: my $hashid=$cnum.':'.$cdom;
13176: &devalidate_cache_new('crschange',$hashid);
13177: }
13178:
13179: # ------------------------------------------------- Update symbolic store links
13180:
13181: sub symblist {
13182: my ($mapname,%newhash)=@_;
13183: $mapname=&deversion(&declutter($mapname));
13184: my %hash;
13185: if (($env{'request.course.fn'}) && (%newhash)) {
13186: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13187: &GDBM_WRCREAT(),0640)) {
13188: foreach my $url (keys(%newhash)) {
13189: next if ($url eq 'last_known'
13190: && $env{'form.no_update_last_known'});
13191: $hash{declutter($url)}=&encode_symb($mapname,
13192: $newhash{$url}->[1],
13193: $newhash{$url}->[0]);
13194: }
13195: if (untie(%hash)) {
13196: return 'ok';
13197: }
13198: }
13199: }
13200: return 'error';
13201: }
13202:
13203: # --------------------------------------------------------------- Verify a symb
13204:
13205: sub symbverify {
13206: my ($symb,$thisurl,$encstate)=@_;
13207: my $thisfn=$thisurl;
13208: $thisfn=&declutter($thisfn);
13209: # direct jump to resource in page or to a sequence - will construct own symbs
13210: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13211: # check URL part
13212: my ($map,$resid,$url)=&decode_symb($symb);
13213:
13214: unless ($url eq $thisfn) { return 0; }
13215:
13216: $symb=&symbclean($symb);
13217: $thisurl=&deversion($thisurl);
13218: $thisfn=&deversion($thisfn);
13219:
13220: my %bighash;
13221: my $okay=0;
13222:
13223: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13224: &GDBM_READER(),0640)) {
13225: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13226: $thisurl =~ s/\?.+$//;
13227: if ($map =~ m{^uploaded/.+\.page$}) {
13228: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13229: $thisurl =~ s{^\Qhttp://https://\E}{https://};
13230: }
13231: }
13232: my $ids;
13233: if ($map =~ m{^uploaded/.+\.page$}) {
13234: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
13235: } else {
13236: $ids=$bighash{'ids_'.&clutter($thisurl)};
13237: }
13238: unless ($ids) {
13239: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
13240: $ids=$bighash{$idkey};
13241: }
13242: if ($ids) {
13243: # ------------------------------------------------------------------- Has ID(s)
13244: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
13245: $symb =~ s/\?.+$//;
13246: }
13247: foreach my $id (split(/\,/,$ids)) {
13248: my ($mapid,$resid)=split(/\./,$id);
13249: if (
13250: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
13251: eq $symb) {
13252: if (ref($encstate)) {
13253: $$encstate = $bighash{'encrypted_'.$id};
13254: }
13255: if (($env{'request.role.adv'}) ||
13256: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13257: ($thisurl eq '/adm/navmaps')) {
13258: $okay=1;
13259: last;
13260: }
13261: }
13262: }
13263: }
13264: untie(%bighash);
13265: }
13266: return $okay;
13267: }
13268:
13269: # --------------------------------------------------------------- Clean-up symb
13270:
13271: sub symbclean {
13272: my $symb=shift;
13273: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13274: # remove version from map
13275: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
13276:
13277: # remove version from URL
13278: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
13279:
13280: # remove wrapper
13281:
13282: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
13283: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
13284: return $symb;
13285: }
13286:
13287: # ---------------------------------------------- Split symb to find map and url
13288:
13289: sub encode_symb {
13290: my ($map,$resid,$url)=@_;
13291: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13292: }
13293:
13294: sub decode_symb {
13295: my $symb=shift;
13296: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13297: my ($map,$resid,$url)=split(/___/,$symb);
13298: return (&fixversion($map),$resid,&fixversion($url));
13299: }
13300:
13301: sub fixversion {
13302: my $fn=shift;
13303: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
13304: my %bighash;
13305: my $uri=&clutter($fn);
13306: my $key=$env{'request.course.id'}.'_'.$uri;
13307: # is this cached?
13308: my ($result,$cached)=&is_cached_new('courseresversion',$key);
13309: if (defined($cached)) { return $result; }
13310: # unfortunately not cached, or expired
13311: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13312: &GDBM_READER(),0640)) {
13313: if ($bighash{'version_'.$uri}) {
13314: my $version=$bighash{'version_'.$uri};
13315: unless (($version eq 'mostrecent') ||
13316: ($version==&getversion($uri))) {
13317: $uri=~s/\.(\w+)$/\.$version\.$1/;
13318: }
13319: }
13320: untie %bighash;
13321: }
13322: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
13323: }
13324:
13325: sub deversion {
13326: my $url=shift;
13327: $url=~s/\.\d+\.(\w+)$/\.$1/;
13328: return $url;
13329: }
13330:
13331: # ------------------------------------------------------ Return symb list entry
13332:
13333: sub symbread {
13334: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
13335: $ignoresymbdb,$noenccheck)=@_;
13336: my $cache_str='request.symbread.cached.'.$thisfn;
13337: if (defined($env{$cache_str})) {
13338: unless (ref($possibles) eq 'HASH') {
13339: if ($ignorecachednull) {
13340: return $env{$cache_str} unless ($env{$cache_str} eq '');
13341: } else {
13342: return $env{$cache_str};
13343: }
13344: }
13345: }
13346: # no filename provided? try from environment
13347: unless ($thisfn) {
13348: if ($env{'request.symb'}) {
13349: return $env{$cache_str}=&symbclean($env{'request.symb'});
13350: }
13351: $thisfn=$env{'request.filename'};
13352: }
13353: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13354: # is that filename actually a symb? Verify, clean, and return
13355: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
13356: if (&symbverify($thisfn,$1)) {
13357: return $env{$cache_str}=&symbclean($thisfn);
13358: }
13359: }
13360: $thisfn=declutter($thisfn);
13361: my %hash;
13362: my %bighash;
13363: my $syval='';
13364: if (($env{'request.course.fn'}) && ($thisfn)) {
13365: my $targetfn = $thisfn;
13366: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
13367: $targetfn = 'adm/wrapper/'.$thisfn;
13368: }
13369: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
13370: $targetfn=$1;
13371: }
13372: unless ($ignoresymbdb) {
13373: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13374: &GDBM_READER(),0640)) {
13375: $syval=$hash{$targetfn};
13376: untie(%hash);
13377: }
13378: if ($syval && $checkforblock) {
13379: my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
13380: if (@blockers) {
13381: $syval='';
13382: }
13383: }
13384: }
13385: # ---------------------------------------------------------- There was an entry
13386: if ($syval) {
13387: #unless ($syval=~/\_\d+$/) {
13388: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
13389: #&appenv({'request.ambiguous' => $thisfn});
13390: #return $env{$cache_str}='';
13391: #}
13392: #$syval.=$1;
13393: #}
13394: } else {
13395: # ------------------------------------------------------- Was not in symb table
13396: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13397: &GDBM_READER(),0640)) {
13398: # ---------------------------------------------- Get ID(s) for current resource
13399: my $ids=$bighash{'ids_'.&clutter($thisfn)};
13400: unless ($ids) {
13401: $ids=$bighash{'ids_/'.$thisfn};
13402: }
13403: unless ($ids) {
13404: # alias?
13405: $ids=$bighash{'mapalias_'.$thisfn};
13406: }
13407: if ($ids) {
13408: # ------------------------------------------------------------------- Has ID(s)
13409: my @possibilities=split(/\,/,$ids);
13410: if ($#possibilities==0) {
13411: # ----------------------------------------------- There is only one possibility
13412: my ($mapid,$resid)=split(/\./,$ids);
13413: $syval=&encode_symb($bighash{'map_id_'.$mapid},
13414: $resid,$thisfn);
13415: if (ref($possibles) eq 'HASH') {
13416: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13417: $possibles->{$syval} = 1;
13418: }
13419: }
13420: if ($checkforblock) {
13421: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13422: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
13423: if (@blockers) {
13424: $syval = '';
13425: untie(%bighash);
13426: return $env{$cache_str}='';
13427: }
13428: }
13429: }
13430: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13431: # ------------------------------------------ There is more than one possibility
13432: my $realpossible=0;
13433: foreach my $id (@possibilities) {
13434: my $file=$bighash{'src_'.$id};
13435: my $canaccess;
13436: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13437: $canaccess = 1;
13438: } else {
13439: $canaccess = &allowed('bre',$file);
13440: }
13441: if ($canaccess) {
13442: my ($mapid,$resid)=split(/\./,$id);
13443: if ($bighash{'map_type_'.$mapid} ne 'page') {
13444: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13445: $resid,$thisfn);
13446: next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
13447: next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
13448: if ($checkforblock) {
13449: my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
13450: if (@blockers > 0) {
13451: $syval = '';
13452: } else {
13453: $syval = $poss_syval;
13454: $realpossible++;
13455: }
13456: } else {
13457: $syval = $poss_syval;
13458: $realpossible++;
13459: }
13460: if ($syval) {
13461: if (ref($possibles) eq 'HASH') {
13462: $possibles->{$syval} = 1;
13463: }
13464: }
13465: }
13466: }
13467: }
13468: if ($realpossible!=1) { $syval=''; }
13469: } else {
13470: $syval='';
13471: }
13472: }
13473: untie(%bighash);
13474: }
13475: }
13476: if ($syval) {
13477: return $env{$cache_str}=$syval;
13478: }
13479: }
13480: &appenv({'request.ambiguous' => $thisfn});
13481: return $env{$cache_str}='';
13482: }
13483:
13484: # ---------------------------------------------------------- Return random seed
13485:
13486: sub numval {
13487: my $txt=shift;
13488: $txt=~tr/A-J/0-9/;
13489: $txt=~tr/a-j/0-9/;
13490: $txt=~tr/K-T/0-9/;
13491: $txt=~tr/k-t/0-9/;
13492: $txt=~tr/U-Z/0-5/;
13493: $txt=~tr/u-z/0-5/;
13494: $txt=~s/\D//g;
13495: if ($_64bit) { if ($txt > 2**32) { return -1; } }
13496: return int($txt);
13497: }
13498:
13499: sub numval2 {
13500: my $txt=shift;
13501: $txt=~tr/A-J/0-9/;
13502: $txt=~tr/a-j/0-9/;
13503: $txt=~tr/K-T/0-9/;
13504: $txt=~tr/k-t/0-9/;
13505: $txt=~tr/U-Z/0-5/;
13506: $txt=~tr/u-z/0-5/;
13507: $txt=~s/\D//g;
13508: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13509: my $total;
13510: foreach my $val (@txts) { $total+=$val; }
13511: if ($_64bit) { if ($total > 2**32) { return -1; } }
13512: return int($total);
13513: }
13514:
13515: sub numval3 {
13516: use integer;
13517: my $txt=shift;
13518: $txt=~tr/A-J/0-9/;
13519: $txt=~tr/a-j/0-9/;
13520: $txt=~tr/K-T/0-9/;
13521: $txt=~tr/k-t/0-9/;
13522: $txt=~tr/U-Z/0-5/;
13523: $txt=~tr/u-z/0-5/;
13524: $txt=~s/\D//g;
13525: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13526: my $total;
13527: foreach my $val (@txts) { $total+=$val; }
13528: if ($_64bit) { $total=(($total<<32)>>32); }
13529: return $total;
13530: }
13531:
13532: sub digest {
13533: my ($data)=@_;
13534: my $digest=&Digest::MD5::md5($data);
13535: my ($a,$b,$c,$d)=unpack("iiii",$digest);
13536: my ($e,$f);
13537: {
13538: use integer;
13539: $e=($a+$b);
13540: $f=($c+$d);
13541: if ($_64bit) {
13542: $e=(($e<<32)>>32);
13543: $f=(($f<<32)>>32);
13544: }
13545: }
13546: if (wantarray) {
13547: return ($e,$f);
13548: } else {
13549: my $g;
13550: {
13551: use integer;
13552: $g=($e+$f);
13553: if ($_64bit) {
13554: $g=(($g<<32)>>32);
13555: }
13556: }
13557: return $g;
13558: }
13559: }
13560:
13561: sub latest_rnd_algorithm_id {
13562: return '64bit5';
13563: }
13564:
13565: sub get_rand_alg {
13566: my ($courseid)=@_;
13567: if (!$courseid) { $courseid=(&whichuser())[1]; }
13568: if ($courseid) {
13569: return $env{"course.$courseid.rndseed"};
13570: }
13571: return &latest_rnd_algorithm_id();
13572: }
13573:
13574: sub validCODE {
13575: my ($CODE)=@_;
13576: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13577: return 0;
13578: }
13579:
13580: sub getCODE {
13581: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
13582: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13583: defined($Apache::lonhomework::parsing_a_task) ) &&
13584: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
13585: return $Apache::lonhomework::history{'resource.CODE'};
13586: }
13587: return undef;
13588: }
13589: #
13590: # Determines the random seed for a specific context:
13591: #
13592: # parameters:
13593: # symb - in course context the symb for the seed.
13594: # course_id - The course id of the form domain_coursenum.
13595: # domain - Domain for the user.
13596: # course - Course for the user.
13597: # cenv - environment of the course.
13598: #
13599: # NOTE:
13600: # All parameters are picked out of the environment if missing
13601: # or not defined.
13602: # If a symb cannot be determined the current time is used instead.
13603: #
13604: # For a given well defined symb, courside, domain, username,
13605: # and course environment, the seed is reproducible.
13606: #
13607: sub rndseed {
13608: my ($symb,$courseid,$domain,$username, $cenv)=@_;
13609: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
13610: if (!defined($symb)) {
13611: unless ($symb=$wsymb) { return time; }
13612: }
13613: if (!defined $courseid) {
13614: $courseid=$wcourseid;
13615: }
13616: if (!defined $domain) { $domain=$wdomain; }
13617: if (!defined $username) { $username=$wusername }
13618:
13619: my $which;
13620: if (defined($cenv->{'rndseed'})) {
13621: $which = $cenv->{'rndseed'};
13622: } else {
13623: $which =&get_rand_alg($courseid);
13624: }
13625: if (defined(&getCODE())) {
13626:
13627: if ($which eq '64bit5') {
13628: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
13629: } elsif ($which eq '64bit4') {
13630: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
13631: } else {
13632: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
13633: }
13634: } elsif ($which eq '64bit5') {
13635: return &rndseed_64bit5($symb,$courseid,$domain,$username);
13636: } elsif ($which eq '64bit4') {
13637: return &rndseed_64bit4($symb,$courseid,$domain,$username);
13638: } elsif ($which eq '64bit3') {
13639: return &rndseed_64bit3($symb,$courseid,$domain,$username);
13640: } elsif ($which eq '64bit2') {
13641: return &rndseed_64bit2($symb,$courseid,$domain,$username);
13642: } elsif ($which eq '64bit') {
13643: return &rndseed_64bit($symb,$courseid,$domain,$username);
13644: }
13645: return &rndseed_32bit($symb,$courseid,$domain,$username);
13646: }
13647:
13648: sub rndseed_32bit {
13649: my ($symb,$courseid,$domain,$username)=@_;
13650: {
13651: use integer;
13652: my $symbchck=unpack("%32C*",$symb) << 27;
13653: my $symbseed=numval($symb) << 22;
13654: my $namechck=unpack("%32C*",$username) << 17;
13655: my $nameseed=numval($username) << 12;
13656: my $domainseed=unpack("%32C*",$domain) << 7;
13657: my $courseseed=unpack("%32C*",$courseid);
13658: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
13659: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13660: #&logthis("rndseed :$num:$symb");
13661: if ($_64bit) { $num=(($num<<32)>>32); }
13662: return $num;
13663: }
13664: }
13665:
13666: sub rndseed_64bit {
13667: my ($symb,$courseid,$domain,$username)=@_;
13668: {
13669: use integer;
13670: my $symbchck=unpack("%32S*",$symb) << 21;
13671: my $symbseed=numval($symb) << 10;
13672: my $namechck=unpack("%32S*",$username);
13673:
13674: my $nameseed=numval($username) << 21;
13675: my $domainseed=unpack("%32S*",$domain) << 10;
13676: my $courseseed=unpack("%32S*",$courseid);
13677:
13678: my $num1=$symbchck+$symbseed+$namechck;
13679: my $num2=$nameseed+$domainseed+$courseseed;
13680: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13681: #&logthis("rndseed :$num:$symb");
13682: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13683: return "$num1,$num2";
13684: }
13685: }
13686:
13687: sub rndseed_64bit2 {
13688: my ($symb,$courseid,$domain,$username)=@_;
13689: {
13690: use integer;
13691: # strings need to be an even # of cahracters long, it it is odd the
13692: # last characters gets thrown away
13693: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13694: my $symbseed=numval($symb) << 10;
13695: my $namechck=unpack("%32S*",$username.' ');
13696:
13697: my $nameseed=numval($username) << 21;
13698: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13699: my $courseseed=unpack("%32S*",$courseid.' ');
13700:
13701: my $num1=$symbchck+$symbseed+$namechck;
13702: my $num2=$nameseed+$domainseed+$courseseed;
13703: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13704: #&logthis("rndseed :$num:$symb");
13705: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13706: return "$num1,$num2";
13707: }
13708: }
13709:
13710: sub rndseed_64bit3 {
13711: my ($symb,$courseid,$domain,$username)=@_;
13712: {
13713: use integer;
13714: # strings need to be an even # of cahracters long, it it is odd the
13715: # last characters gets thrown away
13716: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13717: my $symbseed=numval2($symb) << 10;
13718: my $namechck=unpack("%32S*",$username.' ');
13719:
13720: my $nameseed=numval2($username) << 21;
13721: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13722: my $courseseed=unpack("%32S*",$courseid.' ');
13723:
13724: my $num1=$symbchck+$symbseed+$namechck;
13725: my $num2=$nameseed+$domainseed+$courseseed;
13726: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13727: #&logthis("rndseed :$num1:$num2:$_64bit");
13728: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13729:
13730: return "$num1:$num2";
13731: }
13732: }
13733:
13734: sub rndseed_64bit4 {
13735: my ($symb,$courseid,$domain,$username)=@_;
13736: {
13737: use integer;
13738: # strings need to be an even # of cahracters long, it it is odd the
13739: # last characters gets thrown away
13740: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13741: my $symbseed=numval3($symb) << 10;
13742: my $namechck=unpack("%32S*",$username.' ');
13743:
13744: my $nameseed=numval3($username) << 21;
13745: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13746: my $courseseed=unpack("%32S*",$courseid.' ');
13747:
13748: my $num1=$symbchck+$symbseed+$namechck;
13749: my $num2=$nameseed+$domainseed+$courseseed;
13750: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13751: #&logthis("rndseed :$num1:$num2:$_64bit");
13752: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13753:
13754: return "$num1:$num2";
13755: }
13756: }
13757:
13758: sub rndseed_64bit5 {
13759: my ($symb,$courseid,$domain,$username)=@_;
13760: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13761: return "$num1:$num2";
13762: }
13763:
13764: sub rndseed_CODE_64bit {
13765: my ($symb,$courseid,$domain,$username)=@_;
13766: {
13767: use integer;
13768: my $symbchck=unpack("%32S*",$symb.' ') << 16;
13769: my $symbseed=numval2($symb);
13770: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13771: my $CODEseed=numval(&getCODE());
13772: my $courseseed=unpack("%32S*",$courseid.' ');
13773: my $num1=$symbseed+$CODEchck;
13774: my $num2=$CODEseed+$courseseed+$symbchck;
13775: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13776: #&logthis("rndseed :$num1:$num2:$symb");
13777: if ($_64bit) { $num1=(($num1<<32)>>32); }
13778: if ($_64bit) { $num2=(($num2<<32)>>32); }
13779: return "$num1:$num2";
13780: }
13781: }
13782:
13783: sub rndseed_CODE_64bit4 {
13784: my ($symb,$courseid,$domain,$username)=@_;
13785: {
13786: use integer;
13787: my $symbchck=unpack("%32S*",$symb.' ') << 16;
13788: my $symbseed=numval3($symb);
13789: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13790: my $CODEseed=numval3(&getCODE());
13791: my $courseseed=unpack("%32S*",$courseid.' ');
13792: my $num1=$symbseed+$CODEchck;
13793: my $num2=$CODEseed+$courseseed+$symbchck;
13794: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13795: #&logthis("rndseed :$num1:$num2:$symb");
13796: if ($_64bit) { $num1=(($num1<<32)>>32); }
13797: if ($_64bit) { $num2=(($num2<<32)>>32); }
13798: return "$num1:$num2";
13799: }
13800: }
13801:
13802: sub rndseed_CODE_64bit5 {
13803: my ($symb,$courseid,$domain,$username)=@_;
13804: my $code = &getCODE();
13805: my ($num1,$num2)=&digest("$symb,$courseid,$code");
13806: return "$num1:$num2";
13807: }
13808:
13809: sub setup_random_from_rndseed {
13810: my ($rndseed)=@_;
13811: if ($rndseed =~/([,:])/) {
13812: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13813: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13814: &Math::Random::random_set_seed_from_phrase($rndseed);
13815: } else {
13816: &Math::Random::random_set_seed($num1,$num2);
13817: }
13818: } else {
13819: &Math::Random::random_set_seed_from_phrase($rndseed);
13820: }
13821: }
13822:
13823: sub latest_receipt_algorithm_id {
13824: return 'receipt3';
13825: }
13826:
13827: sub recunique {
13828: my $fucourseid=shift;
13829: my $unique;
13830: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13831: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13832: $unique=$env{"course.$fucourseid.internal.encseed"};
13833: } else {
13834: $unique=$perlvar{'lonReceipt'};
13835: }
13836: return unpack("%32C*",$unique);
13837: }
13838:
13839: sub recprefix {
13840: my $fucourseid=shift;
13841: my $prefix;
13842: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13843: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13844: $prefix=$env{"course.$fucourseid.internal.encpref"};
13845: } else {
13846: $prefix=$perlvar{'lonHostID'};
13847: }
13848: return unpack("%32C*",$prefix);
13849: }
13850:
13851: sub ireceipt {
13852: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13853:
13854: my $return =&recprefix($fucourseid).'-';
13855:
13856: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13857: $env{'request.state'} eq 'construct') {
13858: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13859: return $return;
13860: }
13861:
13862: my $cuname=unpack("%32C*",$funame);
13863: my $cudom=unpack("%32C*",$fudom);
13864: my $cucourseid=unpack("%32C*",$fucourseid);
13865: my $cusymb=unpack("%32C*",$fusymb);
13866: my $cunique=&recunique($fucourseid);
13867: my $cpart=unpack("%32S*",$part);
13868: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13869:
13870: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
13871:
13872: $return.= ($cunique%$cuname+
13873: $cunique%$cudom+
13874: $cusymb%$cuname+
13875: $cusymb%$cudom+
13876: $cucourseid%$cuname+
13877: $cucourseid%$cudom+
13878: $cpart%$cuname+
13879: $cpart%$cudom);
13880: } else {
13881: $return.= ($cunique%$cuname+
13882: $cunique%$cudom+
13883: $cusymb%$cuname+
13884: $cusymb%$cudom+
13885: $cucourseid%$cuname+
13886: $cucourseid%$cudom);
13887: }
13888: return $return;
13889: }
13890:
13891: sub receipt {
13892: my ($part)=@_;
13893: my ($symb,$courseid,$domain,$name) = &whichuser();
13894: return &ireceipt($name,$domain,$courseid,$symb,$part);
13895: }
13896:
13897: sub whichuser {
13898: my ($passedsymb)=@_;
13899: my ($symb,$courseid,$domain,$name,$publicuser);
13900: if (defined($env{'form.grade_symb'})) {
13901: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13902: my $allowed=&allowed('vgr',$tmp_courseid);
13903: if (!$allowed &&
13904: exists($env{'request.course.sec'}) &&
13905: $env{'request.course.sec'} !~ /^\s*$/) {
13906: $allowed=&allowed('vgr',$tmp_courseid.
13907: '/'.$env{'request.course.sec'});
13908: }
13909: if ($allowed) {
13910: ($symb)=&get_env_multiple('form.grade_symb');
13911: $courseid=$tmp_courseid;
13912: ($domain)=&get_env_multiple('form.grade_domain');
13913: ($name)=&get_env_multiple('form.grade_username');
13914: return ($symb,$courseid,$domain,$name,$publicuser);
13915: }
13916: }
13917: if (!$passedsymb) {
13918: $symb=&symbread();
13919: } else {
13920: $symb=$passedsymb;
13921: }
13922: $courseid=$env{'request.course.id'};
13923: $domain=$env{'user.domain'};
13924: $name=$env{'user.name'};
13925: if ($name eq 'public' && $domain eq 'public') {
13926: if (!defined($env{'form.username'})) {
13927: $env{'form.username'}.=time.rand(10000000);
13928: }
13929: $name.=$env{'form.username'};
13930: }
13931: return ($symb,$courseid,$domain,$name,$publicuser);
13932:
13933: }
13934:
13935: # ------------------------------------------------------------ Serves up a file
13936: # returns either the contents of the file or
13937: # -1 if the file doesn't exist
13938: #
13939: # if the target is a file that was uploaded via DOCS,
13940: # a check will be made to see if a current copy exists on the local server,
13941: # if it does this will be served, otherwise a copy will be retrieved from
13942: # the home server for the course and stored in /home/httpd/html/userfiles on
13943: # the local server.
13944:
13945: sub getfile {
13946: my ($file) = @_;
13947: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13948: &repcopy($file);
13949: return &readfile($file);
13950: }
13951:
13952: sub repcopy_userfile {
13953: my ($file)=@_;
13954: my $londocroot = $perlvar{'lonDocRoot'};
13955: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13956: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13957: my ($cdom,$cnum,$filename) =
13958: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13959: my $uri="/uploaded/$cdom/$cnum/$filename";
13960: if (-e "$file") {
13961: # we already have a local copy, check it out
13962: my @fileinfo = stat($file);
13963: my $rtncode;
13964: my $info;
13965: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13966: if ($lwpresp ne 'ok') {
13967: # there is no such file anymore, even though we had a local copy
13968: if ($rtncode eq '404') {
13969: unlink($file);
13970: }
13971: return -1;
13972: }
13973: if ($info < $fileinfo[9]) {
13974: # nice, the file we have is up-to-date, just say okay
13975: return 'ok';
13976: } else {
13977: # the file is outdated, get rid of it
13978: unlink($file);
13979: }
13980: }
13981: # one way or the other, at this point, we don't have the file
13982: # construct the correct path for the file
13983: my @parts = ($cdom,$cnum);
13984: if ($filename =~ m|^(.+)/[^/]+$|) {
13985: push @parts, split(/\//,$1);
13986: }
13987: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13988: foreach my $part (@parts) {
13989: $path .= '/'.$part;
13990: if (!-e $path) {
13991: mkdir($path,0770);
13992: }
13993: }
13994: # now the path exists for sure
13995: # get a user agent
13996: my $transferfile=$file.'.in.transfer';
13997: # FIXME: this should flock
13998: if (-e $transferfile) { return 'ok'; }
13999: my $request;
14000: $uri=~s/^\///;
14001: my $homeserver = &homeserver($cnum,$cdom);
14002: my $hostname = &hostname($homeserver);
14003: my $protocol = $protocol{$homeserver};
14004: $protocol = 'http' if ($protocol ne 'https');
14005: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
14006: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
14007: # did it work?
14008: if ($response->is_error()) {
14009: unlink($transferfile);
14010: &logthis("Userfile repcopy failed for $uri");
14011: return -1;
14012: }
14013: # worked, rename the transfer file
14014: rename($transferfile,$file);
14015: return 'ok';
14016: }
14017:
14018: sub tokenwrapper {
14019: my $uri=shift;
14020: $uri=~s|^https?\://([^/]+)||;
14021: $uri=~s|^/||;
14022: $env{'user.environment'}=~/\/([^\/]+)\.id/;
14023: my $token=$1;
14024: my (undef,$udom,$uname,$file)=split('/',$uri,4);
14025: if ($udom && $uname && $file) {
14026: $file=~s|(\?\.*)*$||;
14027: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
14028: my $homeserver = &homeserver($uname,$udom);
14029: my $hostname = &hostname($homeserver);
14030: my $protocol = $protocol{$homeserver};
14031: $protocol = 'http' if ($protocol ne 'https');
14032: return $protocol.'://'.$hostname.'/'.$uri.
14033: (($uri=~/\?/)?'&':'?').'token='.$token.
14034: '&tokenissued='.$perlvar{'lonHostID'};
14035: } else {
14036: return '/adm/notfound.html';
14037: }
14038: }
14039:
14040: # call with reqtype HEAD: get last modification time
14041: # call with reqtype GET: get the file contents
14042: # Do not call this with reqtype GET for large files! It loads everything into memory
14043: #
14044: sub getuploaded {
14045: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
14046: $uri=~s/^\///;
14047: my $homeserver = &homeserver($cnum,$cdom);
14048: my $hostname = &hostname($homeserver);
14049: my $protocol = $protocol{$homeserver};
14050: $protocol = 'http' if ($protocol ne 'https');
14051: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
14052: my $request=new HTTP::Request($reqtype,$uri);
14053: my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
14054: $$rtncode = $response->code;
14055: if (! $response->is_success()) {
14056: return 'failed';
14057: }
14058: if ($reqtype eq 'HEAD') {
14059: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
14060: } elsif ($reqtype eq 'GET') {
14061: $$info = $response->content;
14062: }
14063: return 'ok';
14064: }
14065:
14066: sub readfile {
14067: my $file = shift;
14068: if ( (! -e $file ) || ($file eq '') ) { return -1; };
14069: my $fh;
14070: open($fh,"<",$file);
14071: my $a='';
14072: while (my $line = <$fh>) { $a .= $line; }
14073: return $a;
14074: }
14075:
14076: sub filelocation {
14077: my ($dir,$file) = @_;
14078: my $location;
14079: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
14080:
14081: if ($file =~ m-^/adm/-) {
14082: $file=~s-^/adm/wrapper/-/-;
14083: $file=~s-^/adm/coursedocs/showdoc/-/-;
14084: }
14085:
14086: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
14087: $location = $file;
14088: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
14089: my ($udom,$uname,$filename)=
14090: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
14091: my $home=&homeserver($uname,$udom);
14092: my $is_me=0;
14093: my @ids=¤t_machine_ids();
14094: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
14095: if ($is_me) {
14096: $location=propath($udom,$uname).'/userfiles/'.$filename;
14097: } else {
14098: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14099: $udom.'/'.$uname.'/'.$filename;
14100: }
14101: } elsif ($file =~ m-^/adm/-) {
14102: $location = $perlvar{'lonDocRoot'}.'/'.$file;
14103: } else {
14104: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
14105: $file=~s:^/(res|priv)/:/:;
14106: my $space=$1;
14107: if ( !( $file =~ m:^/:) ) {
14108: $location = $dir. '/'.$file;
14109: } else {
14110: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
14111: }
14112: }
14113: $location=~s://+:/:g; # remove duplicate /
14114: while ($location=~m{/\.\./}) {
14115: if ($location =~ m{/[^/]+/\.\./}) {
14116: $location=~ s{/[^/]+/\.\./}{/}g;
14117: } else {
14118: $location=~ s{/\.\./}{/}g;
14119: }
14120: } #remove dir/..
14121: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14122: return $location;
14123: }
14124:
14125: sub hreflocation {
14126: my ($dir,$file)=@_;
14127: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
14128: $file=filelocation($dir,$file);
14129: } elsif ($file=~m-^/adm/-) {
14130: $file=~s-^/adm/wrapper/-/-;
14131: $file=~s-^/adm/coursedocs/showdoc/-/-;
14132: }
14133: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14134: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14135: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
14136: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14137: {/uploaded/$1/$2/}x;
14138: }
14139: if ($file=~ m{^/userfiles/}) {
14140: $file =~ s{^/userfiles/}{/uploaded/};
14141: }
14142: return $file;
14143: }
14144:
14145:
14146:
14147:
14148:
14149: sub current_machine_domains {
14150: return &machine_domains(&hostname($perlvar{'lonHostID'}));
14151: }
14152:
14153: sub machine_domains {
14154: my ($hostname) = @_;
14155: my @domains;
14156: my %hostname = &all_hostnames();
14157: while( my($id, $name) = each(%hostname)) {
14158: # &logthis("-$id-$name-$hostname-");
14159: if ($hostname eq $name) {
14160: push(@domains,&host_domain($id));
14161: }
14162: }
14163: return @domains;
14164: }
14165:
14166: sub current_machine_ids {
14167: return &machine_ids(&hostname($perlvar{'lonHostID'}));
14168: }
14169:
14170: sub machine_ids {
14171: my ($hostname) = @_;
14172: $hostname ||= &hostname($perlvar{'lonHostID'});
14173: my @ids;
14174: my %name_to_host = &all_names();
14175: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14176: return @{ $name_to_host{$hostname} };
14177: }
14178: return;
14179: }
14180:
14181: sub additional_machine_domains {
14182: my @domains;
14183: open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
14184: while( my $line = <$fh>) {
14185: $line =~ s/\s//g;
14186: push(@domains,$line);
14187: }
14188: return @domains;
14189: }
14190:
14191: sub default_login_domain {
14192: my $domain = $perlvar{'lonDefDomain'};
14193: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14194: foreach my $posdom (¤t_machine_domains(),
14195: &additional_machine_domains()) {
14196: if (lc($posdom) eq lc($testdomain)) {
14197: $domain=$posdom;
14198: last;
14199: }
14200: }
14201: return $domain;
14202: }
14203:
14204: sub shared_institution {
14205: my ($dom) = @_;
14206: my $same_intdom;
14207: my $hostintdom = &internet_dom($perlvar{'lonHostID'});
14208: if ($hostintdom ne '') {
14209: my %iphost = &get_iphost();
14210: my $primary_id = &domain($dom,'primary');
14211: my $primary_ip = &get_host_ip($primary_id);
14212: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14213: foreach my $id (@{$iphost{$primary_ip}}) {
14214: my $intdom = &internet_dom($id);
14215: if ($intdom eq $hostintdom) {
14216: $same_intdom = 1;
14217: last;
14218: }
14219: }
14220: }
14221: }
14222: return $same_intdom;
14223: }
14224:
14225: sub uses_sts {
14226: my ($ignore_cache) = @_;
14227: my $lonhost = $perlvar{'lonHostID'};
14228: my $hostname = &hostname($lonhost);
14229: my $sts_on;
14230: if ($protocol{$lonhost} eq 'https') {
14231: my $cachetime = 12*3600;
14232: if (!$ignore_cache) {
14233: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14234: if (defined($cached)) {
14235: return $sts_on;
14236: }
14237: }
14238: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14239: my $request=new HTTP::Request('HEAD',$url);
14240: my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14241: if ($response->is_success) {
14242: my $has_sts = $response->header('Strict-Transport-Security');
14243: if ($has_sts eq '') {
14244: $sts_on = 0;
14245: } else {
14246: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14247: my $maxage = $1;
14248: if ($maxage) {
14249: $sts_on = 1;
14250: } else {
14251: $sts_on = 0;
14252: }
14253: } else {
14254: $sts_on = 0;
14255: }
14256: }
14257: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14258: }
14259: }
14260: return;
14261: }
14262:
14263: # ------------------------------------------------------------- Declutters URLs
14264:
14265: sub declutter {
14266: my $thisfn=shift;
14267: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14268: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
14269: $thisfn=~s{^/home/httpd/html}{};
14270: }
14271: $thisfn=~s/^\///;
14272: $thisfn=~s|^adm/wrapper/||;
14273: $thisfn=~s|^adm/coursedocs/showdoc/||;
14274: $thisfn=~s/^res\///;
14275: $thisfn=~s/^priv\///;
14276: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
14277: $thisfn=~s/\?.+$//;
14278: }
14279: return $thisfn;
14280: }
14281:
14282: # ------------------------------------------------------------- Clutter up URLs
14283:
14284: sub clutter {
14285: my $thisfn='/'.&declutter(shift);
14286: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
14287: || $thisfn =~ m{^/adm/(includes|pages)} ) {
14288: $thisfn='/res'.$thisfn;
14289: }
14290: if ($thisfn !~m|^/adm|) {
14291: if ($thisfn =~ m|^/ext/|) {
14292: $thisfn='/adm/wrapper'.$thisfn;
14293: } else {
14294: my ($ext) = ($thisfn =~ /\.(\w+)$/);
14295: my $embstyle=&Apache::loncommon::fileembstyle($ext);
14296: if ($embstyle eq 'ssi'
14297: || ($embstyle eq 'hdn')
14298: || ($embstyle eq 'rat')
14299: || ($embstyle eq 'prv')
14300: || ($embstyle eq 'ign')) {
14301: #do nothing with these
14302: } elsif (($embstyle eq 'img')
14303: || ($embstyle eq 'emb')
14304: || ($embstyle eq 'wrp')) {
14305: $thisfn='/adm/wrapper'.$thisfn;
14306: } elsif ($embstyle eq 'unk'
14307: && $thisfn!~/\.(sequence|page)$/) {
14308: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
14309: } else {
14310: # &logthis("Got a blank emb style");
14311: }
14312: }
14313: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
14314: $thisfn='/adm/wrapper'.$thisfn;
14315: }
14316: return $thisfn;
14317: }
14318:
14319: sub clutter_with_no_wrapper {
14320: my $uri = &clutter(shift);
14321: if ($uri =~ m-^/adm/-) {
14322: $uri =~ s-^/adm/wrapper/-/-;
14323: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
14324: }
14325: return $uri;
14326: }
14327:
14328: sub freeze_escape {
14329: my ($value)=@_;
14330: if (ref($value)) {
14331: $value=&nfreeze($value);
14332: return '__FROZEN__'.&escape($value);
14333: }
14334: return &escape($value);
14335: }
14336:
14337:
14338: sub thaw_unescape {
14339: my ($value)=@_;
14340: if ($value =~ /^__FROZEN__/) {
14341: substr($value,0,10,undef);
14342: $value=&unescape($value);
14343: return &thaw($value);
14344: }
14345: return &unescape($value);
14346: }
14347:
14348: sub correct_line_ends {
14349: my ($result)=@_;
14350: $$result =~s/\r\n/\n/mg;
14351: $$result =~s/\r/\n/mg;
14352: }
14353: # ================================================================ Main Program
14354:
14355: sub goodbye {
14356: &logthis("Starting Shut down");
14357: #not converted to using infrastruture and probably shouldn't be
14358: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
14359: #converted
14360: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
14361: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14362: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14363: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
14364: #1.1 only
14365: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14366: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14367: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14368: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14369: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
14370: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14371: &logthis(sprintf("%-20s is %s",'hits',$hits));
14372: &flushcourselogs();
14373: &logthis("Shutting down");
14374: }
14375:
14376: sub get_dns {
14377: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
14378: if (!$ignore_cache) {
14379: my ($content,$cached)=
14380: &Apache::lonnet::is_cached_new('dns',$url);
14381: if ($cached) {
14382: &$func($content,$hashref);
14383: return;
14384: }
14385: }
14386:
14387: my %alldns;
14388: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
14389: foreach my $dns (<$config>) {
14390: next if ($dns !~ /^\^(\S*)/x);
14391: my $line = $1;
14392: my ($host,$protocol) = split(/:/,$line);
14393: if ($protocol ne 'https') {
14394: $protocol = 'http';
14395: }
14396: $alldns{$host} = $protocol;
14397: }
14398: close($config);
14399: }
14400: while (%alldns) {
14401: my ($dns) = sort { $b cmp $a } keys(%alldns);
14402: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
14403: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
14404: delete($alldns{$dns});
14405: next if ($response->is_error());
14406: if ($url eq '/adm/dns/loncapaCRL') {
14407: return &$func($response);
14408: } else {
14409: my @content = split("\n",$response->content);
14410: unless ($nocache) {
14411: &do_cache_new('dns',$url,\@content,30*24*60*60);
14412: }
14413: &$func(\@content,$hashref);
14414: return;
14415: }
14416: }
14417: my $which = (split('/',$url,4))[3];
14418: if ($which eq 'loncapaCRL') {
14419: my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14420: if (-e $diskfile) {
14421: &logthis("unable to contact DNS, on disk file $diskfile not updated");
14422: } else {
14423: &logthis("unable to contact DNS, no on disk file $diskfile available");
14424: }
14425: } else {
14426: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
14427: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14428: my @content = <$config>;
14429: close($config);
14430: &$func(\@content,$hashref);
14431: }
14432: }
14433: return;
14434: }
14435:
14436: # ------------------------------------------------------Get DNS checksums file
14437: sub parse_dns_checksums_tab {
14438: my ($lines,$hashref) = @_;
14439: my $lonhost = $perlvar{'lonHostID'};
14440: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
14441: my $loncaparev = &get_server_loncaparev($machine_dom);
14442: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14443: my $webconfdir = '/etc/httpd/conf';
14444: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14445: $webconfdir = '/etc/apache2';
14446: } elsif ($distro =~ /^sles(\d+)$/) {
14447: if ($1 >= 10) {
14448: $webconfdir = '/etc/apache2';
14449: }
14450: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14451: if ($1 >= 10.0) {
14452: $webconfdir = '/etc/apache2';
14453: }
14454: }
14455: my ($release,$timestamp) = split(/\-/,$loncaparev);
14456: my (%chksum,%revnum);
14457: if (ref($lines) eq 'ARRAY') {
14458: chomp(@{$lines});
14459: my $version = shift(@{$lines});
14460: if ($version eq $release) {
14461: foreach my $line (@{$lines}) {
14462: my ($file,$version,$shasum) = split(/,/,$line);
14463: if ($file =~ m{^/etc/httpd/conf}) {
14464: if ($webconfdir eq '/etc/apache2') {
14465: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14466: }
14467: }
14468: $chksum{$file} = $shasum;
14469: $revnum{$file} = $version;
14470: }
14471: if (ref($hashref) eq 'HASH') {
14472: %{$hashref} = (
14473: sums => \%chksum,
14474: versions => \%revnum,
14475: );
14476: }
14477: }
14478: }
14479: return;
14480: }
14481:
14482: sub fetch_dns_checksums {
14483: my %checksums;
14484: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
14485: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
14486: my ($release,$timestamp) = split(/\-/,$loncaparev);
14487: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
14488: \%checksums);
14489: return \%checksums;
14490: }
14491:
14492: sub fetch_crl_pemfile {
14493: return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
14494: }
14495:
14496: sub save_crl_pem {
14497: my ($response) = @_;
14498: my ($msg,$hadchanges);
14499: if (ref($response)) {
14500: my $now = time;
14501: my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
14502: my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
14503: if (open(my $fh,'>',"$tmpcrl")) {
14504: print $fh $response->content;
14505: close($fh);
14506: if (-e $lonca) {
14507: if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
14508: my $check = <PIPE>;
14509: close(PIPE);
14510: chomp($check);
14511: if ($check eq 'verify OK') {
14512: my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14513: my $backup;
14514: if (-e $dest) {
14515: if (&File::Copy::move($dest,"$dest.bak")) {
14516: $backup = 'ok';
14517: }
14518: }
14519: if (&File::Copy::move($tmpcrl,$dest)) {
14520: $msg = 'ok';
14521: if ($backup) {
14522: my (%oldnums,%newnums);
14523: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
14524: while (<PIPE>) {
14525: $oldnums{(split(/:/))[1]} = 1;
14526: }
14527: close(PIPE);
14528: }
14529: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
14530: while(<PIPE>) {
14531: $newnums{(split(/:/))[1]} = 1;
14532: }
14533: close(PIPE);
14534: }
14535: foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
14536: unless (exists($oldnums{$key})) {
14537: $hadchanges = 1;
14538: last;
14539: }
14540: }
14541: unless ($hadchanges) {
14542: foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
14543: unless (exists($newnums{$key})) {
14544: $hadchanges = 1;
14545: last;
14546: }
14547: }
14548: }
14549: }
14550: }
14551: } else {
14552: unlink($tmpcrl);
14553: }
14554: } else {
14555: unlink($tmpcrl);
14556: }
14557: } else {
14558: unlink($tmpcrl);
14559: }
14560: }
14561: }
14562: return ($msg,$hadchanges);
14563: }
14564:
14565: # ------------------------------------------------------------ Read domain file
14566: {
14567: my $loaded;
14568: my %domain;
14569:
14570: sub parse_domain_tab {
14571: my ($lines) = @_;
14572: foreach my $line (@$lines) {
14573: next if ($line =~ /^(\#|\s*$ )/x);
14574:
14575: chomp($line);
14576: my ($name,@elements) = split(/:/,$line,9);
14577: my %this_domain;
14578: foreach my $field ('description', 'auth_def', 'auth_arg_def',
14579: 'lang_def', 'city', 'longi', 'lati',
14580: 'primary') {
14581: $this_domain{$field} = shift(@elements);
14582: }
14583: $domain{$name} = \%this_domain;
14584: }
14585: }
14586:
14587: sub reset_domain_info {
14588: undef($loaded);
14589: undef(%domain);
14590: }
14591:
14592: sub load_domain_tab {
14593: my ($ignore_cache,$nocache) = @_;
14594: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
14595: my $fh;
14596: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
14597: my @lines = <$fh>;
14598: &parse_domain_tab(\@lines);
14599: }
14600: close($fh);
14601: $loaded = 1;
14602: }
14603:
14604: sub domain {
14605: &load_domain_tab() if (!$loaded);
14606:
14607: my ($name,$what) = @_;
14608: return if ( !exists($domain{$name}) );
14609:
14610: if (!$what) {
14611: return $domain{$name}{'description'};
14612: }
14613: return $domain{$name}{$what};
14614: }
14615:
14616: sub domain_info {
14617: &load_domain_tab() if (!$loaded);
14618: return %domain;
14619: }
14620:
14621: }
14622:
14623:
14624: # ------------------------------------------------------------- Read hosts file
14625: {
14626: my %hostname;
14627: my %hostdom;
14628: my %libserv;
14629: my $loaded;
14630: my %name_to_host;
14631: my %internetdom;
14632: my %LC_dns_serv;
14633:
14634: sub parse_hosts_tab {
14635: my ($file) = @_;
14636: foreach my $configline (@$file) {
14637: next if ($configline =~ /^(\#|\s*$ )/x);
14638: chomp($configline);
14639: if ($configline =~ /^\^/) {
14640: if ($configline =~ /^\^([\w.\-]+)/) {
14641: $LC_dns_serv{$1} = 1;
14642: }
14643: next;
14644: }
14645: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
14646: $name=~s/\s//g;
14647: if ($id && $domain && $role && $name) {
14648: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
14649: my $curr = $hostname{$id};
14650: my $skip;
14651: if (ref($name_to_host{$curr}) eq 'ARRAY') {
14652: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
14653: $skip = 1;
14654: } else {
14655: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
14656: }
14657: }
14658: unless ($skip) {
14659: push(@{$name_to_host{$name}},$id);
14660: }
14661: } else {
14662: push(@{$name_to_host{$name}},$id);
14663: }
14664: $hostname{$id}=$name;
14665: $hostdom{$id}=$domain;
14666: if ($role eq 'library') { $libserv{$id}=$name; }
14667: if (defined($protocol)) {
14668: if ($protocol eq 'https') {
14669: $protocol{$id} = $protocol;
14670: } else {
14671: $protocol{$id} = 'http';
14672: }
14673: } else {
14674: $protocol{$id} = 'http';
14675: }
14676: if (defined($intdom)) {
14677: $internetdom{$id} = $intdom;
14678: }
14679: }
14680: }
14681: }
14682:
14683: sub reset_hosts_info {
14684: &purge_remembered();
14685: &reset_domain_info();
14686: &reset_hosts_ip_info();
14687: undef(%internetdom);
14688: undef(%name_to_host);
14689: undef(%hostname);
14690: undef(%hostdom);
14691: undef(%libserv);
14692: undef($loaded);
14693: }
14694:
14695: sub load_hosts_tab {
14696: my ($ignore_cache,$nocache) = @_;
14697: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
14698: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
14699: my @config = <$config>;
14700: &parse_hosts_tab(\@config);
14701: close($config);
14702: $loaded=1;
14703: }
14704:
14705: sub hostname {
14706: &load_hosts_tab() if (!$loaded);
14707:
14708: my ($lonid) = @_;
14709: return $hostname{$lonid};
14710: }
14711:
14712: sub all_hostnames {
14713: &load_hosts_tab() if (!$loaded);
14714:
14715: return %hostname;
14716: }
14717:
14718: sub all_names {
14719: my ($ignore_cache,$nocache) = @_;
14720: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
14721:
14722: return %name_to_host;
14723: }
14724:
14725: sub all_host_domain {
14726: &load_hosts_tab() if (!$loaded);
14727: return %hostdom;
14728: }
14729:
14730: sub all_host_intdom {
14731: &load_hosts_tab() if (!$loaded);
14732: return %internetdom;
14733: }
14734:
14735: sub is_library {
14736: &load_hosts_tab() if (!$loaded);
14737:
14738: return exists($libserv{$_[0]});
14739: }
14740:
14741: sub all_library {
14742: &load_hosts_tab() if (!$loaded);
14743:
14744: return %libserv;
14745: }
14746:
14747: sub unique_library {
14748: #2x reverse removes all hostnames that appear more than once
14749: my %unique = reverse &all_library();
14750: return reverse %unique;
14751: }
14752:
14753: sub get_servers {
14754: &load_hosts_tab() if (!$loaded);
14755:
14756: my ($domain,$type) = @_;
14757: my %possible_hosts = ($type eq 'library') ? %libserv
14758: : %hostname;
14759: my %result;
14760: if (ref($domain) eq 'ARRAY') {
14761: while ( my ($host,$hostname) = each(%possible_hosts)) {
14762: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
14763: $result{$host} = $hostname;
14764: }
14765: }
14766: } else {
14767: while ( my ($host,$hostname) = each(%possible_hosts)) {
14768: if ($hostdom{$host} eq $domain) {
14769: $result{$host} = $hostname;
14770: }
14771: }
14772: }
14773: return %result;
14774: }
14775:
14776: sub get_unique_servers {
14777: my %unique = reverse &get_servers(@_);
14778: return reverse %unique;
14779: }
14780:
14781: sub host_domain {
14782: &load_hosts_tab() if (!$loaded);
14783:
14784: my ($lonid) = @_;
14785: return $hostdom{$lonid};
14786: }
14787:
14788: sub all_domains {
14789: &load_hosts_tab() if (!$loaded);
14790:
14791: my %seen;
14792: my @uniq = grep(!$seen{$_}++, values(%hostdom));
14793: return @uniq;
14794: }
14795:
14796: sub internet_dom {
14797: &load_hosts_tab() if (!$loaded);
14798:
14799: my ($lonid) = @_;
14800: return $internetdom{$lonid};
14801: }
14802:
14803: sub is_LC_dns {
14804: &load_hosts_tab() if (!$loaded);
14805:
14806: my ($hostname) = @_;
14807: return exists($LC_dns_serv{$hostname});
14808: }
14809:
14810: }
14811:
14812: {
14813: my %iphost;
14814: my %name_to_ip;
14815: my %lonid_to_ip;
14816:
14817: sub get_hosts_from_ip {
14818: my ($ip) = @_;
14819: my %iphosts = &get_iphost();
14820: if (ref($iphosts{$ip})) {
14821: return @{$iphosts{$ip}};
14822: }
14823: return;
14824: }
14825:
14826: sub reset_hosts_ip_info {
14827: undef(%iphost);
14828: undef(%name_to_ip);
14829: undef(%lonid_to_ip);
14830: }
14831:
14832: sub get_host_ip {
14833: my ($lonid) = @_;
14834: if (exists($lonid_to_ip{$lonid})) {
14835: return $lonid_to_ip{$lonid};
14836: }
14837: my $name=&hostname($lonid);
14838: my $ip = gethostbyname($name);
14839: return if (!$ip || length($ip) ne 4);
14840: $ip=inet_ntoa($ip);
14841: $name_to_ip{$name} = $ip;
14842: $lonid_to_ip{$lonid} = $ip;
14843: return $ip;
14844: }
14845:
14846: sub get_iphost {
14847: my ($ignore_cache,$nocache) = @_;
14848:
14849: if (!$ignore_cache) {
14850: if (%iphost) {
14851: return %iphost;
14852: }
14853: my ($ip_info,$cached)=
14854: &Apache::lonnet::is_cached_new('iphost','iphost');
14855: if ($cached) {
14856: %iphost = %{$ip_info->[0]};
14857: %name_to_ip = %{$ip_info->[1]};
14858: %lonid_to_ip = %{$ip_info->[2]};
14859: return %iphost;
14860: }
14861: }
14862:
14863: # get yesterday's info for fallback
14864: my %old_name_to_ip;
14865: my ($ip_info,$cached)=
14866: &Apache::lonnet::is_cached_new('iphost','iphost');
14867: if ($cached) {
14868: %old_name_to_ip = %{$ip_info->[1]};
14869: }
14870:
14871: my %name_to_host = &all_names($ignore_cache,$nocache);
14872: foreach my $name (keys(%name_to_host)) {
14873: my $ip;
14874: if (!exists($name_to_ip{$name})) {
14875: $ip = gethostbyname($name);
14876: if (!$ip || length($ip) ne 4) {
14877: if (defined($old_name_to_ip{$name})) {
14878: $ip = $old_name_to_ip{$name};
14879: &logthis("Can't find $name defaulting to old $ip");
14880: } else {
14881: &logthis("Name $name no IP found");
14882: next;
14883: }
14884: } else {
14885: $ip=inet_ntoa($ip);
14886: }
14887: $name_to_ip{$name} = $ip;
14888: } else {
14889: $ip = $name_to_ip{$name};
14890: }
14891: foreach my $id (@{ $name_to_host{$name} }) {
14892: $lonid_to_ip{$id} = $ip;
14893: }
14894: push(@{$iphost{$ip}},@{$name_to_host{$name}});
14895: }
14896: unless ($nocache) {
14897: &do_cache_new('iphost','iphost',
14898: [\%iphost,\%name_to_ip,\%lonid_to_ip],
14899: 48*60*60);
14900: }
14901:
14902: return %iphost;
14903: }
14904:
14905: #
14906: # Given a DNS returns the loncapa host name for that DNS
14907: #
14908: sub host_from_dns {
14909: my ($dns) = @_;
14910: my @hosts;
14911: my $ip;
14912:
14913: if (exists($name_to_ip{$dns})) {
14914: $ip = $name_to_ip{$dns};
14915: }
14916: if (!$ip) {
14917: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14918: if (length($ip) == 4) {
14919: $ip = &IO::Socket::inet_ntoa($ip);
14920: }
14921: }
14922: if ($ip) {
14923: @hosts = get_hosts_from_ip($ip);
14924: return $hosts[0];
14925: }
14926: return undef;
14927: }
14928:
14929: sub get_internet_names {
14930: my ($lonid) = @_;
14931: return if ($lonid eq '');
14932: my ($idnref,$cached)=
14933: &Apache::lonnet::is_cached_new('internetnames',$lonid);
14934: if ($cached) {
14935: return $idnref;
14936: }
14937: my $ip = &get_host_ip($lonid);
14938: my @hosts = &get_hosts_from_ip($ip);
14939: my %iphost = &get_iphost();
14940: my (@idns,%seen);
14941: foreach my $id (@hosts) {
14942: my $dom = &host_domain($id);
14943: my $prim_id = &domain($dom,'primary');
14944: my $prim_ip = &get_host_ip($prim_id);
14945: next if ($seen{$prim_ip});
14946: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14947: foreach my $id (@{$iphost{$prim_ip}}) {
14948: my $intdom = &internet_dom($id);
14949: unless (grep(/^\Q$intdom\E$/,@idns)) {
14950: push(@idns,$intdom);
14951: }
14952: }
14953: }
14954: $seen{$prim_ip} = 1;
14955: }
14956: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
14957: }
14958:
14959: }
14960:
14961: sub all_loncaparevs {
14962: 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);
14963: }
14964:
14965: # ---------------------------------------------------------- Read loncaparev table
14966: {
14967: sub load_loncaparevs {
14968: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14969: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14970: while (my $configline=<$config>) {
14971: chomp($configline);
14972: my ($hostid,$loncaparev)=split(/:/,$configline);
14973: $loncaparevs{$hostid}=$loncaparev;
14974: }
14975: close($config);
14976: }
14977: }
14978: }
14979: }
14980:
14981: # ---------------------------------------------------------- Read serverhostID table
14982: {
14983: sub load_serverhomeIDs {
14984: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14985: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14986: while (my $configline=<$config>) {
14987: chomp($configline);
14988: my ($name,$id)=split(/:/,$configline);
14989: $serverhomeIDs{$name}=$id;
14990: }
14991: close($config);
14992: }
14993: }
14994: }
14995: }
14996:
14997:
14998: BEGIN {
14999:
15000: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
15001: unless ($readit) {
15002: {
15003: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
15004: %perlvar = (%perlvar,%{$configvars});
15005: }
15006:
15007:
15008: # ------------------------------------------------------ Read spare server file
15009: {
15010: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
15011:
15012: while (my $configline=<$config>) {
15013: chomp($configline);
15014: if ($configline) {
15015: my ($host,$type) = split(':',$configline,2);
15016: if (!defined($type) || $type eq '') { $type = 'default' };
15017: push(@{ $spareid{$type} }, $host);
15018: }
15019: }
15020: close($config);
15021: }
15022: # ------------------------------------------------------------ Read permissions
15023: {
15024: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
15025:
15026: while (my $configline=<$config>) {
15027: chomp($configline);
15028: if ($configline) {
15029: my ($role,$perm)=split(/ /,$configline);
15030: if ($perm ne '') { $pr{$role}=$perm; }
15031: }
15032: }
15033: close($config);
15034: }
15035:
15036: # -------------------------------------------- Read plain texts for permissions
15037: {
15038: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
15039:
15040: while (my $configline=<$config>) {
15041: chomp($configline);
15042: if ($configline) {
15043: my ($short,@plain)=split(/:/,$configline);
15044: %{$prp{$short}} = ();
15045: if (@plain > 0) {
15046: $prp{$short}{'std'} = $plain[0];
15047: for (my $i=1; $i<@plain; $i++) {
15048: $prp{$short}{'alt'.$i} = $plain[$i];
15049: }
15050: }
15051: }
15052: }
15053: close($config);
15054: }
15055:
15056: # ---------------------------------------------------------- Read package table
15057: {
15058: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
15059:
15060: while (my $configline=<$config>) {
15061: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
15062: chomp($configline);
15063: my ($short,$plain)=split(/:/,$configline);
15064: my ($pack,$name)=split(/\&/,$short);
15065: if ($plain ne '') {
15066: $packagetab{$pack.'&'.$name.'&name'}=$name;
15067: $packagetab{$short}=$plain;
15068: }
15069: }
15070: close($config);
15071: }
15072:
15073: # ---------------------------------------------------------- Read loncaparev table
15074:
15075: &load_loncaparevs();
15076:
15077: # ---------------------------------------------------------- Read serverhostID table
15078:
15079: &load_serverhomeIDs();
15080:
15081: # ---------------------------------------------------------- Read releaseslist XML
15082: {
15083: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
15084: if (-e $file) {
15085: my $parser = HTML::LCParser->new($file);
15086: while (my $token = $parser->get_token()) {
15087: if ($token->[0] eq 'S') {
15088: my $item = $token->[1];
15089: my $name = $token->[2]{'name'};
15090: my $value = $token->[2]{'value'};
15091: my $valuematch = $token->[2]{'valuematch'};
15092: my $namematch = $token->[2]{'namematch'};
15093: if ($item eq 'parameter') {
15094: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
15095: my $release = $parser->get_text();
15096: $release =~ s/(^\s*|\s*$ )//gx;
15097: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
15098: }
15099: } elsif ($item ne '' && $name ne '') {
15100: my $release = $parser->get_text();
15101: $release =~ s/(^\s*|\s*$ )//gx;
15102: $needsrelease{$item.':'.$name.':'.$value} = $release;
15103: }
15104: }
15105: }
15106: }
15107: }
15108:
15109: # ---------------------------------------------------------- Read managers table
15110: {
15111: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
15112: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
15113: while (my $configline=<$config>) {
15114: chomp($configline);
15115: next if ($configline =~ /^\#/);
15116: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
15117: $managerstab{$configline} = 1;
15118: }
15119: }
15120: close($config);
15121: }
15122: }
15123: }
15124:
15125: # ------------- set up temporary directory
15126: {
15127: $tmpdir = LONCAPA::tempdir();
15128:
15129: }
15130:
15131: # ------------- set default texengine (domain default overrides this)
15132: {
15133: $deftex = LONCAPA::texengine();
15134: }
15135:
15136: # ------------- set default minimum length for passwords for internal auth users
15137: {
15138: $passwdmin = LONCAPA::passwd_min();
15139: }
15140:
15141: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
15142: 'compress_threshold'=> 20_000,
15143: });
15144:
15145: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
15146: $dumpcount=0;
15147: $locknum=0;
15148:
15149: &logtouch();
15150: &logthis('<font color="yellow">INFO: Read configuration</font>');
15151: $readit=1;
15152: {
15153: use integer;
15154: my $test=(2**32)+1;
15155: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
15156: &logthis(" Detected 64bit platform ($_64bit)");
15157: }
15158: }
15159: }
15160:
15161: 1;
15162: __END__
15163:
15164: =pod
15165:
15166: =head1 NAME
15167:
15168: Apache::lonnet - Subroutines to ask questions about things in the network.
15169:
15170: =head1 SYNOPSIS
15171:
15172: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
15173:
15174: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
15175:
15176: Common parameters:
15177:
15178: =over 4
15179:
15180: =item *
15181:
15182: $uname : an internal username (if $cname expecting a course Id specifically)
15183:
15184: =item *
15185:
15186: $udom : a domain (if $cdom expecting a course's domain specifically)
15187:
15188: =item *
15189:
15190: $symb : a resource instance identifier
15191:
15192: =item *
15193:
15194: $namespace : the name of a .db file that contains the data needed or
15195: being set.
15196:
15197: =back
15198:
15199: =head1 OVERVIEW
15200:
15201: lonnet provides subroutines which interact with the
15202: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
15203: about classes, users, and resources.
15204:
15205: For many of these objects you can also use this to store data about
15206: them or modify them in various ways.
15207:
15208: =head2 Symbs
15209:
15210: To identify a specific instance of a resource, LON-CAPA uses symbols
15211: or "symbs"X<symb>. These identifiers are built from the URL of the
15212: map, the resource number of the resource in the map, and the URL of
15213: the resource itself. The latter is somewhat redundant, but might help
15214: if maps change.
15215:
15216: An example is
15217:
15218: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
15219:
15220: The respective map entry is
15221:
15222: <resource id="19" src="/res/msu/korte/tests/part12.problem"
15223: title="Problem 2">
15224: </resource>
15225:
15226: Symbs are used by the random number generator, as well as to store and
15227: restore data specific to a certain instance of for example a problem.
15228:
15229: =head2 Storing And Retrieving Data
15230:
15231: X<store()>X<cstore()>X<restore()>Three of the most important functions
15232: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
15233: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
15234: is is the non-critical message twin of cstore. These functions are for
15235: handlers to store a perl hash to a user's permanent data space in an
15236: easy manner, and to retrieve it again on another call. It is expected
15237: that a handler would use this once at the beginning to retrieve data,
15238: and then again once at the end to send only the new data back.
15239:
15240: The data is stored in the user's data directory on the user's
15241: homeserver under the ID of the course.
15242:
15243: The hash that is returned by restore will have all of the previous
15244: value for all of the elements of the hash.
15245:
15246: Example:
15247:
15248: #creating a hash
15249: my %hash;
15250: $hash{'foo'}='bar';
15251:
15252: #storing it
15253: &Apache::lonnet::cstore(\%hash);
15254:
15255: #changing a value
15256: $hash{'foo'}='notbar';
15257:
15258: #adding a new value
15259: $hash{'bar'}='foo';
15260: &Apache::lonnet::cstore(\%hash);
15261:
15262: #retrieving the hash
15263: my %history=&Apache::lonnet::restore();
15264:
15265: #print the hash
15266: foreach my $key (sort(keys(%history))) {
15267: print("\%history{$key} = $history{$key}");
15268: }
15269:
15270: Will print out:
15271:
15272: %history{1:foo} = bar
15273: %history{1:keys} = foo:timestamp
15274: %history{1:timestamp} = 990455579
15275: %history{2:bar} = foo
15276: %history{2:foo} = notbar
15277: %history{2:keys} = foo:bar:timestamp
15278: %history{2:timestamp} = 990455580
15279: %history{bar} = foo
15280: %history{foo} = notbar
15281: %history{timestamp} = 990455580
15282: %history{version} = 2
15283:
15284: Note that the special hash entries C<keys>, C<version> and
15285: C<timestamp> were added to the hash. C<version> will be equal to the
15286: total number of versions of the data that have been stored. The
15287: C<timestamp> attribute will be the UNIX time the hash was
15288: stored. C<keys> is available in every historical section to list which
15289: keys were added or changed at a specific historical revision of a
15290: hash.
15291:
15292: B<Warning>: do not store the hash that restore returns directly. This
15293: will cause a mess since it will restore the historical keys as if the
15294: were new keys. I.E. 1:foo will become 1:1:foo etc.
15295:
15296: Calling convention:
15297:
15298: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
15299: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
15300:
15301: For more detailed information, see lonnet specific documentation.
15302:
15303: =head1 RETURN MESSAGES
15304:
15305: =over 4
15306:
15307: =item * B<con_lost>: unable to contact remote host
15308:
15309: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15310: when the connection is brought back up
15311:
15312: =item * B<con_failed>: unable to contact remote host and unable to save message
15313: for later delivery
15314:
15315: =item * B<error:>: an error a occurred, a description of the error follows the :
15316:
15317: =item * B<no_such_host>: unable to fund a host associated with the user/domain
15318: that was requested
15319:
15320: =back
15321:
15322: =head1 PUBLIC SUBROUTINES
15323:
15324: =head2 Session Environment Functions
15325:
15326: =over 4
15327:
15328: =item *
15329: X<appenv()>
15330: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
15331: the user envirnoment file, and will be restored for each access this
15332: user makes during this session, also modifies the %env for the current
15333: process. Optional rolesarrayref - if defined contains a reference to an array
15334: of roles which are exempt from the restriction on modifying user.role entries
15335: in the user's environment.db and in %env.
15336:
15337: =item *
15338: X<delenv()>
15339: B<delenv($delthis,$regexp)>: removes all items from the session
15340: environment file that begin with $delthis. If the
15341: optional second arg - $regexp - is true, $delthis is treated as a
15342: regular expression, otherwise \Q$delthis\E is used.
15343: The values are also deleted from the current processes %env.
15344:
15345: =item * get_env_multiple($name)
15346:
15347: gets $name from the %env hash, it seemlessly handles the cases where multiple
15348: values may be defined and end up as an array ref.
15349:
15350: returns an array of values
15351:
15352: =back
15353:
15354: =head2 User Information
15355:
15356: =over 4
15357:
15358: =item *
15359: X<queryauthenticate()>
15360: B<queryauthenticate($uname,$udom)>: try to determine user's current
15361: authentication scheme
15362:
15363: =item *
15364: X<authenticate()>
15365: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
15366: authenticate user from domain's lib servers (first use the current
15367: one). C<$upass> should be the users password.
15368: $checkdefauth is optional (value is 1 if a check should be made to
15369: authenticate user using default authentication method, and allow
15370: account creation if username does not have account in the domain).
15371: $clientcancheckhost is optional (value is 1 if checking whether the
15372: server can host will occur on the client side in lonauth.pm).
15373:
15374: =item *
15375: X<homeserver()>
15376: B<homeserver($uname,$udom)>: find the server which has
15377: the user's directory and files (there must be only one), this caches
15378: the answer, and also caches if there is a borken connection.
15379:
15380: =item *
15381: X<idget()>
15382: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
15383: a list of student/employee IDs or clicker IDs
15384: (student/employee IDs are a unique resource in a domain, there must be
15385: only 1 ID per username, and only 1 username per ID in a specific domain).
15386: clickerIDs are not necessarily unique, as students might share clickers.
15387: (returns hash: id=>name,id=>name)
15388:
15389: =item *
15390: X<idrget()>
15391: B<idrget($udom,@unames)>: find the IDs behind a list of
15392: usernames (returns hash: name=>id,name=>id)
15393:
15394: =item *
15395: X<idput()>
15396: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
15397: names and associated student/employee IDs or clicker IDs.
15398:
15399: =item *
15400: X<iddel()>
15401: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
15402: student/employee ID or clicker ID username look-ups from domain.
15403: The homeserver ($uhome) and namespace ($namespace) are optional.
15404: If no $uhome is provided, it will be determined usig &homeserver()
15405: for each user. If no $namespace is provided, the default is ids.
15406:
15407: =item *
15408: X<updateclickers()>
15409: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
15410: clicker ID-to-username look-ups in clickers.db on library server.
15411: Permitted actions are add or del (i.e., add or delete). The
15412: clickers.db contains clickerID as keys (escaped), and each corresponding
15413: value is an escaped comma-separated list of usernames (for whom the
15414: library server is the homeserver), who registered that particular ID.
15415: If $critical is true, the update will be sent via &critical, otherwise
15416: &reply() will be used.
15417:
15418: =item *
15419: X<rolesinit()>
15420: B<rolesinit($udom,$username)>: get user privileges.
15421: returns user role, first access and timer interval hashes
15422:
15423: =item *
15424: X<privileged()>
15425: B<privileged($username,$domain)>: returns a true if user has a
15426: privileged and active role (i.e. su or dc), false otherwise.
15427:
15428: =item *
15429: X<getsection()>
15430: B<getsection($udom,$uname,$cname)>: finds the section of student in the
15431: course $cname, return section name/number or '' for "not in course"
15432: and '-1' for "no section"
15433:
15434: =item *
15435: X<userenvironment()>
15436: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
15437: passed in @what from the requested user's environment, returns a hash
15438:
15439: =item *
15440: X<userlog_query()>
15441: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
15442: activity.log file. %filters defines filters applied when parsing the
15443: log file. These can be start or end timestamps, or the type of action
15444: - log to look for Login or Logout events, check for Checkin or
15445: Checkout, role for role selection. The response is in the form
15446: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
15447: escaped strings of the action recorded in the activity.log file.
15448:
15449: =back
15450:
15451: =head2 User Roles
15452:
15453: =over 4
15454:
15455: =item *
15456:
15457: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
15458: returns codes for allowed actions.
15459:
15460: The first argument is required, all others are optional.
15461:
15462: $priv is the privilege being checked.
15463: $uri contains additional information about what is being checked for access (e.g.,
15464: URL, course ID etc.).
15465: $symb is the unique resource instance identifier in a course; if needed,
15466: but not provided, it will be retrieved via a call to &symbread().
15467: $role is the role for which a priv is being checked (only used if priv is evb).
15468: $clientip is the user's IP address (only used when checking for access to portfolio
15469: files).
15470: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
15471: prevents recursive calls to &allowed.
15472:
15473: F: full access
15474: U,I,K: authentication modes (cxx only)
15475: '': forbidden
15476: 1: user needs to choose course
15477: 2: browse allowed
15478: A: passphrase authentication needed
15479: B: access temporarily blocked because of a blocking event in a course.
15480: D: access blocked because access is required via session initiated via deep-link
15481:
15482: =item *
15483:
15484: constructaccess($url,$setpriv) : check for access to construction space URL
15485:
15486: See if the owner domain and name in the URL match those in the
15487: expected environment. If so, return three element list
15488: ($ownername,$ownerdomain,$ownerhome).
15489:
15490: Otherwise return the null string.
15491:
15492: If second argument 'setpriv' is true, it assigns the privileges,
15493: and returns the same three element list, unless the owner has
15494: blocked "ad hoc" Domain Coordinator access to the Author Space,
15495: in which case the null string is returned.
15496:
15497: =item *
15498:
15499: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
15500: define a custom role rolename set privileges in format of lonTabs/roles.tab
15501: for system, domain, and course level. $uname and $udom are optional (current
15502: user's username and domain will be used when either of $uname or $udom are absent.
15503:
15504: =item *
15505:
15506: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
15507: (rolesplain.tab); plain text explanation of a user role term.
15508: $type is Course (default) or Community.
15509: If $forcedefault evaluates to true, text returned will be default
15510: text for $type. Otherwise, if this is a course, the text returned
15511: will be a custom name for the role (if defined in the course's
15512: environment). If no custom name is defined the default is returned.
15513:
15514: =item *
15515:
15516: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
15517: All arguments are optional. Returns a hash of a roles, either for
15518: co-author/assistant author roles for a user's Construction Space
15519: (default), or if $context is 'userroles', roles for the user himself,
15520: In the hash, keys are set to colon-separated $uname,$udom,$role, and
15521: (optionally) if $withsec is true, a fourth colon-separated item - $section.
15522: For each key, value is set to colon-separated start and end times for
15523: the role. If no username and domain are specified, will default to
15524: current user/domain. Types, roles, and roledoms are references to arrays
15525: of role statuses (active, future or previous), roles
15526: (e.g., cc,in, st etc.) and domains of the roles which can be used
15527: to restrict the list of roles reported. If no array ref is
15528: provided for types, will default to return only active roles.
15529:
15530: =item *
15531:
15532: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
15533: user: $uname:$udom has a role in the course: $cdom_$cnum.
15534:
15535: Additional optional arguments are: $type (if role checking is to be restricted
15536: to certain user status types -- previous (expired roles), active (currently
15537: available roles) or future (roles available in the future), and
15538: $hideprivileged -- if true will not report course roles for users who
15539: have active Domain Coordinator role in course's domain or in additional
15540: domains (specified in 'Domains to check for privileged users' in course
15541: environment -- set via: Course Settings -> Classlists and staff listing).
15542:
15543: =item *
15544:
15545: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15546: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15547: $possdomains and $possroles are optional array refs -- to domains to check and
15548: roles to check. If $possdomains is not specified, a dump will be done of the
15549: users' roles.db to check for a dc or su role in any domain. This can be
15550: time consuming if &privileged is called repeatedly (e.g., when displaying a
15551: classlist), so in such cases, supplying a $possdomains array is preferred, as
15552: this then allows &privileged_by_domain() to be used, which caches the identity
15553: of privileged users, eliminating the need for repeated calls to &dump().
15554:
15555: =item *
15556:
15557: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15558: where the outer hash keys are domains specified in the $possdomains array ref,
15559: next inner hash keys are privileged roles specified in the $roles array ref,
15560: and the innermost hash contains key = value pairs for username:domain = end:start
15561: for active or future "privileged" users with that role in that domain. To avoid
15562: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15563: innerhash are cached using priv_$role and $dom as the identifiers.
15564:
15565: =back
15566:
15567: =head2 User Modification
15568:
15569: =over 4
15570:
15571: =item *
15572:
15573: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
15574: user for the level given by URL. Optional start and end dates (leave empty
15575: string or zero for "no date")
15576:
15577: =item *
15578:
15579: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15580: change a users, password, possible return values are: ok,
15581: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15582: refused
15583:
15584: =item *
15585:
15586: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
15587:
15588: =item *
15589:
15590: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
15591: $forceid,$desiredhome,$email,$inststatus,$candelete) :
15592:
15593: will update user information (firstname,middlename,lastname,generation,
15594: permanentemail), and if forceid is true, student/employee ID also.
15595: A user's institutional affiliation(s) can also be updated.
15596: User information fields will not be overwritten with empty entries
15597: unless the field is included in the $candelete array reference.
15598: This array is included when a single user is modified via "Manage Users",
15599: or when Autoupdate.pl is run by cron in a domain.
15600:
15601: =item *
15602:
15603: modifystudent
15604:
15605: modify a student's enrollment and identification information.
15606: The course id is resolved based on the current user's environment.
15607: This means the invoking user must be a course coordinator or otherwise
15608: associated with a course.
15609:
15610: This call is essentially a wrapper for lonnet::modifyuser and
15611: lonnet::modify_student_enrollment
15612:
15613: Inputs:
15614:
15615: =over 4
15616:
15617: =item B<$udom> Student's loncapa domain
15618:
15619: =item B<$uname> Student's loncapa login name
15620:
15621: =item B<$uid> Student/Employee ID
15622:
15623: =item B<$umode> Student's authentication mode
15624:
15625: =item B<$upass> Student's password
15626:
15627: =item B<$first> Student's first name
15628:
15629: =item B<$middle> Student's middle name
15630:
15631: =item B<$last> Student's last name
15632:
15633: =item B<$gene> Student's generation
15634:
15635: =item B<$usec> Student's section in course
15636:
15637: =item B<$end> Unix time of the roles expiration
15638:
15639: =item B<$start> Unix time of the roles start date
15640:
15641: =item B<$forceid> If defined, allow $uid to be changed
15642:
15643: =item B<$desiredhome> server to use as home server for student
15644:
15645: =item B<$email> Student's permanent e-mail address
15646:
15647: =item B<$type> Type of enrollment (auto or manual)
15648:
15649: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
15650:
15651: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
15652:
15653: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
15654:
15655: =item B<$context> role change context (shown in User Management Logs display in a course)
15656:
15657: =item B<$inststatus> institutional status of user - : separated string of escaped status types
15658:
15659: =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.
15660:
15661: =back
15662:
15663: =item *
15664:
15665: modify_student_enrollment
15666:
15667: Change a student's enrollment status in a class. The environment variable
15668: 'role.request.course' must be defined for this function to proceed.
15669:
15670: Inputs:
15671:
15672: =over 4
15673:
15674: =item $udom, student's domain
15675:
15676: =item $uname, student's name
15677:
15678: =item $uid, student's user id
15679:
15680: =item $first, student's first name
15681:
15682: =item $middle
15683:
15684: =item $last
15685:
15686: =item $gene
15687:
15688: =item $usec
15689:
15690: =item $end
15691:
15692: =item $start
15693:
15694: =item $type
15695:
15696: =item $locktype
15697:
15698: =item $cid
15699:
15700: =item $selfenroll
15701:
15702: =item $context
15703:
15704: =item $credits, number of credits student will earn from this class
15705:
15706: =item $instsec, institutional course section code for student
15707:
15708: =back
15709:
15710:
15711: =item *
15712:
15713: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
15714: custom role; give a custom role to a user for the level given by URL. Specify
15715: name and domain of role author, and role name
15716:
15717: =item *
15718:
15719: revokerole($udom,$uname,$url,$role) : revoke a role for url
15720:
15721: =item *
15722:
15723: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
15724:
15725: =back
15726:
15727: =head2 Course Infomation
15728:
15729: =over 4
15730:
15731: =item *
15732:
15733: coursedescription($courseid,$options) : returns a hash of information about the
15734: specified course id, including all environment settings for the
15735: course, the description of the course will be in the hash under the
15736: key 'description'
15737:
15738: $options is an optional parameter that if supplied is a hash reference that controls
15739: what how this function works. It has the following key/values:
15740:
15741: =over 4
15742:
15743: =item freshen_cache
15744:
15745: If defined, and the environment cache for the course is valid, it is
15746: returned in the returned hash.
15747:
15748: =item one_time
15749:
15750: If defined, the last cache time is set to _now_
15751:
15752: =item user
15753:
15754: If defined, the supplied username is used instead of the current user.
15755:
15756:
15757: =back
15758:
15759: =item *
15760:
15761: resdata($name,$domain,$type,@which) : request for current parameter
15762: setting for a specific $type, where $type is either 'course' or 'user',
15763: @what should be a list of parameters to ask about. This routine caches
15764: answers for 10 minutes.
15765:
15766: =item *
15767:
15768: get_courseresdata($courseid, $domain) : dump the entire course resource
15769: data base, returning a hash that is keyed by the resource name and has
15770: values that are the resource value. I believe that the timestamps and
15771: versions are also returned.
15772:
15773: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15774: supplemental content area. This routine caches the number of files for
15775: 10 minutes.
15776:
15777: =back
15778:
15779: =head2 Course Modification
15780:
15781: =over 4
15782:
15783: =item *
15784:
15785: writecoursepref($courseid,%prefs) : write preferences (environment
15786: database) for a course
15787:
15788: =item *
15789:
15790: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15791:
15792: =item *
15793:
15794: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
15795:
15796: =item *
15797:
15798: is_course($courseid), is_course($cdom, $cnum)
15799:
15800: Accepts either a combined $courseid (in the form of domain_courseid) or the
15801: two component version $cdom, $cnum. It checks if the specified course exists.
15802:
15803: Returns:
15804: undef if the course doesn't exist, otherwise
15805: in scalar context the combined courseid.
15806: in list context the two components of the course identifier, domain and
15807: courseid.
15808:
15809: =back
15810:
15811: =head2 Bubblesheet Configuration
15812:
15813: =over 4
15814:
15815: =item *
15816:
15817: get_scantron_config($which)
15818:
15819: $which - the name of the configuration to parse from the file.
15820:
15821: Parses and returns the bubblesheet configuration line selected as a
15822: hash of configuration file fields.
15823:
15824:
15825: Returns:
15826: If the named configuration is not in the file, an empty
15827: hash is returned.
15828:
15829: a hash with the fields
15830: name - internal name for the this configuration setup
15831: description - text to display to operator that describes this config
15832: CODElocation - if 0 or the string 'none'
15833: - no CODE exists for this config
15834: if -1 || the string 'letter'
15835: - a CODE exists for this config and is
15836: a string of letters
15837: Unsupported value (but planned for future support)
15838: if a positive integer
15839: - The CODE exists as the first n items from
15840: the question section of the form
15841: if the string 'number'
15842: - The CODE exists for this config and is
15843: a string of numbers
15844: CODEstart - (only matter if a CODE exists) column in the line where
15845: the CODE starts
15846: CODElength - length of the CODE
15847: IDstart - column where the student/employee ID starts
15848: IDlength - length of the student/employee ID info
15849: Qstart - column where the information from the bubbled
15850: 'questions' start
15851: Qlength - number of columns comprising a single bubble line from
15852: the sheet. (usually either 1 or 10)
15853: Qon - either a single character representing the character used
15854: to signal a bubble was chosen in the positional setup, or
15855: the string 'letter' if the letter of the chosen bubble is
15856: in the final, or 'number' if a number representing the
15857: chosen bubble is in the file (1->A 0->J)
15858: Qoff - the character used to represent that a bubble was
15859: left blank
15860: PaperID - if the scanning process generates a unique number for each
15861: sheet scanned the column that this ID number starts in
15862: PaperIDlength - number of columns that comprise the unique ID number
15863: for the sheet of paper
15864: FirstName - column that the first name starts in
15865: FirstNameLength - number of columns that the first name spans
15866: LastName - column that the last name starts in
15867: LastNameLength - number of columns that the last name spans
15868: BubblesPerRow - number of bubbles available in each row used to
15869: bubble an answer. (If not specified, 10 assumed).
15870:
15871:
15872: =item *
15873:
15874: get_scantronformat_file($cdom)
15875:
15876: $cdom - the course's domain (optional); if not supplied, uses
15877: domain for current $env{'request.course.id'}.
15878:
15879: Returns an array containing lines from the scantron format file for
15880: the domain of the course.
15881:
15882: If a url for a custom.tab file is listed in domain's configuration.db,
15883: lines are from this file.
15884:
15885: Otherwise, if a default.tab has been published in RES space by the
15886: domainconfig user, lines are from this file.
15887:
15888: Otherwise, fall back to getting lines from the legacy file on the
15889: local server: /home/httpd/lonTabs/default_scantronformat.tab
15890:
15891: =back
15892:
15893: =head2 Resource Subroutines
15894:
15895: =over 4
15896:
15897: =item *
15898:
15899: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
15900:
15901: =item *
15902:
15903: repcopy($filename) : subscribes to the requested file, and attempts to
15904: replicate from the owning library server, Might return
15905: 'unavailable', 'not_found', 'forbidden', 'ok', or
15906: 'bad_request', also attempts to grab the metadata for the
15907: resource. Expects the local filesystem pathname
15908: (/home/httpd/html/res/....)
15909:
15910: =back
15911:
15912: =head2 Resource Information
15913:
15914: =over 4
15915:
15916: =item *
15917:
15918: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
15919: and returns the value of a variety of different possible values,
15920: $varname should be a request string, and the other parameters can be
15921: used to specify who and what one is asking about. Ordinarily, $cid
15922: does not need to be specified, as it is retrived from
15923: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15924: within lonuserstate::loadmap() when initializing a course, before
15925: $env{'request.course.id'} has been set, so it needs to be provided
15926: in that one case.
15927:
15928: Possible values for $varname are environment.lastname (or other item
15929: from the envirnment hash), user.name (or someother aspect about the
15930: user), resource.0.maxtries (or some other part and parameter of a
15931: resource)
15932:
15933: =item *
15934:
15935: directcondval($number) : get current value of a condition; reads from a state
15936: string
15937:
15938: =item *
15939:
15940: condval($condidx) : value of condition index based on state
15941:
15942: =item *
15943:
15944: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
15945: resource's metadata, $what should be either a specific key, or either
15946: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15947: packages that this resource currently uses, the last 3 arguments are
15948: only used internally for recursive metadata.
15949:
15950: the toolsymb is only used where the uri is for an external tool (for which
15951: the uri as well as the symb are guaranteed to be unique).
15952:
15953: this function automatically caches all requests except any made recursively
15954: to retrieve a list of metadata keys for an imported library file ($liburi is
15955: defined).
15956:
15957: =item *
15958:
15959: metadata_query($query,$custom,$customshow) : make a metadata query against the
15960: network of library servers; returns file handle of where SQL and regex results
15961: will be stored for query
15962:
15963: =item *
15964:
15965: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
15966: return symbolic list entry (all arguments optional).
15967:
15968: Args: filename is the filename (including path) for the file for which a symb
15969: is required; donotrecurse, if true will prevent calls to allowed() being made
15970: to check access status if more than one resource was found in the bighash
15971: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
15972: a randompick); ignorecachednull, if true will prevent a symb of '' being
15973: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15974: cause possible symbs to be checked to determine if they are subject to content
15975: blocking, if so they will not be included as possible symbs; possibles is a
15976: ref to a hash, which, as a side effect, will be populated with all possible
15977: symbs (content blocking not tested).
15978:
15979: returns the data handle
15980:
15981: =item *
15982:
15983: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15984: and is a possible symb for the URL in $thisfn, and if is an encrypted
15985: resource that the user accessed using /enc/ returns a 1 on success, 0
15986: on failure, user must be in a course, as it assumes the existence of
15987: the course initial hash, and uses $env('request.course.id'}. The third
15988: arg is an optional reference to a scalar. If this arg is passed in the
15989: call to symbverify, it will be set to 1 if the symb has been set to be
15990: encrypted; otherwise it will be null.
15991:
15992: =item *
15993:
15994: symbclean($symb) : removes versions numbers from a symb, returns the
15995: cleaned symb
15996:
15997: =item *
15998:
15999: is_on_map($uri) : checks if the $uri is somewhere on the current
16000: course map, user must be in a course for it to work.
16001:
16002: =item *
16003:
16004: numval($salt) : return random seed value (addend for rndseed)
16005:
16006: =item *
16007:
16008: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
16009: a random seed, all arguments are optional, if they aren't sent it uses the
16010: environment to derive them. Note: if symb isn't sent and it can't get one
16011: from &symbread it will use the current time as its return value
16012:
16013: =item *
16014:
16015: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
16016: unfakeable, receipt
16017:
16018: =item *
16019:
16020: receipt() : API to ireceipt working off of env values; given out to users
16021:
16022: =item *
16023:
16024: countacc($url) : count the number of accesses to a given URL
16025:
16026: =item *
16027:
16028: 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
16029:
16030: =item *
16031:
16032: 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)
16033:
16034: =item *
16035:
16036: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
16037:
16038: =item *
16039:
16040: devalidate($symb) : devalidate temporary spreadsheet calculations,
16041: forcing spreadsheet to reevaluate the resource scores next time.
16042:
16043: =item *
16044:
16045: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
16046: when viewing in course context.
16047:
16048: input: six args -- filename (decluttered), course number, course domain,
16049: url, symb (if registered) and group (if this is a
16050: group item -- e.g., bulletin board, group page etc.).
16051:
16052: output: array of five scalars --
16053: $cfile -- url for file editing if editable on current server
16054: $home -- homeserver of resource (i.e., for author if published,
16055: or course if uploaded.).
16056: $switchserver -- 1 if server switch will be needed.
16057: $forceedit -- 1 if icon/link should be to go to edit mode
16058: $forceview -- 1 if icon/link should be to go to view mode
16059:
16060: =item *
16061:
16062: is_course_upload($file,$cnum,$cdom)
16063:
16064: Used in course context to determine if current file was uploaded to
16065: the course (i.e., would be found in /userfiles/docs on the course's
16066: homeserver.
16067:
16068: input: 3 args -- filename (decluttered), course number and course domain.
16069: output: boolean -- 1 if file was uploaded.
16070:
16071: =back
16072:
16073: =head2 Storing/Retreiving Data
16074:
16075: =over 4
16076:
16077: =item *
16078:
16079: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
16080: permanently for this url; hashref needs to be given and should be a \%hashname;
16081: the remaining args aren't required and if they aren't passed or are '' they will
16082: be derived from the env (with the exception of $laststore, which is an
16083: optional arg used when a user's submission is stored in grading).
16084: $laststore is $version=$timestamp, where $version is the most recent version
16085: number retrieved for the corresponding $symb in the $namespace db file, and
16086: $timestamp is the timestamp for that transaction (UNIX time).
16087: $laststore is currently only passed when cstore() is called by
16088: structuretags::finalize_storage().
16089:
16090: =item *
16091:
16092: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
16093: but uses critical subroutine
16094:
16095: =item *
16096:
16097: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
16098: all args are optional
16099:
16100: =item *
16101:
16102: dumpstore($namespace,$udom,$uname,$regexp,$range) :
16103: dumps the complete (or key matching regexp) namespace into a hash
16104: ($udom, $uname, $regexp, $range are optional) for a namespace that is
16105: normally &store()ed into
16106:
16107: $range should be either an integer '100' (give me the first 100
16108: matching records)
16109: or be two integers sperated by a - with no spaces
16110: '30-50' (give me the 30th through the 50th matching
16111: records)
16112:
16113:
16114: =item *
16115:
16116: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
16117: replaces a &store() version of data with a replacement set of data
16118: for a particular resource in a namespace passed in the $storehash hash
16119: reference. If $tolog is true, the transaction is logged in the courselog
16120: with an action=PUTSTORE.
16121:
16122: =item *
16123:
16124: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
16125: works very similar to store/cstore, but all data is stored in a
16126: temporary location and can be reset using tmpreset, $storehash should
16127: be a hash reference, returns nothing on success
16128:
16129: =item *
16130:
16131: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
16132: similar to restore, but all data is stored in a temporary location and
16133: can be reset using tmpreset. Returns a hash of values on success,
16134: error string otherwise.
16135:
16136: =item *
16137:
16138: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
16139: deltes all keys for $symb form the temporary storage hash.
16140:
16141: =item *
16142:
16143: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16144: reference filled in from namesp ($udom and $uname are optional)
16145:
16146: =item *
16147:
16148: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
16149: namesp ($udom and $uname are optional)
16150:
16151: =item *
16152:
16153: dump($namespace,$udom,$uname,$regexp,$range) :
16154: dumps the complete (or key matching regexp) namespace into a hash
16155: ($udom, $uname, $regexp, $range are optional)
16156:
16157: $range should be either an integer '100' (give me the first 100
16158: matching records)
16159: or be two integers sperated by a - with no spaces
16160: '30-50' (give me the 30th through the 50th matching
16161: records)
16162: =item *
16163:
16164: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
16165: $store can be a scalar, an array reference, or if the amount to be
16166: incremented is > 1, a hash reference.
16167:
16168: ($udom and $uname are optional)
16169:
16170: =item *
16171:
16172: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
16173: ($udom and $uname are optional)
16174:
16175: =item *
16176:
16177: cput($namespace,$storehash,$udom,$uname) : critical put
16178: ($udom and $uname are optional)
16179:
16180: =item *
16181:
16182: newput($namespace,$storehash,$udom,$uname) :
16183:
16184: Attempts to store the items in the $storehash, but only if they don't
16185: currently exist, if this succeeds you can be certain that you have
16186: successfully created a new key value pair in the $namespace db.
16187:
16188:
16189: Args:
16190: $namespace: name of database to store values to
16191: $storehash: hashref to store to the db
16192: $udom: (optional) domain of user containing the db
16193: $uname: (optional) name of user caontaining the db
16194:
16195: Returns:
16196: 'ok' -> succeeded in storing all keys of $storehash
16197: 'key_exists: <key>' -> failed to anything out of $storehash, as at
16198: least <key> already existed in the db (other
16199: requested keys may also already exist)
16200: 'error: <msg>' -> unable to tie the DB or other error occurred
16201: 'con_lost' -> unable to contact request server
16202: 'refused' -> action was not allowed by remote machine
16203:
16204:
16205: =item *
16206:
16207: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16208: reference filled in from namesp (encrypts the return communication)
16209: ($udom and $uname are optional)
16210:
16211: =item *
16212:
16213: log($udom,$name,$home,$message) : write to permanent log for user; use
16214: critical subroutine
16215:
16216: =item *
16217:
16218: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
16219: array reference filled in from namespace found in domain level on either
16220: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
16221:
16222: =item *
16223:
16224: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
16225: domain level either on specified domain server ($uhome) or primary domain
16226: server ($udom and $uhome are optional)
16227:
16228: =item *
16229:
16230: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
16231: for: authentication, language, quotas, timezone, date locale, and portal URL in
16232: the target domain.
16233:
16234: May also include additional key => value pairs for the following groups:
16235:
16236: =over
16237:
16238: =item
16239: disk quotas (MB allocated by default to portfolios and authoring spaces).
16240:
16241: =over
16242:
16243: =item defaultquota, authorquota
16244:
16245: =back
16246:
16247: =item
16248: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
16249: portfolio for users).
16250:
16251: =over
16252:
16253: =item
16254: aboutme, blog, webdav, portfolio
16255:
16256: =back
16257:
16258: =item
16259: requestcourses: ability to request courses, and how requests are processed.
16260:
16261: =over
16262:
16263: =item
16264: official, unofficial, community, textbook, placement
16265:
16266: =back
16267:
16268: =item
16269: inststatus: types of institutional affiliation, and order in which they are displayed.
16270:
16271: =over
16272:
16273: =item
16274: inststatustypes, inststatusorder, inststatusguest
16275:
16276: =back
16277:
16278: =item
16279: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
16280: for course's uploaded content.
16281:
16282: =over
16283:
16284: =item
16285: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
16286: communityquota, textbookquota, placementquota
16287:
16288: =back
16289:
16290: =item
16291: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16292: on your servers.
16293:
16294: =over
16295:
16296: =item
16297: remotesessions, hostedsessions
16298:
16299: =back
16300:
16301: =back
16302:
16303: In cases where a domain coordinator has never used the "Set Domain Configuration"
16304: utility to create a configuration.db file on a domain's primary library server
16305: only the following domain defaults: auth_def, auth_arg_def, lang_def
16306: -- corresponding values are authentication type (internal, krb4, krb5,
16307: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
16308: will be available. Values are retrieved from cache (if current), unless the
16309: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16310: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16311:
16312: Typical usage:
16313:
16314: %domdefaults = &get_domain_defaults($target_domain);
16315:
16316: =back
16317:
16318: =head2 Network Status Functions
16319:
16320: =over 4
16321:
16322: =item *
16323:
16324: dirlist() : return directory list based on URI (first arg).
16325:
16326: Inputs: 1 required, 5 optional.
16327:
16328: =over
16329:
16330: =item
16331: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16332:
16333: =item
16334: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
16335:
16336: =item
16337: $username - username of user/course to be listed. Extracted from $uri if absent.
16338:
16339: =item
16340: $getpropath - boolean: 1 if prepend path using &propath().
16341:
16342: =item
16343: $getuserdir - boolean: 1 if prepend path for "userfiles".
16344:
16345: =item
16346: $alternateRoot - path to prepend in place of path from $uri.
16347:
16348: =back
16349:
16350: Returns: Array of up to two items.
16351:
16352: =over
16353:
16354: a reference to an array of files/subdirectories
16355:
16356: =over
16357:
16358: Each element in the array of files/subdirectories is a & separated list of
16359: item name and the result of running stat on the item. If dirlist was requested
16360: for a file instead of a directory, the item name will be ''. For a directory
16361: listing, if the item is a metadata file, the element will end &N&M
16362: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
16363: default copyright set (1).
16364:
16365: =back
16366:
16367: a scalar containing error condition (if encountered).
16368:
16369: =over
16370:
16371: =item
16372: no_host (no homeserver identified for $username:$domain).
16373:
16374: =item
16375: no_such_host (server contacted for listing not identified as valid host).
16376:
16377: =item
16378: con_lost (connection to remote server failed).
16379:
16380: =item
16381: refused (invalid $username:$domain received on lond side).
16382:
16383: =item
16384: no_such_dir (directory at specified path on lond side does not exist).
16385:
16386: =item
16387: empty (directory at specified path on lond side is empty).
16388:
16389: =over
16390:
16391: This is currently not encountered because the &ls3, &ls2,
16392: &ls (_handler) routines on the lond side do not filter out
16393: . and .. from a directory listing.
16394:
16395: =back
16396:
16397: =back
16398:
16399: =back
16400:
16401: =item *
16402:
16403: spareserver() : find server with least workload from spare.tab
16404:
16405:
16406: =item *
16407:
16408: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
16409: if there is no corresponding loncapa host.
16410:
16411: =back
16412:
16413:
16414: =head2 Apache Request
16415:
16416: =over 4
16417:
16418: =item *
16419:
16420: ssi($url,%hash) : server side include, does a complete request cycle on url to
16421: localhost, posts hash
16422:
16423: =back
16424:
16425: =head2 Data to String to Data
16426:
16427: =over 4
16428:
16429: =item *
16430:
16431: hash2str(%hash) : convert a hash into a string complete with escaping and '='
16432: and '&' separators, supports elements that are arrayrefs and hashrefs
16433:
16434: =item *
16435:
16436: hashref2str($hashref) : convert a hashref into a string complete with
16437: escaping and '=' and '&' separators, supports elements that are
16438: arrayrefs and hashrefs
16439:
16440: =item *
16441:
16442: arrayref2str($arrayref) : convert an arrayref into a string complete
16443: with escaping and '&' separators, supports elements that are arrayrefs
16444: and hashrefs
16445:
16446: =item *
16447:
16448: str2hash($string) : convert string to hash using unescaping and
16449: splitting on '=' and '&', supports elements that are arrayrefs and
16450: hashrefs
16451:
16452: =item *
16453:
16454: str2array($string) : convert string to hash using unescaping and
16455: splitting on '&', supports elements that are arrayrefs and hashrefs
16456:
16457: =back
16458:
16459: =head2 Logging Routines
16460:
16461:
16462: These routines allow one to make log messages in the lonnet.log and
16463: lonnet.perm logfiles.
16464:
16465: =over 4
16466:
16467: =item *
16468:
16469: logtouch() : make sure the logfile, lonnet.log, exists
16470:
16471: =item *
16472:
16473: logthis() : append message to the normal lonnet.log file, it gets
16474: preiodically rolled over and deleted.
16475:
16476: =item *
16477:
16478: logperm() : append a permanent message to lonnet.perm.log, this log
16479: file never gets deleted by any automated portion of the system, only
16480: messages of critical importance should go in here.
16481:
16482:
16483: =back
16484:
16485: =head2 General File Helper Routines
16486:
16487: =over 4
16488:
16489: =item *
16490:
16491: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
16492: (a) files in /uploaded
16493: (i) If a local copy of the file exists -
16494: compares modification date of local copy with last-modified date for
16495: definitive version stored on home server for course. If local copy is
16496: stale, requests a new version from the home server and stores it.
16497: If the original has been removed from the home server, then local copy
16498: is unlinked.
16499: (ii) If local copy does not exist -
16500: requests the file from the home server and stores it.
16501:
16502: If $caller is 'uploadrep':
16503: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
16504: for request for files originally uploaded via DOCS.
16505: - returns 'ok' if fresh local copy now available, -1 otherwise.
16506:
16507: Otherwise:
16508: This indicates a call from the content generation phase of the request.
16509: - returns the entire contents of the file or -1.
16510:
16511: (b) files in /res
16512: - returns the entire contents of a file or -1;
16513: it properly subscribes to and replicates the file if neccessary.
16514:
16515:
16516: =item *
16517:
16518: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
16519: reference
16520:
16521: returns either a stat() list of data about the file or an empty list
16522: if the file doesn't exist or couldn't find out about it (connection
16523: problems or user unknown)
16524:
16525: =item *
16526:
16527: filelocation($dir,$file) : returns file system location of a file
16528: based on URI; meant to be "fairly clean" absolute reference, $dir is a
16529: directory that relative $file lookups are to looked in ($dir of /a/dir
16530: and a file of ../bob will become /a/bob)
16531:
16532: =item *
16533:
16534: hreflocation($dir,$file) : returns file system location or a URL; same as
16535: filelocation except for hrefs
16536:
16537: =item *
16538:
16539: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16540: also removes beginning /home/httpd/html unless /priv/ follows it.
16541:
16542: =back
16543:
16544: =head2 Usererfile file routines (/uploaded*)
16545:
16546: =over 4
16547:
16548: =item *
16549:
16550: userfileupload(): main rotine for putting a file in a user or course's
16551: filespace, arguments are,
16552:
16553: formname - required - this is the name of the element in $env where the
16554: filename, and the contents of the file to create/modifed exist
16555: the filename is in $env{'form.'.$formname.'.filename'} and the
16556: contents of the file is located in $env{'form.'.$formname}
16557: context - if coursedoc, store the file in the course of the active role
16558: of the current user;
16559: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16560: if 'canceloverwrite': delete file in tmp/overwrites directory
16561: subdir - required - subdirectory to put the file in under ../userfiles/
16562: if undefined, it will be placed in "unknown"
16563:
16564: (This routine calls clean_filename() to remove any dangerous
16565: characters from the filename, and then calls finuserfileupload() to
16566: complete the transaction)
16567:
16568: returns either the url of the uploaded file (/uploaded/....) if successful
16569: and /adm/notfound.html if unsuccessful
16570:
16571: =item *
16572:
16573: clean_filename(): routine for cleaing a filename up for storage in
16574: userfile space, argument is:
16575:
16576: filename - proposed filename
16577:
16578: returns: the new clean filename
16579:
16580: =item *
16581:
16582: finishuserfileupload(): routine that creates and sends the file to
16583: userspace, probably shouldn't be called directly
16584:
16585: docuname: username or courseid of destination for the file
16586: docudom: domain of user/course of destination for the file
16587: formname: same as for userfileupload()
16588: fname: filename (including subdirectories) for the file
16589: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
16590: if hashref, and context is scantron, will convert csv format to standard format
16591: allfiles: reference to hash used to store objects found by parser
16592: codebase: reference to hash used for codebases of java objects found by parser
16593: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
16594: thumbheight: height (pixels) of thumbnail to be created for uploaded image
16595: resizewidth: width to be used to resize image using resizeImage from ImageMagick
16596: resizeheight: height to be used to resize image using resizeImage from ImageMagick
16597: context: if 'overwrite', will move the uploaded file from its temporary location to
16598: userfiles to facilitate overwriting a previously uploaded file with same name.
16599: mimetype: reference to scalar to accommodate mime type determined
16600: from File::MMagic if $parser = parse.
16601:
16602: returns either the url of the uploaded file (/uploaded/....) if successful
16603: and /adm/notfound.html if unsuccessful (or an error message if context
16604: was 'overwrite').
16605:
16606:
16607: =item *
16608:
16609: renameuserfile(): renames an existing userfile to a new name
16610:
16611: Args:
16612: docuname: username or courseid of destination for the file
16613: docudom: domain of user/course of destination for the file
16614: old: current file name (including any subdirs under userfiles)
16615: new: desired file name (including any subdirs under userfiles)
16616:
16617: =item *
16618:
16619: mkdiruserfile(): creates a directory is a userfiles dir
16620:
16621: Args:
16622: docuname: username or courseid of destination for the file
16623: docudom: domain of user/course of destination for the file
16624: dir: dir to create (including any subdirs under userfiles)
16625:
16626: =item *
16627:
16628: removeuserfile(): removes a file that exists in userfiles
16629:
16630: Args:
16631: docuname: username or courseid of destination for the file
16632: docudom: domain of user/course of destination for the file
16633: fname: filname to delete (including any subdirs under userfiles)
16634:
16635: =item *
16636:
16637: removeuploadedurl(): convience function for removeuserfile()
16638:
16639: Args:
16640: url: a full /uploaded/... url to delete
16641:
16642: =item *
16643:
16644: get_portfile_permissions():
16645: Args:
16646: domain: domain of user or course contain the portfolio files
16647: user: name of user or num of course contain the portfolio files
16648: Returns:
16649: hashref of a dump of the proper file_permissions.db
16650:
16651:
16652: =item *
16653:
16654: get_access_controls():
16655:
16656: Args:
16657: current_permissions: the hash ref returned from get_portfile_permissions()
16658: group: (optional) the group you want the files associated with
16659: file: (optional) the file you want access info on
16660:
16661: Returns:
16662: a hash (keys are file names) of hashes containing
16663: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
16664: values are XML containing access control settings (see below)
16665:
16666: Internal notes:
16667:
16668: access controls are stored in file_permissions.db as key=value pairs.
16669: key -> path to file/file_name\0uniqueID:scope_end_start
16670: where scope -> public,guest,course,group,domains or users.
16671: end -> UNIX time for end of access (0 -> no end date)
16672: start -> UNIX time for start of access
16673:
16674: value -> XML description of access control
16675: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
16676: <start></start>
16677: <end></end>
16678:
16679: <password></password> for scope type = guest
16680:
16681: <domain></domain> for scope type = course or group
16682: <number></number>
16683: <roles id="">
16684: <role></role>
16685: <access></access>
16686: <section></section>
16687: <group></group>
16688: </roles>
16689:
16690: <dom></dom> for scope type = domains
16691:
16692: <users> for scope type = users
16693: <user>
16694: <uname></uname>
16695: <udom></udom>
16696: </user>
16697: </users>
16698: </scope>
16699:
16700: Access data is also aggregated for each file in an additional key=value pair:
16701: key -> path to file/file_name\0accesscontrol
16702: value -> reference to hash
16703: hash contains key = value pairs
16704: where key = uniqueID:scope_end_start
16705: value = UNIX time record was last updated
16706:
16707: Used to improve speed of look-ups of access controls for each file.
16708:
16709: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
16710:
16711: =item *
16712:
16713: modify_access_controls():
16714:
16715: Modifies access controls for a portfolio file
16716: Args
16717: 1. file name
16718: 2. reference to hash of required changes,
16719: 3. domain
16720: 4. username
16721: where domain,username are the domain of the portfolio owner
16722: (either a user or a course)
16723:
16724: Returns:
16725: 1. result of additions or updates ('ok' or 'error', with error message).
16726: 2. result of deletions ('ok' or 'error', with error message).
16727: 3. reference to hash of any new or updated access controls.
16728: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
16729: key = integer (inbound ID)
16730: value = uniqueID
16731:
16732: =item *
16733:
16734: get_timebased_id():
16735:
16736: Attempts to get a unique timestamp-based suffix for use with items added to a
16737: course via the Course Editor (e.g., folders, composite pages,
16738: group bulletin boards).
16739:
16740: Args: (first three required; six others optional)
16741:
16742: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
16743: docssequence, or name of group
16744:
16745: 2. keyid (alphanumeric): name of temporary locking key in hash,
16746: e.g., num, boardids
16747:
16748: 3. namespace: name of gdbm file used to store suffixes already assigned;
16749: file will be named nohist_namespace.db
16750:
16751: 4. cdom: domain of course; default is current course domain from %env
16752:
16753: 5. cnum: course number; default is current course number from %env
16754:
16755: 6. idtype: set to concat if an additional digit is to be appended to the
16756: unix timestamp to form the suffix, if the plain timestamp is already
16757: in use. Default is to not do this, but simply increment the unix
16758: timestamp by 1 until a unique key is obtained.
16759:
16760: 7. who: holder of locking key; defaults to user:domain for user.
16761:
16762: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
16763: retrying); default is 3.
16764:
16765: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
16766:
16767: Returns:
16768:
16769: 1. suffix obtained (numeric)
16770:
16771: 2. result of deleting locking key (ok if deleted, or lock never obtained)
16772:
16773: 3. error: contains (localized) error message if an error occurred.
16774:
16775:
16776: =back
16777:
16778: =head2 HTTP Helper Routines
16779:
16780: =over 4
16781:
16782: =item *
16783:
16784: escape() : unpack non-word characters into CGI-compatible hex codes
16785:
16786: =item *
16787:
16788: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
16789:
16790: =back
16791:
16792: =head1 PRIVATE SUBROUTINES
16793:
16794: =head2 Underlying communication routines (Shouldn't call)
16795:
16796: =over 4
16797:
16798: =item *
16799:
16800: subreply() : tries to pass a message to lonc, returns con_lost if incapable
16801:
16802: =item *
16803:
16804: reply() : uses subreply to send a message to remote machine, logs all failures
16805:
16806: =item *
16807:
16808: critical() : passes a critical message to another server; if cannot
16809: get through then place message in connection buffer directory and
16810: returns con_delayed, if incapable of saving message, returns
16811: con_failed
16812:
16813: =item *
16814:
16815: reconlonc() : tries to reconnect lonc client processes.
16816:
16817: =back
16818:
16819: =head2 Resource Access Logging
16820:
16821: =over 4
16822:
16823: =item *
16824:
16825: flushcourselogs() : flush (save) buffer logs and access logs
16826:
16827: =item *
16828:
16829: courselog($what) : save message for course in hash
16830:
16831: =item *
16832:
16833: courseacclog($what) : save message for course using &courselog(). Perform
16834: special processing for specific resource types (problems, exams, quizzes, etc).
16835:
16836: =item *
16837:
16838: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16839: as a PerlChildExitHandler
16840:
16841: =back
16842:
16843: =head2 Other
16844:
16845: =over 4
16846:
16847: =item *
16848:
16849: symblist($mapname,%newhash) : update symbolic storage links
16850:
16851: =back
16852:
16853: =cut
16854:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>