1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.1214 2013/02/08 16:07:43 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 LWP::UserAgent();
75: use HTTP::Date;
76: use Image::Magick;
77:
78:
79: use Encode;
80:
81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $apache
82: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
83: %managerstab);
84:
85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
86: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
87: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
88: %courseownerbuf, %coursetypebuf,$locknum);
89:
90: use IO::Socket;
91: use GDBM_File;
92: use HTML::LCParser;
93: use Fcntl qw(:flock);
94: use Storable qw(thaw nfreeze);
95: use Time::HiRes qw( gettimeofday tv_interval );
96: use Cache::Memcached;
97: use Digest::MD5;
98: use Math::Random;
99: use File::MMagic;
100: use LONCAPA qw(:DEFAULT :match);
101: use LONCAPA::Configuration;
102: use LONCAPA::lonmetadata;
103: use LONCAPA::Lond;
104:
105: use File::Copy;
106:
107: my $readit;
108: my $max_connection_retries = 10; # Or some such value.
109:
110: require Exporter;
111:
112: our @ISA = qw (Exporter);
113: our @EXPORT = qw(%env);
114:
115:
116: # ------------------------------------ Logging (parameters, docs, slots, roles)
117: {
118: my $logid;
119: sub write_log {
120: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
121: if ($context eq 'course') {
122: if (($cnum eq '') || ($cdom eq '')) {
123: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
124: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
125: }
126: }
127: $logid ++;
128: my $now = time();
129: my $id=$now.'00000'.$$.'00000'.$logid;
130: my $logentry = {
131: $id => {
132: 'exe_uname' => $env{'user.name'},
133: 'exe_udom' => $env{'user.domain'},
134: 'exe_time' => $now,
135: 'exe_ip' => $ENV{'REMOTE_ADDR'},
136: 'delflag' => $delflag,
137: 'logentry' => $storehash,
138: 'uname' => $uname,
139: 'udom' => $udom,
140: }
141: };
142: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
143: }
144: }
145:
146: sub logtouch {
147: my $execdir=$perlvar{'lonDaemons'};
148: unless (-e "$execdir/logs/lonnet.log") {
149: open(my $fh,">>$execdir/logs/lonnet.log");
150: close $fh;
151: }
152: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
153: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
154: }
155:
156: sub logthis {
157: my $message=shift;
158: my $execdir=$perlvar{'lonDaemons'};
159: my $now=time;
160: my $local=localtime($now);
161: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
162: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
163: print $fh $logstring;
164: close($fh);
165: }
166: return 1;
167: }
168:
169: sub logperm {
170: my $message=shift;
171: my $execdir=$perlvar{'lonDaemons'};
172: my $now=time;
173: my $local=localtime($now);
174: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
175: print $fh "$now:$message:$local\n";
176: close($fh);
177: }
178: return 1;
179: }
180:
181: sub create_connection {
182: my ($hostname,$lonid) = @_;
183: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
184: Type => SOCK_STREAM,
185: Timeout => 10);
186: return 0 if (!$client);
187: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
188: my $result = <$client>;
189: chomp($result);
190: return 1 if ($result eq 'done');
191: return 0;
192: }
193:
194: sub get_server_timezone {
195: my ($cnum,$cdom) = @_;
196: my $home=&homeserver($cnum,$cdom);
197: if ($home ne 'no_host') {
198: my $cachetime = 24*3600;
199: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
200: if (defined($cached)) {
201: return $timezone;
202: } else {
203: my $timezone = &reply('servertimezone',$home);
204: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
205: }
206: }
207: }
208:
209: sub get_server_distarch {
210: my ($lonhost,$ignore_cache) = @_;
211: if (defined($lonhost)) {
212: if (!defined(&hostname($lonhost))) {
213: return;
214: }
215: my $cachetime = 12*3600;
216: if (!$ignore_cache) {
217: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
218: if (defined($cached)) {
219: return $distarch;
220: }
221: }
222: my $rep = &reply('serverdistarch',$lonhost);
223: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
224: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
225: $rep eq '') {
226: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
227: }
228: }
229: return;
230: }
231:
232: sub get_server_loncaparev {
233: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
234: if (defined($lonhost)) {
235: if (!defined(&hostname($lonhost))) {
236: undef($lonhost);
237: }
238: }
239: if (!defined($lonhost)) {
240: if (defined(&domain($dom,'primary'))) {
241: $lonhost=&domain($dom,'primary');
242: if ($lonhost eq 'no_host') {
243: undef($lonhost);
244: }
245: }
246: }
247: if (defined($lonhost)) {
248: my $cachetime = 12*3600;
249: if (!$ignore_cache) {
250: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
251: if (defined($cached)) {
252: return $loncaparev;
253: }
254: }
255: my ($answer,$loncaparev);
256: my @ids=¤t_machine_ids();
257: if (grep(/^\Q$lonhost\E$/,@ids)) {
258: $answer = $perlvar{'lonVersion'};
259: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
260: $loncaparev = $1;
261: }
262: } else {
263: $answer = &reply('serverloncaparev',$lonhost);
264: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
265: if ($caller eq 'loncron') {
266: my $ua=new LWP::UserAgent;
267: $ua->timeout(4);
268: my $protocol = $protocol{$lonhost};
269: $protocol = 'http' if ($protocol ne 'https');
270: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
271: my $request=new HTTP::Request('GET',$url);
272: my $response=$ua->request($request);
273: unless ($response->is_error()) {
274: my $content = $response->content;
275: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
276: $loncaparev = $1;
277: }
278: }
279: } else {
280: $loncaparev = $loncaparevs{$lonhost};
281: }
282: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
283: $loncaparev = $1;
284: }
285: }
286: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
287: }
288: }
289:
290: sub get_server_homeID {
291: my ($hostname,$ignore_cache,$caller) = @_;
292: unless ($ignore_cache) {
293: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
294: if (defined($cached)) {
295: return $serverhomeID;
296: }
297: }
298: my $cachetime = 12*3600;
299: my $serverhomeID;
300: if ($caller eq 'loncron') {
301: my @machine_ids = &machine_ids($hostname);
302: foreach my $id (@machine_ids) {
303: my $response = &reply('serverhomeID',$id);
304: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
305: $serverhomeID = $response;
306: last;
307: }
308: }
309: if ($serverhomeID eq '') {
310: $serverhomeID = $machine_ids[-1];
311: }
312: } else {
313: $serverhomeID = $serverhomeIDs{$hostname};
314: }
315: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
316: }
317:
318: sub get_remote_globals {
319: my ($lonhost,$whathash,$ignore_cache) = @_;
320: my ($result,%returnhash,%whatneeded);
321: if (ref($whathash) eq 'HASH') {
322: foreach my $what (sort(keys(%{$whathash}))) {
323: my $hashid = $lonhost.'-'.$what;
324: my ($response,$cached);
325: unless ($ignore_cache) {
326: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
327: }
328: if (defined($cached)) {
329: $returnhash{$what} = $response;
330: } else {
331: $whatneeded{$what} = 1;
332: }
333: }
334: if (keys(%whatneeded) == 0) {
335: $result = 'ok';
336: } else {
337: my $requested = &freeze_escape(\%whatneeded);
338: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
339: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
340: ($rep eq 'unknown_cmd')) {
341: $result = $rep;
342: } else {
343: $result = 'ok';
344: my @pairs=split(/\&/,$rep);
345: foreach my $item (@pairs) {
346: my ($key,$value)=split(/=/,$item,2);
347: my $what = &unescape($key);
348: my $hashid = $lonhost.'-'.$what;
349: $returnhash{$what}=&thaw_unescape($value);
350: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
351: }
352: }
353: }
354: }
355: return ($result,\%returnhash);
356: }
357:
358: sub remote_devalidate_cache {
359: my ($lonhost,$name,$id) = @_;
360: my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
361: return $response;
362: }
363:
364: # -------------------------------------------------- Non-critical communication
365: sub subreply {
366: my ($cmd,$server)=@_;
367: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
368: #
369: # With loncnew process trimming, there's a timing hole between lonc server
370: # process exit and the master server picking up the listen on the AF_UNIX
371: # socket. In that time interval, a lock file will exist:
372:
373: my $lockfile=$peerfile.".lock";
374: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
375: sleep(1);
376: }
377: # At this point, either a loncnew parent is listening or an old lonc
378: # or loncnew child is listening so we can connect or everything's dead.
379: #
380: # We'll give the connection a few tries before abandoning it. If
381: # connection is not possible, we'll con_lost back to the client.
382: #
383: my $client;
384: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
385: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
386: Type => SOCK_STREAM,
387: Timeout => 10);
388: if ($client) {
389: last; # Connected!
390: } else {
391: &create_connection(&hostname($server),$server);
392: }
393: sleep(1); # Try again later if failed connection.
394: }
395: my $answer;
396: if ($client) {
397: print $client "sethost:$server:$cmd\n";
398: $answer=<$client>;
399: if (!$answer) { $answer="con_lost"; }
400: chomp($answer);
401: } else {
402: $answer = 'con_lost'; # Failed connection.
403: }
404: return $answer;
405: }
406:
407: sub reply {
408: my ($cmd,$server)=@_;
409: unless (defined(&hostname($server))) { return 'no_such_host'; }
410: my $answer=subreply($cmd,$server);
411: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
412: &logthis("<font color=\"blue\">WARNING:".
413: " $cmd to $server returned $answer</font>");
414: }
415: return $answer;
416: }
417:
418: # ----------------------------------------------------------- Send USR1 to lonc
419:
420: sub reconlonc {
421: my ($lonid) = @_;
422: my $hostname = &hostname($lonid);
423: if ($lonid) {
424: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
425: if ($hostname && -e $peerfile) {
426: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
427: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
428: Type => SOCK_STREAM,
429: Timeout => 10);
430: if ($client) {
431: print $client ("reset_retries\n");
432: my $answer=<$client>;
433: #reset just this one.
434: }
435: }
436: return;
437: }
438:
439: &logthis("Trying to reconnect lonc");
440: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
441: if (open(my $fh,"<$loncfile")) {
442: my $loncpid=<$fh>;
443: chomp($loncpid);
444: if (kill 0 => $loncpid) {
445: &logthis("lonc at pid $loncpid responding, sending USR1");
446: kill USR1 => $loncpid;
447: sleep 1;
448: } else {
449: &logthis(
450: "<font color=\"blue\">WARNING:".
451: " lonc at pid $loncpid not responding, giving up</font>");
452: }
453: } else {
454: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
455: }
456: }
457:
458: # ------------------------------------------------------ Critical communication
459:
460: sub critical {
461: my ($cmd,$server)=@_;
462: unless (&hostname($server)) {
463: &logthis("<font color=\"blue\">WARNING:".
464: " Critical message to unknown server ($server)</font>");
465: return 'no_such_host';
466: }
467: my $answer=reply($cmd,$server);
468: if ($answer eq 'con_lost') {
469: &reconlonc("$perlvar{'lonSockDir'}/$server");
470: my $answer=reply($cmd,$server);
471: if ($answer eq 'con_lost') {
472: my $now=time;
473: my $middlename=$cmd;
474: $middlename=substr($middlename,0,16);
475: $middlename=~s/\W//g;
476: my $dfilename=
477: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
478: $dumpcount++;
479: {
480: my $dfh;
481: if (open($dfh,">$dfilename")) {
482: print $dfh "$cmd\n";
483: close($dfh);
484: }
485: }
486: sleep 2;
487: my $wcmd='';
488: {
489: my $dfh;
490: if (open($dfh,"<$dfilename")) {
491: $wcmd=<$dfh>;
492: close($dfh);
493: }
494: }
495: chomp($wcmd);
496: if ($wcmd eq $cmd) {
497: &logthis("<font color=\"blue\">WARNING: ".
498: "Connection buffer $dfilename: $cmd</font>");
499: &logperm("D:$server:$cmd");
500: return 'con_delayed';
501: } else {
502: &logthis("<font color=\"red\">CRITICAL:"
503: ." Critical connection failed: $server $cmd</font>");
504: &logperm("F:$server:$cmd");
505: return 'con_failed';
506: }
507: }
508: }
509: return $answer;
510: }
511:
512: # ------------------------------------------- check if return value is an error
513:
514: sub error {
515: my ($result) = @_;
516: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
517: if ($2 == 2) { return undef; }
518: return $1;
519: }
520: return undef;
521: }
522:
523: sub convert_and_load_session_env {
524: my ($lonidsdir,$handle)=@_;
525: my @profile;
526: {
527: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
528: if (!$opened) {
529: return 0;
530: }
531: flock($idf,LOCK_SH);
532: @profile=<$idf>;
533: close($idf);
534: }
535: my %temp_env;
536: foreach my $line (@profile) {
537: if ($line !~ m/=/) {
538: return 0;
539: }
540: chomp($line);
541: my ($envname,$envvalue)=split(/=/,$line,2);
542: $temp_env{&unescape($envname)} = &unescape($envvalue);
543: }
544: unlink("$lonidsdir/$handle.id");
545: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
546: 0640)) {
547: %disk_env = %temp_env;
548: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
549: untie(%disk_env);
550: }
551: return 1;
552: }
553:
554: # ------------------------------------------- Transfer profile into environment
555: my $env_loaded;
556: sub transfer_profile_to_env {
557: my ($lonidsdir,$handle,$force_transfer) = @_;
558: if (!$force_transfer && $env_loaded) { return; }
559:
560: if (!defined($lonidsdir)) {
561: $lonidsdir = $perlvar{'lonIDsDir'};
562: }
563: if (!defined($handle)) {
564: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
565: }
566:
567: my $convert;
568: {
569: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
570: if (!$opened) {
571: return;
572: }
573: flock($idf,LOCK_SH);
574: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
575: &GDBM_READER(),0640)) {
576: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
577: untie(%disk_env);
578: } else {
579: $convert = 1;
580: }
581: }
582: if ($convert) {
583: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
584: &logthis("Failed to load session, or convert session.");
585: }
586: }
587:
588: my %remove;
589: while ( my $envname = each(%env) ) {
590: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
591: if ($time < time-300) {
592: $remove{$key}++;
593: }
594: }
595: }
596:
597: $env{'user.environment'} = "$lonidsdir/$handle.id";
598: $env_loaded=1;
599: foreach my $expired_key (keys(%remove)) {
600: &delenv($expired_key);
601: }
602: }
603:
604: # ---------------------------------------------------- Check for valid session
605: sub check_for_valid_session {
606: my ($r,$name) = @_;
607: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
608: if ($name eq '') {
609: $name = 'lonID';
610: }
611: my $lonid=$cookies{$name};
612: return undef if (!$lonid);
613:
614: my $handle=&LONCAPA::clean_handle($lonid->value);
615: my $lonidsdir;
616: if ($name eq 'lonDAV') {
617: $lonidsdir=$r->dir_config('lonDAVsessDir');
618: } else {
619: $lonidsdir=$r->dir_config('lonIDsDir');
620: }
621: return undef if (!-e "$lonidsdir/$handle.id");
622:
623: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
624: return undef if (!$opened);
625:
626: flock($idf,LOCK_SH);
627: my %disk_env;
628: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
629: &GDBM_READER(),0640)) {
630: return undef;
631: }
632:
633: if (!defined($disk_env{'user.name'})
634: || !defined($disk_env{'user.domain'})) {
635: return undef;
636: }
637: if (($r->user() eq '') && ($apache >= 2.4)) {
638: if ($disk_env{'user.domain'} eq $r->dir_config('lonDefDomain')) {
639: $r->user($disk_env{'user.name'});
640: } else {
641: $r->user($disk_env{'user.name'}.':'.$disk_env{'user.domain'});
642: }
643: }
644: return $handle;
645: }
646:
647: sub timed_flock {
648: my ($file,$lock_type) = @_;
649: my $failed=0;
650: eval {
651: local $SIG{__DIE__}='DEFAULT';
652: local $SIG{ALRM}=sub {
653: $failed=1;
654: die("failed lock");
655: };
656: alarm(13);
657: flock($file,$lock_type);
658: alarm(0);
659: };
660: if ($failed) {
661: return undef;
662: } else {
663: return 1;
664: }
665: }
666:
667: # ---------------------------------------------------------- Append Environment
668:
669: sub appenv {
670: my ($newenv,$roles) = @_;
671: if (ref($newenv) eq 'HASH') {
672: foreach my $key (keys(%{$newenv})) {
673: my $refused = 0;
674: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
675: $refused = 1;
676: if (ref($roles) eq 'ARRAY') {
677: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
678: if (grep(/^\Q$role\E$/,@{$roles})) {
679: $refused = 0;
680: }
681: }
682: }
683: if ($refused) {
684: &logthis("<font color=\"blue\">WARNING: ".
685: "Attempt to modify environment ".$key." to ".$newenv->{$key}
686: .'</font>');
687: delete($newenv->{$key});
688: } else {
689: $env{$key}=$newenv->{$key};
690: }
691: }
692: my $opened = open(my $env_file,'+<',$env{'user.environment'});
693: if ($opened
694: && &timed_flock($env_file,LOCK_EX)
695: &&
696: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
697: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
698: while (my ($key,$value) = each(%{$newenv})) {
699: $disk_env{$key} = $value;
700: }
701: untie(%disk_env);
702: }
703: }
704: return 'ok';
705: }
706: # ----------------------------------------------------- Delete from Environment
707:
708: sub delenv {
709: my ($delthis,$regexp,$roles) = @_;
710: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
711: my $refused = 1;
712: if (ref($roles) eq 'ARRAY') {
713: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
714: if (grep(/^\Q$role\E$/,@{$roles})) {
715: $refused = 0;
716: }
717: }
718: if ($refused) {
719: &logthis("<font color=\"blue\">WARNING: ".
720: "Attempt to delete from environment ".$delthis);
721: return 'error';
722: }
723: }
724: my $opened = open(my $env_file,'+<',$env{'user.environment'});
725: if ($opened
726: && &timed_flock($env_file,LOCK_EX)
727: &&
728: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
729: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
730: foreach my $key (keys(%disk_env)) {
731: if ($regexp) {
732: if ($key=~/^$delthis/) {
733: delete($env{$key});
734: delete($disk_env{$key});
735: }
736: } else {
737: if ($key=~/^\Q$delthis\E/) {
738: delete($env{$key});
739: delete($disk_env{$key});
740: }
741: }
742: }
743: untie(%disk_env);
744: }
745: return 'ok';
746: }
747:
748: sub get_env_multiple {
749: my ($name) = @_;
750: my @values;
751: if (defined($env{$name})) {
752: # exists is it an array
753: if (ref($env{$name})) {
754: @values=@{ $env{$name} };
755: } else {
756: $values[0]=$env{$name};
757: }
758: }
759: return(@values);
760: }
761:
762: # ------------------------------------------------------------------- Locking
763:
764: sub set_lock {
765: my ($text)=@_;
766: $locknum++;
767: my $id=$$.'-'.$locknum;
768: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
769: 'session.lock.'.$id => $text});
770: return $id;
771: }
772:
773: sub get_locks {
774: my $num=0;
775: my %texts=();
776: foreach my $lock (split(/\,/,$env{'session.locks'})) {
777: if ($lock=~/\w/) {
778: $num++;
779: $texts{$lock}=$env{'session.lock.'.$lock};
780: }
781: }
782: return ($num,%texts);
783: }
784:
785: sub remove_lock {
786: my ($id)=@_;
787: my $newlocks='';
788: foreach my $lock (split(/\,/,$env{'session.locks'})) {
789: if (($lock=~/\w/) && ($lock ne $id)) {
790: $newlocks.=','.$lock;
791: }
792: }
793: &appenv({'session.locks' => $newlocks});
794: &delenv('session.lock.'.$id);
795: }
796:
797: sub remove_all_locks {
798: my $activelocks=$env{'session.locks'};
799: foreach my $lock (split(/\,/,$env{'session.locks'})) {
800: if ($lock=~/\w/) {
801: &remove_lock($lock);
802: }
803: }
804: }
805:
806:
807: # ------------------------------------------ Find out current server userload
808: sub userload {
809: my $numusers=0;
810: {
811: opendir(LONIDS,$perlvar{'lonIDsDir'});
812: my $filename;
813: my $curtime=time;
814: while ($filename=readdir(LONIDS)) {
815: next if ($filename eq '.' || $filename eq '..');
816: next if ($filename =~ /publicuser_\d+\.id/);
817: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
818: if ($curtime-$mtime < 1800) { $numusers++; }
819: }
820: closedir(LONIDS);
821: }
822: my $userloadpercent=0;
823: my $maxuserload=$perlvar{'lonUserLoadLim'};
824: if ($maxuserload) {
825: $userloadpercent=100*$numusers/$maxuserload;
826: }
827: $userloadpercent=sprintf("%.2f",$userloadpercent);
828: return $userloadpercent;
829: }
830:
831: # ------------------------------ Find server with least workload from spare.tab
832:
833: sub spareserver {
834: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
835: my $spare_server;
836: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
837: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
838: : $userloadpercent;
839: my ($uint_dom,$remotesessions);
840: if (($udom ne '') && (&domain($udom) ne '')) {
841: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
842: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
843: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
844: $remotesessions = $udomdefaults{'remotesessions'};
845: }
846: my $spareshash = &this_host_spares($udom);
847: if (ref($spareshash) eq 'HASH') {
848: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
849: foreach my $try_server (@{ $spareshash->{'primary'} }) {
850: if ($uint_dom) {
851: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
852: $try_server));
853: }
854: ($spare_server, $lowest_load) =
855: &compare_server_load($try_server, $spare_server, $lowest_load);
856: }
857: }
858:
859: my $found_server = ($spare_server ne '' && $lowest_load < 100);
860:
861: if (!$found_server) {
862: if (ref($spareshash->{'default'}) eq 'ARRAY') {
863: foreach my $try_server (@{ $spareshash->{'default'} }) {
864: if ($uint_dom) {
865: next unless (&spare_can_host($udom,$uint_dom,
866: $remotesessions,$try_server));
867: }
868: ($spare_server, $lowest_load) =
869: &compare_server_load($try_server, $spare_server, $lowest_load);
870: }
871: }
872: }
873: }
874:
875: if (!$want_server_name) {
876: my $protocol = 'http';
877: if ($protocol{$spare_server} eq 'https') {
878: $protocol = $protocol{$spare_server};
879: }
880: if (defined($spare_server)) {
881: my $hostname = &hostname($spare_server);
882: if (defined($hostname)) {
883: $spare_server = $protocol.'://'.$hostname;
884: }
885: }
886: }
887: return $spare_server;
888: }
889:
890: sub compare_server_load {
891: my ($try_server, $spare_server, $lowest_load) = @_;
892:
893: my $loadans = &reply('load', $try_server);
894: my $userloadans = &reply('userload',$try_server);
895:
896: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
897: return ($spare_server, $lowest_load); #didn't get a number from the server
898: }
899:
900: my $load;
901: if ($loadans =~ /\d/) {
902: if ($userloadans =~ /\d/) {
903: #both are numbers, pick the bigger one
904: $load = ($loadans > $userloadans) ? $loadans
905: : $userloadans;
906: } else {
907: $load = $loadans;
908: }
909: } else {
910: $load = $userloadans;
911: }
912:
913: if (($load =~ /\d/) && ($load < $lowest_load)) {
914: $spare_server = $try_server;
915: $lowest_load = $load;
916: }
917: return ($spare_server,$lowest_load);
918: }
919:
920: # --------------------------- ask offload servers if user already has a session
921: sub find_existing_session {
922: my ($udom,$uname) = @_;
923: my $spareshash = &this_host_spares($udom);
924: if (ref($spareshash) eq 'HASH') {
925: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
926: foreach my $try_server (@{ $spareshash->{'primary'} }) {
927: return $try_server if (&has_user_session($try_server, $udom, $uname));
928: }
929: }
930: if (ref($spareshash->{'default'}) eq 'ARRAY') {
931: foreach my $try_server (@{ $spareshash->{'default'} }) {
932: return $try_server if (&has_user_session($try_server, $udom, $uname));
933: }
934: }
935: }
936: return;
937: }
938:
939: # -------------------------------- ask if server already has a session for user
940: sub has_user_session {
941: my ($lonid,$udom,$uname) = @_;
942: my $result = &reply(join(':','userhassession',
943: map {&escape($_)} ($udom,$uname)),$lonid);
944: return 1 if ($result eq 'ok');
945:
946: return 0;
947: }
948:
949: # --------- determine least loaded server in a user's domain which allows login
950:
951: sub choose_server {
952: my ($udom,$checkloginvia) = @_;
953: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
954: my %servers = &get_servers($udom);
955: my $lowest_load = 30000;
956: my ($login_host,$hostname,$portal_path,$isredirect);
957: foreach my $lonhost (keys(%servers)) {
958: my $loginvia;
959: if ($checkloginvia) {
960: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
961: if ($loginvia) {
962: my ($server,$path) = split(/:/,$loginvia);
963: ($login_host, $lowest_load) =
964: &compare_server_load($server, $login_host, $lowest_load);
965: if ($login_host eq $server) {
966: $portal_path = $path;
967: $isredirect = 1;
968: }
969: } else {
970: ($login_host, $lowest_load) =
971: &compare_server_load($lonhost, $login_host, $lowest_load);
972: if ($login_host eq $lonhost) {
973: $portal_path = '';
974: $isredirect = '';
975: }
976: }
977: } else {
978: ($login_host, $lowest_load) =
979: &compare_server_load($lonhost, $login_host, $lowest_load);
980: }
981: }
982: if ($login_host ne '') {
983: $hostname = &hostname($login_host);
984: }
985: return ($login_host,$hostname,$portal_path,$isredirect);
986: }
987:
988: # --------------------------------------------- Try to change a user's password
989:
990: sub changepass {
991: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
992: $currentpass = &escape($currentpass);
993: $newpass = &escape($newpass);
994: my $lonhost = $perlvar{'lonHostID'};
995: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
996: $server);
997: if (! $answer) {
998: &logthis("No reply on password change request to $server ".
999: "by $uname in domain $udom.");
1000: } elsif ($answer =~ "^ok") {
1001: &logthis("$uname in $udom successfully changed their password ".
1002: "on $server.");
1003: } elsif ($answer =~ "^pwchange_failure") {
1004: &logthis("$uname in $udom was unable to change their password ".
1005: "on $server. The action was blocked by either lcpasswd ".
1006: "or pwchange");
1007: } elsif ($answer =~ "^non_authorized") {
1008: &logthis("$uname in $udom did not get their password correct when ".
1009: "attempting to change it on $server.");
1010: } elsif ($answer =~ "^auth_mode_error") {
1011: &logthis("$uname in $udom attempted to change their password despite ".
1012: "not being locally or internally authenticated on $server.");
1013: } elsif ($answer =~ "^unknown_user") {
1014: &logthis("$uname in $udom attempted to change their password ".
1015: "on $server but were unable to because $server is not ".
1016: "their home server.");
1017: } elsif ($answer =~ "^refused") {
1018: &logthis("$server refused to change $uname in $udom password because ".
1019: "it was sent an unencrypted request to change the password.");
1020: } elsif ($answer =~ "invalid_client") {
1021: &logthis("$server refused to change $uname in $udom password because ".
1022: "it was a reset by e-mail originating from an invalid server.");
1023: }
1024: return $answer;
1025: }
1026:
1027: # ----------------------- Try to determine user's current authentication scheme
1028:
1029: sub queryauthenticate {
1030: my ($uname,$udom)=@_;
1031: my $uhome=&homeserver($uname,$udom);
1032: if (!$uhome) {
1033: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1034: return 'no_host';
1035: }
1036: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1037: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1038: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1039: }
1040: return $answer;
1041: }
1042:
1043: # --------- Try to authenticate user from domain's lib servers (first this one)
1044:
1045: sub authenticate {
1046: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1047: $upass=&escape($upass);
1048: $uname= &LONCAPA::clean_username($uname);
1049: my $uhome=&homeserver($uname,$udom,1);
1050: my $newhome;
1051: if ((!$uhome) || ($uhome eq 'no_host')) {
1052: # Maybe the machine was offline and only re-appeared again recently?
1053: &reconlonc();
1054: # One more
1055: $uhome=&homeserver($uname,$udom,1);
1056: if (($uhome eq 'no_host') && $checkdefauth) {
1057: if (defined(&domain($udom,'primary'))) {
1058: $newhome=&domain($udom,'primary');
1059: }
1060: if ($newhome ne '') {
1061: $uhome = $newhome;
1062: }
1063: }
1064: if ((!$uhome) || ($uhome eq 'no_host')) {
1065: &logthis("User $uname at $udom is unknown in authenticate");
1066: return 'no_host';
1067: }
1068: }
1069: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1070: if ($answer eq 'authorized') {
1071: if ($newhome) {
1072: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1073: return 'no_account_on_host';
1074: } else {
1075: &logthis("User $uname at $udom authorized by $uhome");
1076: return $uhome;
1077: }
1078: }
1079: if ($answer eq 'non_authorized') {
1080: &logthis("User $uname at $udom rejected by $uhome");
1081: return 'no_host';
1082: }
1083: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1084: return 'no_host';
1085: }
1086:
1087: sub can_host_session {
1088: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1089: my $canhost = 1;
1090: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1091: if (ref($remotesessions) eq 'HASH') {
1092: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1093: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1094: $canhost = 0;
1095: } else {
1096: $canhost = 1;
1097: }
1098: }
1099: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1100: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1101: $canhost = 1;
1102: } else {
1103: $canhost = 0;
1104: }
1105: }
1106: if ($canhost) {
1107: if ($remotesessions->{'version'} ne '') {
1108: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1109: if ($reqmajor ne '' && $reqminor ne '') {
1110: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1111: my $major = $1;
1112: my $minor = $2;
1113: if (($major < $reqmajor ) ||
1114: (($major == $reqmajor) && ($minor < $reqminor))) {
1115: $canhost = 0;
1116: }
1117: } else {
1118: $canhost = 0;
1119: }
1120: }
1121: }
1122: }
1123: }
1124: if ($canhost) {
1125: if (ref($hostedsessions) eq 'HASH') {
1126: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1127: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1128: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1129: if (($uint_dom ne '') &&
1130: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1131: $canhost = 0;
1132: } else {
1133: $canhost = 1;
1134: }
1135: }
1136: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1137: if (($uint_dom ne '') &&
1138: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1139: $canhost = 1;
1140: } else {
1141: $canhost = 0;
1142: }
1143: }
1144: }
1145: }
1146: return $canhost;
1147: }
1148:
1149: sub spare_can_host {
1150: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1151: my $canhost=1;
1152: my @intdoms;
1153: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1154: if (ref($internet_names) eq 'ARRAY') {
1155: @intdoms = @{$internet_names};
1156: }
1157: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1158: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1159: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1160: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1161: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1162: $canhost = &can_host_session($udom,$try_server,$remoterev,
1163: $remotesessions,
1164: $defdomdefaults{'hostedsessions'});
1165: }
1166: return $canhost;
1167: }
1168:
1169: sub this_host_spares {
1170: my ($dom) = @_;
1171: my ($dom_in_use,$lonhost_in_use,$result);
1172: my @hosts = ¤t_machine_ids();
1173: foreach my $lonhost (@hosts) {
1174: if (&host_domain($lonhost) eq $dom) {
1175: $dom_in_use = $dom;
1176: $lonhost_in_use = $lonhost;
1177: last;
1178: }
1179: }
1180: if ($dom_in_use ne '') {
1181: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1182: }
1183: if (ref($result) ne 'HASH') {
1184: $lonhost_in_use = $perlvar{'lonHostID'};
1185: $dom_in_use = &host_domain($lonhost_in_use);
1186: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1187: if (ref($result) ne 'HASH') {
1188: $result = \%spareid;
1189: }
1190: }
1191: return $result;
1192: }
1193:
1194: sub spares_for_offload {
1195: my ($dom_in_use,$lonhost_in_use) = @_;
1196: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1197: if (defined($cached)) {
1198: return $result;
1199: } else {
1200: my $cachetime = 60*60*24;
1201: my %domconfig =
1202: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1203: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1204: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1205: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1206: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1207: }
1208: }
1209: }
1210: }
1211: return;
1212: }
1213:
1214: sub get_lonbalancer_config {
1215: my ($servers) = @_;
1216: my ($currbalancer,$currtargets);
1217: if (ref($servers) eq 'HASH') {
1218: foreach my $server (keys(%{$servers})) {
1219: my %what = (
1220: spareid => 1,
1221: perlvar => 1,
1222: );
1223: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1224: if ($result eq 'ok') {
1225: if (ref($returnhash) eq 'HASH') {
1226: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1227: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1228: $currbalancer = $server;
1229: $currtargets = {};
1230: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1231: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1232: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1233: }
1234: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1235: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1236: }
1237: }
1238: last;
1239: }
1240: }
1241: }
1242: }
1243: }
1244: }
1245: return ($currbalancer,$currtargets);
1246: }
1247:
1248: sub check_loadbalancing {
1249: my ($uname,$udom) = @_;
1250: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1251: $rule_in_effect,$offloadto,$otherserver);
1252: my $lonhost = $perlvar{'lonHostID'};
1253: my @hosts = ¤t_machine_ids();
1254: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1255: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1256: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1257: my $serverhomedom = &host_domain($lonhost);
1258:
1259: my $cachetime = 60*60*24;
1260:
1261: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1262: $dom_in_use = $udom;
1263: $homeintdom = 1;
1264: } else {
1265: $dom_in_use = $serverhomedom;
1266: }
1267: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1268: unless (defined($cached)) {
1269: my %domconfig =
1270: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1271: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1272: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1273: }
1274: }
1275: if (ref($result) eq 'HASH') {
1276: ($is_balancer,$currtargets,$currrules) =
1277: &check_balancer_result($result,@hosts);
1278: if ($is_balancer) {
1279: if (ref($currrules) eq 'HASH') {
1280: if ($homeintdom) {
1281: if ($uname ne '') {
1282: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1283: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1284: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1285: $rule_in_effect = $currrules->{'_LC_author'};
1286: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1287: $rule_in_effect = $currrules->{'_LC_adv'}
1288: }
1289: }
1290: if ($rule_in_effect eq '') {
1291: my %userenv = &userenvironment($udom,$uname,'inststatus');
1292: if ($userenv{'inststatus'} ne '') {
1293: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1294: my ($othertitle,$usertypes,$types) =
1295: &Apache::loncommon::sorted_inst_types($udom);
1296: if (ref($types) eq 'ARRAY') {
1297: foreach my $type (@{$types}) {
1298: if (grep(/^\Q$type\E$/,@statuses)) {
1299: if (exists($currrules->{$type})) {
1300: $rule_in_effect = $currrules->{$type};
1301: }
1302: }
1303: }
1304: }
1305: } else {
1306: if (exists($currrules->{'default'})) {
1307: $rule_in_effect = $currrules->{'default'};
1308: }
1309: }
1310: }
1311: } else {
1312: if (exists($currrules->{'default'})) {
1313: $rule_in_effect = $currrules->{'default'};
1314: }
1315: }
1316: } else {
1317: if ($currrules->{'_LC_external'} ne '') {
1318: $rule_in_effect = $currrules->{'_LC_external'};
1319: }
1320: }
1321: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1322: $uname,$udom);
1323: }
1324: }
1325: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1326: my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1327: unless (defined($cached)) {
1328: my %domconfig =
1329: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1330: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1331: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1332: }
1333: }
1334: if (ref($result) eq 'HASH') {
1335: ($is_balancer,$currtargets,$currrules) =
1336: &check_balancer_result($result,@hosts);
1337: if ($is_balancer) {
1338: if (ref($currrules) eq 'HASH') {
1339: if ($currrules->{'_LC_internetdom'} ne '') {
1340: $rule_in_effect = $currrules->{'_LC_internetdom'};
1341: }
1342: }
1343: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1344: $uname,$udom);
1345: }
1346: } else {
1347: if ($perlvar{'lonBalancer'} eq 'yes') {
1348: $is_balancer = 1;
1349: $offloadto = &this_host_spares($dom_in_use);
1350: }
1351: }
1352: } else {
1353: if ($perlvar{'lonBalancer'} eq 'yes') {
1354: $is_balancer = 1;
1355: $offloadto = &this_host_spares($dom_in_use);
1356: }
1357: }
1358: if ($is_balancer) {
1359: my $lowest_load = 30000;
1360: if (ref($offloadto) eq 'HASH') {
1361: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1362: foreach my $try_server (@{$offloadto->{'primary'}}) {
1363: ($otherserver,$lowest_load) =
1364: &compare_server_load($try_server,$otherserver,$lowest_load);
1365: }
1366: }
1367: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1368:
1369: if (!$found_server) {
1370: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1371: foreach my $try_server (@{$offloadto->{'default'}}) {
1372: ($otherserver,$lowest_load) =
1373: &compare_server_load($try_server,$otherserver,$lowest_load);
1374: }
1375: }
1376: }
1377: } elsif (ref($offloadto) eq 'ARRAY') {
1378: if (@{$offloadto} == 1) {
1379: $otherserver = $offloadto->[0];
1380: } elsif (@{$offloadto} > 1) {
1381: foreach my $try_server (@{$offloadto}) {
1382: ($otherserver,$lowest_load) =
1383: &compare_server_load($try_server,$otherserver,$lowest_load);
1384: }
1385: }
1386: }
1387: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1388: $is_balancer = 0;
1389: if ($uname ne '' && $udom ne '') {
1390: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1391:
1392: &appenv({'user.loadbalexempt' => $lonhost,
1393: 'user.loadbalcheck.time' => time});
1394: }
1395: }
1396: }
1397: }
1398: return ($is_balancer,$otherserver);
1399: }
1400:
1401: sub check_balancer_result {
1402: my ($result,@hosts) = @_;
1403: my ($is_balancer,$currtargets,$currrules);
1404: if (ref($result) eq 'HASH') {
1405: if ($result->{'lonhost'} ne '') {
1406: my $currbalancer = $result->{'lonhost'};
1407: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1408: $is_balancer = 1;
1409: $currtargets = $result->{'targets'};
1410: $currrules = $result->{'rules'};
1411: }
1412: } else {
1413: foreach my $key (keys(%{$result})) {
1414: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1415: (ref($result->{$key}) eq 'HASH')) {
1416: $is_balancer = 1;
1417: $currrules = $result->{$key}{'rules'};
1418: $currtargets = $result->{$key}{'targets'};
1419: last;
1420: }
1421: }
1422: }
1423: }
1424: return ($is_balancer,$currtargets,$currrules);
1425: }
1426:
1427: sub get_loadbalancer_targets {
1428: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1429: my $offloadto;
1430: if ($rule_in_effect eq 'none') {
1431: return [$perlvar{'lonHostID'}];
1432: } elsif ($rule_in_effect eq '') {
1433: $offloadto = $currtargets;
1434: } else {
1435: if ($rule_in_effect eq 'homeserver') {
1436: my $homeserver = &homeserver($uname,$udom);
1437: if ($homeserver ne 'no_host') {
1438: $offloadto = [$homeserver];
1439: }
1440: } elsif ($rule_in_effect eq 'externalbalancer') {
1441: my %domconfig =
1442: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1443: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1444: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1445: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1446: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1447: }
1448: }
1449: } else {
1450: my %servers = &internet_dom_servers($udom);
1451: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1452: if (&hostname($remotebalancer) ne '') {
1453: $offloadto = [$remotebalancer];
1454: }
1455: }
1456: } elsif (&hostname($rule_in_effect) ne '') {
1457: $offloadto = [$rule_in_effect];
1458: }
1459: }
1460: return $offloadto;
1461: }
1462:
1463: sub internet_dom_servers {
1464: my ($dom) = @_;
1465: my (%uniqservers,%servers);
1466: my $primaryserver = &hostname(&domain($dom,'primary'));
1467: my @machinedoms = &machine_domains($primaryserver);
1468: foreach my $mdom (@machinedoms) {
1469: my %currservers = %servers;
1470: my %server = &get_servers($mdom);
1471: %servers = (%currservers,%server);
1472: }
1473: my %by_hostname;
1474: foreach my $id (keys(%servers)) {
1475: push(@{$by_hostname{$servers{$id}}},$id);
1476: }
1477: foreach my $hostname (sort(keys(%by_hostname))) {
1478: if (@{$by_hostname{$hostname}} > 1) {
1479: my $match = 0;
1480: foreach my $id (@{$by_hostname{$hostname}}) {
1481: if (&host_domain($id) eq $dom) {
1482: $uniqservers{$id} = $hostname;
1483: $match = 1;
1484: }
1485: }
1486: unless ($match) {
1487: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1488: }
1489: } else {
1490: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1491: }
1492: }
1493: return %uniqservers;
1494: }
1495:
1496: # ---------------------- Find the homebase for a user from domain's lib servers
1497:
1498: my %homecache;
1499: sub homeserver {
1500: my ($uname,$udom,$ignoreBadCache)=@_;
1501: my $index="$uname:$udom";
1502:
1503: if (exists($homecache{$index})) { return $homecache{$index}; }
1504:
1505: my %servers = &get_servers($udom,'library');
1506: foreach my $tryserver (keys(%servers)) {
1507: next if ($ignoreBadCache ne 'true' &&
1508: exists($badServerCache{$tryserver}));
1509:
1510: my $answer=reply("home:$udom:$uname",$tryserver);
1511: if ($answer eq 'found') {
1512: delete($badServerCache{$tryserver});
1513: return $homecache{$index}=$tryserver;
1514: } elsif ($answer eq 'no_host') {
1515: $badServerCache{$tryserver}=1;
1516: }
1517: }
1518: return 'no_host';
1519: }
1520:
1521: # ------------------------------------- Find the usernames behind a list of IDs
1522:
1523: sub idget {
1524: my ($udom,@ids)=@_;
1525: my %returnhash=();
1526:
1527: my %servers = &get_servers($udom,'library');
1528: foreach my $tryserver (keys(%servers)) {
1529: my $idlist=join('&',@ids);
1530: $idlist=~tr/A-Z/a-z/;
1531: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1532: my @answer=();
1533: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1534: @answer=split(/\&/,$reply);
1535: } ;
1536: my $i;
1537: for ($i=0;$i<=$#ids;$i++) {
1538: if ($answer[$i]) {
1539: $returnhash{$ids[$i]}=$answer[$i];
1540: }
1541: }
1542: }
1543: return %returnhash;
1544: }
1545:
1546: # ------------------------------------- Find the IDs behind a list of usernames
1547:
1548: sub idrget {
1549: my ($udom,@unames)=@_;
1550: my %returnhash=();
1551: foreach my $uname (@unames) {
1552: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1553: }
1554: return %returnhash;
1555: }
1556:
1557: # ------------------------------- Store away a list of names and associated IDs
1558:
1559: sub idput {
1560: my ($udom,%ids)=@_;
1561: my %servers=();
1562: foreach my $uname (keys(%ids)) {
1563: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1564: my $uhom=&homeserver($uname,$udom);
1565: if ($uhom ne 'no_host') {
1566: my $id=&escape($ids{$uname});
1567: $id=~tr/A-Z/a-z/;
1568: my $esc_unam=&escape($uname);
1569: if ($servers{$uhom}) {
1570: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1571: } else {
1572: $servers{$uhom}=$id.'='.$esc_unam;
1573: }
1574: }
1575: }
1576: foreach my $server (keys(%servers)) {
1577: &critical('idput:'.$udom.':'.$servers{$server},$server);
1578: }
1579: }
1580:
1581: # ------------------------------dump from db file owned by domainconfig user
1582: sub dump_dom {
1583: my ($namespace, $udom, $regexp) = @_;
1584:
1585: $udom ||= $env{'user.domain'};
1586:
1587: return () unless $udom;
1588:
1589: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1590: }
1591:
1592: # ------------------------------------------ get items from domain db files
1593:
1594: sub get_dom {
1595: my ($namespace,$storearr,$udom,$uhome)=@_;
1596: my $items='';
1597: foreach my $item (@$storearr) {
1598: $items.=&escape($item).'&';
1599: }
1600: $items=~s/\&$//;
1601: if (!$udom) {
1602: $udom=$env{'user.domain'};
1603: if (defined(&domain($udom,'primary'))) {
1604: $uhome=&domain($udom,'primary');
1605: } else {
1606: undef($uhome);
1607: }
1608: } else {
1609: if (!$uhome) {
1610: if (defined(&domain($udom,'primary'))) {
1611: $uhome=&domain($udom,'primary');
1612: }
1613: }
1614: }
1615: if ($udom && $uhome && ($uhome ne 'no_host')) {
1616: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1617: my %returnhash;
1618: if ($rep eq '' || $rep =~ /^error: 2 /) {
1619: return %returnhash;
1620: }
1621: my @pairs=split(/\&/,$rep);
1622: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1623: return @pairs;
1624: }
1625: my $i=0;
1626: foreach my $item (@$storearr) {
1627: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1628: $i++;
1629: }
1630: return %returnhash;
1631: } else {
1632: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1633: }
1634: }
1635:
1636: # -------------------------------------------- put items in domain db files
1637:
1638: sub put_dom {
1639: my ($namespace,$storehash,$udom,$uhome)=@_;
1640: if (!$udom) {
1641: $udom=$env{'user.domain'};
1642: if (defined(&domain($udom,'primary'))) {
1643: $uhome=&domain($udom,'primary');
1644: } else {
1645: undef($uhome);
1646: }
1647: } else {
1648: if (!$uhome) {
1649: if (defined(&domain($udom,'primary'))) {
1650: $uhome=&domain($udom,'primary');
1651: }
1652: }
1653: }
1654: if ($udom && $uhome && ($uhome ne 'no_host')) {
1655: my $items='';
1656: foreach my $item (keys(%$storehash)) {
1657: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1658: }
1659: $items=~s/\&$//;
1660: return &reply("putdom:$udom:$namespace:$items",$uhome);
1661: } else {
1662: &logthis("put_dom failed - no homeserver and/or domain");
1663: }
1664: }
1665:
1666: # --------------------- newput for items in db file owned by domainconfig user
1667: sub newput_dom {
1668: my ($namespace,$storehash,$udom) = @_;
1669: my $result;
1670: if (!$udom) {
1671: $udom=$env{'user.domain'};
1672: }
1673: if ($udom) {
1674: my $uname = &get_domainconfiguser($udom);
1675: $result = &newput($namespace,$storehash,$udom,$uname);
1676: }
1677: return $result;
1678: }
1679:
1680: # --------------------- delete for items in db file owned by domainconfig user
1681: sub del_dom {
1682: my ($namespace,$storearr,$udom)=@_;
1683: if (ref($storearr) eq 'ARRAY') {
1684: if (!$udom) {
1685: $udom=$env{'user.domain'};
1686: }
1687: if ($udom) {
1688: my $uname = &get_domainconfiguser($udom);
1689: return &del($namespace,$storearr,$udom,$uname);
1690: }
1691: }
1692: }
1693:
1694: # ----------------------------------construct domainconfig user for a domain
1695: sub get_domainconfiguser {
1696: my ($udom) = @_;
1697: return $udom.'-domainconfig';
1698: }
1699:
1700: sub retrieve_inst_usertypes {
1701: my ($udom) = @_;
1702: my (%returnhash,@order);
1703: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1704: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1705: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1706: %returnhash = %{$domdefs{'inststatustypes'}};
1707: @order = @{$domdefs{'inststatusorder'}};
1708: } else {
1709: if (defined(&domain($udom,'primary'))) {
1710: my $uhome=&domain($udom,'primary');
1711: my $rep=&reply("inst_usertypes:$udom",$uhome);
1712: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1713: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1714: return (\%returnhash,\@order);
1715: }
1716: my ($hashitems,$orderitems) = split(/:/,$rep);
1717: my @pairs=split(/\&/,$hashitems);
1718: foreach my $item (@pairs) {
1719: my ($key,$value)=split(/=/,$item,2);
1720: $key = &unescape($key);
1721: next if ($key =~ /^error: 2 /);
1722: $returnhash{$key}=&thaw_unescape($value);
1723: }
1724: my @esc_order = split(/\&/,$orderitems);
1725: foreach my $item (@esc_order) {
1726: push(@order,&unescape($item));
1727: }
1728: } else {
1729: &logthis("get_dom failed - no primary domain server for $udom");
1730: }
1731: }
1732: return (\%returnhash,\@order);
1733: }
1734:
1735: sub is_domainimage {
1736: my ($url) = @_;
1737: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1738: if (&domain($1) ne '') {
1739: return '1';
1740: }
1741: }
1742: return;
1743: }
1744:
1745: sub inst_directory_query {
1746: my ($srch) = @_;
1747: my $udom = $srch->{'srchdomain'};
1748: my %results;
1749: my $homeserver = &domain($udom,'primary');
1750: my $outcome;
1751: if ($homeserver ne '') {
1752: my $queryid=&reply("querysend:instdirsearch:".
1753: &escape($srch->{'srchby'}).':'.
1754: &escape($srch->{'srchterm'}).':'.
1755: &escape($srch->{'srchtype'}),$homeserver);
1756: my $host=&hostname($homeserver);
1757: if ($queryid !~/^\Q$host\E\_/) {
1758: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1759: return;
1760: }
1761: my $response = &get_query_reply($queryid);
1762: my $maxtries = 5;
1763: my $tries = 1;
1764: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1765: $response = &get_query_reply($queryid);
1766: $tries ++;
1767: }
1768:
1769: if (!&error($response) && $response ne 'refused') {
1770: if ($response eq 'unavailable') {
1771: $outcome = $response;
1772: } else {
1773: $outcome = 'ok';
1774: my @matches = split(/\n/,$response);
1775: foreach my $match (@matches) {
1776: my ($key,$value) = split(/=/,$match);
1777: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1778: }
1779: }
1780: }
1781: }
1782: return ($outcome,%results);
1783: }
1784:
1785: sub usersearch {
1786: my ($srch) = @_;
1787: my $dom = $srch->{'srchdomain'};
1788: my %results;
1789: my %libserv = &all_library();
1790: my $query = 'usersearch';
1791: foreach my $tryserver (keys(%libserv)) {
1792: if (&host_domain($tryserver) eq $dom) {
1793: my $host=&hostname($tryserver);
1794: my $queryid=
1795: &reply("querysend:".&escape($query).':'.
1796: &escape($srch->{'srchby'}).':'.
1797: &escape($srch->{'srchtype'}).':'.
1798: &escape($srch->{'srchterm'}),$tryserver);
1799: if ($queryid !~/^\Q$host\E\_/) {
1800: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1801: next;
1802: }
1803: my $reply = &get_query_reply($queryid);
1804: my $maxtries = 1;
1805: my $tries = 1;
1806: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1807: $reply = &get_query_reply($queryid);
1808: $tries ++;
1809: }
1810: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1811: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1812: } else {
1813: my @matches;
1814: if ($reply =~ /\n/) {
1815: @matches = split(/\n/,$reply);
1816: } else {
1817: @matches = split(/\&/,$reply);
1818: }
1819: foreach my $match (@matches) {
1820: my ($uname,$udom,%userhash);
1821: foreach my $entry (split(/:/,$match)) {
1822: my ($key,$value) =
1823: map {&unescape($_);} split(/=/,$entry);
1824: $userhash{$key} = $value;
1825: if ($key eq 'username') {
1826: $uname = $value;
1827: } elsif ($key eq 'domain') {
1828: $udom = $value;
1829: }
1830: }
1831: $results{$uname.':'.$udom} = \%userhash;
1832: }
1833: }
1834: }
1835: }
1836: return %results;
1837: }
1838:
1839: sub get_instuser {
1840: my ($udom,$uname,$id) = @_;
1841: my $homeserver = &domain($udom,'primary');
1842: my ($outcome,%results);
1843: if ($homeserver ne '') {
1844: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1845: &escape($id).':'.&escape($udom),$homeserver);
1846: my $host=&hostname($homeserver);
1847: if ($queryid !~/^\Q$host\E\_/) {
1848: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1849: return;
1850: }
1851: my $response = &get_query_reply($queryid);
1852: my $maxtries = 5;
1853: my $tries = 1;
1854: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1855: $response = &get_query_reply($queryid);
1856: $tries ++;
1857: }
1858: if (!&error($response) && $response ne 'refused') {
1859: if ($response eq 'unavailable') {
1860: $outcome = $response;
1861: } else {
1862: $outcome = 'ok';
1863: my @matches = split(/\n/,$response);
1864: foreach my $match (@matches) {
1865: my ($key,$value) = split(/=/,$match);
1866: $results{&unescape($key)} = &thaw_unescape($value);
1867: }
1868: }
1869: }
1870: }
1871: my %userinfo;
1872: if (ref($results{$uname}) eq 'HASH') {
1873: %userinfo = %{$results{$uname}};
1874: }
1875: return ($outcome,%userinfo);
1876: }
1877:
1878: sub inst_rulecheck {
1879: my ($udom,$uname,$id,$item,$rules) = @_;
1880: my %returnhash;
1881: if ($udom ne '') {
1882: if (ref($rules) eq 'ARRAY') {
1883: @{$rules} = map {&escape($_);} (@{$rules});
1884: my $rulestr = join(':',@{$rules});
1885: my $homeserver=&domain($udom,'primary');
1886: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1887: my $response;
1888: if ($item eq 'username') {
1889: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1890: ':'.&escape($uname).':'.$rulestr,
1891: $homeserver));
1892: } elsif ($item eq 'id') {
1893: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1894: ':'.&escape($id).':'.$rulestr,
1895: $homeserver));
1896: } elsif ($item eq 'selfcreate') {
1897: $response=&unescape(&reply('instselfcreatecheck:'.
1898: &escape($udom).':'.&escape($uname).
1899: ':'.$rulestr,$homeserver));
1900: }
1901: if ($response ne 'refused') {
1902: my @pairs=split(/\&/,$response);
1903: foreach my $item (@pairs) {
1904: my ($key,$value)=split(/=/,$item,2);
1905: $key = &unescape($key);
1906: next if ($key =~ /^error: 2 /);
1907: $returnhash{$key}=&thaw_unescape($value);
1908: }
1909: }
1910: }
1911: }
1912: }
1913: return %returnhash;
1914: }
1915:
1916: sub inst_userrules {
1917: my ($udom,$check) = @_;
1918: my (%ruleshash,@ruleorder);
1919: if ($udom ne '') {
1920: my $homeserver=&domain($udom,'primary');
1921: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1922: my $response;
1923: if ($check eq 'id') {
1924: $response=&reply('instidrules:'.&escape($udom),
1925: $homeserver);
1926: } elsif ($check eq 'email') {
1927: $response=&reply('instemailrules:'.&escape($udom),
1928: $homeserver);
1929: } else {
1930: $response=&reply('instuserrules:'.&escape($udom),
1931: $homeserver);
1932: }
1933: if (($response ne 'refused') && ($response ne 'error') &&
1934: ($response ne 'unknown_cmd') &&
1935: ($response ne 'no_such_host')) {
1936: my ($hashitems,$orderitems) = split(/:/,$response);
1937: my @pairs=split(/\&/,$hashitems);
1938: foreach my $item (@pairs) {
1939: my ($key,$value)=split(/=/,$item,2);
1940: $key = &unescape($key);
1941: next if ($key =~ /^error: 2 /);
1942: $ruleshash{$key}=&thaw_unescape($value);
1943: }
1944: my @esc_order = split(/\&/,$orderitems);
1945: foreach my $item (@esc_order) {
1946: push(@ruleorder,&unescape($item));
1947: }
1948: }
1949: }
1950: }
1951: return (\%ruleshash,\@ruleorder);
1952: }
1953:
1954: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1955:
1956: sub get_domain_defaults {
1957: my ($domain) = @_;
1958: my $cachetime = 60*60*24;
1959: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1960: if (defined($cached)) {
1961: if (ref($result) eq 'HASH') {
1962: return %{$result};
1963: }
1964: }
1965: my %domdefaults;
1966: my %domconfig =
1967: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1968: 'requestcourses','inststatus',
1969: 'coursedefaults','usersessions',
1970: 'requestauthor'],$domain);
1971: if (ref($domconfig{'defaults'}) eq 'HASH') {
1972: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1973: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1974: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1975: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1976: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1977: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1978: } else {
1979: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1980: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1981: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1982: }
1983: if (ref($domconfig{'quotas'}) eq 'HASH') {
1984: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1985: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1986: } else {
1987: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1988: }
1989: my @usertools = ('aboutme','blog','webdav','portfolio');
1990: foreach my $item (@usertools) {
1991: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1992: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1993: }
1994: }
1995: }
1996: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1997: foreach my $item ('official','unofficial','community') {
1998: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1999: }
2000: }
2001: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2002: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2003: }
2004: if (ref($domconfig{'inststatus'}) eq 'HASH') {
2005: foreach my $item ('inststatustypes','inststatusorder') {
2006: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2007: }
2008: }
2009: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
2010: foreach my $item ('canuse_pdfforms') {
2011: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
2012: }
2013: }
2014: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2015: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2016: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2017: }
2018: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2019: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2020: }
2021: }
2022: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
2023: $cachetime);
2024: return %domdefaults;
2025: }
2026:
2027: # --------------------------------------------------- Assign a key to a student
2028:
2029: sub assign_access_key {
2030: #
2031: # a valid key looks like uname:udom#comments
2032: # comments are being appended
2033: #
2034: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2035: $kdom=
2036: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
2037: $knum=
2038: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
2039: $cdom=
2040: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2041: $cnum=
2042: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2043: $udom=$env{'user.name'} unless (defined($udom));
2044: $uname=$env{'user.domain'} unless (defined($uname));
2045: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
2046: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
2047: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
2048: # assigned to this person
2049: # - this should not happen,
2050: # unless something went wrong
2051: # the first time around
2052: # ready to assign
2053: $logentry=$1.'; '.$logentry;
2054: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
2055: $kdom,$knum) eq 'ok') {
2056: # key now belongs to user
2057: my $envkey='key.'.$cdom.'_'.$cnum;
2058: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
2059: &appenv({'environment.'.$envkey => $ckey});
2060: return 'ok';
2061: } else {
2062: return
2063: 'error: Count not permanently assign key, will need to be re-entered later.';
2064: }
2065: } else {
2066: return 'error: Could not assign key, try again later.';
2067: }
2068: } elsif (!$existing{$ckey}) {
2069: # the key does not exist
2070: return 'error: The key does not exist';
2071: } else {
2072: # the key is somebody else's
2073: return 'error: The key is already in use';
2074: }
2075: }
2076:
2077: # ------------------------------------------ put an additional comment on a key
2078:
2079: sub comment_access_key {
2080: #
2081: # a valid key looks like uname:udom#comments
2082: # comments are being appended
2083: #
2084: my ($ckey,$cdom,$cnum,$logentry)=@_;
2085: $cdom=
2086: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2087: $cnum=
2088: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2089: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2090: if ($existing{$ckey}) {
2091: $existing{$ckey}.='; '.$logentry;
2092: # ready to assign
2093: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
2094: $cdom,$cnum) eq 'ok') {
2095: return 'ok';
2096: } else {
2097: return 'error: Count not store comment.';
2098: }
2099: } else {
2100: # the key does not exist
2101: return 'error: The key does not exist';
2102: }
2103: }
2104:
2105: # ------------------------------------------------------ Generate a set of keys
2106:
2107: sub generate_access_keys {
2108: my ($number,$cdom,$cnum,$logentry)=@_;
2109: $cdom=
2110: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2111: $cnum=
2112: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2113: unless (&allowed('mky',$cdom)) { return 0; }
2114: unless (($cdom) && ($cnum)) { return 0; }
2115: if ($number>10000) { return 0; }
2116: sleep(2); # make sure don't get same seed twice
2117: srand(time()^($$+($$<<15))); # from "Programming Perl"
2118: my $total=0;
2119: for (my $i=1;$i<=$number;$i++) {
2120: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2121: sprintf("%lx",int(100000*rand)).'-'.
2122: sprintf("%lx",int(100000*rand));
2123: $newkey=~s/1/g/g; # folks mix up 1 and l
2124: $newkey=~s/0/h/g; # and also 0 and O
2125: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2126: if ($existing{$newkey}) {
2127: $i--;
2128: } else {
2129: if (&put('accesskeys',
2130: { $newkey => '# generated '.localtime().
2131: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
2132: '; '.$logentry },
2133: $cdom,$cnum) eq 'ok') {
2134: $total++;
2135: }
2136: }
2137: }
2138: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
2139: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2140: return $total;
2141: }
2142:
2143: # ------------------------------------------------------- Validate an accesskey
2144:
2145: sub validate_access_key {
2146: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2147: $cdom=
2148: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2149: $cnum=
2150: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2151: $udom=$env{'user.domain'} unless (defined($udom));
2152: $uname=$env{'user.name'} unless (defined($uname));
2153: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2154: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
2155: }
2156:
2157: # ------------------------------------- Find the section of student in a course
2158: sub devalidate_getsection_cache {
2159: my ($udom,$unam,$courseid)=@_;
2160: my $hashid="$udom:$unam:$courseid";
2161: &devalidate_cache_new('getsection',$hashid);
2162: }
2163:
2164: sub courseid_to_courseurl {
2165: my ($courseid) = @_;
2166: #already url style courseid
2167: return $courseid if ($courseid =~ m{^/});
2168:
2169: if (exists($env{'course.'.$courseid.'.num'})) {
2170: my $cnum = $env{'course.'.$courseid.'.num'};
2171: my $cdom = $env{'course.'.$courseid.'.domain'};
2172: return "/$cdom/$cnum";
2173: }
2174:
2175: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2176: if (exists($courseinfo{'num'})) {
2177: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2178: }
2179:
2180: return undef;
2181: }
2182:
2183: sub getsection {
2184: my ($udom,$unam,$courseid)=@_;
2185: my $cachetime=1800;
2186:
2187: my $hashid="$udom:$unam:$courseid";
2188: my ($result,$cached)=&is_cached_new('getsection',$hashid);
2189: if (defined($cached)) { return $result; }
2190:
2191: my %Pending;
2192: my %Expired;
2193: #
2194: # Each role can either have not started yet (pending), be active,
2195: # or have expired.
2196: #
2197: # If there is an active role, we are done.
2198: #
2199: # If there is more than one role which has not started yet,
2200: # choose the one which will start sooner
2201: # If there is one role which has not started yet, return it.
2202: #
2203: # If there is more than one expired role, choose the one which ended last.
2204: # If there is a role which has expired, return it.
2205: #
2206: $courseid = &courseid_to_courseurl($courseid);
2207: my %roleshash = &dump('roles',$udom,$unam,$courseid);
2208: foreach my $key (keys(%roleshash)) {
2209: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
2210: my $section=$1;
2211: if ($key eq $courseid.'_st') { $section=''; }
2212: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
2213: my $now=time;
2214: if (defined($end) && $end && ($now > $end)) {
2215: $Expired{$end}=$section;
2216: next;
2217: }
2218: if (defined($start) && $start && ($now < $start)) {
2219: $Pending{$start}=$section;
2220: next;
2221: }
2222: return &do_cache_new('getsection',$hashid,$section,$cachetime);
2223: }
2224: #
2225: # Presumedly there will be few matching roles from the above
2226: # loop and the sorting time will be negligible.
2227: if (scalar(keys(%Pending))) {
2228: my ($time) = sort {$a <=> $b} keys(%Pending);
2229: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
2230: }
2231: if (scalar(keys(%Expired))) {
2232: my @sorted = sort {$a <=> $b} keys(%Expired);
2233: my $time = pop(@sorted);
2234: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
2235: }
2236: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
2237: }
2238:
2239: sub save_cache {
2240: &purge_remembered();
2241: #&Apache::loncommon::validate_page();
2242: undef(%env);
2243: undef($env_loaded);
2244: }
2245:
2246: my $to_remember=-1;
2247: my %remembered;
2248: my %accessed;
2249: my $kicks=0;
2250: my $hits=0;
2251: sub make_key {
2252: my ($name,$id) = @_;
2253: if (length($id) > 65
2254: && length(&escape($id)) > 200) {
2255: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2256: }
2257: return &escape($name.':'.$id);
2258: }
2259:
2260: sub devalidate_cache_new {
2261: my ($name,$id,$debug) = @_;
2262: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
2263: $id=&make_key($name,$id);
2264: $memcache->delete($id);
2265: delete($remembered{$id});
2266: delete($accessed{$id});
2267: }
2268:
2269: sub is_cached_new {
2270: my ($name,$id,$debug) = @_;
2271: $id=&make_key($name,$id);
2272: if (exists($remembered{$id})) {
2273: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
2274: $accessed{$id}=[&gettimeofday()];
2275: $hits++;
2276: return ($remembered{$id},1);
2277: }
2278: my $value = $memcache->get($id);
2279: if (!(defined($value))) {
2280: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
2281: return (undef,undef);
2282: }
2283: if ($value eq '__undef__') {
2284: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2285: $value=undef;
2286: }
2287: &make_room($id,$value,$debug);
2288: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2289: return ($value,1);
2290: }
2291:
2292: sub do_cache_new {
2293: my ($name,$id,$value,$time,$debug) = @_;
2294: $id=&make_key($name,$id);
2295: my $setvalue=$value;
2296: if (!defined($setvalue)) {
2297: $setvalue='__undef__';
2298: }
2299: if (!defined($time) ) {
2300: $time=600;
2301: }
2302: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
2303: my $result = $memcache->set($id,$setvalue,$time);
2304: if (! $result) {
2305: &logthis("caching of id -> $id failed");
2306: $memcache->disconnect_all();
2307: }
2308: # need to make a copy of $value
2309: &make_room($id,$value,$debug);
2310: return $value;
2311: }
2312:
2313: sub make_room {
2314: my ($id,$value,$debug)=@_;
2315:
2316: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2317: : $value;
2318: if ($to_remember<0) { return; }
2319: $accessed{$id}=[&gettimeofday()];
2320: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2321: my $to_kick;
2322: my $max_time=0;
2323: foreach my $other (keys(%accessed)) {
2324: if (&tv_interval($accessed{$other}) > $max_time) {
2325: $to_kick=$other;
2326: $max_time=&tv_interval($accessed{$other});
2327: }
2328: }
2329: delete($remembered{$to_kick});
2330: delete($accessed{$to_kick});
2331: $kicks++;
2332: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
2333: return;
2334: }
2335:
2336: sub purge_remembered {
2337: #&logthis("Tossing ".scalar(keys(%remembered)));
2338: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
2339: undef(%remembered);
2340: undef(%accessed);
2341: }
2342: # ------------------------------------- Read an entry from a user's environment
2343:
2344: sub userenvironment {
2345: my ($udom,$unam,@what)=@_;
2346: my $items;
2347: foreach my $item (@what) {
2348: $items.=&escape($item).'&';
2349: }
2350: $items=~s/\&$//;
2351: my %returnhash=();
2352: my $uhome = &homeserver($unam,$udom);
2353: unless ($uhome eq 'no_host') {
2354: my @answer=split(/\&/,
2355: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
2356: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2357: return %returnhash;
2358: }
2359: my $i;
2360: for ($i=0;$i<=$#what;$i++) {
2361: $returnhash{$what[$i]}=&unescape($answer[$i]);
2362: }
2363: }
2364: return %returnhash;
2365: }
2366:
2367: # ---------------------------------------------------------- Get a studentphoto
2368: sub studentphoto {
2369: my ($udom,$unam,$ext) = @_;
2370: my $home=&Apache::lonnet::homeserver($unam,$udom);
2371: if (defined($env{'request.course.id'})) {
2372: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
2373: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2374: return(&retrievestudentphoto($udom,$unam,$ext));
2375: } else {
2376: my ($result,$perm_reqd)=
2377: &Apache::lonnet::auto_photo_permission($unam,$udom);
2378: if ($result eq 'ok') {
2379: if (!($perm_reqd eq 'yes')) {
2380: return(&retrievestudentphoto($udom,$unam,$ext));
2381: }
2382: }
2383: }
2384: }
2385: } else {
2386: my ($result,$perm_reqd) =
2387: &Apache::lonnet::auto_photo_permission($unam,$udom);
2388: if ($result eq 'ok') {
2389: if (!($perm_reqd eq 'yes')) {
2390: return(&retrievestudentphoto($udom,$unam,$ext));
2391: }
2392: }
2393: }
2394: return '/adm/lonKaputt/lonlogo_broken.gif';
2395: }
2396:
2397: sub retrievestudentphoto {
2398: my ($udom,$unam,$ext,$type) = @_;
2399: my $home=&Apache::lonnet::homeserver($unam,$udom);
2400: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2401: if ($ret eq 'ok') {
2402: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2403: if ($type eq 'thumbnail') {
2404: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2405: }
2406: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2407: return $tokenurl;
2408: } else {
2409: if ($type eq 'thumbnail') {
2410: return '/adm/lonKaputt/genericstudent_tn.gif';
2411: } else {
2412: return '/adm/lonKaputt/lonlogo_broken.gif';
2413: }
2414: }
2415: }
2416:
2417: # -------------------------------------------------------------------- New chat
2418:
2419: sub chatsend {
2420: my ($newentry,$anon,$group)=@_;
2421: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2422: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2423: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
2424: &reply('chatsend:'.$cdom.':'.$cnum.':'.
2425: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
2426: &escape($newentry)).':'.$group,$chome);
2427: }
2428:
2429: # ------------------------------------------ Find current version of a resource
2430:
2431: sub getversion {
2432: my $fname=&clutter(shift);
2433: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
2434: return ¤tversion(&filelocation('',$fname));
2435: }
2436:
2437: sub currentversion {
2438: my $fname=shift;
2439: my $author=$fname;
2440: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2441: my ($udom,$uname)=split(/\//,$author);
2442: my $home=&homeserver($uname,$udom);
2443: if ($home eq 'no_host') {
2444: return -1;
2445: }
2446: my $answer=&reply("currentversion:$fname",$home);
2447: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2448: return -1;
2449: }
2450: return $answer;
2451: }
2452:
2453: #
2454: # Return special version number of resource if set by override, empty otherwise
2455: #
2456: sub usedversion {
2457: my $fname=shift;
2458: unless ($fname) { $fname=$env{'request.uri'}; }
2459: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2460: if ($urlversion) { return $urlversion; }
2461: return '';
2462: }
2463:
2464: # ----------------------------- Subscribe to a resource, return URL if possible
2465:
2466: sub subscribe {
2467: my $fname=shift;
2468: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
2469: $fname=~s/[\n\r]//g;
2470: my $author=$fname;
2471: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2472: my ($udom,$uname)=split(/\//,$author);
2473: my $home=homeserver($uname,$udom);
2474: if ($home eq 'no_host') {
2475: return 'not_found';
2476: }
2477: my $answer=reply("sub:$fname",$home);
2478: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2479: $answer.=' by '.$home;
2480: }
2481: return $answer;
2482: }
2483:
2484: # -------------------------------------------------------------- Replicate file
2485:
2486: sub repcopy {
2487: my $filename=shift;
2488: $filename=~s/\/+/\//g;
2489: my $londocroot = $perlvar{'lonDocRoot'};
2490: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
2491: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
2492: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2493: $filename=~m{^/*(uploaded|editupload)/}) {
2494: return &repcopy_userfile($filename);
2495: }
2496: $filename=~s/[\n\r]//g;
2497: my $transname="$filename.in.transfer";
2498: # FIXME: this should flock
2499: if ((-e $filename) || (-e $transname)) { return 'ok'; }
2500: my $remoteurl=subscribe($filename);
2501: if ($remoteurl =~ /^con_lost by/) {
2502: &logthis("Subscribe returned $remoteurl: $filename");
2503: return 'unavailable';
2504: } elsif ($remoteurl eq 'not_found') {
2505: #&logthis("Subscribe returned not_found: $filename");
2506: return 'not_found';
2507: } elsif ($remoteurl =~ /^rejected by/) {
2508: &logthis("Subscribe returned $remoteurl: $filename");
2509: return 'forbidden';
2510: } elsif ($remoteurl eq 'directory') {
2511: return 'ok';
2512: } else {
2513: my $author=$filename;
2514: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2515: my ($udom,$uname)=split(/\//,$author);
2516: my $home=homeserver($uname,$udom);
2517: unless ($home eq $perlvar{'lonHostID'}) {
2518: my @parts=split(/\//,$filename);
2519: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2520: if ($path ne "$londocroot/res") {
2521: &logthis("Malconfiguration for replication: $filename");
2522: return 'bad_request';
2523: }
2524: my $count;
2525: for ($count=5;$count<$#parts;$count++) {
2526: $path.="/$parts[$count]";
2527: if ((-e $path)!=1) {
2528: mkdir($path,0777);
2529: }
2530: }
2531: my $ua=new LWP::UserAgent;
2532: my $request=new HTTP::Request('GET',"$remoteurl");
2533: my $response=$ua->request($request,$transname);
2534: if ($response->is_error()) {
2535: unlink($transname);
2536: my $message=$response->status_line;
2537: &logthis("<font color=\"blue\">WARNING:"
2538: ." LWP get: $message: $filename</font>");
2539: return 'unavailable';
2540: } else {
2541: if ($remoteurl!~/\.meta$/) {
2542: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2543: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2544: if ($mresponse->is_error()) {
2545: unlink($filename.'.meta');
2546: &logthis(
2547: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
2548: }
2549: }
2550: rename($transname,$filename);
2551: return 'ok';
2552: }
2553: }
2554: }
2555: }
2556:
2557: # ------------------------------------------------ Get server side include body
2558: sub ssi_body {
2559: my ($filelink,%form)=@_;
2560: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2561: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2562: }
2563: my $output='';
2564: my $response;
2565: if ($filelink=~/^https?\:/) {
2566: ($output,$response)=&externalssi($filelink);
2567: } else {
2568: $filelink .= $filelink=~/\?/ ? '&' : '?';
2569: $filelink .= 'inhibitmenu=yes';
2570: ($output,$response)=&ssi($filelink,%form);
2571: }
2572: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
2573: $output=~s/^.*?\<body[^\>]*\>//si;
2574: $output=~s/\<\/body\s*\>.*?$//si;
2575: if (wantarray) {
2576: return ($output, $response);
2577: } else {
2578: return $output;
2579: }
2580: }
2581:
2582: # --------------------------------------------------------- Server Side Include
2583:
2584: sub absolute_url {
2585: my ($host_name) = @_;
2586: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2587: if ($host_name eq '') {
2588: $host_name = $ENV{'SERVER_NAME'};
2589: }
2590: return $protocol.$host_name;
2591: }
2592:
2593: #
2594: # Server side include.
2595: # Parameters:
2596: # fn Possibly encrypted resource name/id.
2597: # form Hash that describes how the rendering should be done
2598: # and other things.
2599: # Returns:
2600: # Scalar context: The content of the response.
2601: # Array context: 2 element list of the content and the full response object.
2602: #
2603: sub ssi {
2604:
2605: my ($fn,%form)=@_;
2606: my $ua=new LWP::UserAgent;
2607: my $request;
2608:
2609: $form{'no_update_last_known'}=1;
2610: &Apache::lonenc::check_encrypt(\$fn);
2611: if (%form) {
2612: $request=new HTTP::Request('POST',&absolute_url().$fn);
2613: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
2614: } else {
2615: $request=new HTTP::Request('GET',&absolute_url().$fn);
2616: }
2617:
2618: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2619: my $response= $ua->request($request);
2620: my $content = $response->content;
2621:
2622:
2623: if (wantarray) {
2624: return ($content, $response);
2625: } else {
2626: return $content;
2627: }
2628: }
2629:
2630: sub externalssi {
2631: my ($url)=@_;
2632: my $ua=new LWP::UserAgent;
2633: my $request=new HTTP::Request('GET',$url);
2634: my $response=$ua->request($request);
2635: if (wantarray) {
2636: return ($response->content, $response);
2637: } else {
2638: return $response->content;
2639: }
2640: }
2641:
2642: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2643:
2644: sub allowuploaded {
2645: my ($srcurl,$url)=@_;
2646: $url=&clutter(&declutter($url));
2647: my $dir=$url;
2648: $dir=~s/\/[^\/]+$//;
2649: my %httpref=();
2650: my $httpurl=&hreflocation('',$url);
2651: $httpref{'httpref.'.$httpurl}=$srcurl;
2652: &Apache::lonnet::appenv(\%httpref);
2653: }
2654:
2655: #
2656: # Determine if the current user should be able to edit a particular resource,
2657: # when viewing in course context.
2658: # (a) When viewing resource used to determine if "Edit" item is included in
2659: # Functions.
2660: # (b) When displaying folder contents in course editor, used to determine if
2661: # "Edit" link will be displayed alongside resource.
2662: #
2663: # input: six args -- filename (decluttered), course number, course domain,
2664: # url, symb (if registered) and group (if this is a group
2665: # item -- e.g., bulletin board, group page etc.).
2666: # output: array of five scalars --
2667: # $cfile -- url for file editing if editable on current server
2668: # $home -- homeserver of resource (i.e., for author if published,
2669: # or course if uploaded.).
2670: # $switchserver -- 1 if server switch will be needed.
2671: # $forceedit -- 1 if icon/link should be to go to edit mode
2672: # $forceview -- 1 if icon/link should be to go to view mode
2673: #
2674:
2675: sub can_edit_resource {
2676: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2677: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2678: #
2679: # For aboutme pages user can only edit his/her own.
2680: #
2681: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
2682: my ($sdom,$sname) = ($1,$2);
2683: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2684: $home = $env{'user.home'};
2685: $cfile = $resurl;
2686: if ($env{'form.forceedit'}) {
2687: $forceview = 1;
2688: } else {
2689: $forceedit = 1;
2690: }
2691: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2692: } else {
2693: return;
2694: }
2695: }
2696:
2697: if ($env{'request.course.id'}) {
2698: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2699: if ($group ne '') {
2700: # if this is a group homepage or group bulletin board, check group privs
2701: my $allowed = 0;
2702: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2703: if ((&allowed('mdg',$env{'request.course.id'}.
2704: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2705: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2706: $allowed = 1;
2707: }
2708: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2709: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2710: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2711: $allowed = 1;
2712: }
2713: }
2714: if ($allowed) {
2715: $home=&homeserver($cnum,$cdom);
2716: if ($env{'form.forceedit'}) {
2717: $forceview = 1;
2718: } else {
2719: $forceedit = 1;
2720: }
2721: $cfile = $resurl;
2722: } else {
2723: return;
2724: }
2725: } else {
2726: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2727: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2728: return;
2729: }
2730: } elsif (!$crsedit) {
2731: #
2732: # No edit allowed where CC has switched to student role.
2733: #
2734: return;
2735: }
2736: }
2737: }
2738:
2739: if ($file ne '') {
2740: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
2741: if (&is_course_upload($file,$cnum,$cdom)) {
2742: $uploaded = 1;
2743: $incourse = 1;
2744: if ($file =~/\.(htm|html|css|js|txt)$/) {
2745: $cfile = &hreflocation('',$file);
2746: if ($env{'form.forceedit'}) {
2747: $forceview = 1;
2748: } else {
2749: $forceedit = 1;
2750: }
2751: }
2752: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2753: $incourse = 1;
2754: if ($env{'form.forceedit'}) {
2755: $forceview = 1;
2756: } else {
2757: $forceedit = 1;
2758: }
2759: $cfile = $resurl;
2760: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2761: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2762: $incourse = 1;
2763: if ($env{'form.forceedit'}) {
2764: $forceview = 1;
2765: } else {
2766: $forceedit = 1;
2767: }
2768: $cfile = $resurl;
2769: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
2770: $incourse = 1;
2771: $cfile = $resurl.'/smpedit';
2772: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
2773: $incourse = 1;
2774: if ($env{'form.forceedit'}) {
2775: $forceview = 1;
2776: } else {
2777: $forceedit = 1;
2778: }
2779: $cfile = $resurl;
2780: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2781: $incourse = 1;
2782: if ($env{'form.forceedit'}) {
2783: $forceview = 1;
2784: } else {
2785: $forceedit = 1;
2786: }
2787: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
2788: }
2789: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2790: my $template = '/res/lib/templates/simpleproblem.problem';
2791: if (&is_on_map($template)) {
2792: $incourse = 1;
2793: $forceview = 1;
2794: $cfile = $template;
2795: }
2796: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2797: $incourse = 1;
2798: if ($env{'form.forceedit'}) {
2799: $forceview = 1;
2800: } else {
2801: $forceedit = 1;
2802: }
2803: $cfile = $resurl;
2804: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2805: $incourse = 1;
2806: $forceview = 1;
2807: if ($symb) {
2808: my ($map,$id,$res)=&decode_symb($symb);
2809: $env{'request.symb'} = $symb;
2810: $cfile = &clutter($res);
2811: } else {
2812: $cfile = $env{'form.suppurl'};
2813: $cfile =~ s{^http://}{};
2814: $cfile = '/adm/wrapper/ext/'.$cfile;
2815: }
2816: }
2817: }
2818: if ($uploaded || $incourse) {
2819: $home=&homeserver($cnum,$cdom);
2820: } elsif ($file !~ m{/$}) {
2821: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2822: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2823: # Check that the user has permission to edit this resource
2824: my $setpriv = 1;
2825: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2826: if (defined($cfudom)) {
2827: $home=&homeserver($cfuname,$cfudom);
2828: $cfile=$file;
2829: }
2830: }
2831: if (($cfile ne '') && (!$incourse || $uploaded) &&
2832: (($home ne '') && ($home ne 'no_host'))) {
2833: my @ids=¤t_machine_ids();
2834: unless (grep(/^\Q$home\E$/,@ids)) {
2835: $switchserver=1;
2836: }
2837: }
2838: }
2839: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2840: }
2841:
2842: sub is_course_upload {
2843: my ($file,$cnum,$cdom) = @_;
2844: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2845: $uploadpath =~ s{^\/}{};
2846: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2847: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
2848: return 1;
2849: }
2850: return;
2851: }
2852:
2853: sub in_course {
2854: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2855: if ($hideprivileged) {
2856: my $skipuser;
2857: if (&privileged($uname,$udom)) {
2858: $skipuser = 1;
2859: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2860: if ($coursehash{'nothideprivileged'}) {
2861: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2862: my $user;
2863: if ($item =~ /:/) {
2864: $user = $item;
2865: } else {
2866: $user = join(':',split(/[\@]/,$item));
2867: }
2868: if ($user eq $uname.':'.$udom) {
2869: undef($skipuser);
2870: last;
2871: }
2872: }
2873: }
2874: if ($skipuser) {
2875: return 0;
2876: }
2877: }
2878: }
2879: $type ||= 'any';
2880: if (!defined($cdom) || !defined($cnum)) {
2881: my $cid = $env{'request.course.id'};
2882: $cdom = $env{'course.'.$cid.'.domain'};
2883: $cnum = $env{'course.'.$cid.'.num'};
2884: }
2885: my $typesref;
2886: if (($type eq 'any') || ($type eq 'all')) {
2887: $typesref = ['active','previous','future'];
2888: } elsif ($type eq 'previous' || $type eq 'future') {
2889: $typesref = [$type];
2890: }
2891: my %roles = &get_my_roles($uname,$udom,'userroles',
2892: $typesref,undef,[$cdom]);
2893: my ($tmp) = keys(%roles);
2894: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
2895: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
2896: if (@course_roles > 0) {
2897: return 1;
2898: }
2899: return 0;
2900: }
2901:
2902: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
2903: # input: action, courseID, current domain, intended
2904: # path to file, source of file, instruction to parse file for objects,
2905: # ref to hash for embedded objects,
2906: # ref to hash for codebase of java objects.
2907: # reference to scalar to accommodate mime type determined
2908: # from File::MMagic if $parser = parse.
2909: #
2910: # output: url to file (if action was uploaddoc),
2911: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
2912: #
2913: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2914: # course.
2915: #
2916: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2917: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2918: # course's home server.
2919: #
2920: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2921: # be copied from $source (current location) to
2922: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2923: # and will then be copied to
2924: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2925: # course's home server.
2926: #
2927: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2928: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
2929: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2930: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2931: # in course's home server.
2932: #
2933:
2934: sub process_coursefile {
2935: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2936: $mimetype)=@_;
2937: my $fetchresult;
2938: my $home=&homeserver($docuname,$docudom);
2939: if ($action eq 'propagate') {
2940: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2941: $home);
2942: } else {
2943: my $fpath = '';
2944: my $fname = $file;
2945: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2946: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2947: my $filepath = &build_filepath($fpath);
2948: if ($action eq 'copy') {
2949: if ($source eq '') {
2950: $fetchresult = 'no source file';
2951: return $fetchresult;
2952: } else {
2953: my $destination = $filepath.'/'.$fname;
2954: rename($source,$destination);
2955: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2956: $home);
2957: }
2958: } elsif ($action eq 'uploaddoc') {
2959: open(my $fh,'>'.$filepath.'/'.$fname);
2960: print $fh $env{'form.'.$source};
2961: close($fh);
2962: if ($parser eq 'parse') {
2963: my $mm = new File::MMagic;
2964: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2965: if ($type eq 'text/html') {
2966: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2967: unless ($parse_result eq 'ok') {
2968: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2969: }
2970: }
2971: if (ref($mimetype)) {
2972: $$mimetype = $type;
2973: }
2974: }
2975: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2976: $home);
2977: if ($fetchresult eq 'ok') {
2978: return '/uploaded/'.$fpath.'/'.$fname;
2979: } else {
2980: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2981: ' to host '.$home.': '.$fetchresult);
2982: return '/adm/notfound.html';
2983: }
2984: }
2985: }
2986: unless ( $fetchresult eq 'ok') {
2987: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2988: ' to host '.$home.': '.$fetchresult);
2989: }
2990: return $fetchresult;
2991: }
2992:
2993: sub build_filepath {
2994: my ($fpath) = @_;
2995: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2996: unless ($fpath eq '') {
2997: my @parts=split('/',$fpath);
2998: foreach my $part (@parts) {
2999: $filepath.= '/'.$part;
3000: if ((-e $filepath)!=1) {
3001: mkdir($filepath,0777);
3002: }
3003: }
3004: }
3005: return $filepath;
3006: }
3007:
3008: sub store_edited_file {
3009: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
3010: my $file = $primary_url;
3011: $file =~ s#^/uploaded/$docudom/$docuname/##;
3012: my $fpath = '';
3013: my $fname = $file;
3014: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3015: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3016: my $filepath = &build_filepath($fpath);
3017: open(my $fh,'>'.$filepath.'/'.$fname);
3018: print $fh $content;
3019: close($fh);
3020: my $home=&homeserver($docuname,$docudom);
3021: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3022: $home);
3023: if ($$fetchresult eq 'ok') {
3024: return '/uploaded/'.$fpath.'/'.$fname;
3025: } else {
3026: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3027: ' to host '.$home.': '.$$fetchresult);
3028: return '/adm/notfound.html';
3029: }
3030: }
3031:
3032: sub clean_filename {
3033: my ($fname,$args)=@_;
3034: # Replace Windows backslashes by forward slashes
3035: $fname=~s/\\/\//g;
3036: if (!$args->{'keep_path'}) {
3037: # Get rid of everything but the actual filename
3038: $fname=~s/^.*\/([^\/]+)$/$1/;
3039: }
3040: # Replace spaces by underscores
3041: $fname=~s/\s+/\_/g;
3042: # Replace all other weird characters by nothing
3043: $fname=~s{[^/\w\.\-]}{}g;
3044: # Replace all .\d. sequences with _\d. so they no longer look like version
3045: # numbers
3046: $fname=~s/\.(\d+)(?=\.)/_$1/g;
3047: return $fname;
3048: }
3049: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3050: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3051: # image with the same aspect ratio as the original, but with dimensions which do
3052: # not exceed $resizewidth and $resizeheight.
3053:
3054: sub resizeImage {
3055: my ($img_path,$resizewidth,$resizeheight) = @_;
3056: my $ima = Image::Magick->new;
3057: my $resized;
3058: if (-e $img_path) {
3059: $ima->Read($img_path);
3060: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3061: my $width = $ima->Get('width');
3062: my $height = $ima->Get('height');
3063: if ($width > $resizewidth) {
3064: my $factor = $width/$resizewidth;
3065: my $newheight = $height/$factor;
3066: $ima->Scale(width=>$resizewidth,height=>$newheight);
3067: $resized = 1;
3068: }
3069: }
3070: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3071: my $width = $ima->Get('width');
3072: my $height = $ima->Get('height');
3073: if ($height > $resizeheight) {
3074: my $factor = $height/$resizeheight;
3075: my $newwidth = $width/$factor;
3076: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3077: $resized = 1;
3078: }
3079: }
3080: if ($resized) {
3081: $ima->Write($img_path);
3082: }
3083: }
3084: return;
3085: }
3086:
3087: # --------------- Take an uploaded file and put it into the userfiles directory
3088: # input: $formname - the contents of the file are in $env{"form.$formname"}
3089: # the desired filename is in $env{"form.$formname.filename"}
3090: # $context - possible values: coursedoc, existingfile, overwrite,
3091: # canceloverwrite, or ''.
3092: # if 'coursedoc': upload to the current course
3093: # if 'existingfile': write file to tmp/overwrites directory
3094: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3095: # $context is passed as argument to &finishuserfileupload
3096: # $subdir - directory in userfile to store the file into
3097: # $parser - instruction to parse file for objects ($parser = parse)
3098: # $allfiles - reference to hash for embedded objects
3099: # $codebase - reference to hash for codebase of java objects
3100: # $desuname - username for permanent storage of uploaded file
3101: # $dsetudom - domain for permanaent storage of uploaded file
3102: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3103: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
3104: # $resizewidth - width (pixels) to which to resize uploaded image
3105: # $resizeheight - height (pixels) to which to resize uploaded image
3106: # $mimetype - reference to scalar to accommodate mime type determined
3107: # from File::MMagic.
3108: #
3109: # output: url of file in userspace, or error: <message>
3110: # or /adm/notfound.html if failure to upload occurse
3111:
3112: sub userfileupload {
3113: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
3114: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
3115: if (!defined($subdir)) { $subdir='unknown'; }
3116: my $fname=$env{'form.'.$formname.'.filename'};
3117: $fname=&clean_filename($fname);
3118: # See if there is anything left
3119: unless ($fname) { return 'error: no uploaded file'; }
3120: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3121: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3122: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3123: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3124: my $now = time;
3125: my $filepath;
3126: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
3127: $filepath = 'tmp/helprequests/'.$now;
3128: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3129: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3130: '_'.$env{'user.domain'}.'/pending';
3131: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3132: my ($docuname,$docudom);
3133: if ($destudom) {
3134: $docudom = $destudom;
3135: } else {
3136: $docudom = $env{'user.domain'};
3137: }
3138: if ($destuname) {
3139: $docuname = $destuname;
3140: } else {
3141: $docuname = $env{'user.name'};
3142: }
3143: if (exists($env{'form.group'})) {
3144: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3145: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3146: }
3147: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3148: if ($context eq 'canceloverwrite') {
3149: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3150: if (-e $tempfile) {
3151: my @info = stat($tempfile);
3152: if ($info[9] eq $env{'form.timestamp'}) {
3153: unlink($tempfile);
3154: }
3155: }
3156: return;
3157: }
3158: }
3159: # Create the directory if not present
3160: my @parts=split(/\//,$filepath);
3161: my $fullpath = $perlvar{'lonDaemons'};
3162: for (my $i=0;$i<@parts;$i++) {
3163: $fullpath .= '/'.$parts[$i];
3164: if ((-e $fullpath)!=1) {
3165: mkdir($fullpath,0777);
3166: }
3167: }
3168: open(my $fh,'>'.$fullpath.'/'.$fname);
3169: print $fh $env{'form.'.$formname};
3170: close($fh);
3171: if ($context eq 'existingfile') {
3172: my @info = stat($fullpath.'/'.$fname);
3173: return ($fullpath.'/'.$fname,$info[9]);
3174: } else {
3175: return $fullpath.'/'.$fname;
3176: }
3177: }
3178: if ($subdir eq 'scantron') {
3179: $fname = 'scantron_orig_'.$fname;
3180: } else {
3181: $fname="$subdir/$fname";
3182: }
3183: if ($context eq 'coursedoc') {
3184: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3185: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3186: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
3187: return &finishuserfileupload($docuname,$docudom,
3188: $formname,$fname,$parser,$allfiles,
3189: $codebase,$thumbwidth,$thumbheight,
3190: $resizewidth,$resizeheight,$context,$mimetype);
3191: } else {
3192: $fname=$env{'form.folder'}.'/'.$fname;
3193: return &process_coursefile('uploaddoc',$docuname,$docudom,
3194: $fname,$formname,$parser,
3195: $allfiles,$codebase,$mimetype);
3196: }
3197: } elsif (defined($destuname)) {
3198: my $docuname=$destuname;
3199: my $docudom=$destudom;
3200: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3201: $parser,$allfiles,$codebase,
3202: $thumbwidth,$thumbheight,
3203: $resizewidth,$resizeheight,$context,$mimetype);
3204: } else {
3205: my $docuname=$env{'user.name'};
3206: my $docudom=$env{'user.domain'};
3207: if (exists($env{'form.group'})) {
3208: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3209: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3210: }
3211: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3212: $parser,$allfiles,$codebase,
3213: $thumbwidth,$thumbheight,
3214: $resizewidth,$resizeheight,$context,$mimetype);
3215: }
3216: }
3217:
3218: sub finishuserfileupload {
3219: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
3220: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
3221: my $path=$docudom.'/'.$docuname.'/';
3222: my $filepath=$perlvar{'lonDocRoot'};
3223:
3224: my ($fnamepath,$file,$fetchthumb);
3225: $file=$fname;
3226: if ($fname=~m|/|) {
3227: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3228: $path.=$fnamepath.'/';
3229: }
3230: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
3231: my $count;
3232: for ($count=4;$count<=$#parts;$count++) {
3233: $filepath.="/$parts[$count]";
3234: if ((-e $filepath)!=1) {
3235: mkdir($filepath,0777);
3236: }
3237: }
3238:
3239: # Save the file
3240: {
3241: if (!open(FH,'>'.$filepath.'/'.$file)) {
3242: &logthis('Failed to create '.$filepath.'/'.$file);
3243: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3244: return '/adm/notfound.html';
3245: }
3246: if ($context eq 'overwrite') {
3247: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
3248: my $target = $filepath.'/'.$file;
3249: if (-e $source) {
3250: my @info = stat($source);
3251: if ($info[9] eq $env{'form.timestamp'}) {
3252: unless (&File::Copy::move($source,$target)) {
3253: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3254: return "Moving from $source failed";
3255: }
3256: } else {
3257: return "Temporary file: $source had unexpected date/time for last modification";
3258: }
3259: } else {
3260: return "Temporary file: $source missing";
3261: }
3262: } elsif (!print FH ($env{'form.'.$formname})) {
3263: &logthis('Failed to write to '.$filepath.'/'.$file);
3264: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3265: return '/adm/notfound.html';
3266: }
3267: close(FH);
3268: if ($resizewidth && $resizeheight) {
3269: my $mm = new File::MMagic;
3270: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3271: if ($mime_type =~ m{^image/}) {
3272: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3273: }
3274: }
3275: }
3276: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3277: if (ref($mimetype)) {
3278: if ($$mimetype eq '') {
3279: my $mm = new File::MMagic;
3280: my $type = $mm->checktype_filename($filepath.'/'.$file);
3281: $$mimetype = $type;
3282: }
3283: }
3284: }
3285: if ($parser eq 'parse') {
3286: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
3287: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3288: $allfiles,$codebase);
3289: unless ($parse_result eq 'ok') {
3290: &logthis('Failed to parse '.$filepath.$file.
3291: ' for embedded media: '.$parse_result);
3292: }
3293: }
3294: }
3295: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3296: my $input = $filepath.'/'.$file;
3297: my $output = $filepath.'/'.'tn-'.$file;
3298: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3299: system("convert -sample $thumbsize $input $output");
3300: if (-e $filepath.'/'.'tn-'.$file) {
3301: $fetchthumb = 1;
3302: }
3303: }
3304:
3305: # Notify homeserver to grep it
3306: #
3307: my $docuhome=&homeserver($docuname,$docudom);
3308: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
3309: if ($fetchresult eq 'ok') {
3310: if ($fetchthumb) {
3311: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3312: if ($thumbresult ne 'ok') {
3313: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3314: $docuhome.': '.$thumbresult);
3315: }
3316: }
3317: #
3318: # Return the URL to it
3319: return '/uploaded/'.$path.$file;
3320: } else {
3321: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3322: ': '.$fetchresult);
3323: return '/adm/notfound.html';
3324: }
3325: }
3326:
3327: sub extract_embedded_items {
3328: my ($fullpath,$allfiles,$codebase,$content) = @_;
3329: my @state = ();
3330: my (%lastids,%related,%shockwave,%flashvars);
3331: my %javafiles = (
3332: codebase => '',
3333: code => '',
3334: archive => ''
3335: );
3336: my %mediafiles = (
3337: src => '',
3338: movie => '',
3339: );
3340: my $p;
3341: if ($content) {
3342: $p = HTML::LCParser->new($content);
3343: } else {
3344: $p = HTML::LCParser->new($fullpath);
3345: }
3346: while (my $t=$p->get_token()) {
3347: if ($t->[0] eq 'S') {
3348: my ($tagname, $attr) = ($t->[1],$t->[2]);
3349: push(@state, $tagname);
3350: if (lc($tagname) eq 'allow') {
3351: &add_filetype($allfiles,$attr->{'src'},'src');
3352: }
3353: if (lc($tagname) eq 'img') {
3354: &add_filetype($allfiles,$attr->{'src'},'src');
3355: }
3356: if (lc($tagname) eq 'a') {
3357: &add_filetype($allfiles,$attr->{'href'},'href');
3358: }
3359: if (lc($tagname) eq 'script') {
3360: my $src;
3361: if ($attr->{'archive'} =~ /\.jar$/i) {
3362: &add_filetype($allfiles,$attr->{'archive'},'archive');
3363: } else {
3364: if ($attr->{'src'} ne '') {
3365: $src = $attr->{'src'};
3366: &add_filetype($allfiles,$src,'src');
3367: }
3368: }
3369: my $text = $p->get_trimmed_text();
3370: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3371: my @swfargs = split(/,/,$1);
3372: foreach my $item (@swfargs) {
3373: $item =~ s/["']//g;
3374: $item =~ s/^\s+//;
3375: $item =~ s/\s+$//;
3376: }
3377: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3378: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3379: push(@{$related{$swfargs[0]}},$swfargs[2]);
3380: } else {
3381: $related{$swfargs[0]} = [$swfargs[2]];
3382: }
3383: }
3384: }
3385: }
3386: if (lc($tagname) eq 'link') {
3387: if (lc($attr->{'rel'}) eq 'stylesheet') {
3388: &add_filetype($allfiles,$attr->{'href'},'href');
3389: }
3390: }
3391: if (lc($tagname) eq 'object' ||
3392: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3393: foreach my $item (keys(%javafiles)) {
3394: $javafiles{$item} = '';
3395: }
3396: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3397: $lastids{lc($tagname)} = $attr->{'id'};
3398: }
3399: }
3400: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3401: my $name = lc($attr->{'name'});
3402: foreach my $item (keys(%javafiles)) {
3403: if ($name eq $item) {
3404: $javafiles{$item} = $attr->{'value'};
3405: last;
3406: }
3407: }
3408: my $pathfrom;
3409: foreach my $item (keys(%mediafiles)) {
3410: if ($name eq $item) {
3411: $pathfrom = $attr->{'value'};
3412: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3413: &add_filetype($allfiles,$pathfrom,$name);
3414: last;
3415: }
3416: }
3417: if ($name eq 'flashvars') {
3418: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3419: }
3420: if ($pathfrom ne '') {
3421: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3422: $pathfrom);
3423: }
3424: }
3425: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3426: foreach my $item (keys(%javafiles)) {
3427: if ($attr->{$item}) {
3428: $javafiles{$item} = $attr->{$item};
3429: last;
3430: }
3431: }
3432: foreach my $item (keys(%mediafiles)) {
3433: if ($attr->{$item}) {
3434: &add_filetype($allfiles,$attr->{$item},$item);
3435: last;
3436: }
3437: }
3438: if (lc($tagname) eq 'embed') {
3439: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3440: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3441: $attr->{'src'});
3442: }
3443: }
3444: }
3445: if ($t->[4] =~ m{/>$}) {
3446: pop(@state);
3447: }
3448: } elsif ($t->[0] eq 'E') {
3449: my ($tagname) = ($t->[1]);
3450: if ($javafiles{'codebase'} ne '') {
3451: $javafiles{'codebase'} .= '/';
3452: }
3453: if (lc($tagname) eq 'applet' ||
3454: lc($tagname) eq 'object' ||
3455: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3456: ) {
3457: foreach my $item (keys(%javafiles)) {
3458: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3459: my $file=$javafiles{'codebase'}.$javafiles{$item};
3460: &add_filetype($allfiles,$file,$item);
3461: }
3462: }
3463: }
3464: pop @state;
3465: }
3466: }
3467: foreach my $id (sort(keys(%flashvars))) {
3468: if ($shockwave{$id} ne '') {
3469: my @pairs = split(/\&/,$flashvars{$id});
3470: foreach my $pair (@pairs) {
3471: my ($key,$value) = split(/\=/,$pair);
3472: if ($key eq 'thumb') {
3473: &add_filetype($allfiles,$value,$key);
3474: } elsif ($key eq 'content') {
3475: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3476: my ($ext) = ($value =~ /\.([^.]+)$/);
3477: if ($ext ne '') {
3478: &add_filetype($allfiles,$path.$value,$ext);
3479: }
3480: }
3481: }
3482: }
3483: }
3484: return 'ok';
3485: }
3486:
3487: sub add_filetype {
3488: my ($allfiles,$file,$type)=@_;
3489: if (exists($allfiles->{$file})) {
3490: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3491: push(@{$allfiles->{$file}}, &escape($type));
3492: }
3493: } else {
3494: @{$allfiles->{$file}} = (&escape($type));
3495: }
3496: }
3497:
3498: sub embedded_dependency {
3499: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3500: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3501: if (($identifier ne '') &&
3502: (ref($related->{$identifier}) eq 'ARRAY') &&
3503: ($pathfrom ne '')) {
3504: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3505: foreach my $dep (@{$related->{$identifier}}) {
3506: &add_filetype($allfiles,$path.$dep,'object');
3507: }
3508: }
3509: }
3510: return;
3511: }
3512:
3513: sub removeuploadedurl {
3514: my ($url)=@_;
3515: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
3516: return &removeuserfile($uname,$udom,$fname);
3517: }
3518:
3519: sub removeuserfile {
3520: my ($docuname,$docudom,$fname)=@_;
3521: my $home=&homeserver($docuname,$docudom);
3522: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
3523: if ($result eq 'ok') {
3524: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3525: my $metafile = $fname.'.meta';
3526: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
3527: my $url = "/uploaded/$docudom/$docuname/$fname";
3528: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
3529: my $sqlresult =
3530: &update_portfolio_table($docuname,$docudom,$file,
3531: 'portfolio_metadata',$group,
3532: 'delete');
3533: }
3534: }
3535: return $result;
3536: }
3537:
3538: sub mkdiruserfile {
3539: my ($docuname,$docudom,$dir)=@_;
3540: my $home=&homeserver($docuname,$docudom);
3541: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3542: }
3543:
3544: sub renameuserfile {
3545: my ($docuname,$docudom,$old,$new)=@_;
3546: my $home=&homeserver($docuname,$docudom);
3547: my $result = &reply("renameuserfile:$docudom:$docuname:".
3548: &escape("$old").':'.&escape("$new"),$home);
3549: if ($result eq 'ok') {
3550: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3551: my $oldmeta = $old.'.meta';
3552: my $newmeta = $new.'.meta';
3553: my $metaresult =
3554: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
3555: my $url = "/uploaded/$docudom/$docuname/$old";
3556: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
3557: my $sqlresult =
3558: &update_portfolio_table($docuname,$docudom,$file,
3559: 'portfolio_metadata',$group,
3560: 'delete');
3561: }
3562: }
3563: return $result;
3564: }
3565:
3566: # ------------------------------------------------------------------------- Log
3567:
3568: sub log {
3569: my ($dom,$nam,$hom,$what)=@_;
3570: return critical("log:$dom:$nam:$what",$hom);
3571: }
3572:
3573: # ------------------------------------------------------------------ Course Log
3574: #
3575: # This routine flushes several buffers of non-mission-critical nature
3576: #
3577:
3578: sub flushcourselogs {
3579: &logthis('Flushing log buffers');
3580: #
3581: # course logs
3582: # This is a log of all transactions in a course, which can be used
3583: # for data mining purposes
3584: #
3585: # It also collects the courseid database, which lists last transaction
3586: # times and course titles for all courseids
3587: #
3588: my %courseidbuffer=();
3589: foreach my $crsid (keys(%courselogs)) {
3590: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
3591: &escape($courselogs{$crsid}),
3592: $coursehombuf{$crsid}) eq 'ok') {
3593: delete $courselogs{$crsid};
3594: } else {
3595: &logthis('Failed to flush log buffer for '.$crsid);
3596: if (length($courselogs{$crsid})>40000) {
3597: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
3598: " exceeded maximum size, deleting.</font>");
3599: delete $courselogs{$crsid};
3600: }
3601: }
3602: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
3603: 'description' => $coursedescrbuf{$crsid},
3604: 'inst_code' => $courseinstcodebuf{$crsid},
3605: 'type' => $coursetypebuf{$crsid},
3606: 'owner' => $courseownerbuf{$crsid},
3607: };
3608: }
3609: #
3610: # Write course id database (reverse lookup) to homeserver of courses
3611: # Is used in pickcourse
3612: #
3613: foreach my $crs_home (keys(%courseidbuffer)) {
3614: my $response = &courseidput(&host_domain($crs_home),
3615: $courseidbuffer{$crs_home},
3616: $crs_home,'timeonly');
3617: }
3618: #
3619: # File accesses
3620: # Writes to the dynamic metadata of resources to get hit counts, etc.
3621: #
3622: foreach my $entry (keys(%accesshash)) {
3623: if ($entry =~ /___count$/) {
3624: my ($dom,$name);
3625: ($dom,$name,undef)=
3626: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
3627: if (! defined($dom) || $dom eq '' ||
3628: ! defined($name) || $name eq '') {
3629: my $cid = $env{'request.course.id'};
3630: $dom = $env{'request.'.$cid.'.domain'};
3631: $name = $env{'request.'.$cid.'.num'};
3632: }
3633: my $value = $accesshash{$entry};
3634: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3635: my %temphash=($url => $value);
3636: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3637: if ($result eq 'ok') {
3638: delete $accesshash{$entry};
3639: }
3640: } else {
3641: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
3642: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
3643: my %temphash=($entry => $accesshash{$entry});
3644: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3645: delete $accesshash{$entry};
3646: }
3647: }
3648: }
3649: #
3650: # Roles
3651: # Reverse lookup of user roles for course faculty/staff and co-authorship
3652: #
3653: foreach my $entry (keys(%userrolehash)) {
3654: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
3655: split(/\:/,$entry);
3656: if (&Apache::lonnet::put('nohist_userroles',
3657: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
3658: $rudom,$runame) eq 'ok') {
3659: delete $userrolehash{$entry};
3660: }
3661: }
3662: #
3663: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3664: #
3665: my %domrolebuffer = ();
3666: foreach my $entry (keys(%domainrolehash)) {
3667: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
3668: if ($domrolebuffer{$rudom}) {
3669: $domrolebuffer{$rudom}.='&'.&escape($entry).
3670: '='.&escape($domainrolehash{$entry});
3671: } else {
3672: $domrolebuffer{$rudom}.=&escape($entry).
3673: '='.&escape($domainrolehash{$entry});
3674: }
3675: delete $domainrolehash{$entry};
3676: }
3677: foreach my $dom (keys(%domrolebuffer)) {
3678: my %servers = &get_servers($dom,'library');
3679: foreach my $tryserver (keys(%servers)) {
3680: unless (&reply('domroleput:'.$dom.':'.
3681: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3682: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3683: }
3684: }
3685: }
3686: $dumpcount++;
3687: }
3688:
3689: sub courselog {
3690: my $what=shift;
3691: $what=time.':'.$what;
3692: unless ($env{'request.course.id'}) { return ''; }
3693: $coursedombuf{$env{'request.course.id'}}=
3694: $env{'course.'.$env{'request.course.id'}.'.domain'};
3695: $coursenumbuf{$env{'request.course.id'}}=
3696: $env{'course.'.$env{'request.course.id'}.'.num'};
3697: $coursehombuf{$env{'request.course.id'}}=
3698: $env{'course.'.$env{'request.course.id'}.'.home'};
3699: $coursedescrbuf{$env{'request.course.id'}}=
3700: $env{'course.'.$env{'request.course.id'}.'.description'};
3701: $courseinstcodebuf{$env{'request.course.id'}}=
3702: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3703: $courseownerbuf{$env{'request.course.id'}}=
3704: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
3705: $coursetypebuf{$env{'request.course.id'}}=
3706: $env{'course.'.$env{'request.course.id'}.'.type'};
3707: if (defined $courselogs{$env{'request.course.id'}}) {
3708: $courselogs{$env{'request.course.id'}}.='&'.$what;
3709: } else {
3710: $courselogs{$env{'request.course.id'}}.=$what;
3711: }
3712: if (length($courselogs{$env{'request.course.id'}})>4048) {
3713: &flushcourselogs();
3714: }
3715: }
3716:
3717: sub courseacclog {
3718: my $fnsymb=shift;
3719: unless ($env{'request.course.id'}) { return ''; }
3720: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
3721: if ($fnsymb=~/$LONCAPA::assess_re/) {
3722: $what.=':POST';
3723: # FIXME: Probably ought to escape things....
3724: foreach my $key (keys(%env)) {
3725: if ($key=~/^form\.(.*)/) {
3726: my $formitem = $1;
3727: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3728: $what.=':'.$formitem.'='.$env{$key};
3729: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3730: $what.=':'.$formitem.'='.$env{$key};
3731: }
3732: }
3733: }
3734: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3735: # FIXME: We should not be depending on a form parameter that someone
3736: # editing lonsearchcat.pm might change in the future.
3737: if ($env{'form.phase'} eq 'course_search') {
3738: $what.= ':POST';
3739: # FIXME: Probably ought to escape things....
3740: foreach my $element ('courseexp','crsfulltext','crsrelated',
3741: 'crsdiscuss') {
3742: $what.=':'.$element.'='.$env{'form.'.$element};
3743: }
3744: }
3745: }
3746: &courselog($what);
3747: }
3748:
3749: sub countacc {
3750: my $url=&declutter(shift);
3751: return if (! defined($url) || $url eq '');
3752: unless ($env{'request.course.id'}) { return ''; }
3753: #
3754: # Mark that this url was used in this course
3755: #
3756: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
3757: #
3758: # Increase the access count for this resource in this child process
3759: #
3760: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
3761: $accesshash{$key}++;
3762: }
3763:
3764: sub linklog {
3765: my ($from,$to)=@_;
3766: $from=&declutter($from);
3767: $to=&declutter($to);
3768: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3769: $accesshash{$to.'___'.$from.'___goto'}=1;
3770: }
3771:
3772: sub statslog {
3773: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3774: if ($users<2) { return; }
3775: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3776: 'course' => $env{'request.course.id'},
3777: 'sections' => '"all"',
3778: 'num_students' => $users,
3779: 'part' => $part,
3780: 'symb' => $symb,
3781: 'mean_tries' => $av_attempts,
3782: 'deg_of_diff' => $degdiff});
3783: foreach my $key (keys(%dynstore)) {
3784: $accesshash{$key}=$dynstore{$key};
3785: }
3786: }
3787:
3788: sub userrolelog {
3789: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
3790: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
3791: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3792: $userrolehash
3793: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3794: =$tend.':'.$tstart;
3795: }
3796: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
3797: $userrolehash
3798: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3799: =$tend.':'.$tstart;
3800: }
3801: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
3802: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3803: $domainrolehash
3804: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3805: = $tend.':'.$tstart;
3806: }
3807: }
3808:
3809: sub courserolelog {
3810: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3811: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3812: my $cdom = $1;
3813: my $cnum = $2;
3814: my $sec = $3;
3815: my $namespace = 'rolelog';
3816: my %storehash = (
3817: role => $trole,
3818: start => $tstart,
3819: end => $tend,
3820: selfenroll => $selfenroll,
3821: context => $context,
3822: );
3823: if ($trole eq 'gr') {
3824: $namespace = 'groupslog';
3825: $storehash{'group'} = $sec;
3826: } else {
3827: $storehash{'section'} = $sec;
3828: }
3829: &write_log('course',$namespace,\%storehash,$delflag,$username,
3830: $domain,$cnum,$cdom);
3831: if (($trole ne 'st') || ($sec ne '')) {
3832: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3833: }
3834: }
3835: return;
3836: }
3837:
3838: sub domainrolelog {
3839: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3840: if ($area =~ m{^/($match_domain)/$}) {
3841: my $cdom = $1;
3842: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
3843: my $namespace = 'rolelog';
3844: my %storehash = (
3845: role => $trole,
3846: start => $tstart,
3847: end => $tend,
3848: context => $context,
3849: );
3850: &write_log('domain',$namespace,\%storehash,$delflag,$username,
3851: $domain,$domconfiguser,$cdom);
3852: }
3853: return;
3854:
3855: }
3856:
3857: sub coauthorrolelog {
3858: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3859: if ($area =~ m{^/($match_domain)/($match_username)$}) {
3860: my $audom = $1;
3861: my $auname = $2;
3862: my $namespace = 'rolelog';
3863: my %storehash = (
3864: role => $trole,
3865: start => $tstart,
3866: end => $tend,
3867: context => $context,
3868: );
3869: &write_log('author',$namespace,\%storehash,$delflag,$username,
3870: $domain,$auname,$audom);
3871: }
3872: return;
3873: }
3874:
3875: sub get_course_adv_roles {
3876: my ($cid,$codes) = @_;
3877: $cid=$env{'request.course.id'} unless (defined($cid));
3878: my %coursehash=&coursedescription($cid);
3879: my $crstype = &Apache::loncommon::course_type($cid);
3880: my %nothide=();
3881: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3882: if ($user !~ /:/) {
3883: $nothide{join(':',split(/[\@]/,$user))}=1;
3884: } else {
3885: $nothide{$user}=1;
3886: }
3887: }
3888: my %returnhash=();
3889: my %dumphash=
3890: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3891: my $now=time;
3892: my %privileged;
3893: foreach my $entry (keys(%dumphash)) {
3894: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3895: if (($tstart) && ($tstart<0)) { next; }
3896: if (($tend) && ($tend<$now)) { next; }
3897: if (($tstart) && ($now<$tstart)) { next; }
3898: my ($role,$username,$domain,$section)=split(/\:/,$entry);
3899: if ($username eq '' || $domain eq '') { next; }
3900: unless (ref($privileged{$domain}) eq 'HASH') {
3901: my %dompersonnel =
3902: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3903: $privileged{$domain} = {};
3904: foreach my $server (keys(%dompersonnel)) {
3905: if (ref($dompersonnel{$server}) eq 'HASH') {
3906: foreach my $user (keys(%{$dompersonnel{$server}})) {
3907: my ($trole,$uname,$udom) = split(/:/,$user);
3908: $privileged{$udom}{$uname} = 1;
3909: }
3910: }
3911: }
3912: }
3913: if ((exists($privileged{$domain}{$username})) &&
3914: (!$nothide{$username.':'.$domain})) { next; }
3915: if ($role eq 'cr') { next; }
3916: if ($codes) {
3917: if ($section) { $role .= ':'.$section; }
3918: if ($returnhash{$role}) {
3919: $returnhash{$role}.=','.$username.':'.$domain;
3920: } else {
3921: $returnhash{$role}=$username.':'.$domain;
3922: }
3923: } else {
3924: my $key=&plaintext($role,$crstype);
3925: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
3926: if ($returnhash{$key}) {
3927: $returnhash{$key}.=','.$username.':'.$domain;
3928: } else {
3929: $returnhash{$key}=$username.':'.$domain;
3930: }
3931: }
3932: }
3933: return %returnhash;
3934: }
3935:
3936: sub get_my_roles {
3937: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
3938: unless (defined($uname)) { $uname=$env{'user.name'}; }
3939: unless (defined($udom)) { $udom=$env{'user.domain'}; }
3940: my (%dumphash,%nothide);
3941: if ($context eq 'userroles') {
3942: %dumphash = &dump('roles',$udom,$uname);
3943: } else {
3944: %dumphash=
3945: &dump('nohist_userroles',$udom,$uname);
3946: if ($hidepriv) {
3947: my %coursehash=&coursedescription($udom.'_'.$uname);
3948: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3949: if ($user !~ /:/) {
3950: $nothide{join(':',split(/[\@]/,$user))} = 1;
3951: } else {
3952: $nothide{$user} = 1;
3953: }
3954: }
3955: }
3956: }
3957: my %returnhash=();
3958: my $now=time;
3959: my %privileged;
3960: foreach my $entry (keys(%dumphash)) {
3961: my ($role,$tend,$tstart);
3962: if ($context eq 'userroles') {
3963: next if ($entry =~ /^rolesdef/);
3964: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3965: } else {
3966: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3967: }
3968: if (($tstart) && ($tstart<0)) { next; }
3969: my $status = 'active';
3970: if (($tend) && ($tend<=$now)) {
3971: $status = 'previous';
3972: }
3973: if (($tstart) && ($now<$tstart)) {
3974: $status = 'future';
3975: }
3976: if (ref($types) eq 'ARRAY') {
3977: if (!grep(/^\Q$status\E$/,@{$types})) {
3978: next;
3979: }
3980: } else {
3981: if ($status ne 'active') {
3982: next;
3983: }
3984: }
3985: my ($rolecode,$username,$domain,$section,$area);
3986: if ($context eq 'userroles') {
3987: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
3988: (undef,$domain,$username,$section) = split(/\//,$area);
3989: } else {
3990: ($role,$username,$domain,$section) = split(/\:/,$entry);
3991: }
3992: if (ref($roledoms) eq 'ARRAY') {
3993: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3994: next;
3995: }
3996: }
3997: if (ref($roles) eq 'ARRAY') {
3998: if (!grep(/^\Q$role\E$/,@{$roles})) {
3999: if ($role =~ /^cr\//) {
4000: if (!grep(/^cr$/,@{$roles})) {
4001: next;
4002: }
4003: } elsif ($role =~ /^gr\//) {
4004: if (!grep(/^gr$/,@{$roles})) {
4005: next;
4006: }
4007: } else {
4008: next;
4009: }
4010: }
4011: }
4012: if ($hidepriv) {
4013: if ($context eq 'userroles') {
4014: if ((&privileged($username,$domain)) &&
4015: (!$nothide{$username.':'.$domain})) {
4016: next;
4017: }
4018: } else {
4019: unless (ref($privileged{$domain}) eq 'HASH') {
4020: my %dompersonnel =
4021: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
4022: $privileged{$domain} = {};
4023: if (keys(%dompersonnel)) {
4024: foreach my $server (keys(%dompersonnel)) {
4025: if (ref($dompersonnel{$server}) eq 'HASH') {
4026: foreach my $user (keys(%{$dompersonnel{$server}})) {
4027: my ($trole,$uname,$udom) = split(/:/,$user);
4028: $privileged{$udom}{$uname} = $trole;
4029: }
4030: }
4031: }
4032: }
4033: }
4034: if (exists($privileged{$domain}{$username})) {
4035: if (!$nothide{$username.':'.$domain}) {
4036: next;
4037: }
4038: }
4039: }
4040: }
4041: if ($withsec) {
4042: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4043: $tstart.':'.$tend;
4044: } else {
4045: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4046: }
4047: }
4048: return %returnhash;
4049: }
4050:
4051: # ----------------------------------------------------- Frontpage Announcements
4052: #
4053: #
4054:
4055: sub postannounce {
4056: my ($server,$text)=@_;
4057: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
4058: unless ($text=~/\w/) { $text=''; }
4059: return &reply('setannounce:'.&escape($text),$server);
4060: }
4061:
4062: sub getannounce {
4063:
4064: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
4065: my $announcement='';
4066: while (my $line = <$fh>) { $announcement .= $line; }
4067: close($fh);
4068: if ($announcement=~/\w/) {
4069: return
4070: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
4071: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
4072: } else {
4073: return '';
4074: }
4075: } else {
4076: return '';
4077: }
4078: }
4079:
4080: # ---------------------------------------------------------- Course ID routines
4081: # Deal with domain's nohist_courseid.db files
4082: #
4083:
4084: sub courseidput {
4085: my ($domain,$storehash,$coursehome,$caller) = @_;
4086: return unless (ref($storehash) eq 'HASH');
4087: my $outcome;
4088: if ($caller eq 'timeonly') {
4089: my $cids = '';
4090: foreach my $item (keys(%$storehash)) {
4091: $cids.=&escape($item).'&';
4092: }
4093: $cids=~s/\&$//;
4094: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4095: $coursehome);
4096: } else {
4097: my $items = '';
4098: foreach my $item (keys(%$storehash)) {
4099: $items.= &escape($item).'='.
4100: &freeze_escape($$storehash{$item}).'&';
4101: }
4102: $items=~s/\&$//;
4103: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4104: $coursehome);
4105: }
4106: if ($outcome eq 'unknown_cmd') {
4107: my $what;
4108: foreach my $cid (keys(%$storehash)) {
4109: $what .= &escape($cid).'=';
4110: foreach my $item ('description','inst_code','owner','type') {
4111: $what .= &escape($storehash->{$cid}{$item}).':';
4112: }
4113: $what =~ s/\:$/&/;
4114: }
4115: $what =~ s/\&$//;
4116: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4117: } else {
4118: return $outcome;
4119: }
4120: }
4121:
4122: sub courseiddump {
4123: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
4124: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
4125: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
4126: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
4127: my $as_hash = 1;
4128: my %returnhash;
4129: if (!$domfilter) { $domfilter=''; }
4130: my %libserv = &all_library();
4131: foreach my $tryserver (keys(%libserv)) {
4132: if ( ( $hostidflag == 1
4133: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4134: || (!defined($hostidflag)) ) {
4135:
4136: if (($domfilter eq '') ||
4137: (&host_domain($tryserver) eq $domfilter)) {
4138: my $rep;
4139: if (grep { $_ eq $tryserver } current_machine_ids()) {
4140: $rep = LONCAPA::Lond::dump_course_id_handler(
4141: join(":", (&host_domain($tryserver), $sincefilter,
4142: &escape($descfilter), &escape($instcodefilter),
4143: &escape($ownerfilter), &escape($coursefilter),
4144: &escape($typefilter), &escape($regexp_ok),
4145: $as_hash, &escape($selfenrollonly),
4146: &escape($catfilter), $showhidden, $caller,
4147: &escape($cloner), &escape($cc_clone), $cloneonly,
4148: &escape($createdbefore), &escape($createdafter),
4149: &escape($creationcontext), $domcloner)));
4150: } else {
4151: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4152: $sincefilter.':'.&escape($descfilter).':'.
4153: &escape($instcodefilter).':'.&escape($ownerfilter).
4154: ':'.&escape($coursefilter).':'.&escape($typefilter).
4155: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4156: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4157: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4158: &escape($cc_clone).':'.$cloneonly.':'.
4159: &escape($createdbefore).':'.&escape($createdafter).':'.
4160: &escape($creationcontext).':'.$domcloner,
4161: $tryserver);
4162: }
4163:
4164: my @pairs=split(/\&/,$rep);
4165: foreach my $item (@pairs) {
4166: my ($key,$value)=split(/\=/,$item,2);
4167: $key = &unescape($key);
4168: next if ($key =~ /^error: 2 /);
4169: my $result = &thaw_unescape($value);
4170: if (ref($result) eq 'HASH') {
4171: $returnhash{$key}=$result;
4172: } else {
4173: my @responses = split(/:/,$value);
4174: my @items = ('description','inst_code','owner','type');
4175: for (my $i=0; $i<@responses; $i++) {
4176: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
4177: }
4178: }
4179: }
4180: }
4181: }
4182: }
4183: return %returnhash;
4184: }
4185:
4186: sub courselastaccess {
4187: my ($cdom,$cnum,$hostidref) = @_;
4188: my %returnhash;
4189: if ($cdom && $cnum) {
4190: my $chome = &homeserver($cnum,$cdom);
4191: if ($chome ne 'no_host') {
4192: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4193: &extract_lastaccess(\%returnhash,$rep);
4194: }
4195: } else {
4196: if (!$cdom) { $cdom=''; }
4197: my %libserv = &all_library();
4198: foreach my $tryserver (keys(%libserv)) {
4199: if (ref($hostidref) eq 'ARRAY') {
4200: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4201: }
4202: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4203: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4204: &extract_lastaccess(\%returnhash,$rep);
4205: }
4206: }
4207: }
4208: return %returnhash;
4209: }
4210:
4211: sub extract_lastaccess {
4212: my ($returnhash,$rep) = @_;
4213: if (ref($returnhash) eq 'HASH') {
4214: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4215: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4216: $rep eq '') {
4217: my @pairs=split(/\&/,$rep);
4218: foreach my $item (@pairs) {
4219: my ($key,$value)=split(/\=/,$item,2);
4220: $key = &unescape($key);
4221: next if ($key =~ /^error: 2 /);
4222: $returnhash->{$key} = &thaw_unescape($value);
4223: }
4224: }
4225: }
4226: return;
4227: }
4228:
4229: # ---------------------------------------------------------- DC e-mail
4230:
4231: sub dcmailput {
4232: my ($domain,$msgid,$message,$server)=@_;
4233: my $status = &Apache::lonnet::critical(
4234: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4235: &escape($message),$server);
4236: return $status;
4237: }
4238:
4239: sub dcmaildump {
4240: my ($dom,$startdate,$enddate,$senders) = @_;
4241: my %returnhash=();
4242:
4243: if (defined(&domain($dom,'primary'))) {
4244: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4245: &escape($enddate).':';
4246: my @esc_senders=map { &escape($_)} @$senders;
4247: $cmd.=&escape(join('&',@esc_senders));
4248: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
4249: my ($key,$value) = split(/\=/,$line,2);
4250: if (($key) && ($value)) {
4251: $returnhash{&unescape($key)} = &unescape($value);
4252: }
4253: }
4254: }
4255: return %returnhash;
4256: }
4257: # ---------------------------------------------------------- Domain roles
4258:
4259: sub get_domain_roles {
4260: my ($dom,$roles,$startdate,$enddate)=@_;
4261: if ((!defined($startdate)) || ($startdate eq '')) {
4262: $startdate = '.';
4263: }
4264: if ((!defined($enddate)) || ($enddate eq '')) {
4265: $enddate = '.';
4266: }
4267: my $rolelist;
4268: if (ref($roles) eq 'ARRAY') {
4269: $rolelist = join(':',@{$roles});
4270: }
4271: my %personnel = ();
4272:
4273: my %servers = &get_servers($dom,'library');
4274: foreach my $tryserver (keys(%servers)) {
4275: %{$personnel{$tryserver}}=();
4276: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4277: &escape($startdate).':'.
4278: &escape($enddate).':'.
4279: &escape($rolelist), $tryserver))) {
4280: my ($key,$value) = split(/\=/,$line,2);
4281: if (($key) && ($value)) {
4282: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4283: }
4284: }
4285: }
4286: return %personnel;
4287: }
4288:
4289: # ----------------------------------------------------------- Interval timing
4290:
4291: {
4292: # Caches needed for speedup of navmaps
4293: # We don't want to cache this for very long at all (5 seconds at most)
4294: #
4295: # The user for whom we cache
4296: my $cachedkey='';
4297: # The cached times for this user
4298: my %cachedtimes=();
4299: # When this was last done
4300: my $cachedtime=();
4301:
4302: sub load_all_first_access {
4303: my ($uname,$udom)=@_;
4304: if (($cachedkey eq $uname.':'.$udom) &&
4305: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
4306: return;
4307: }
4308: $cachedtime=time;
4309: $cachedkey=$uname.':'.$udom;
4310: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
4311: }
4312:
4313: sub get_first_access {
4314: my ($type,$argsymb,$argmap)=@_;
4315: my ($symb,$courseid,$udom,$uname)=&whichuser();
4316: if ($argsymb) { $symb=$argsymb; }
4317: my ($map,$id,$res)=&decode_symb($symb);
4318: if ($argmap) { $map = $argmap; }
4319: if ($type eq 'course') {
4320: $res='course';
4321: } elsif ($type eq 'map') {
4322: $res=&symbread($map);
4323: } else {
4324: $res=$symb;
4325: }
4326: &load_all_first_access($uname,$udom);
4327: return $cachedtimes{"$courseid\0$res"};
4328: }
4329:
4330: sub set_first_access {
4331: my ($type,$interval)=@_;
4332: my ($symb,$courseid,$udom,$uname)=&whichuser();
4333: my ($map,$id,$res)=&decode_symb($symb);
4334: if ($type eq 'course') {
4335: $res='course';
4336: } elsif ($type eq 'map') {
4337: $res=&symbread($map);
4338: } else {
4339: $res=$symb;
4340: }
4341: $cachedkey='';
4342: my $firstaccess=&get_first_access($type,$symb,$map);
4343: if (!$firstaccess) {
4344: my $start = time;
4345: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4346: $udom,$uname);
4347: if ($putres eq 'ok') {
4348: &put('timerinterval',{"$courseid\0$res"=>$interval},
4349: $udom,$uname);
4350: &appenv(
4351: {
4352: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4353: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4354: }
4355: );
4356: }
4357: return $putres;
4358: }
4359: return 'already_set';
4360: }
4361: }
4362: # --------------------------------------------- Set Expire Date for Spreadsheet
4363:
4364: sub expirespread {
4365: my ($uname,$udom,$stype,$usymb)=@_;
4366: my $cid=$env{'request.course.id'};
4367: if ($cid) {
4368: my $now=time;
4369: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
4370: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4371: $env{'course.'.$cid.'.num'}.
4372: ':nohist_expirationdates:'.
4373: &escape($key).'='.$now,
4374: $env{'course.'.$cid.'.home'})
4375: }
4376: return 'ok';
4377: }
4378:
4379: # ----------------------------------------------------- Devalidate Spreadsheets
4380:
4381: sub devalidate {
4382: my ($symb,$uname,$udom)=@_;
4383: my $cid=$env{'request.course.id'};
4384: if ($cid) {
4385: # delete the stored spreadsheets for
4386: # - the student level sheet of this user in course's homespace
4387: # - the assessment level sheet for this resource
4388: # for this user in user's homespace
4389: # - current conditional state info
4390: my $key=$uname.':'.$udom.':';
4391: my $status=
4392: &del('nohist_calculatedsheets',
4393: [$key.'studentcalc:'],
4394: $env{'course.'.$cid.'.domain'},
4395: $env{'course.'.$cid.'.num'})
4396: .' '.
4397: &del('nohist_calculatedsheets_'.$cid,
4398: [$key.'assesscalc:'.$symb],$udom,$uname);
4399: unless ($status eq 'ok ok') {
4400: &logthis('Could not devalidate spreadsheet '.
4401: $uname.' at '.$udom.' for '.
4402: $symb.': '.$status);
4403: }
4404: &delenv('user.state.'.$cid);
4405: }
4406: }
4407:
4408: sub get_scalar {
4409: my ($string,$end) = @_;
4410: my $value;
4411: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4412: $value = $1;
4413: } elsif ($$string =~ s/^([^&]*?)&//) {
4414: $value = $1;
4415: }
4416: return &unescape($value);
4417: }
4418:
4419: sub array2str {
4420: my (@array) = @_;
4421: my $result=&arrayref2str(\@array);
4422: $result=~s/^__ARRAY_REF__//;
4423: $result=~s/__END_ARRAY_REF__$//;
4424: return $result;
4425: }
4426:
4427: sub arrayref2str {
4428: my ($arrayref) = @_;
4429: my $result='__ARRAY_REF__';
4430: foreach my $elem (@$arrayref) {
4431: if(ref($elem) eq 'ARRAY') {
4432: $result.=&arrayref2str($elem).'&';
4433: } elsif(ref($elem) eq 'HASH') {
4434: $result.=&hashref2str($elem).'&';
4435: } elsif(ref($elem)) {
4436: #print("Got a ref of ".(ref($elem))." skipping.");
4437: } else {
4438: $result.=&escape($elem).'&';
4439: }
4440: }
4441: $result=~s/\&$//;
4442: $result .= '__END_ARRAY_REF__';
4443: return $result;
4444: }
4445:
4446: sub hash2str {
4447: my (%hash) = @_;
4448: my $result=&hashref2str(\%hash);
4449: $result=~s/^__HASH_REF__//;
4450: $result=~s/__END_HASH_REF__$//;
4451: return $result;
4452: }
4453:
4454: sub hashref2str {
4455: my ($hashref)=@_;
4456: my $result='__HASH_REF__';
4457: foreach my $key (sort(keys(%$hashref))) {
4458: if (ref($key) eq 'ARRAY') {
4459: $result.=&arrayref2str($key).'=';
4460: } elsif (ref($key) eq 'HASH') {
4461: $result.=&hashref2str($key).'=';
4462: } elsif (ref($key)) {
4463: $result.='=';
4464: #print("Got a ref of ".(ref($key))." skipping.");
4465: } else {
4466: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
4467: }
4468:
4469: if(ref($hashref->{$key}) eq 'ARRAY') {
4470: $result.=&arrayref2str($hashref->{$key}).'&';
4471: } elsif(ref($hashref->{$key}) eq 'HASH') {
4472: $result.=&hashref2str($hashref->{$key}).'&';
4473: } elsif(ref($hashref->{$key})) {
4474: $result.='&';
4475: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
4476: } else {
4477: $result.=&escape($hashref->{$key}).'&';
4478: }
4479: }
4480: $result=~s/\&$//;
4481: $result .= '__END_HASH_REF__';
4482: return $result;
4483: }
4484:
4485: sub str2hash {
4486: my ($string)=@_;
4487: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4488: return %$hash;
4489: }
4490:
4491: sub str2hashref {
4492: my ($string) = @_;
4493:
4494: my %hash;
4495:
4496: if($string !~ /^__HASH_REF__/) {
4497: if (! ($string eq '' || !defined($string))) {
4498: $hash{'error'}='Not hash reference';
4499: }
4500: return (\%hash, $string);
4501: }
4502:
4503: $string =~ s/^__HASH_REF__//;
4504:
4505: while($string !~ /^__END_HASH_REF__/) {
4506: #key
4507: my $key='';
4508: if($string =~ /^__HASH_REF__/) {
4509: ($key, $string)=&str2hashref($string);
4510: if(defined($key->{'error'})) {
4511: $hash{'error'}='Bad data';
4512: return (\%hash, $string);
4513: }
4514: } elsif($string =~ /^__ARRAY_REF__/) {
4515: ($key, $string)=&str2arrayref($string);
4516: if($key->[0] eq 'Array reference error') {
4517: $hash{'error'}='Bad data';
4518: return (\%hash, $string);
4519: }
4520: } else {
4521: $string =~ s/^(.*?)=//;
4522: $key=&unescape($1);
4523: }
4524: $string =~ s/^=//;
4525:
4526: #value
4527: my $value='';
4528: if($string =~ /^__HASH_REF__/) {
4529: ($value, $string)=&str2hashref($string);
4530: if(defined($value->{'error'})) {
4531: $hash{'error'}='Bad data';
4532: return (\%hash, $string);
4533: }
4534: } elsif($string =~ /^__ARRAY_REF__/) {
4535: ($value, $string)=&str2arrayref($string);
4536: if($value->[0] eq 'Array reference error') {
4537: $hash{'error'}='Bad data';
4538: return (\%hash, $string);
4539: }
4540: } else {
4541: $value=&get_scalar(\$string,'__END_HASH_REF__');
4542: }
4543: $string =~ s/^&//;
4544:
4545: $hash{$key}=$value;
4546: }
4547:
4548: $string =~ s/^__END_HASH_REF__//;
4549:
4550: return (\%hash, $string);
4551: }
4552:
4553: sub str2array {
4554: my ($string)=@_;
4555: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4556: return @$array;
4557: }
4558:
4559: sub str2arrayref {
4560: my ($string) = @_;
4561: my @array;
4562:
4563: if($string !~ /^__ARRAY_REF__/) {
4564: if (! ($string eq '' || !defined($string))) {
4565: $array[0]='Array reference error';
4566: }
4567: return (\@array, $string);
4568: }
4569:
4570: $string =~ s/^__ARRAY_REF__//;
4571:
4572: while($string !~ /^__END_ARRAY_REF__/) {
4573: my $value='';
4574: if($string =~ /^__HASH_REF__/) {
4575: ($value, $string)=&str2hashref($string);
4576: if(defined($value->{'error'})) {
4577: $array[0] ='Array reference error';
4578: return (\@array, $string);
4579: }
4580: } elsif($string =~ /^__ARRAY_REF__/) {
4581: ($value, $string)=&str2arrayref($string);
4582: if($value->[0] eq 'Array reference error') {
4583: $array[0] ='Array reference error';
4584: return (\@array, $string);
4585: }
4586: } else {
4587: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4588: }
4589: $string =~ s/^&//;
4590:
4591: push(@array, $value);
4592: }
4593:
4594: $string =~ s/^__END_ARRAY_REF__//;
4595:
4596: return (\@array, $string);
4597: }
4598:
4599: # -------------------------------------------------------------------Temp Store
4600:
4601: sub tmpreset {
4602: my ($symb,$namespace,$domain,$stuname) = @_;
4603: if (!$symb) {
4604: $symb=&symbread();
4605: if (!$symb) { $symb= $env{'request.url'}; }
4606: }
4607: $symb=escape($symb);
4608:
4609: if (!$namespace) { $namespace=$env{'request.state'}; }
4610: $namespace=~s/\//\_/g;
4611: $namespace=~s/\W//g;
4612:
4613: if (!$domain) { $domain=$env{'user.domain'}; }
4614: if (!$stuname) { $stuname=$env{'user.name'}; }
4615: if ($domain eq 'public' && $stuname eq 'public') {
4616: $stuname=$ENV{'REMOTE_ADDR'};
4617: }
4618: my $path=LONCAPA::tempdir();
4619: my %hash;
4620: if (tie(%hash,'GDBM_File',
4621: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4622: &GDBM_WRCREAT(),0640)) {
4623: foreach my $key (keys(%hash)) {
4624: if ($key=~ /:$symb/) {
4625: delete($hash{$key});
4626: }
4627: }
4628: }
4629: }
4630:
4631: sub tmpstore {
4632: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4633:
4634: if (!$symb) {
4635: $symb=&symbread();
4636: if (!$symb) { $symb= $env{'request.url'}; }
4637: }
4638: $symb=escape($symb);
4639:
4640: if (!$namespace) {
4641: # I don't think we would ever want to store this for a course.
4642: # it seems this will only be used if we don't have a course.
4643: #$namespace=$env{'request.course.id'};
4644: #if (!$namespace) {
4645: $namespace=$env{'request.state'};
4646: #}
4647: }
4648: $namespace=~s/\//\_/g;
4649: $namespace=~s/\W//g;
4650: if (!$domain) { $domain=$env{'user.domain'}; }
4651: if (!$stuname) { $stuname=$env{'user.name'}; }
4652: if ($domain eq 'public' && $stuname eq 'public') {
4653: $stuname=$ENV{'REMOTE_ADDR'};
4654: }
4655: my $now=time;
4656: my %hash;
4657: my $path=LONCAPA::tempdir();
4658: if (tie(%hash,'GDBM_File',
4659: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4660: &GDBM_WRCREAT(),0640)) {
4661: $hash{"version:$symb"}++;
4662: my $version=$hash{"version:$symb"};
4663: my $allkeys='';
4664: foreach my $key (keys(%$storehash)) {
4665: $allkeys.=$key.':';
4666: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
4667: }
4668: $hash{"$version:$symb:timestamp"}=$now;
4669: $allkeys.='timestamp';
4670: $hash{"$version:keys:$symb"}=$allkeys;
4671: if (untie(%hash)) {
4672: return 'ok';
4673: } else {
4674: return "error:$!";
4675: }
4676: } else {
4677: return "error:$!";
4678: }
4679: }
4680:
4681: # -----------------------------------------------------------------Temp Restore
4682:
4683: sub tmprestore {
4684: my ($symb,$namespace,$domain,$stuname) = @_;
4685:
4686: if (!$symb) {
4687: $symb=&symbread();
4688: if (!$symb) { $symb= $env{'request.url'}; }
4689: }
4690: $symb=escape($symb);
4691:
4692: if (!$namespace) { $namespace=$env{'request.state'}; }
4693:
4694: if (!$domain) { $domain=$env{'user.domain'}; }
4695: if (!$stuname) { $stuname=$env{'user.name'}; }
4696: if ($domain eq 'public' && $stuname eq 'public') {
4697: $stuname=$ENV{'REMOTE_ADDR'};
4698: }
4699: my %returnhash;
4700: $namespace=~s/\//\_/g;
4701: $namespace=~s/\W//g;
4702: my %hash;
4703: my $path=LONCAPA::tempdir();
4704: if (tie(%hash,'GDBM_File',
4705: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4706: &GDBM_READER(),0640)) {
4707: my $version=$hash{"version:$symb"};
4708: $returnhash{'version'}=$version;
4709: my $scope;
4710: for ($scope=1;$scope<=$version;$scope++) {
4711: my $vkeys=$hash{"$scope:keys:$symb"};
4712: my @keys=split(/:/,$vkeys);
4713: my $key;
4714: $returnhash{"$scope:keys"}=$vkeys;
4715: foreach $key (@keys) {
4716: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4717: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4718: }
4719: }
4720: if (!(untie(%hash))) {
4721: return "error:$!";
4722: }
4723: } else {
4724: return "error:$!";
4725: }
4726: return %returnhash;
4727: }
4728:
4729: # ----------------------------------------------------------------------- Store
4730:
4731: sub store {
4732: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4733: my $home='';
4734:
4735: if ($stuname) { $home=&homeserver($stuname,$domain); }
4736:
4737: $symb=&symbclean($symb);
4738: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4739:
4740: if (!$domain) { $domain=$env{'user.domain'}; }
4741: if (!$stuname) { $stuname=$env{'user.name'}; }
4742:
4743: &devalidate($symb,$stuname,$domain);
4744:
4745: $symb=escape($symb);
4746: if (!$namespace) {
4747: unless ($namespace=$env{'request.course.id'}) {
4748: return '';
4749: }
4750: }
4751: if (!$home) { $home=$env{'user.home'}; }
4752:
4753: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4754: $$storehash{'host'}=$perlvar{'lonHostID'};
4755:
4756: my $namevalue='';
4757: foreach my $key (keys(%$storehash)) {
4758: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4759: }
4760: $namevalue=~s/\&$//;
4761: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
4762: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4763: }
4764:
4765: # -------------------------------------------------------------- Critical Store
4766:
4767: sub cstore {
4768: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4769: my $home='';
4770:
4771: if ($stuname) { $home=&homeserver($stuname,$domain); }
4772:
4773: $symb=&symbclean($symb);
4774: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4775:
4776: if (!$domain) { $domain=$env{'user.domain'}; }
4777: if (!$stuname) { $stuname=$env{'user.name'}; }
4778:
4779: &devalidate($symb,$stuname,$domain);
4780:
4781: $symb=escape($symb);
4782: if (!$namespace) {
4783: unless ($namespace=$env{'request.course.id'}) {
4784: return '';
4785: }
4786: }
4787: if (!$home) { $home=$env{'user.home'}; }
4788:
4789: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4790: $$storehash{'host'}=$perlvar{'lonHostID'};
4791:
4792: my $namevalue='';
4793: foreach my $key (keys(%$storehash)) {
4794: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4795: }
4796: $namevalue=~s/\&$//;
4797: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
4798: return critical
4799: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4800: }
4801:
4802: # --------------------------------------------------------------------- Restore
4803:
4804: sub restore {
4805: my ($symb,$namespace,$domain,$stuname) = @_;
4806: my $home='';
4807:
4808: if ($stuname) { $home=&homeserver($stuname,$domain); }
4809:
4810: if (!$symb) {
4811: unless ($symb=escape(&symbread())) { return ''; }
4812: } else {
4813: $symb=&escape(&symbclean($symb));
4814: }
4815: if (!$namespace) {
4816: unless ($namespace=$env{'request.course.id'}) {
4817: return '';
4818: }
4819: }
4820: if (!$domain) { $domain=$env{'user.domain'}; }
4821: if (!$stuname) { $stuname=$env{'user.name'}; }
4822: if (!$home) { $home=$env{'user.home'}; }
4823: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4824:
4825: my %returnhash=();
4826: foreach my $line (split(/\&/,$answer)) {
4827: my ($name,$value)=split(/\=/,$line);
4828: $returnhash{&unescape($name)}=&thaw_unescape($value);
4829: }
4830: my $version;
4831: for ($version=1;$version<=$returnhash{'version'};$version++) {
4832: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4833: $returnhash{$item}=$returnhash{$version.':'.$item};
4834: }
4835: }
4836: return %returnhash;
4837: }
4838:
4839: # ---------------------------------------------------------- Course Description
4840: #
4841: #
4842:
4843: sub coursedescription {
4844: my ($courseid,$args)=@_;
4845: $courseid=~s/^\///;
4846: $courseid=~s/\_/\//g;
4847: my ($cdomain,$cnum)=split(/\//,$courseid);
4848: my $chome=&homeserver($cnum,$cdomain);
4849: my $normalid=$cdomain.'_'.$cnum;
4850: # need to always cache even if we get errors otherwise we keep
4851: # trying and trying and trying to get the course description.
4852: my %envhash=();
4853: my %returnhash=();
4854:
4855: my $expiretime=600;
4856: if ($env{'request.course.id'} eq $normalid) {
4857: $expiretime=120;
4858: }
4859:
4860: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4861: if (!$args->{'freshen_cache'}
4862: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4863: foreach my $key (keys(%env)) {
4864: next if ($key !~ /^\Q$prefix\E(.*)/);
4865: my ($setting) = $1;
4866: $returnhash{$setting} = $env{$key};
4867: }
4868: return %returnhash;
4869: }
4870:
4871: # get the data again
4872:
4873: if (!$args->{'one_time'}) {
4874: $envhash{'course.'.$normalid.'.last_cache'}=time;
4875: }
4876:
4877: if ($chome ne 'no_host') {
4878: %returnhash=&dump('environment',$cdomain,$cnum);
4879: if (!exists($returnhash{'con_lost'})) {
4880: my $username = $env{'user.name'}; # Defult username
4881: if(defined $args->{'user'}) {
4882: $username = $args->{'user'};
4883: }
4884: $returnhash{'home'}= $chome;
4885: $returnhash{'domain'} = $cdomain;
4886: $returnhash{'num'} = $cnum;
4887: if (!defined($returnhash{'type'})) {
4888: $returnhash{'type'} = 'Course';
4889: }
4890: while (my ($name,$value) = each %returnhash) {
4891: $envhash{'course.'.$normalid.'.'.$name}=$value;
4892: }
4893: $returnhash{'url'}=&clutter($returnhash{'url'});
4894: $returnhash{'fn'}=LONCAPA::tempdir() .
4895: $username.'_'.$cdomain.'_'.$cnum;
4896: $envhash{'course.'.$normalid.'.home'}=$chome;
4897: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4898: $envhash{'course.'.$normalid.'.num'}=$cnum;
4899: }
4900: }
4901: if (!$args->{'one_time'}) {
4902: &appenv(\%envhash);
4903: }
4904: return %returnhash;
4905: }
4906:
4907: sub update_released_required {
4908: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4909: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4910: $cid = $env{'request.course.id'};
4911: $cdom = $env{'course.'.$cid.'.domain'};
4912: $cnum = $env{'course.'.$cid.'.num'};
4913: $chome = $env{'course.'.$cid.'.home'};
4914: }
4915: if ($needsrelease) {
4916: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4917: my $needsupdate;
4918: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4919: $needsupdate = 1;
4920: } else {
4921: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4922: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4923: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4924: $needsupdate = 1;
4925: }
4926: }
4927: if ($needsupdate) {
4928: my %needshash = (
4929: 'internal.releaserequired' => $needsrelease,
4930: );
4931: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4932: if ($putresult eq 'ok') {
4933: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4934: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4935: if (ref($crsinfo{$cid}) eq 'HASH') {
4936: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4937: &courseidput($cdom,\%crsinfo,$chome,'notime');
4938: }
4939: }
4940: }
4941: }
4942: return;
4943: }
4944:
4945: # -------------------------------------------------See if a user is privileged
4946:
4947: sub privileged {
4948: my ($username,$domain)=@_;
4949:
4950: my %rolesdump = &dump("roles", $domain, $username) or return 0;
4951: my $now = time;
4952:
4953: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
4954: my ($trole, $tend, $tstart) = split(/_/, $role);
4955: if (($trole eq 'dc') || ($trole eq 'su')) {
4956: return 1 unless ($tend && $tend < $now)
4957: or ($tstart && $tstart > $now);
4958: }
4959: }
4960:
4961: return 0;
4962: }
4963:
4964: # -------------------------------------------------------- Get user privileges
4965:
4966: sub rolesinit {
4967: my ($domain, $username) = @_;
4968: my %userroles = ('user.login.time' => time);
4969: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
4970:
4971: # firstaccess and timerinterval are related to timed maps/resources.
4972: # also, blocking can be triggered by an activating timer
4973: # it's saved in the user's %env.
4974: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
4975: my %timerinterval = &dump('timerinterval', $domain, $username);
4976: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
4977: %timerintchk, %timerintenv);
4978:
4979: foreach my $key (keys(%firstaccess)) {
4980: my ($cid, $rest) = split(/\0/, $key);
4981: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
4982: }
4983:
4984: foreach my $key (keys(%timerinterval)) {
4985: my ($cid,$rest) = split(/\0/,$key);
4986: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
4987: }
4988:
4989: my %allroles=();
4990: my %allgroups=();
4991:
4992: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
4993: my $role = $rolesdump{$area};
4994: $area =~ s/\_\w\w$//;
4995:
4996: my ($trole, $tend, $tstart, $group_privs);
4997:
4998: if ($role =~ /^cr/) {
4999: # Custom role, defined by a user
5000: # e.g., user.role.cr/msu/smith/mynewrole
5001: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5002: $trole = $1;
5003: ($tend, $tstart) = split('_', $2);
5004: } else {
5005: $trole = $role;
5006: }
5007: } elsif ($role =~ m|^gr/|) {
5008: # Role of member in a group, defined within a course/community
5009: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5010: ($trole, $tend, $tstart) = split(/_/, $role);
5011: next if $tstart eq '-1';
5012: ($trole, $group_privs) = split(/\//, $trole);
5013: $group_privs = &unescape($group_privs);
5014: } else {
5015: # Just a normal role, defined in roles.tab
5016: ($trole, $tend, $tstart) = split(/_/,$role);
5017: }
5018:
5019: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5020: $username);
5021: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5022:
5023: # role expired or not available yet?
5024: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5025: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5026:
5027: next if $area eq '' or $trole eq '';
5028:
5029: my $spec = "$trole.$area";
5030: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5031:
5032: if ($trole =~ /^cr\//) {
5033: # Custom role, defined by a user
5034: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5035: } elsif ($trole eq 'gr') {
5036: # Role of a member in a group, defined within a course/community
5037: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5038: next;
5039: } else {
5040: # Normal role, defined in roles.tab
5041: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5042: }
5043:
5044: my $cid = $tdomain.'_'.$trest;
5045: unless ($firstaccchk{$cid}) {
5046: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5047: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5048: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5049: $coursetimerstarts{$cid}{$item};
5050: }
5051: }
5052: $firstaccchk{$cid} = 1;
5053: }
5054: unless ($timerintchk{$cid}) {
5055: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5056: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5057: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5058: $coursetimerintervals{$cid}{$item};
5059: }
5060: }
5061: $timerintchk{$cid} = 1;
5062: }
5063: }
5064:
5065: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5066: \%allroles, \%allgroups);
5067: $env{'user.adv'} = $userroles{'user.adv'};
5068:
5069: return (\%userroles,\%firstaccenv,\%timerintenv);
5070: }
5071:
5072: sub set_arearole {
5073: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
5074: # log the associated role with the area
5075: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5076: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
5077: }
5078:
5079: sub custom_roleprivs {
5080: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5081: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
5082: my $homsvr=homeserver($rauthor,$rdomain);
5083: if (&hostname($homsvr) ne '') {
5084: my ($rdummy,$roledef)=
5085: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5086: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5087: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5088: if (defined($syspriv)) {
5089: if ($trest =~ /^$match_community$/) {
5090: $syspriv =~ s/bre\&S//;
5091: }
5092: $$allroles{'cm./'}.=':'.$syspriv;
5093: $$allroles{$spec.'./'}.=':'.$syspriv;
5094: }
5095: if ($tdomain ne '') {
5096: if (defined($dompriv)) {
5097: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5098: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5099: }
5100: if (($trest ne '') && (defined($coursepriv))) {
5101: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5102: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5103: }
5104: }
5105: }
5106: }
5107: }
5108:
5109: sub group_roleprivs {
5110: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5111: my $access = 1;
5112: my $now = time;
5113: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5114: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5115: if ($access) {
5116: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
5117: $$allgroups{$course}{$group} .=':'.$group_privs;
5118: }
5119: }
5120:
5121: sub standard_roleprivs {
5122: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5123: if (defined($pr{$trole.':s'})) {
5124: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5125: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5126: }
5127: if ($tdomain ne '') {
5128: if (defined($pr{$trole.':d'})) {
5129: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5130: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5131: }
5132: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5133: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5134: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5135: }
5136: }
5137: }
5138:
5139: sub set_userprivs {
5140: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
5141: my $author=0;
5142: my $adv=0;
5143: my %grouproles = ();
5144: if (keys(%{$allgroups}) > 0) {
5145: my @groupkeys;
5146: foreach my $role (keys(%{$allroles})) {
5147: push(@groupkeys,$role);
5148: }
5149: if (ref($groups_roles) eq 'HASH') {
5150: foreach my $key (keys(%{$groups_roles})) {
5151: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5152: push(@groupkeys,$key);
5153: }
5154: }
5155: }
5156: if (@groupkeys > 0) {
5157: foreach my $role (@groupkeys) {
5158: my ($trole,$area,$sec,$extendedarea);
5159: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5160: $trole = $1;
5161: $area = $2;
5162: $sec = $3;
5163: $extendedarea = $area.$sec;
5164: if (exists($$allgroups{$area})) {
5165: foreach my $group (keys(%{$$allgroups{$area}})) {
5166: my $spec = $trole.'.'.$extendedarea;
5167: $grouproles{$spec.'.'.$area.'/'.$group} =
5168: $$allgroups{$area}{$group};
5169: }
5170: }
5171: }
5172: }
5173: }
5174: }
5175: foreach my $group (keys(%grouproles)) {
5176: $$allroles{$group} = $grouproles{$group};
5177: }
5178: foreach my $role (keys(%{$allroles})) {
5179: my %thesepriv;
5180: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
5181: foreach my $item (split(/:/,$$allroles{$role})) {
5182: if ($item ne '') {
5183: my ($privilege,$restrictions)=split(/&/,$item);
5184: if ($restrictions eq '') {
5185: $thesepriv{$privilege}='F';
5186: } elsif ($thesepriv{$privilege} ne 'F') {
5187: $thesepriv{$privilege}.=$restrictions;
5188: }
5189: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5190: }
5191: }
5192: my $thesestr='';
5193: foreach my $priv (sort(keys(%thesepriv))) {
5194: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5195: }
5196: $userroles->{'user.priv.'.$role} = $thesestr;
5197: }
5198: return ($author,$adv);
5199: }
5200:
5201: sub role_status {
5202: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
5203: my @pwhere = ();
5204: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
5205: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
5206: unless (!defined($$role) || $$role eq '') {
5207: $$where=join('.',@pwhere);
5208: $$trolecode=$$role.'.'.$$where;
5209: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5210: $$tstatus='is';
5211: if ($$tstart && $$tstart>$update) {
5212: $$tstatus='future';
5213: if ($$tstart<$now) {
5214: if ($$tstart && $$tstart>$refresh) {
5215: if (($$where ne '') && ($$role ne '')) {
5216: my (%allroles,%allgroups,$group_privs,
5217: %groups_roles,@rolecodes);
5218: my %userroles = (
5219: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5220: );
5221: @rolecodes = ('cm');
5222: my $spec=$$role.'.'.$$where;
5223: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5224: if ($$role =~ /^cr\//) {
5225: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
5226: push(@rolecodes,'cr');
5227: } elsif ($$role eq 'gr') {
5228: push(@rolecodes,$$role);
5229: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5230: $env{'user.name'});
5231: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
5232: (undef,my $group_privs) = split(/\//,$trole);
5233: $group_privs = &unescape($group_privs);
5234: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
5235: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
5236: &get_groups_roles($tdomain,$trest,
5237: \%course_roles,\@rolecodes,
5238: \%groups_roles);
5239: } else {
5240: push(@rolecodes,$$role);
5241: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5242: }
5243: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5244: &appenv(\%userroles,\@rolecodes);
5245: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5246: }
5247: }
5248: $$tstatus = 'is';
5249: }
5250: }
5251: if ($$tend) {
5252: if ($$tend<$update) {
5253: $$tstatus='expired';
5254: } elsif ($$tend<$now) {
5255: $$tstatus='will_not';
5256: }
5257: }
5258: }
5259: }
5260: }
5261:
5262: sub get_groups_roles {
5263: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5264: return unless((ref($cdom_courseroles) eq 'HASH') &&
5265: (ref($rolecodes) eq 'ARRAY') &&
5266: (ref($groups_roles) eq 'HASH'));
5267: if (keys(%{$cdom_courseroles}) > 0) {
5268: my ($cnum) = ($rest =~ /^($match_courseid)/);
5269: if ($cdom ne '' && $cnum ne '') {
5270: foreach my $key (keys(%{$cdom_courseroles})) {
5271: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5272: my $crsrole = $1;
5273: my $crssec = $2;
5274: if ($crsrole =~ /^cr/) {
5275: unless (grep(/^cr$/,@{$rolecodes})) {
5276: push(@{$rolecodes},'cr');
5277: }
5278: } else {
5279: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5280: push(@{$rolecodes},$crsrole);
5281: }
5282: }
5283: my $rolekey = "$crsrole./$cdom/$cnum";
5284: if ($crssec ne '') {
5285: $rolekey .= "/$crssec";
5286: }
5287: $rolekey .= './';
5288: $groups_roles->{$rolekey} = $rolecodes;
5289: }
5290: }
5291: }
5292: }
5293: return;
5294: }
5295:
5296: sub delete_env_groupprivs {
5297: my ($where,$courseroles,$possroles) = @_;
5298: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5299: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5300: unless (ref($courseroles->{$udom}) eq 'HASH') {
5301: %{$courseroles->{$udom}} =
5302: &get_my_roles('','','userroles',['active'],
5303: $possroles,[$udom],1);
5304: }
5305: if (ref($courseroles->{$udom}) eq 'HASH') {
5306: foreach my $item (keys(%{$courseroles->{$udom}})) {
5307: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5308: my $area = '/'.$cdom.'/'.$cnum;
5309: my $privkey = "user.priv.$crsrole.$area";
5310: if ($crssec ne '') {
5311: $privkey .= '/'.$crssec;
5312: }
5313: $privkey .= ".$area/$group";
5314: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5315: }
5316: }
5317: return;
5318: }
5319:
5320: sub check_adhoc_privs {
5321: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
5322: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
5323: my $setprivs;
5324: if ($env{$cckey}) {
5325: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
5326: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
5327: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
5328: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
5329: $setprivs = 1;
5330: }
5331: } else {
5332: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
5333: $setprivs = 1;
5334: }
5335: return $setprivs;
5336: }
5337:
5338: sub set_adhoc_privileges {
5339: # role can be cc or ca
5340: my ($dcdom,$pickedcourse,$role,$caller) = @_;
5341: my $area = '/'.$dcdom.'/'.$pickedcourse;
5342: my $spec = $role.'.'.$area;
5343: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
5344: $env{'user.name'});
5345: my %ccrole = ();
5346: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5347: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5348: &appenv(\%userroles,[$role,'cm']);
5349: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5350: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5351: &appenv( {'request.role' => $spec,
5352: 'request.role.domain' => $dcdom,
5353: 'request.course.sec' => ''
5354: }
5355: );
5356: my $tadv=0;
5357: if (&allowed('adv') eq 'F') { $tadv=1; }
5358: &appenv({'request.role.adv' => $tadv});
5359: }
5360: }
5361:
5362: # --------------------------------------------------------------- get interface
5363:
5364: sub get {
5365: my ($namespace,$storearr,$udomain,$uname)=@_;
5366: my $items='';
5367: foreach my $item (@$storearr) {
5368: $items.=&escape($item).'&';
5369: }
5370: $items=~s/\&$//;
5371: if (!$udomain) { $udomain=$env{'user.domain'}; }
5372: if (!$uname) { $uname=$env{'user.name'}; }
5373: my $uhome=&homeserver($uname,$udomain);
5374:
5375: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
5376: my @pairs=split(/\&/,$rep);
5377: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5378: return @pairs;
5379: }
5380: my %returnhash=();
5381: my $i=0;
5382: foreach my $item (@$storearr) {
5383: $returnhash{$item}=&thaw_unescape($pairs[$i]);
5384: $i++;
5385: }
5386: return %returnhash;
5387: }
5388:
5389: # --------------------------------------------------------------- del interface
5390:
5391: sub del {
5392: my ($namespace,$storearr,$udomain,$uname)=@_;
5393: my $items='';
5394: foreach my $item (@$storearr) {
5395: $items.=&escape($item).'&';
5396: }
5397:
5398: $items=~s/\&$//;
5399: if (!$udomain) { $udomain=$env{'user.domain'}; }
5400: if (!$uname) { $uname=$env{'user.name'}; }
5401: my $uhome=&homeserver($uname,$udomain);
5402: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
5403: }
5404:
5405: # -------------------------------------------------------------- dump interface
5406:
5407: sub unserialize {
5408: my ($rep, $escapedkeys) = @_;
5409:
5410: return {} if $rep =~ /^error/;
5411:
5412: my %returnhash=();
5413: foreach my $item (split /\&/, $rep) {
5414: my ($key, $value) = split(/=/, $item, 2);
5415: $key = unescape($key) unless $escapedkeys;
5416: next if $key =~ /^error: 2 /;
5417: $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
5418: }
5419: #return %returnhash;
5420: return \%returnhash;
5421: }
5422:
5423: # see Lond::dump_with_regexp
5424: # if $escapedkeys hash keys won't get unescaped.
5425: sub dump {
5426: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
5427: if (!$udomain) { $udomain=$env{'user.domain'}; }
5428: if (!$uname) { $uname=$env{'user.name'}; }
5429: my $uhome=&homeserver($uname,$udomain);
5430:
5431: my $reply;
5432: if (grep { $_ eq $uhome } current_machine_ids()) {
5433: # user is hosted on this machine
5434: $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
5435: $uname, $namespace, $regexp, $range)), $loncaparevs{$uhome});
5436: return %{unserialize($reply, $escapedkeys)};
5437: }
5438: if ($regexp) {
5439: $regexp=&escape($regexp);
5440: } else {
5441: $regexp='.';
5442: }
5443: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
5444: my @pairs=split(/\&/,$rep);
5445: my %returnhash=();
5446: if (!($rep =~ /^error/ )) {
5447: foreach my $item (@pairs) {
5448: my ($key,$value)=split(/=/,$item,2);
5449: $key = unescape($key) unless $escapedkeys;
5450: #$key = &unescape($key);
5451: next if ($key =~ /^error: 2 /);
5452: $returnhash{$key}=&thaw_unescape($value);
5453: }
5454: }
5455: return %returnhash;
5456: }
5457:
5458:
5459: # --------------------------------------------------------- dumpstore interface
5460:
5461: sub dumpstore {
5462: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
5463: # same as dump but keys must be escaped. They may contain colon separated
5464: # lists of values that may themself contain colons (e.g. symbs).
5465: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
5466: }
5467:
5468: # -------------------------------------------------------------- keys interface
5469:
5470: sub getkeys {
5471: my ($namespace,$udomain,$uname)=@_;
5472: if (!$udomain) { $udomain=$env{'user.domain'}; }
5473: if (!$uname) { $uname=$env{'user.name'}; }
5474: my $uhome=&homeserver($uname,$udomain);
5475: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5476: my @keyarray=();
5477: foreach my $key (split(/\&/,$rep)) {
5478: next if ($key =~ /^error: 2 /);
5479: push(@keyarray,&unescape($key));
5480: }
5481: return @keyarray;
5482: }
5483:
5484: # --------------------------------------------------------------- currentdump
5485: sub currentdump {
5486: my ($courseid,$sdom,$sname)=@_;
5487: $courseid = $env{'request.course.id'} if (! defined($courseid));
5488: $sdom = $env{'user.domain'} if (! defined($sdom));
5489: $sname = $env{'user.name'} if (! defined($sname));
5490: my $uhome = &homeserver($sname,$sdom);
5491: my $rep;
5492:
5493: if (grep { $_ eq $uhome } current_machine_ids()) {
5494: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5495: $courseid)));
5496: } else {
5497: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5498: }
5499:
5500: return if ($rep =~ /^(error:|no_such_host)/);
5501: #
5502: my %returnhash=();
5503: #
5504: if ($rep eq "unknown_cmd") {
5505: # an old lond will not know currentdump
5506: # Do a dump and make it look like a currentdump
5507: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
5508: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5509: my %hash = @tmp;
5510: @tmp=();
5511: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
5512: } else {
5513: my @pairs=split(/\&/,$rep);
5514: foreach my $pair (@pairs) {
5515: my ($key,$value)=split(/=/,$pair,2);
5516: my ($symb,$param) = split(/:/,$key);
5517: $returnhash{&unescape($symb)}->{&unescape($param)} =
5518: &thaw_unescape($value);
5519: }
5520: }
5521: return %returnhash;
5522: }
5523:
5524: sub convert_dump_to_currentdump{
5525: my %hash = %{shift()};
5526: my %returnhash;
5527: # Code ripped from lond, essentially. The only difference
5528: # here is the unescaping done by lonnet::dump(). Conceivably
5529: # we might run in to problems with parameter names =~ /^v\./
5530: while (my ($key,$value) = each(%hash)) {
5531: my ($v,$symb,$param) = split(/:/,$key);
5532: $symb = &unescape($symb);
5533: $param = &unescape($param);
5534: next if ($v eq 'version' || $symb eq 'keys');
5535: next if (exists($returnhash{$symb}) &&
5536: exists($returnhash{$symb}->{$param}) &&
5537: $returnhash{$symb}->{'v.'.$param} > $v);
5538: $returnhash{$symb}->{$param}=$value;
5539: $returnhash{$symb}->{'v.'.$param}=$v;
5540: }
5541: #
5542: # Remove all of the keys in the hashes which keep track of
5543: # the version of the parameter.
5544: while (my ($symb,$param_hash) = each(%returnhash)) {
5545: # use a foreach because we are going to delete from the hash.
5546: foreach my $key (keys(%$param_hash)) {
5547: delete($param_hash->{$key}) if ($key =~ /^v\./);
5548: }
5549: }
5550: return \%returnhash;
5551: }
5552:
5553: # ------------------------------------------------------ critical inc interface
5554:
5555: sub cinc {
5556: return &inc(@_,'critical');
5557: }
5558:
5559: # --------------------------------------------------------------- inc interface
5560:
5561: sub inc {
5562: my ($namespace,$store,$udomain,$uname,$critical) = @_;
5563: if (!$udomain) { $udomain=$env{'user.domain'}; }
5564: if (!$uname) { $uname=$env{'user.name'}; }
5565: my $uhome=&homeserver($uname,$udomain);
5566: my $items='';
5567: if (! ref($store)) {
5568: # got a single value, so use that instead
5569: $items = &escape($store).'=&';
5570: } elsif (ref($store) eq 'SCALAR') {
5571: $items = &escape($$store).'=&';
5572: } elsif (ref($store) eq 'ARRAY') {
5573: $items = join('=&',map {&escape($_);} @{$store});
5574: } elsif (ref($store) eq 'HASH') {
5575: while (my($key,$value) = each(%{$store})) {
5576: $items.= &escape($key).'='.&escape($value).'&';
5577: }
5578: }
5579: $items=~s/\&$//;
5580: if ($critical) {
5581: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5582: } else {
5583: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5584: }
5585: }
5586:
5587: # --------------------------------------------------------------- put interface
5588:
5589: sub put {
5590: my ($namespace,$storehash,$udomain,$uname)=@_;
5591: if (!$udomain) { $udomain=$env{'user.domain'}; }
5592: if (!$uname) { $uname=$env{'user.name'}; }
5593: my $uhome=&homeserver($uname,$udomain);
5594: my $items='';
5595: foreach my $item (keys(%$storehash)) {
5596: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5597: }
5598: $items=~s/\&$//;
5599: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
5600: }
5601:
5602: # ------------------------------------------------------------ newput interface
5603:
5604: sub newput {
5605: my ($namespace,$storehash,$udomain,$uname)=@_;
5606: if (!$udomain) { $udomain=$env{'user.domain'}; }
5607: if (!$uname) { $uname=$env{'user.name'}; }
5608: my $uhome=&homeserver($uname,$udomain);
5609: my $items='';
5610: foreach my $key (keys(%$storehash)) {
5611: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5612: }
5613: $items=~s/\&$//;
5614: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5615: }
5616:
5617: # --------------------------------------------------------- putstore interface
5618:
5619: sub putstore {
5620: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5621: if (!$udomain) { $udomain=$env{'user.domain'}; }
5622: if (!$uname) { $uname=$env{'user.name'}; }
5623: my $uhome=&homeserver($uname,$udomain);
5624: my $items='';
5625: foreach my $key (keys(%$storehash)) {
5626: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
5627: }
5628: $items=~s/\&$//;
5629: my $esc_symb=&escape($symb);
5630: my $esc_v=&escape($version);
5631: my $reply =
5632: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
5633: $uhome);
5634: if ($reply eq 'unknown_cmd') {
5635: # gfall back to way things use to be done
5636: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5637: $uname);
5638: }
5639: return $reply;
5640: }
5641:
5642: sub old_putstore {
5643: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5644: if (!$udomain) { $udomain=$env{'user.domain'}; }
5645: if (!$uname) { $uname=$env{'user.name'}; }
5646: my $uhome=&homeserver($uname,$udomain);
5647: my %newstorehash;
5648: foreach my $item (keys(%$storehash)) {
5649: my $key = $version.':'.&escape($symb).':'.$item;
5650: $newstorehash{$key} = $storehash->{$item};
5651: }
5652: my $items='';
5653: my %allitems = ();
5654: foreach my $item (keys(%newstorehash)) {
5655: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
5656: my $key = $1.':keys:'.$2;
5657: $allitems{$key} .= $3.':';
5658: }
5659: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
5660: }
5661: foreach my $item (keys(%allitems)) {
5662: $allitems{$item} =~ s/\:$//;
5663: $items.= $item.'='.$allitems{$item}.'&';
5664: }
5665: $items=~s/\&$//;
5666: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
5667: }
5668:
5669: # ------------------------------------------------------ critical put interface
5670:
5671: sub cput {
5672: my ($namespace,$storehash,$udomain,$uname)=@_;
5673: if (!$udomain) { $udomain=$env{'user.domain'}; }
5674: if (!$uname) { $uname=$env{'user.name'}; }
5675: my $uhome=&homeserver($uname,$udomain);
5676: my $items='';
5677: foreach my $item (keys(%$storehash)) {
5678: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5679: }
5680: $items=~s/\&$//;
5681: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
5682: }
5683:
5684: # -------------------------------------------------------------- eget interface
5685:
5686: sub eget {
5687: my ($namespace,$storearr,$udomain,$uname)=@_;
5688: my $items='';
5689: foreach my $item (@$storearr) {
5690: $items.=&escape($item).'&';
5691: }
5692: $items=~s/\&$//;
5693: if (!$udomain) { $udomain=$env{'user.domain'}; }
5694: if (!$uname) { $uname=$env{'user.name'}; }
5695: my $uhome=&homeserver($uname,$udomain);
5696: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
5697: my @pairs=split(/\&/,$rep);
5698: my %returnhash=();
5699: my $i=0;
5700: foreach my $item (@$storearr) {
5701: $returnhash{$item}=&thaw_unescape($pairs[$i]);
5702: $i++;
5703: }
5704: return %returnhash;
5705: }
5706:
5707: # ------------------------------------------------------------ tmpput interface
5708: sub tmpput {
5709: my ($storehash,$server,$context)=@_;
5710: my $items='';
5711: foreach my $item (keys(%$storehash)) {
5712: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5713: }
5714: $items=~s/\&$//;
5715: if (defined($context)) {
5716: $items .= ':'.&escape($context);
5717: }
5718: return &reply("tmpput:$items",$server);
5719: }
5720:
5721: # ------------------------------------------------------------ tmpget interface
5722: sub tmpget {
5723: my ($token,$server)=@_;
5724: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5725: my $rep=&reply("tmpget:$token",$server);
5726: my %returnhash;
5727: foreach my $item (split(/\&/,$rep)) {
5728: my ($key,$value)=split(/=/,$item);
5729: next if ($key =~ /^error: 2 /);
5730: $returnhash{&unescape($key)}=&thaw_unescape($value);
5731: }
5732: return %returnhash;
5733: }
5734:
5735: # ------------------------------------------------------------ tmpdel interface
5736: sub tmpdel {
5737: my ($token,$server)=@_;
5738: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5739: return &reply("tmpdel:$token",$server);
5740: }
5741:
5742: # ------------------------------------------------------------ get_timebased_id
5743:
5744: sub get_timebased_id {
5745: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5746: $maxtries) = @_;
5747: my ($newid,$error,$dellock);
5748: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5749: return ('','ok','invalid call to get suffix');
5750: }
5751:
5752: # set defaults for any optional args for which values were not supplied
5753: if ($who eq '') {
5754: $who = $env{'user.name'}.':'.$env{'user.domain'};
5755: }
5756: if (!$locktries) {
5757: $locktries = 3;
5758: }
5759: if (!$maxtries) {
5760: $maxtries = 10;
5761: }
5762:
5763: if (($cdom eq '') || ($cnum eq '')) {
5764: if ($env{'request.course.id'}) {
5765: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5766: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5767: }
5768: if (($cdom eq '') || ($cnum eq '')) {
5769: return ('','ok','call to get suffix not in course context');
5770: }
5771: }
5772:
5773: # construct locking item
5774: my $lockhash = {
5775: $prefix."\0".'locked_'.$keyid => $who,
5776: };
5777: my $tries = 0;
5778:
5779: # attempt to get lock on nohist_$namespace file
5780: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5781: while (($gotlock ne 'ok') && $tries <$locktries) {
5782: $tries ++;
5783: sleep 1;
5784: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5785: }
5786:
5787: # attempt to get unique identifier, based on current timestamp
5788: if ($gotlock eq 'ok') {
5789: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
5790: my $id = time;
5791: $newid = $id;
5792: my $idtries = 0;
5793: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
5794: if ($idtype eq 'concat') {
5795: $newid = $id.$idtries;
5796: } else {
5797: $newid ++;
5798: }
5799: $idtries ++;
5800: }
5801: if (!exists($inuse{$prefix."\0".$newid})) {
5802: my %new_item = (
5803: $prefix."\0".$newid => $who,
5804: );
5805: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
5806: $cdom,$cnum);
5807: if ($putresult ne 'ok') {
5808: undef($newid);
5809: $error = 'error saving new item: '.$putresult;
5810: }
5811: } else {
5812: $error = ('error: no unique suffix available for the new item ');
5813: }
5814: # remove lock
5815: my @del_lock = ($prefix."\0".'locked_'.$keyid);
5816: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
5817: } else {
5818: $error = "error: could not obtain lockfile\n";
5819: $dellock = 'ok';
5820: }
5821: return ($newid,$dellock,$error);
5822: }
5823:
5824: # -------------------------------------------------- portfolio access checking
5825:
5826: sub portfolio_access {
5827: my ($requrl) = @_;
5828: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5829: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
5830: if ($result) {
5831: my %setters;
5832: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5833: my ($startblock,$endblock) =
5834: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5835: if ($startblock && $endblock) {
5836: return 'B';
5837: }
5838: } else {
5839: my ($startblock,$endblock) =
5840: &Apache::loncommon::blockcheck(\%setters,'port');
5841: if ($startblock && $endblock) {
5842: return 'B';
5843: }
5844: }
5845: }
5846: if ($result eq 'ok') {
5847: return 'F';
5848: } elsif ($result =~ /^[^:]+:guest_/) {
5849: return 'A';
5850: }
5851: return '';
5852: }
5853:
5854: sub get_portfolio_access {
5855: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5856:
5857: if (!ref($access_hash)) {
5858: my $current_perms = &get_portfile_permissions($udom,$unum);
5859: my %access_controls = &get_access_controls($current_perms,$group,
5860: $file_name);
5861: $access_hash = $access_controls{$file_name};
5862: }
5863:
5864: my ($public,$guest,@domains,@users,@courses,@groups);
5865: my $now = time;
5866: if (ref($access_hash) eq 'HASH') {
5867: foreach my $key (keys(%{$access_hash})) {
5868: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5869: if ($start > $now) {
5870: next;
5871: }
5872: if ($end && $end<$now) {
5873: next;
5874: }
5875: if ($scope eq 'public') {
5876: $public = $key;
5877: last;
5878: } elsif ($scope eq 'guest') {
5879: $guest = $key;
5880: } elsif ($scope eq 'domains') {
5881: push(@domains,$key);
5882: } elsif ($scope eq 'users') {
5883: push(@users,$key);
5884: } elsif ($scope eq 'course') {
5885: push(@courses,$key);
5886: } elsif ($scope eq 'group') {
5887: push(@groups,$key);
5888: }
5889: }
5890: if ($public) {
5891: return 'ok';
5892: }
5893: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5894: if ($guest) {
5895: return $guest;
5896: }
5897: } else {
5898: if (@domains > 0) {
5899: foreach my $domkey (@domains) {
5900: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
5901: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
5902: return 'ok';
5903: }
5904: }
5905: }
5906: }
5907: if (@users > 0) {
5908: foreach my $userkey (@users) {
5909: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
5910: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
5911: if (ref($item) eq 'HASH') {
5912: if (($item->{'uname'} eq $env{'user.name'}) &&
5913: ($item->{'udom'} eq $env{'user.domain'})) {
5914: return 'ok';
5915: }
5916: }
5917: }
5918: }
5919: }
5920: }
5921: my %roleshash;
5922: my @courses_and_groups = @courses;
5923: push(@courses_and_groups,@groups);
5924: if (@courses_and_groups > 0) {
5925: my (%allgroups,%allroles);
5926: my ($start,$end,$role,$sec,$group);
5927: foreach my $envkey (%env) {
5928: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
5929: my $cid = $2.'_'.$3;
5930: if ($1 eq 'gr') {
5931: $group = $4;
5932: $allgroups{$cid}{$group} = $env{$envkey};
5933: } else {
5934: if ($4 eq '') {
5935: $sec = 'none';
5936: } else {
5937: $sec = $4;
5938: }
5939: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5940: }
5941: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
5942: my $cid = $2.'_'.$3;
5943: if ($4 eq '') {
5944: $sec = 'none';
5945: } else {
5946: $sec = $4;
5947: }
5948: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5949: }
5950: }
5951: if (keys(%allroles) == 0) {
5952: return;
5953: }
5954: foreach my $key (@courses_and_groups) {
5955: my %content = %{$$access_hash{$key}};
5956: my $cnum = $content{'number'};
5957: my $cdom = $content{'domain'};
5958: my $cid = $cdom.'_'.$cnum;
5959: if (!exists($allroles{$cid})) {
5960: next;
5961: }
5962: foreach my $role_id (keys(%{$content{'roles'}})) {
5963: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5964: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5965: my @status = @{$content{'roles'}{$role_id}{'access'}};
5966: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5967: foreach my $role (keys(%{$allroles{$cid}})) {
5968: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5969: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5970: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5971: if (grep/^all$/,@sections) {
5972: return 'ok';
5973: } else {
5974: if (grep/^$sec$/,@sections) {
5975: return 'ok';
5976: }
5977: }
5978: }
5979: }
5980: if (keys(%{$allgroups{$cid}}) == 0) {
5981: if (grep/^none$/,@groups) {
5982: return 'ok';
5983: }
5984: } else {
5985: if (grep/^all$/,@groups) {
5986: return 'ok';
5987: }
5988: foreach my $group (keys(%{$allgroups{$cid}})) {
5989: if (grep/^$group$/,@groups) {
5990: return 'ok';
5991: }
5992: }
5993: }
5994: }
5995: }
5996: }
5997: }
5998: }
5999: if ($guest) {
6000: return $guest;
6001: }
6002: }
6003: }
6004: return;
6005: }
6006:
6007: sub course_group_datechecker {
6008: my ($dates,$now,$status) = @_;
6009: my ($start,$end) = split(/\./,$dates);
6010: if (!$start && !$end) {
6011: return 'ok';
6012: }
6013: if (grep/^active$/,@{$status}) {
6014: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6015: return 'ok';
6016: }
6017: }
6018: if (grep/^previous$/,@{$status}) {
6019: if ($end > $now ) {
6020: return 'ok';
6021: }
6022: }
6023: if (grep/^future$/,@{$status}) {
6024: if ($start > $now) {
6025: return 'ok';
6026: }
6027: }
6028: return;
6029: }
6030:
6031: sub parse_portfolio_url {
6032: my ($url) = @_;
6033:
6034: my ($type,$udom,$unum,$group,$file_name);
6035:
6036: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
6037: $type = 1;
6038: $udom = $1;
6039: $unum = $2;
6040: $file_name = $3;
6041: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
6042: $type = 2;
6043: $udom = $1;
6044: $unum = $2;
6045: $group = $3;
6046: $file_name = $3.'/'.$4;
6047: }
6048: if (wantarray) {
6049: return ($type,$udom,$unum,$file_name,$group);
6050: }
6051: return $type;
6052: }
6053:
6054: sub is_portfolio_url {
6055: my ($url) = @_;
6056: return scalar(&parse_portfolio_url($url));
6057: }
6058:
6059: sub is_portfolio_file {
6060: my ($file) = @_;
6061: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
6062: return 1;
6063: }
6064: return;
6065: }
6066:
6067: sub usertools_access {
6068: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
6069: my ($access,%tools);
6070: if ($context eq '') {
6071: $context = 'tools';
6072: }
6073: if ($context eq 'requestcourses') {
6074: %tools = (
6075: official => 1,
6076: unofficial => 1,
6077: community => 1,
6078: );
6079: } elsif ($context eq 'requestauthor') {
6080: %tools = (
6081: requestauthor => 1,
6082: );
6083: } else {
6084: %tools = (
6085: aboutme => 1,
6086: blog => 1,
6087: webdav => 1,
6088: portfolio => 1,
6089: );
6090: }
6091: return if (!defined($tools{$tool}));
6092:
6093: if ((!defined($udom)) || (!defined($uname))) {
6094: $udom = $env{'user.domain'};
6095: $uname = $env{'user.name'};
6096: }
6097:
6098: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6099: if ($action ne 'reload') {
6100: if ($context eq 'requestcourses') {
6101: return $env{'environment.canrequest.'.$tool};
6102: } elsif ($context eq 'requestauthor') {
6103: return $env{'environment.canrequest.author'};
6104: } else {
6105: return $env{'environment.availabletools.'.$tool};
6106: }
6107: }
6108: }
6109:
6110: my ($toolstatus,$inststatus,$envkey);
6111: if ($context eq 'requestauthor') {
6112: $envkey = $context;
6113: } else {
6114: $envkey = $context.'.'.$tool;
6115: }
6116:
6117: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6118: ($action ne 'reload')) {
6119: $toolstatus = $env{'environment.'.$envkey};
6120: $inststatus = $env{'environment.inststatus'};
6121: } else {
6122: if (ref($userenvref) eq 'HASH') {
6123: $toolstatus = $userenvref->{$envkey};
6124: $inststatus = $userenvref->{'inststatus'};
6125: } else {
6126: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6127: $toolstatus = $userenv{$envkey};
6128: $inststatus = $userenv{'inststatus'};
6129: }
6130: }
6131:
6132: if ($toolstatus ne '') {
6133: if ($toolstatus) {
6134: $access = 1;
6135: } else {
6136: $access = 0;
6137: }
6138: return $access;
6139: }
6140:
6141: my ($is_adv,%domdef);
6142: if (ref($is_advref) eq 'HASH') {
6143: $is_adv = $is_advref->{'is_adv'};
6144: } else {
6145: $is_adv = &is_advanced_user($udom,$uname);
6146: }
6147: if (ref($domdefref) eq 'HASH') {
6148: %domdef = %{$domdefref};
6149: } else {
6150: %domdef = &get_domain_defaults($udom);
6151: }
6152: if (ref($domdef{$tool}) eq 'HASH') {
6153: if ($is_adv) {
6154: if ($domdef{$tool}{'_LC_adv'} ne '') {
6155: if ($domdef{$tool}{'_LC_adv'}) {
6156: $access = 1;
6157: } else {
6158: $access = 0;
6159: }
6160: return $access;
6161: }
6162: }
6163: if ($inststatus ne '') {
6164: my ($hasaccess,$hasnoaccess);
6165: foreach my $affiliation (split(/:/,$inststatus)) {
6166: if ($domdef{$tool}{$affiliation} ne '') {
6167: if ($domdef{$tool}{$affiliation}) {
6168: $hasaccess = 1;
6169: } else {
6170: $hasnoaccess = 1;
6171: }
6172: }
6173: }
6174: if ($hasaccess || $hasnoaccess) {
6175: if ($hasaccess) {
6176: $access = 1;
6177: } elsif ($hasnoaccess) {
6178: $access = 0;
6179: }
6180: return $access;
6181: }
6182: } else {
6183: if ($domdef{$tool}{'default'} ne '') {
6184: if ($domdef{$tool}{'default'}) {
6185: $access = 1;
6186: } elsif ($domdef{$tool}{'default'} == 0) {
6187: $access = 0;
6188: }
6189: return $access;
6190: }
6191: }
6192: } else {
6193: if (($context eq 'tools') && ($tool ne 'webdav')) {
6194: $access = 1;
6195: } else {
6196: $access = 0;
6197: }
6198: return $access;
6199: }
6200: }
6201:
6202: sub is_course_owner {
6203: my ($cdom,$cnum,$udom,$uname) = @_;
6204: if (($udom eq '') || ($uname eq '')) {
6205: $udom = $env{'user.domain'};
6206: $uname = $env{'user.name'};
6207: }
6208: unless (($udom eq '') || ($uname eq '')) {
6209: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6210: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6211: return 1;
6212: } else {
6213: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6214: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6215: return 1;
6216: }
6217: }
6218: }
6219: }
6220: return;
6221: }
6222:
6223: sub is_advanced_user {
6224: my ($udom,$uname) = @_;
6225: if ($udom ne '' && $uname ne '') {
6226: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6227: if (wantarray) {
6228: return ($env{'user.adv'},$env{'user.author'});
6229: } else {
6230: return $env{'user.adv'};
6231: }
6232: }
6233: }
6234: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6235: my %allroles;
6236: my ($is_adv,$is_author);
6237: foreach my $role (keys(%roleshash)) {
6238: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6239: my $area = '/'.$tdomain.'/'.$trest;
6240: if ($sec ne '') {
6241: $area .= '/'.$sec;
6242: }
6243: if (($area ne '') && ($trole ne '')) {
6244: my $spec=$trole.'.'.$area;
6245: if ($trole =~ /^cr\//) {
6246: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6247: } elsif ($trole ne 'gr') {
6248: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6249: }
6250: if ($trole eq 'au') {
6251: $is_author = 1;
6252: }
6253: }
6254: }
6255: foreach my $role (keys(%allroles)) {
6256: last if ($is_adv);
6257: foreach my $item (split(/:/,$allroles{$role})) {
6258: if ($item ne '') {
6259: my ($privilege,$restrictions)=split(/&/,$item);
6260: if ($privilege eq 'adv') {
6261: $is_adv = 1;
6262: last;
6263: }
6264: }
6265: }
6266: }
6267: if (wantarray) {
6268: return ($is_adv,$is_author);
6269: }
6270: return $is_adv;
6271: }
6272:
6273: sub check_can_request {
6274: my ($dom,$can_request,$request_domains) = @_;
6275: my $canreq = 0;
6276: my ($types,$typename) = &Apache::loncommon::course_types();
6277: my @options = ('approval','validate','autolimit');
6278: my $optregex = join('|',@options);
6279: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6280: foreach my $type (@{$types}) {
6281: if (&usertools_access($env{'user.name'},
6282: $env{'user.domain'},
6283: $type,undef,'requestcourses')) {
6284: $canreq ++;
6285: if (ref($request_domains) eq 'HASH') {
6286: push(@{$request_domains->{$type}},$env{'user.domain'});
6287: }
6288: if ($dom eq $env{'user.domain'}) {
6289: $can_request->{$type} = 1;
6290: }
6291: }
6292: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6293: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6294: if (@curr > 0) {
6295: foreach my $item (@curr) {
6296: if (ref($request_domains) eq 'HASH') {
6297: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6298: if ($otherdom ne '') {
6299: if (ref($request_domains->{$type}) eq 'ARRAY') {
6300: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6301: push(@{$request_domains->{$type}},$otherdom);
6302: }
6303: } else {
6304: push(@{$request_domains->{$type}},$otherdom);
6305: }
6306: }
6307: }
6308: }
6309: unless($dom eq $env{'user.domain'}) {
6310: $canreq ++;
6311: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6312: $can_request->{$type} = 1;
6313: }
6314: }
6315: }
6316: }
6317: }
6318: }
6319: return $canreq;
6320: }
6321:
6322: # ---------------------------------------------- Custom access rule evaluation
6323:
6324: sub customaccess {
6325: my ($priv,$uri)=@_;
6326: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
6327: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
6328: $udom = &LONCAPA::clean_domain($udom);
6329: $ucrs = &LONCAPA::clean_username($ucrs);
6330: my $access=0;
6331: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
6332: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6333: if ($type eq 'user') {
6334: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6335: my ($tdom,$tuname)=split(m{/},$scope);
6336: if ($tdom) {
6337: if ($tdom ne $env{'user.domain'}) { next; }
6338: }
6339: if ($tuname) {
6340: if ($tuname ne $env{'user.name'}) { next; }
6341: }
6342: $access=($effect eq 'allow');
6343: last;
6344: }
6345: } else {
6346: if ($role) {
6347: if ($role ne $urole) { next; }
6348: }
6349: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6350: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6351: if ($tdom) {
6352: if ($tdom ne $udom) { next; }
6353: }
6354: if ($tcrs) {
6355: if ($tcrs ne $ucrs) { next; }
6356: }
6357: if ($tsec) {
6358: if ($tsec ne $usec) { next; }
6359: }
6360: $access=($effect eq 'allow');
6361: last;
6362: }
6363: if ($realm eq '' && $role eq '') {
6364: $access=($effect eq 'allow');
6365: }
6366: }
6367: }
6368: return $access;
6369: }
6370:
6371: # ------------------------------------------------- Check for a user privilege
6372:
6373: sub allowed {
6374: my ($priv,$uri,$symb,$role)=@_;
6375: my $ver_orguri=$uri;
6376: $uri=&deversion($uri);
6377: my $orguri=$uri;
6378: $uri=&declutter($uri);
6379:
6380: if ($priv eq 'evb') {
6381: # Evade communication block restrictions for specified role in a course
6382: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6383: return $1;
6384: } else {
6385: return;
6386: }
6387: }
6388:
6389: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
6390: # Free bre access to adm and meta resources
6391: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
6392: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6393: && ($priv eq 'bre')) {
6394: return 'F';
6395: }
6396:
6397: # Free bre access to user's own portfolio contents
6398: my ($space,$domain,$name,@dir)=split('/',$uri);
6399: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
6400: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
6401: my %setters;
6402: my ($startblock,$endblock) =
6403: &Apache::loncommon::blockcheck(\%setters,'port');
6404: if ($startblock && $endblock) {
6405: return 'B';
6406: } else {
6407: return 'F';
6408: }
6409: }
6410:
6411: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
6412: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6413: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6414: if (exists($env{'request.course.id'})) {
6415: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6416: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6417: if (($domain eq $cdom) && ($name eq $cnum)) {
6418: my $courseprivid=$env{'request.course.id'};
6419: $courseprivid=~s/\_/\//;
6420: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6421: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6422: return $1;
6423: } else {
6424: if ($env{'request.course.sec'}) {
6425: $courseprivid.='/'.$env{'request.course.sec'};
6426: }
6427: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6428: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6429: return $2;
6430: }
6431: }
6432: }
6433: }
6434: }
6435:
6436: # Free bre to public access
6437:
6438: if ($priv eq 'bre') {
6439: my $copyright=&metadata($uri,'copyright');
6440: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
6441: return 'F';
6442: }
6443: if ($copyright eq 'priv') {
6444: $uri=~/([^\/]+)\/([^\/]+)\//;
6445: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
6446: return '';
6447: }
6448: }
6449: if ($copyright eq 'domain') {
6450: $uri=~/([^\/]+)\/([^\/]+)\//;
6451: unless (($env{'user.domain'} eq $1) ||
6452: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
6453: return '';
6454: }
6455: }
6456: if ($env{'request.role'}=~ /li\.\//) {
6457: # Library role, so allow browsing of resources in this domain.
6458: return 'F';
6459: }
6460: if ($copyright eq 'custom') {
6461: unless (&customaccess($priv,$uri)) { return ''; }
6462: }
6463: }
6464: # Domain coordinator is trying to create a course
6465: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
6466: # uri is the requested domain in this case.
6467: # comparison to 'request.role.domain' shows if the user has selected
6468: # a role of dc for the domain in question.
6469: return 'F' if ($uri eq $env{'request.role.domain'});
6470: }
6471:
6472: my $thisallowed='';
6473: my $statecond=0;
6474: my $courseprivid='';
6475:
6476: my $ownaccess;
6477: # Community Coordinator or Assistant Co-author browsing resource space.
6478: if (($priv eq 'bro') && ($env{'user.author'})) {
6479: if ($uri eq '') {
6480: $ownaccess = 1;
6481: } else {
6482: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6483: my $udom = $env{'user.domain'};
6484: my $uname = $env{'user.name'};
6485: if ($uri =~ m{^\Q$udom\E/?$}) {
6486: $ownaccess = 1;
6487: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
6488: unless ($uri =~ m{\.\./}) {
6489: $ownaccess = 1;
6490: }
6491: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6492: my $now = time;
6493: if ($uri =~ m{^([^/]+)/?$}) {
6494: my $adom = $1;
6495: foreach my $key (keys(%env)) {
6496: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
6497: my ($start,$end) = split('.',$env{$key});
6498: if (($now >= $start) && (!$end || $end < $now)) {
6499: $ownaccess = 1;
6500: last;
6501: }
6502: }
6503: }
6504: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6505: my $adom = $1;
6506: my $aname = $2;
6507: foreach my $role ('ca','aa') {
6508: if ($env{"user.role.$role./$adom/$aname"}) {
6509: my ($start,$end) =
6510: split('.',$env{"user.role.$role./$adom/$aname"});
6511: if (($now >= $start) && (!$end || $end < $now)) {
6512: $ownaccess = 1;
6513: last;
6514: }
6515: }
6516: }
6517: }
6518: }
6519: }
6520: }
6521: }
6522:
6523: # Course
6524:
6525: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
6526: unless (($priv eq 'bro') && (!$ownaccess)) {
6527: $thisallowed.=$1;
6528: }
6529: }
6530:
6531: # Domain
6532:
6533: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
6534: =~/\Q$priv\E\&([^\:]*)/) {
6535: unless (($priv eq 'bro') && (!$ownaccess)) {
6536: $thisallowed.=$1;
6537: }
6538: }
6539:
6540: # User who is not author or co-author might still be able to edit
6541: # resource of an author in the domain (e.g., if Domain Coordinator).
6542: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6543: (&allowed('mdc',$env{'request.course.id'}))) {
6544: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6545: $thisallowed.=$1;
6546: }
6547: }
6548:
6549: # Course: uri itself is a course
6550: my $courseuri=$uri;
6551: $courseuri=~s/\_(\d)/\/$1/;
6552: $courseuri=~s/^([^\/])/\/$1/;
6553:
6554: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
6555: =~/\Q$priv\E\&([^\:]*)/) {
6556: unless (($priv eq 'bro') && (!$ownaccess)) {
6557: $thisallowed.=$1;
6558: }
6559: }
6560:
6561: # URI is an uploaded document for this course, default permissions don't matter
6562: # not allowing 'edit' access (editupload) to uploaded course docs
6563: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
6564: $thisallowed='';
6565: my ($match)=&is_on_map($uri);
6566: if ($match) {
6567: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6568: =~/\Q$priv\E\&([^\:]*)/) {
6569: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6570: if (@blockers > 0) {
6571: $thisallowed = 'B';
6572: } else {
6573: $thisallowed.=$1;
6574: }
6575: }
6576: } else {
6577: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
6578: if ($refuri) {
6579: if ($refuri =~ m|^/adm/|) {
6580: $thisallowed='F';
6581: } else {
6582: $refuri=&declutter($refuri);
6583: my ($match) = &is_on_map($refuri);
6584: if ($match) {
6585: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6586: if (@blockers > 0) {
6587: $thisallowed = 'B';
6588: } else {
6589: $thisallowed='F';
6590: }
6591: }
6592: }
6593: }
6594: }
6595: }
6596:
6597: if ($priv eq 'bre'
6598: && $thisallowed ne 'F'
6599: && $thisallowed ne '2'
6600: && &is_portfolio_url($uri)) {
6601: $thisallowed = &portfolio_access($uri);
6602: }
6603:
6604: # Full access at system, domain or course-wide level? Exit.
6605: if ($thisallowed=~/F/) {
6606: return 'F';
6607: }
6608:
6609: # If this is generating or modifying users, exit with special codes
6610:
6611: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6612: if (($priv eq 'cca') || ($priv eq 'caa')) {
6613: my ($audom,$auname)=split('/',$uri);
6614: # no author name given, so this just checks on the general right to make a co-author in this domain
6615: unless ($auname) { return $thisallowed; }
6616: # an author name is given, so we are about to actually make a co-author for a certain account
6617: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6618: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6619: ($audom ne $env{'request.role.domain'}))) { return ''; }
6620: }
6621: return $thisallowed;
6622: }
6623: #
6624: # Gathered so far: system, domain and course wide privileges
6625: #
6626: # Course: See if uri or referer is an individual resource that is part of
6627: # the course
6628:
6629: if ($env{'request.course.id'}) {
6630:
6631: $courseprivid=$env{'request.course.id'};
6632: if ($env{'request.course.sec'}) {
6633: $courseprivid.='/'.$env{'request.course.sec'};
6634: }
6635: $courseprivid=~s/\_/\//;
6636: my $checkreferer=1;
6637: my ($match,$cond)=&is_on_map($uri);
6638: if ($match) {
6639: $statecond=$cond;
6640: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
6641: =~/\Q$priv\E\&([^\:]*)/) {
6642: my $value = $1;
6643: if ($priv eq 'bre') {
6644: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6645: if (@blockers > 0) {
6646: $thisallowed = 'B';
6647: } else {
6648: $thisallowed.=$value;
6649: }
6650: } else {
6651: $thisallowed.=$value;
6652: }
6653: $checkreferer=0;
6654: }
6655: }
6656:
6657: if ($checkreferer) {
6658: my $refuri=$env{'httpref.'.$orguri};
6659: unless ($refuri) {
6660: foreach my $key (keys(%env)) {
6661: if ($key=~/^httpref\..*\*/) {
6662: my $pattern=$key;
6663: $pattern=~s/^httpref\.\/res\///;
6664: $pattern=~s/\*/\[\^\/\]\+/g;
6665: $pattern=~s/\//\\\//g;
6666: if ($orguri=~/$pattern/) {
6667: $refuri=$env{$key};
6668: }
6669: }
6670: }
6671: }
6672:
6673: if ($refuri) {
6674: $refuri=&declutter($refuri);
6675: my ($match,$cond)=&is_on_map($refuri);
6676: if ($match) {
6677: my $refstatecond=$cond;
6678: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
6679: =~/\Q$priv\E\&([^\:]*)/) {
6680: my $value = $1;
6681: if ($priv eq 'bre') {
6682: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6683: if (@blockers > 0) {
6684: $thisallowed = 'B';
6685: } else {
6686: $thisallowed.=$value;
6687: }
6688: } else {
6689: $thisallowed.=$value;
6690: }
6691: $uri=$refuri;
6692: $statecond=$refstatecond;
6693: }
6694: }
6695: }
6696: }
6697: }
6698:
6699: #
6700: # Gathered now: all privileges that could apply, and condition number
6701: #
6702: #
6703: # Full or no access?
6704: #
6705:
6706: if ($thisallowed=~/F/) {
6707: return 'F';
6708: }
6709:
6710: unless ($thisallowed) {
6711: return '';
6712: }
6713:
6714: # Restrictions exist, deal with them
6715: #
6716: # C:according to course preferences
6717: # R:according to resource settings
6718: # L:unless locked
6719: # X:according to user session state
6720: #
6721:
6722: # Possibly locked functionality, check all courses
6723: # Locks might take effect only after 10 minutes cache expiration for other
6724: # courses, and 2 minutes for current course
6725:
6726: my $envkey;
6727: if ($thisallowed=~/L/) {
6728: foreach $envkey (keys(%env)) {
6729: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6730: my $courseid=$2;
6731: my $roleid=$1.'.'.$2;
6732: $courseid=~s/^\///;
6733: my $expiretime=600;
6734: if ($env{'request.role'} eq $roleid) {
6735: $expiretime=120;
6736: }
6737: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6738: my $prefix='course.'.$cdom.'_'.$cnum.'.';
6739: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
6740: &coursedescription($courseid,{'freshen_cache' => 1});
6741: }
6742: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6743: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6744: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6745: &log($env{'user.domain'},$env{'user.name'},
6746: $env{'user.home'},
6747: 'Locked by res: '.$priv.' for '.$uri.' due to '.
6748: $cdom.'/'.$cnum.'/'.$csec.' expire '.
6749: $env{$prefix.'priv.'.$priv.'.lock.expire'});
6750: return '';
6751: }
6752: }
6753: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6754: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6755: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6756: &log($env{'user.domain'},$env{'user.name'},
6757: $env{'user.home'},
6758: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
6759: $cdom.'/'.$cnum.'/'.$csec.' expire '.
6760: $env{$prefix.'priv.'.$priv.'.lock.expire'});
6761: return '';
6762: }
6763: }
6764: }
6765: }
6766: }
6767:
6768: #
6769: # Rest of the restrictions depend on selected course
6770: #
6771:
6772: unless ($env{'request.course.id'}) {
6773: if ($thisallowed eq 'A') {
6774: return 'A';
6775: } elsif ($thisallowed eq 'B') {
6776: return 'B';
6777: } else {
6778: return '1';
6779: }
6780: }
6781:
6782: #
6783: # Now user is definitely in a course
6784: #
6785:
6786:
6787: # Course preferences
6788:
6789: if ($thisallowed=~/C/) {
6790: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6791: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6792: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
6793: =~/\Q$rolecode\E/) {
6794: if (($priv ne 'pch') && ($priv ne 'plc')) {
6795: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6796: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6797: $env{'request.course.id'});
6798: }
6799: return '';
6800: }
6801:
6802: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
6803: =~/\Q$unamedom\E/) {
6804: if (($priv ne 'pch') && ($priv ne 'plc')) {
6805: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6806: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6807: $env{'request.course.id'});
6808: }
6809: return '';
6810: }
6811: }
6812:
6813: # Resource preferences
6814:
6815: if ($thisallowed=~/R/) {
6816: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6817: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
6818: if (($priv ne 'pch') && ($priv ne 'plc')) {
6819: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6820: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6821: }
6822: return '';
6823: }
6824: }
6825:
6826: # Restricted by state or randomout?
6827:
6828: if ($thisallowed=~/X/) {
6829: if ($env{'acc.randomout'}) {
6830: if (!$symb) { $symb=&symbread($uri,1); }
6831: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
6832: return '';
6833: }
6834: }
6835: if (&condval($statecond)) {
6836: return '2';
6837: } else {
6838: return '';
6839: }
6840: }
6841:
6842: if ($thisallowed eq 'A') {
6843: return 'A';
6844: } elsif ($thisallowed eq 'B') {
6845: return 'B';
6846: }
6847: return 'F';
6848: }
6849:
6850: # ------------------------------------------- Check construction space access
6851:
6852: sub constructaccess {
6853: my ($url,$setpriv)=@_;
6854:
6855: # We do not allow editing of previous versions of files
6856: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
6857:
6858: # Get username and domain from URL
6859: my ($ownername,$ownerdomain,$ownerhome);
6860:
6861: ($ownerdomain,$ownername) =
6862: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
6863:
6864: # The URL does not really point to any authorspace, forget it
6865: unless (($ownername) && ($ownerdomain)) { return ''; }
6866:
6867: # Now we need to see if the user has access to the authorspace of
6868: # $ownername at $ownerdomain
6869:
6870: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
6871: # Real author for this?
6872: $ownerhome = $env{'user.home'};
6873: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
6874: return ($ownername,$ownerdomain,$ownerhome);
6875: }
6876: } else {
6877: # Co-author for this?
6878: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
6879: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
6880: $ownerhome = &homeserver($ownername,$ownerdomain);
6881: return ($ownername,$ownerdomain,$ownerhome);
6882: }
6883: }
6884:
6885: # We don't have any access right now. If we are not possibly going to do anything about this,
6886: # we might as well leave
6887: unless ($setpriv) { return ''; }
6888:
6889: # Backdoor access?
6890: my $allowed=&allowed('eco',$ownerdomain);
6891: # Nope
6892: unless ($allowed) { return ''; }
6893: # Looks like we may have access, but could be locked by the owner of the construction space
6894: if ($allowed eq 'U') {
6895: my %blocked=&get('environment',['domcoord.author'],
6896: $ownerdomain,$ownername);
6897: # Is blocked by owner
6898: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
6899: }
6900: if (($allowed eq 'F') || ($allowed eq 'U')) {
6901: # Grant temporary access
6902: my $then=$env{'user.login.time'};
6903: my $update=$env{'user.update.time'};
6904: if (!$update) { $update = $then; }
6905: my $refresh=$env{'user.refresh.time'};
6906: if (!$refresh) { $refresh = $update; }
6907: my $now = time;
6908: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
6909: $now,'ca','constructaccess');
6910: $ownerhome = &homeserver($ownername,$ownerdomain);
6911: return($ownername,$ownerdomain,$ownerhome);
6912: }
6913: # No business here
6914: return '';
6915: }
6916:
6917: sub get_comm_blocks {
6918: my ($cdom,$cnum) = @_;
6919: if ($cdom eq '' || $cnum eq '') {
6920: return unless ($env{'request.course.id'});
6921: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6922: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6923: }
6924: my %commblocks;
6925: my $hashid=$cdom.'_'.$cnum;
6926: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
6927: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
6928: %commblocks = %{$blocksref};
6929: } else {
6930: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
6931: my $cachetime = 600;
6932: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
6933: }
6934: return %commblocks;
6935: }
6936:
6937: sub has_comm_blocking {
6938: my ($priv,$symb,$uri,$blocks) = @_;
6939: return unless ($env{'request.course.id'});
6940: return unless ($priv eq 'bre');
6941: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
6942: my %commblocks;
6943: if (ref($blocks) eq 'HASH') {
6944: %commblocks = %{$blocks};
6945: } else {
6946: %commblocks = &get_comm_blocks();
6947: }
6948: return unless (keys(%commblocks) > 0);
6949: if (!$symb) { $symb=&symbread($uri,1); }
6950: my ($map,$resid,undef)=&decode_symb($symb);
6951: my %tocheck = (
6952: maps => $map,
6953: resources => $symb,
6954: );
6955: my @blockers;
6956: my $now = time;
6957: my $navmap = Apache::lonnavmaps::navmap->new();
6958: foreach my $block (keys(%commblocks)) {
6959: if ($block =~ /^(\d+)____(\d+)$/) {
6960: my ($start,$end) = ($1,$2);
6961: if ($start <= $now && $end >= $now) {
6962: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
6963: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
6964: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
6965: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
6966: unless (grep(/^\Q$block\E$/,@blockers)) {
6967: push(@blockers,$block);
6968: }
6969: }
6970: }
6971: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
6972: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
6973: unless (grep(/^\Q$block\E$/,@blockers)) {
6974: push(@blockers,$block);
6975: }
6976: }
6977: }
6978: }
6979: }
6980: }
6981: } elsif ($block =~ /^firstaccess____(.+)$/) {
6982: my $item = $1;
6983: my @to_test;
6984: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
6985: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
6986: my $check_interval;
6987: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
6988: my @interval;
6989: my $type = 'map';
6990: if ($item eq 'course') {
6991: $type = 'course';
6992: @interval=&EXT("resource.0.interval");
6993: } else {
6994: if ($item =~ /___\d+___/) {
6995: $type = 'resource';
6996: @interval=&EXT("resource.0.interval",$item);
6997: if (ref($navmap)) {
6998: my $res = $navmap->getBySymb($item);
6999: push(@to_test,$res);
7000: }
7001: } else {
7002: my $mapsymb = &symbread($item,1);
7003: if ($mapsymb) {
7004: if (ref($navmap)) {
7005: my $mapres = $navmap->getBySymb($mapsymb);
7006: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7007: foreach my $res (@to_test) {
7008: my $symb = $res->symb();
7009: next if ($symb eq $mapsymb);
7010: if ($symb ne '') {
7011: @interval=&EXT("resource.0.interval",$symb);
7012: last;
7013: }
7014: }
7015: }
7016: }
7017: }
7018: }
7019: if ($interval[0] =~ /\d+/) {
7020: my $first_access;
7021: if ($type eq 'resource') {
7022: $first_access=&get_first_access($interval[1],$item);
7023: } elsif ($type eq 'map') {
7024: $first_access=&get_first_access($interval[1],undef,$item);
7025: } else {
7026: $first_access=&get_first_access($interval[1]);
7027: }
7028: if ($first_access) {
7029: my $timesup = $first_access+$interval[0];
7030: if ($timesup > $now) {
7031: foreach my $res (@to_test) {
7032: if ($res->is_problem()) {
7033: if ($res->completable()) {
7034: unless (grep(/^\Q$block\E$/,@blockers)) {
7035: push(@blockers,$block);
7036: }
7037: last;
7038: }
7039: }
7040: }
7041: }
7042: }
7043: }
7044: }
7045: }
7046: }
7047: }
7048: }
7049: return @blockers;
7050: }
7051:
7052: sub check_docs_block {
7053: my ($docsblock,$tocheck) =@_;
7054: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7055: return;
7056: }
7057: if (ref($docsblock->{'maps'}) eq 'HASH') {
7058: if ($tocheck->{'maps'}) {
7059: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7060: return 1;
7061: }
7062: }
7063: }
7064: if (ref($docsblock->{'resources'}) eq 'HASH') {
7065: if ($tocheck->{'resources'}) {
7066: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7067: return 1;
7068: }
7069: }
7070: }
7071: return;
7072: }
7073:
7074: #
7075: # Removes the versino from a URI and
7076: # splits it in to its filename and path to the filename.
7077: # Seems like File::Basename could have done this more clearly.
7078: # Parameters:
7079: # $uri - input URI
7080: # Returns:
7081: # Two element list consisting of
7082: # $pathname - the URI up to and excluding the trailing /
7083: # $filename - The part of the URI following the last /
7084: # NOTE:
7085: # Another realization of this is simply:
7086: # use File::Basename;
7087: # ...
7088: # $uri = shift;
7089: # $filename = basename($uri);
7090: # $path = dirname($uri);
7091: # return ($filename, $path);
7092: #
7093: # The implementation below is probably faster however.
7094: #
7095: sub split_uri_for_cond {
7096: my $uri=&deversion(&declutter(shift));
7097: my @uriparts=split(/\//,$uri);
7098: my $filename=pop(@uriparts);
7099: my $pathname=join('/',@uriparts);
7100: return ($pathname,$filename);
7101: }
7102: # --------------------------------------------------- Is a resource on the map?
7103:
7104: sub is_on_map {
7105: my ($pathname,$filename) = &split_uri_for_cond(shift);
7106: #Trying to find the conditional for the file
7107: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
7108: /\&\Q$filename\E\:([\d\|]+)\&/);
7109: if ($match) {
7110: return (1,$1);
7111: } else {
7112: return (0,0);
7113: }
7114: }
7115:
7116: # --------------------------------------------------------- Get symb from alias
7117:
7118: sub get_symb_from_alias {
7119: my $symb=shift;
7120: my ($map,$resid,$url)=&decode_symb($symb);
7121: # Already is a symb
7122: if ($url) { return $symb; }
7123: # Must be an alias
7124: my $aliassymb='';
7125: my %bighash;
7126: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7127: &GDBM_READER(),0640)) {
7128: my $rid=$bighash{'mapalias_'.$symb};
7129: if ($rid) {
7130: my ($mapid,$resid)=split(/\./,$rid);
7131: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7132: $resid,$bighash{'src_'.$rid});
7133: }
7134: untie %bighash;
7135: }
7136: return $aliassymb;
7137: }
7138:
7139: # ----------------------------------------------------------------- Define Role
7140:
7141: sub definerole {
7142: if (allowed('mcr','/')) {
7143: my ($rolename,$sysrole,$domrole,$courole)=@_;
7144: foreach my $role (split(':',$sysrole)) {
7145: my ($crole,$cqual)=split(/\&/,$role);
7146: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7147: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7148: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
7149: return "refused:s:$crole&$cqual";
7150: }
7151: }
7152: }
7153: foreach my $role (split(':',$domrole)) {
7154: my ($crole,$cqual)=split(/\&/,$role);
7155: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7156: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7157: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
7158: return "refused:d:$crole&$cqual";
7159: }
7160: }
7161: }
7162: foreach my $role (split(':',$courole)) {
7163: my ($crole,$cqual)=split(/\&/,$role);
7164: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7165: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7166: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
7167: return "refused:c:$crole&$cqual";
7168: }
7169: }
7170: }
7171: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7172: "$env{'user.domain'}:$env{'user.name'}:".
7173: "rolesdef_$rolename=".
7174: escape($sysrole.'_'.$domrole.'_'.$courole);
7175: return reply($command,$env{'user.home'});
7176: } else {
7177: return 'refused';
7178: }
7179: }
7180:
7181: # ---------------- Make a metadata query against the network of library servers
7182:
7183: sub metadata_query {
7184: my ($query,$custom,$customshow,$server_array)=@_;
7185: my %rhash;
7186: my %libserv = &all_library();
7187: my @server_list = (defined($server_array) ? @$server_array
7188: : keys(%libserv) );
7189: for my $server (@server_list) {
7190: unless ($custom or $customshow) {
7191: my $reply=&reply("querysend:".&escape($query),$server);
7192: $rhash{$server}=$reply;
7193: }
7194: else {
7195: my $reply=&reply("querysend:".&escape($query).':'.
7196: &escape($custom).':'.&escape($customshow),
7197: $server);
7198: $rhash{$server}=$reply;
7199: }
7200: }
7201: return \%rhash;
7202: }
7203:
7204: # ----------------------------------------- Send log queries and wait for reply
7205:
7206: sub log_query {
7207: my ($uname,$udom,$query,%filters)=@_;
7208: my $uhome=&homeserver($uname,$udom);
7209: if ($uhome eq 'no_host') { return 'error: no_host'; }
7210: my $uhost=&hostname($uhome);
7211: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
7212: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7213: $uhome);
7214: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
7215: return get_query_reply($queryid);
7216: }
7217:
7218: # -------------------------- Update MySQL table for portfolio file
7219:
7220: sub update_portfolio_table {
7221: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
7222: if ($group ne '') {
7223: $file_name =~s /^\Q$group\E//;
7224: }
7225: my $homeserver = &homeserver($uname,$udom);
7226: my $queryid=
7227: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7228: ':'.&escape($file_name).':'.$action,$homeserver);
7229: my $reply = &get_query_reply($queryid);
7230: return $reply;
7231: }
7232:
7233: # -------------------------- Update MySQL allusers table
7234:
7235: sub update_allusers_table {
7236: my ($uname,$udom,$names) = @_;
7237: my $homeserver = &homeserver($uname,$udom);
7238: my $queryid=
7239: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7240: 'lastname='.&escape($names->{'lastname'}).'%%'.
7241: 'firstname='.&escape($names->{'firstname'}).'%%'.
7242: 'middlename='.&escape($names->{'middlename'}).'%%'.
7243: 'generation='.&escape($names->{'generation'}).'%%'.
7244: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7245: 'id='.&escape($names->{'id'}),$homeserver);
7246: return;
7247: }
7248:
7249: # ------- Request retrieval of institutional classlists for course(s)
7250:
7251: sub fetch_enrollment_query {
7252: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
7253: my $homeserver;
7254: my $maxtries = 1;
7255: if ($context eq 'automated') {
7256: $homeserver = $perlvar{'lonHostID'};
7257: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
7258: } else {
7259: $homeserver = &homeserver($cnum,$dom);
7260: }
7261: my $host=&hostname($homeserver);
7262: my $cmd = '';
7263: foreach my $affiliate (keys(%{$affiliatesref})) {
7264: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
7265: }
7266: $cmd =~ s/%%$//;
7267: $cmd = &escape($cmd);
7268: my $query = 'fetchenrollment';
7269: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
7270: unless ($queryid=~/^\Q$host\E\_/) {
7271: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7272: return 'error: '.$queryid;
7273: }
7274: my $reply = &get_query_reply($queryid);
7275: my $tries = 1;
7276: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7277: $reply = &get_query_reply($queryid);
7278: $tries ++;
7279: }
7280: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7281: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7282: } else {
7283: my @responses = split(/:/,$reply);
7284: if ($homeserver eq $perlvar{'lonHostID'}) {
7285: foreach my $line (@responses) {
7286: my ($key,$value) = split(/=/,$line,2);
7287: $$replyref{$key} = $value;
7288: }
7289: } else {
7290: my $pathname = LONCAPA::tempdir();
7291: foreach my $line (@responses) {
7292: my ($key,$value) = split(/=/,$line);
7293: $$replyref{$key} = $value;
7294: if ($value > 0) {
7295: foreach my $item (@{$$affiliatesref{$key}}) {
7296: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
7297: my $destname = $pathname.'/'.$filename;
7298: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
7299: if ($xml_classlist =~ /^error/) {
7300: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7301: } else {
7302: if ( open(FILE,">$destname") ) {
7303: print FILE &unescape($xml_classlist);
7304: close(FILE);
7305: } else {
7306: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
7307: }
7308: }
7309: }
7310: }
7311: }
7312: }
7313: return 'ok';
7314: }
7315: return 'error';
7316: }
7317:
7318: sub get_query_reply {
7319: my $queryid=shift;
7320: my $replyfile=LONCAPA::tempdir().$queryid;
7321: my $reply='';
7322: for (1..100) {
7323: sleep 2;
7324: if (-e $replyfile.'.end') {
7325: if (open(my $fh,$replyfile)) {
7326: $reply = join('',<$fh>);
7327: close($fh);
7328: } else { return 'error: reply_file_error'; }
7329: return &unescape($reply);
7330: }
7331: }
7332: return 'timeout:'.$queryid;
7333: }
7334:
7335: sub courselog_query {
7336: #
7337: # possible filters:
7338: # url: url or symb
7339: # username
7340: # domain
7341: # action: view, submit, grade
7342: # start: timestamp
7343: # end: timestamp
7344: #
7345: my (%filters)=@_;
7346: unless ($env{'request.course.id'}) { return 'no_course'; }
7347: if ($filters{'url'}) {
7348: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7349: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7350: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7351: }
7352: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7353: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7354: return &log_query($cname,$cdom,'courselog',%filters);
7355: }
7356:
7357: sub userlog_query {
7358: #
7359: # possible filters:
7360: # action: log check role
7361: # start: timestamp
7362: # end: timestamp
7363: #
7364: my ($uname,$udom,%filters)=@_;
7365: return &log_query($uname,$udom,'userlog',%filters);
7366: }
7367:
7368: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7369:
7370: sub auto_run {
7371: my ($cnum,$cdom) = @_;
7372: my $response = 0;
7373: my $settings;
7374: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7375: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7376: $settings = $domconfig{'autoenroll'};
7377: if ($settings->{'run'} eq '1') {
7378: $response = 1;
7379: }
7380: } else {
7381: my $homeserver;
7382: if (&is_course($cdom,$cnum)) {
7383: $homeserver = &homeserver($cnum,$cdom);
7384: } else {
7385: $homeserver = &domain($cdom,'primary');
7386: }
7387: if ($homeserver ne 'no_host') {
7388: $response = &reply('autorun:'.$cdom,$homeserver);
7389: }
7390: }
7391: return $response;
7392: }
7393:
7394: sub auto_get_sections {
7395: my ($cnum,$cdom,$inst_coursecode) = @_;
7396: my $homeserver;
7397: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7398: $homeserver = &homeserver($cnum,$cdom);
7399: }
7400: if (!defined($homeserver)) {
7401: if ($cdom =~ /^$match_domain$/) {
7402: $homeserver = &domain($cdom,'primary');
7403: }
7404: }
7405: my @secs;
7406: if (defined($homeserver)) {
7407: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7408: unless ($response eq 'refused') {
7409: @secs = split(/:/,$response);
7410: }
7411: }
7412: return @secs;
7413: }
7414:
7415: sub auto_new_course {
7416: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
7417: my $homeserver = &homeserver($cnum,$cdom);
7418: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
7419: return $response;
7420: }
7421:
7422: sub auto_validate_courseID {
7423: my ($cnum,$cdom,$inst_course_id) = @_;
7424: my $homeserver = &homeserver($cnum,$cdom);
7425: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
7426: return $response;
7427: }
7428:
7429: sub auto_validate_instcode {
7430: my ($cnum,$cdom,$instcode,$owner) = @_;
7431: my ($homeserver,$response);
7432: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7433: $homeserver = &homeserver($cnum,$cdom);
7434: }
7435: if (!defined($homeserver)) {
7436: if ($cdom =~ /^$match_domain$/) {
7437: $homeserver = &domain($cdom,'primary');
7438: }
7439: }
7440: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7441: &escape($instcode).':'.&escape($owner),$homeserver));
7442: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
7443: return ($outcome,$description);
7444: }
7445:
7446: sub auto_create_password {
7447: my ($cnum,$cdom,$authparam,$udom) = @_;
7448: my ($homeserver,$response);
7449: my $create_passwd = 0;
7450: my $authchk = '';
7451: if ($udom =~ /^$match_domain$/) {
7452: $homeserver = &domain($udom,'primary');
7453: }
7454: if ($homeserver eq '') {
7455: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7456: $homeserver = &homeserver($cnum,$cdom);
7457: }
7458: }
7459: if ($homeserver eq '') {
7460: $authchk = 'nodomain';
7461: } else {
7462: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7463: if ($response eq 'refused') {
7464: $authchk = 'refused';
7465: } else {
7466: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
7467: }
7468: }
7469: return ($authparam,$create_passwd,$authchk);
7470: }
7471:
7472: sub auto_photo_permission {
7473: my ($cnum,$cdom,$students) = @_;
7474: my $homeserver = &homeserver($cnum,$cdom);
7475: my ($outcome,$perm_reqd,$conditions) =
7476: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
7477: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7478: return (undef,undef);
7479: }
7480: return ($outcome,$perm_reqd,$conditions);
7481: }
7482:
7483: sub auto_checkphotos {
7484: my ($uname,$udom,$pid) = @_;
7485: my $homeserver = &homeserver($uname,$udom);
7486: my ($result,$resulttype);
7487: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
7488: &escape($uname).':'.&escape($pid),
7489: $homeserver));
7490: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7491: return (undef,undef);
7492: }
7493: if ($outcome) {
7494: ($result,$resulttype) = split(/:/,$outcome);
7495: }
7496: return ($result,$resulttype);
7497: }
7498:
7499: sub auto_photochoice {
7500: my ($cnum,$cdom) = @_;
7501: my $homeserver = &homeserver($cnum,$cdom);
7502: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
7503: &escape($cdom),
7504: $homeserver)));
7505: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7506: return (undef,undef);
7507: }
7508: return ($update,$comment);
7509: }
7510:
7511: sub auto_photoupdate {
7512: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7513: my $homeserver = &homeserver($cnum,$dom);
7514: my $host=&hostname($homeserver);
7515: my $cmd = '';
7516: my $maxtries = 1;
7517: foreach my $affiliate (keys(%{$affiliatesref})) {
7518: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
7519: }
7520: $cmd =~ s/%%$//;
7521: $cmd = &escape($cmd);
7522: my $query = 'institutionalphotos';
7523: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7524: unless ($queryid=~/^\Q$host\E\_/) {
7525: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7526: return 'error: '.$queryid;
7527: }
7528: my $reply = &get_query_reply($queryid);
7529: my $tries = 1;
7530: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7531: $reply = &get_query_reply($queryid);
7532: $tries ++;
7533: }
7534: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7535: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7536: } else {
7537: my @responses = split(/:/,$reply);
7538: my $outcome = shift(@responses);
7539: foreach my $item (@responses) {
7540: my ($key,$value) = split(/=/,$item);
7541: $$photo{$key} = $value;
7542: }
7543: return $outcome;
7544: }
7545: return 'error';
7546: }
7547:
7548: sub auto_instcode_format {
7549: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7550: $cat_order) = @_;
7551: my $courses = '';
7552: my @homeservers;
7553: if ($caller eq 'global') {
7554: my %servers = &get_servers($codedom,'library');
7555: foreach my $tryserver (keys(%servers)) {
7556: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7557: push(@homeservers,$tryserver);
7558: }
7559: }
7560: } elsif ($caller eq 'requests') {
7561: if ($codedom =~ /^$match_domain$/) {
7562: my $chome = &domain($codedom,'primary');
7563: unless ($chome eq 'no_host') {
7564: push(@homeservers,$chome);
7565: }
7566: }
7567: } else {
7568: push(@homeservers,&homeserver($caller,$codedom));
7569: }
7570: foreach my $code (keys(%{$instcodes})) {
7571: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
7572: }
7573: chop($courses);
7574: my $ok_response = 0;
7575: my $response;
7576: while (@homeservers > 0 && $ok_response == 0) {
7577: my $server = shift(@homeservers);
7578: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7579: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7580: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
7581: split(/:/,$response);
7582: %{$codes} = (%{$codes},&str2hash($codes_str));
7583: push(@{$codetitles},&str2array($codetitles_str));
7584: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7585: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7586: $ok_response = 1;
7587: }
7588: }
7589: if ($ok_response) {
7590: return 'ok';
7591: } else {
7592: return $response;
7593: }
7594: }
7595:
7596: sub auto_instcode_defaults {
7597: my ($domain,$returnhash,$code_order) = @_;
7598: my @homeservers;
7599:
7600: my %servers = &get_servers($domain,'library');
7601: foreach my $tryserver (keys(%servers)) {
7602: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7603: push(@homeservers,$tryserver);
7604: }
7605: }
7606:
7607: my $response;
7608: foreach my $server (@homeservers) {
7609: $response=&reply('autoinstcodedefaults:'.$domain,$server);
7610: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7611:
7612: foreach my $pair (split(/\&/,$response)) {
7613: my ($name,$value)=split(/\=/,$pair);
7614: if ($name eq 'code_order') {
7615: @{$code_order} = split(/\&/,&unescape($value));
7616: } else {
7617: $returnhash->{&unescape($name)}=&unescape($value);
7618: }
7619: }
7620: return 'ok';
7621: }
7622:
7623: return $response;
7624: }
7625:
7626: sub auto_possible_instcodes {
7627: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7628: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7629: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7630: return;
7631: }
7632: my (@homeservers,$uhome);
7633: if (defined(&domain($domain,'primary'))) {
7634: $uhome=&domain($domain,'primary');
7635: push(@homeservers,&domain($domain,'primary'));
7636: } else {
7637: my %servers = &get_servers($domain,'library');
7638: foreach my $tryserver (keys(%servers)) {
7639: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7640: push(@homeservers,$tryserver);
7641: }
7642: }
7643: }
7644: my $response;
7645: foreach my $server (@homeservers) {
7646: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7647: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7648: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7649: split(':',$response);
7650: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7651: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
7652: foreach my $item (split('&',$cat_title)) {
7653: my ($name,$value)=split('=',$item);
7654: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
7655: }
7656: foreach my $item (split('&',$cat_order)) {
7657: my ($name,$value)=split('=',$item);
7658: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
7659: }
7660: return 'ok';
7661: }
7662: return $response;
7663: }
7664:
7665: sub auto_courserequest_checks {
7666: my ($dom) = @_;
7667: my ($homeserver,%validations);
7668: if ($dom =~ /^$match_domain$/) {
7669: $homeserver = &domain($dom,'primary');
7670: }
7671: unless ($homeserver eq 'no_host') {
7672: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7673: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7674: my @items = split(/&/,$response);
7675: foreach my $item (@items) {
7676: my ($key,$value) = split('=',$item);
7677: $validations{&unescape($key)} = &thaw_unescape($value);
7678: }
7679: }
7680: }
7681: return %validations;
7682: }
7683:
7684: sub auto_courserequest_validation {
7685: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
7686: my ($homeserver,$response);
7687: if ($dom =~ /^$match_domain$/) {
7688: $homeserver = &domain($dom,'primary');
7689: }
7690: unless ($homeserver eq 'no_host') {
7691:
7692: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
7693: ':'.&escape($crstype).':'.&escape($inststatuslist).
7694: ':'.&escape($instcode).':'.&escape($instseclist),
7695: $homeserver));
7696: }
7697: return $response;
7698: }
7699:
7700: sub auto_validate_class_sec {
7701: my ($cdom,$cnum,$owners,$inst_class) = @_;
7702: my $homeserver = &homeserver($cnum,$cdom);
7703: my $ownerlist;
7704: if (ref($owners) eq 'ARRAY') {
7705: $ownerlist = join(',',@{$owners});
7706: } else {
7707: $ownerlist = $owners;
7708: }
7709: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
7710: &escape($ownerlist).':'.$cdom,$homeserver);
7711: return $response;
7712: }
7713:
7714: # ------------------------------------------------------- Course Group routines
7715:
7716: sub get_coursegroups {
7717: my ($cdom,$cnum,$group,$namespace) = @_;
7718: return(&dump($namespace,$cdom,$cnum,$group));
7719: }
7720:
7721: sub modify_coursegroup {
7722: my ($cdom,$cnum,$groupsettings) = @_;
7723: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7724: }
7725:
7726: sub toggle_coursegroup_status {
7727: my ($cdom,$cnum,$group,$action) = @_;
7728: my ($from_namespace,$to_namespace);
7729: if ($action eq 'delete') {
7730: $from_namespace = 'coursegroups';
7731: $to_namespace = 'deleted_groups';
7732: } else {
7733: $from_namespace = 'deleted_groups';
7734: $to_namespace = 'coursegroups';
7735: }
7736: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
7737: if (my $tmp = &error(%curr_group)) {
7738: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7739: return ('read error',$tmp);
7740: } else {
7741: my %savedsettings = %curr_group;
7742: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
7743: my $deloutcome;
7744: if ($result eq 'ok') {
7745: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
7746: } else {
7747: return ('write error',$result);
7748: }
7749: if ($deloutcome eq 'ok') {
7750: return 'ok';
7751: } else {
7752: return ('delete error',$deloutcome);
7753: }
7754: }
7755: }
7756:
7757: sub modify_group_roles {
7758: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
7759: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7760: my $role = 'gr/'.&escape($userprivs);
7761: my ($uname,$udom) = split(/:/,$user);
7762: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
7763: if ($result eq 'ok') {
7764: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7765: }
7766: return $result;
7767: }
7768:
7769: sub modify_coursegroup_membership {
7770: my ($cdom,$cnum,$membership) = @_;
7771: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7772: return $result;
7773: }
7774:
7775: sub get_active_groups {
7776: my ($udom,$uname,$cdom,$cnum) = @_;
7777: my $now = time;
7778: my %groups = ();
7779: foreach my $key (keys(%env)) {
7780: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
7781: my ($start,$end) = split(/\./,$env{$key});
7782: if (($end!=0) && ($end<$now)) { next; }
7783: if (($start!=0) && ($start>$now)) { next; }
7784: if ($1 eq $cdom && $2 eq $cnum) {
7785: $groups{$3} = $env{$key} ;
7786: }
7787: }
7788: }
7789: return %groups;
7790: }
7791:
7792: sub get_group_membership {
7793: my ($cdom,$cnum,$group) = @_;
7794: return(&dump('groupmembership',$cdom,$cnum,$group));
7795: }
7796:
7797: sub get_users_groups {
7798: my ($udom,$uname,$courseid) = @_;
7799: my @usersgroups;
7800: my $cachetime=1800;
7801:
7802: my $hashid="$udom:$uname:$courseid";
7803: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
7804: if (defined($cached)) {
7805: @usersgroups = split(/:/,$grouplist);
7806: } else {
7807: $grouplist = '';
7808: my $courseurl = &courseid_to_courseurl($courseid);
7809: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
7810: my $access_end = $env{'course.'.$courseid.
7811: '.default_enrollment_end_date'};
7812: my $now = time;
7813: foreach my $key (keys(%roleshash)) {
7814: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
7815: my $group = $1;
7816: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
7817: my $start = $2;
7818: my $end = $1;
7819: if ($start == -1) { next; } # deleted from group
7820: if (($start!=0) && ($start>$now)) { next; }
7821: if (($end!=0) && ($end<$now)) {
7822: if ($access_end && $access_end < $now) {
7823: if ($access_end - $end < 86400) {
7824: push(@usersgroups,$group);
7825: }
7826: }
7827: next;
7828: }
7829: push(@usersgroups,$group);
7830: }
7831: }
7832: }
7833: @usersgroups = &sort_course_groups($courseid,@usersgroups);
7834: $grouplist = join(':',@usersgroups);
7835: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
7836: }
7837: return @usersgroups;
7838: }
7839:
7840: sub devalidate_getgroups_cache {
7841: my ($udom,$uname,$cdom,$cnum)=@_;
7842: my $courseid = $cdom.'_'.$cnum;
7843:
7844: my $hashid="$udom:$uname:$courseid";
7845: &devalidate_cache_new('getgroups',$hashid);
7846: }
7847:
7848: # ------------------------------------------------------------------ Plain Text
7849:
7850: sub plaintext {
7851: my ($short,$type,$cid,$forcedefault) = @_;
7852: if ($short =~ m{^cr/}) {
7853: return (split('/',$short))[-1];
7854: }
7855: if (!defined($cid)) {
7856: $cid = $env{'request.course.id'};
7857: }
7858: my %rolenames = (
7859: Course => 'std',
7860: Community => 'alt1',
7861: );
7862: if ($cid ne '') {
7863: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
7864: unless ($forcedefault) {
7865: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
7866: &Apache::lonlocal::mt_escape(\$roletext);
7867: return &Apache::lonlocal::mt($roletext);
7868: }
7869: }
7870: }
7871: if ((defined($type)) && (defined($rolenames{$type})) &&
7872: (defined($rolenames{$type})) &&
7873: (defined($prp{$short}{$rolenames{$type}}))) {
7874: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
7875: } elsif ($cid ne '') {
7876: my $crstype = $env{'course.'.$cid.'.type'};
7877: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
7878: (defined($prp{$short}{$rolenames{$crstype}}))) {
7879: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
7880: }
7881: }
7882: return &Apache::lonlocal::mt($prp{$short}{'std'});
7883: }
7884:
7885: # ----------------------------------------------------------------- Assign Role
7886:
7887: sub assignrole {
7888: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
7889: $context)=@_;
7890: my $mrole;
7891: if ($role =~ /^cr\//) {
7892: my $cwosec=$url;
7893: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
7894: unless (&allowed('ccr',$cwosec)) {
7895: my $refused = 1;
7896: if ($context eq 'requestcourses') {
7897: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7898: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
7899: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
7900: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7901: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7902: if ($crsenv{'internal.courseowner'} eq
7903: $env{'user.name'}.':'.$env{'user.domain'}) {
7904: $refused = '';
7905: }
7906: }
7907: }
7908: }
7909: }
7910: if ($refused) {
7911: &logthis('Refused custom assignrole: '.
7912: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
7913: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
7914: return 'refused';
7915: }
7916: }
7917: $mrole='cr';
7918: } elsif ($role =~ /^gr\//) {
7919: my $cwogrp=$url;
7920: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
7921: unless (&allowed('mdg',$cwogrp)) {
7922: &logthis('Refused group assignrole: '.
7923: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
7924: $env{'user.name'}.' at '.$env{'user.domain'});
7925: return 'refused';
7926: }
7927: $mrole='gr';
7928: } else {
7929: my $cwosec=$url;
7930: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
7931: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
7932: my $refused;
7933: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
7934: if (!(&allowed('c'.$role,$url))) {
7935: $refused = 1;
7936: }
7937: } else {
7938: $refused = 1;
7939: }
7940: if ($refused) {
7941: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7942: if (!$selfenroll && $context eq 'course') {
7943: my %crsenv;
7944: if ($role eq 'cc' || $role eq 'co') {
7945: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7946: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
7947: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
7948: if ($crsenv{'internal.courseowner'} eq
7949: $env{'user.name'}.':'.$env{'user.domain'}) {
7950: $refused = '';
7951: }
7952: }
7953: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
7954: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
7955: if ($crsenv{'internal.courseowner'} eq
7956: $env{'user.name'}.':'.$env{'user.domain'}) {
7957: $refused = '';
7958: }
7959: }
7960: }
7961: }
7962: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7963: $refused = '';
7964: } elsif ($context eq 'requestcourses') {
7965: my @possroles = ('st','ta','ep','in','cc','co');
7966: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
7967: my $wrongcc;
7968: if ($cnum =~ /^$match_community$/) {
7969: $wrongcc = 1 if ($role eq 'cc');
7970: } else {
7971: $wrongcc = 1 if ($role eq 'co');
7972: }
7973: unless ($wrongcc) {
7974: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7975: if ($crsenv{'internal.courseowner'} eq
7976: $env{'user.name'}.':'.$env{'user.domain'}) {
7977: $refused = '';
7978: }
7979: }
7980: }
7981: } elsif ($context eq 'requestauthor') {
7982: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7983: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
7984: if ($env{'environment.requestauthor'} eq 'automatic') {
7985: $refused = '';
7986: } else {
7987: my %domdefaults = &get_domain_defaults($udom);
7988: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
7989: my $checkbystatus;
7990: if ($env{'user.adv'}) {
7991: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
7992: if ($disposition eq 'automatic') {
7993: $refused = '';
7994: } elsif ($disposition eq '') {
7995: $checkbystatus = 1;
7996: }
7997: } else {
7998: $checkbystatus = 1;
7999: }
8000: if ($checkbystatus) {
8001: if ($env{'environment.inststatus'}) {
8002: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8003: foreach my $type (@inststatuses) {
8004: if (($type ne '') &&
8005: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8006: $refused = '';
8007: }
8008: }
8009: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8010: $refused = '';
8011: }
8012: }
8013: }
8014: }
8015: }
8016: }
8017: if ($refused) {
8018: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8019: ' '.$role.' '.$end.' '.$start.' by '.
8020: $env{'user.name'}.' at '.$env{'user.domain'});
8021: return 'refused';
8022: }
8023: }
8024: } elsif ($role eq 'au') {
8025: if ($url ne '/'.$udom.'/') {
8026: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8027: ' to assign author role for '.$uname.':'.$udom.
8028: ' in domain: '.$url.' refused (wrong domain).');
8029: return 'refused';
8030: }
8031: }
8032: $mrole=$role;
8033: }
8034: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
8035: "$udom:$uname:$url".'_'."$mrole=$role";
8036: if ($end) { $command.='_'.$end; }
8037: if ($start) {
8038: if ($end) {
8039: $command.='_'.$start;
8040: } else {
8041: $command.='_0_'.$start;
8042: }
8043: }
8044: my $origstart = $start;
8045: my $origend = $end;
8046: my $delflag;
8047: # actually delete
8048: if ($deleteflag) {
8049: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
8050: # modify command to delete the role
8051: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
8052: "$udom:$uname:$url".'_'."$mrole";
8053: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
8054: # set start and finish to negative values for userrolelog
8055: $start=-1;
8056: $end=-1;
8057: $delflag = 1;
8058: }
8059: }
8060: # send command
8061: my $answer=&reply($command,&homeserver($uname,$udom));
8062: # log new user role if status is ok
8063: if ($answer eq 'ok') {
8064: &userrolelog($role,$uname,$udom,$url,$start,$end);
8065: if (($role eq 'cc') || ($role eq 'in') ||
8066: ($role eq 'ep') || ($role eq 'ad') ||
8067: ($role eq 'ta') || ($role eq 'st') ||
8068: ($role=~/^cr/) || ($role eq 'gr') ||
8069: ($role eq 'co')) {
8070: # for course roles, perform group memberships changes triggered by role change.
8071: unless ($role =~ /^gr/) {
8072: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8073: $origstart,$selfenroll,$context);
8074: }
8075: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8076: $selfenroll,$context);
8077: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8078: ($role eq 'au') || ($role eq 'dc')) {
8079: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8080: $context);
8081: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8082: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8083: $context);
8084: }
8085: if ($role eq 'cc') {
8086: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8087: }
8088: }
8089: return $answer;
8090: }
8091:
8092: sub autoupdate_coowners {
8093: my ($url,$end,$start,$uname,$udom) = @_;
8094: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8095: if (($cdom ne '') && ($cnum ne '')) {
8096: my $now = time;
8097: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8098: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8099: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8100: my $instcode = $coursehash{'internal.coursecode'};
8101: if ($instcode ne '') {
8102: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8103: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
8104: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
8105: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8106: if ($result eq 'valid') {
8107: if ($coursehash{'internal.co-owners'}) {
8108: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8109: push(@newcoowners,$coowner);
8110: }
8111: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8112: push(@newcoowners,$uname.':'.$udom);
8113: }
8114: @newcoowners = sort(@newcoowners);
8115: } else {
8116: push(@newcoowners,$uname.':'.$udom);
8117: }
8118: } else {
8119: if ($coursehash{'internal.co-owners'}) {
8120: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8121: unless ($coowner eq $uname.':'.$udom) {
8122: push(@newcoowners,$coowner);
8123: }
8124: }
8125: unless (@newcoowners > 0) {
8126: $delcoowners = 1;
8127: $coowners = '';
8128: }
8129: }
8130: }
8131: if (@newcoowners || $delcoowners) {
8132: &store_coowners($cdom,$cnum,$coursehash{'home'},
8133: $delcoowners,@newcoowners);
8134: }
8135: }
8136: }
8137: }
8138: }
8139: }
8140: }
8141:
8142: sub store_coowners {
8143: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8144: my $cid = $cdom.'_'.$cnum;
8145: my ($coowners,$delresult,$putresult);
8146: if (@newcoowners) {
8147: $coowners = join(',',@newcoowners);
8148: my %coownershash = (
8149: 'internal.co-owners' => $coowners,
8150: );
8151: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8152: if ($putresult eq 'ok') {
8153: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8154: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8155: }
8156: }
8157: }
8158: if ($delcoowners) {
8159: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8160: if ($delresult eq 'ok') {
8161: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8162: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8163: }
8164: }
8165: }
8166: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8167: my %crsinfo =
8168: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8169: if (ref($crsinfo{$cid}) eq 'HASH') {
8170: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8171: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8172: }
8173: }
8174: }
8175:
8176: # -------------------------------------------------- Modify user authentication
8177: # Overrides without validation
8178:
8179: sub modifyuserauth {
8180: my ($udom,$uname,$umode,$upass)=@_;
8181: my $uhome=&homeserver($uname,$udom);
8182: unless (&allowed('mau',$udom)) { return 'refused'; }
8183: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
8184: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8185: ' in domain '.$env{'request.role.domain'});
8186: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8187: &escape($upass),$uhome);
8188: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
8189: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8190: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8191: &log($udom,,$uname,$uhome,
8192: 'Authentication changed by '.$env{'user.domain'}.', '.
8193: $env{'user.name'}.', '.$umode.
8194: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8195: unless ($reply eq 'ok') {
8196: &logthis('Authentication mode error: '.$reply);
8197: return 'error: '.$reply;
8198: }
8199: return 'ok';
8200: }
8201:
8202: # --------------------------------------------------------------- Modify a user
8203:
8204: sub modifyuser {
8205: my ($udom, $uname, $uid,
8206: $umode, $upass, $first,
8207: $middle, $last, $gene,
8208: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
8209: $udom= &LONCAPA::clean_domain($udom);
8210: $uname=&LONCAPA::clean_username($uname);
8211: my $showcandelete = 'none';
8212: if (ref($candelete) eq 'ARRAY') {
8213: if (@{$candelete} > 0) {
8214: $showcandelete = join(', ',@{$candelete});
8215: }
8216: }
8217: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
8218: $umode.', '.$first.', '.$middle.', '.
8219: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
8220: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8221: ' desiredhome not specified').
8222: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8223: ' in domain '.$env{'request.role.domain'});
8224: my $uhome=&homeserver($uname,$udom,'true');
8225: my $newuser;
8226: if ($uhome eq 'no_host') {
8227: $newuser = 1;
8228: }
8229: # ----------------------------------------------------------------- Create User
8230: if (($uhome eq 'no_host') &&
8231: (($umode && $upass) || ($umode eq 'localauth'))) {
8232: my $unhome='';
8233: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
8234: $unhome = $desiredhome;
8235: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8236: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
8237: } else { # load balancing routine for determining $unhome
8238: my $loadm=10000000;
8239: my %servers = &get_servers($udom,'library');
8240: foreach my $tryserver (keys(%servers)) {
8241: my $answer=reply('load',$tryserver);
8242: if (($answer=~/\d+/) && ($answer<$loadm)) {
8243: $loadm=$answer;
8244: $unhome=$tryserver;
8245: }
8246: }
8247: }
8248: if (($unhome eq '') || ($unhome eq 'no_host')) {
8249: return 'error: unable to find a home server for '.$uname.
8250: ' in domain '.$udom;
8251: }
8252: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8253: &escape($upass),$unhome);
8254: unless ($reply eq 'ok') {
8255: return 'error: '.$reply;
8256: }
8257: $uhome=&homeserver($uname,$udom,'true');
8258: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
8259: return 'error: unable verify users home machine.';
8260: }
8261: } # End of creation of new user
8262: # ---------------------------------------------------------------------- Add ID
8263: if ($uid) {
8264: $uid=~tr/A-Z/a-z/;
8265: my %uidhash=&idrget($udom,$uname);
8266: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8267: && (!$forceid)) {
8268: unless ($uid eq $uidhash{$uname}) {
8269: return 'error: user id "'.$uid.'" does not match '.
8270: 'current user id "'.$uidhash{$uname}.'".';
8271: }
8272: } else {
8273: &idput($udom,($uname => $uid));
8274: }
8275: }
8276: # -------------------------------------------------------------- Add names, etc
8277: my @tmp=&get('environment',
8278: ['firstname','middlename','lastname','generation','id',
8279: 'permanentemail','inststatus'],
8280: $udom,$uname);
8281: my (%names,%oldnames);
8282: if ($tmp[0] =~ m/^error:.*/) {
8283: %names=();
8284: } else {
8285: %names = @tmp;
8286: %oldnames = %names;
8287: }
8288: #
8289: # If name, email and/or uid are blank (e.g., because an uploaded file
8290: # of users did not contain them), do not overwrite existing values
8291: # unless field is in $candelete array ref.
8292: #
8293:
8294: my @fields = ('firstname','middlename','lastname','generation',
8295: 'permanentemail','id');
8296: my %newvalues;
8297: if (ref($candelete) eq 'ARRAY') {
8298: foreach my $field (@fields) {
8299: if (grep(/^\Q$field\E$/,@{$candelete})) {
8300: if ($field eq 'firstname') {
8301: $names{$field} = $first;
8302: } elsif ($field eq 'middlename') {
8303: $names{$field} = $middle;
8304: } elsif ($field eq 'lastname') {
8305: $names{$field} = $last;
8306: } elsif ($field eq 'generation') {
8307: $names{$field} = $gene;
8308: } elsif ($field eq 'permanentemail') {
8309: $names{$field} = $email;
8310: } elsif ($field eq 'id') {
8311: $names{$field} = $uid;
8312: }
8313: }
8314: }
8315: }
8316: if ($first) { $names{'firstname'} = $first; }
8317: if (defined($middle)) { $names{'middlename'} = $middle; }
8318: if ($last) { $names{'lastname'} = $last; }
8319: if (defined($gene)) { $names{'generation'} = $gene; }
8320: if ($email) {
8321: $email=~s/[^\w\@\.\-\,]//gs;
8322: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
8323: }
8324: if ($uid) { $names{'id'} = $uid; }
8325: if (defined($inststatus)) {
8326: $names{'inststatus'} = '';
8327: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8328: if (ref($usertypes) eq 'HASH') {
8329: my @okstatuses;
8330: foreach my $item (split(/:/,$inststatus)) {
8331: if (defined($usertypes->{$item})) {
8332: push(@okstatuses,$item);
8333: }
8334: }
8335: if (@okstatuses) {
8336: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8337: }
8338: }
8339: }
8340: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
8341: $umode.', '.$first.', '.$middle.', '.
8342: $last.', '.$gene.', '.$email.', '.$inststatus;
8343: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8344: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8345: } else {
8346: $logmsg .= ' during self creation';
8347: }
8348: my $changed;
8349: if ($newuser) {
8350: $changed = 1;
8351: } else {
8352: foreach my $field (@fields) {
8353: if ($names{$field} ne $oldnames{$field}) {
8354: $changed = 1;
8355: last;
8356: }
8357: }
8358: }
8359: unless ($changed) {
8360: $logmsg = 'No changes in user information needed for: '.$logmsg;
8361: &logthis($logmsg);
8362: return 'ok';
8363: }
8364: my $reply = &put('environment', \%names, $udom,$uname);
8365: if ($reply ne 'ok') {
8366: return 'error: '.$reply;
8367: }
8368: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8369: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8370: }
8371: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8372: &devalidate_cache_new('namescache',$uname.':'.$udom);
8373: $logmsg = 'Success modifying user '.$logmsg;
8374: &logthis($logmsg);
8375: return 'ok';
8376: }
8377:
8378: # -------------------------------------------------------------- Modify student
8379:
8380: sub modifystudent {
8381: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
8382: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
8383: $selfenroll,$context,$inststatus)=@_;
8384: if (!$cid) {
8385: unless ($cid=$env{'request.course.id'}) {
8386: return 'not_in_class';
8387: }
8388: }
8389: # --------------------------------------------------------------- Make the user
8390: my $reply=&modifyuser
8391: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
8392: $desiredhome,$email,$inststatus);
8393: unless ($reply eq 'ok') { return $reply; }
8394: # This will cause &modify_student_enrollment to get the uid from the
8395: # students environment
8396: $uid = undef if (!$forceid);
8397: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
8398: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
8399: return $reply;
8400: }
8401:
8402: sub modify_student_enrollment {
8403: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
8404: my ($cdom,$cnum,$chome);
8405: if (!$cid) {
8406: unless ($cid=$env{'request.course.id'}) {
8407: return 'not_in_class';
8408: }
8409: $cdom=$env{'course.'.$cid.'.domain'};
8410: $cnum=$env{'course.'.$cid.'.num'};
8411: } else {
8412: ($cdom,$cnum)=split(/_/,$cid);
8413: }
8414: $chome=$env{'course.'.$cid.'.home'};
8415: if (!$chome) {
8416: $chome=&homeserver($cnum,$cdom);
8417: }
8418: if (!$chome) { return 'unknown_course'; }
8419: # Make sure the user exists
8420: my $uhome=&homeserver($uname,$udom);
8421: if (($uhome eq '') || ($uhome eq 'no_host')) {
8422: return 'error: no such user';
8423: }
8424: # Get student data if we were not given enough information
8425: if (!defined($first) || $first eq '' ||
8426: !defined($last) || $last eq '' ||
8427: !defined($uid) || $uid eq '' ||
8428: !defined($middle) || $middle eq '' ||
8429: !defined($gene) || $gene eq '') {
8430: # They did not supply us with enough data to enroll the student, so
8431: # we need to pick up more information.
8432: my %tmp = &get('environment',
8433: ['firstname','middlename','lastname', 'generation','id']
8434: ,$udom,$uname);
8435:
8436: #foreach my $key (keys(%tmp)) {
8437: # &logthis("key $key = ".$tmp{$key});
8438: #}
8439: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8440: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8441: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
8442: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
8443: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8444: }
8445: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
8446: my $user = "$uname:$udom";
8447: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
8448: my $reply=cput('classlist',
8449: {$user =>
8450: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
8451: $cdom,$cnum);
8452: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8453: &devalidate_getsection_cache($udom,$uname,$cid);
8454: } else {
8455: return 'error: '.$reply;
8456: }
8457: # Add student role to user
8458: my $uurl='/'.$cid;
8459: $uurl=~s/\_/\//g;
8460: if ($usec) {
8461: $uurl.='/'.$usec;
8462: }
8463: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8464: $selfenroll,$context);
8465: if ($result ne 'ok') {
8466: if ($old_entry{$user} ne '') {
8467: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8468: } else {
8469: $reply = &del('classlist',[$user],$cdom,$cnum);
8470: }
8471: }
8472: return $result;
8473: }
8474:
8475: sub format_name {
8476: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8477: my $name;
8478: if ($first ne 'lastname') {
8479: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8480: } else {
8481: if ($lastname=~/\S/) {
8482: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8483: $name=~s/\s+,/,/;
8484: } else {
8485: $name.= $firstname.' '.$middlename.' '.$generation;
8486: }
8487: }
8488: $name=~s/^\s+//;
8489: $name=~s/\s+$//;
8490: $name=~s/\s+/ /g;
8491: return $name;
8492: }
8493:
8494: # ------------------------------------------------- Write to course preferences
8495:
8496: sub writecoursepref {
8497: my ($courseid,%prefs)=@_;
8498: $courseid=~s/^\///;
8499: $courseid=~s/\_/\//g;
8500: my ($cdomain,$cnum)=split(/\//,$courseid);
8501: my $chome=homeserver($cnum,$cdomain);
8502: if (($chome eq '') || ($chome eq 'no_host')) {
8503: return 'error: no such course';
8504: }
8505: my $cstring='';
8506: foreach my $pref (keys(%prefs)) {
8507: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
8508: }
8509: $cstring=~s/\&$//;
8510: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8511: }
8512:
8513: # ---------------------------------------------------------- Make/modify course
8514:
8515: sub createcourse {
8516: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
8517: $course_owner,$crstype,$cnum,$context,$category)=@_;
8518: $url=&declutter($url);
8519: my $cid='';
8520: if ($context eq 'requestcourses') {
8521: my $can_create = 0;
8522: my ($ownername,$ownerdom) = split(':',$course_owner);
8523: if ($udom eq $ownerdom) {
8524: if (&usertools_access($ownername,$ownerdom,$category,undef,
8525: $context)) {
8526: $can_create = 1;
8527: }
8528: } else {
8529: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8530: $category);
8531: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8532: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8533: if (@curr > 0) {
8534: my @options = qw(approval validate autolimit);
8535: my $optregex = join('|',@options);
8536: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8537: $can_create = 1;
8538: }
8539: }
8540: }
8541: }
8542: if ($can_create) {
8543: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8544: unless (&allowed('ccc',$udom)) {
8545: return 'refused';
8546: }
8547: }
8548: } else {
8549: return 'refused';
8550: }
8551: } elsif (!&allowed('ccc',$udom)) {
8552: return 'refused';
8553: }
8554: # --------------------------------------------------------------- Get Unique ID
8555: my $uname;
8556: if ($cnum =~ /^$match_courseid$/) {
8557: my $chome=&homeserver($cnum,$udom,'true');
8558: if (($chome eq '') || ($chome eq 'no_host')) {
8559: $uname = $cnum;
8560: } else {
8561: $uname = &generate_coursenum($udom,$crstype);
8562: }
8563: } else {
8564: $uname = &generate_coursenum($udom,$crstype);
8565: }
8566: return $uname if ($uname =~ /^error/);
8567: # -------------------------------------------------- Check supplied server name
8568: if (!defined($course_server)) {
8569: if (defined(&domain($udom,'primary'))) {
8570: $course_server = &domain($udom,'primary');
8571: } else {
8572: $course_server = $env{'user.home'};
8573: }
8574: }
8575: my %host_servers =
8576: &Apache::lonnet::get_servers($udom,'library');
8577: unless ($host_servers{$course_server}) {
8578: return 'error: invalid home server for course: '.$course_server;
8579: }
8580: # ------------------------------------------------------------- Make the course
8581: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
8582: $course_server);
8583: unless ($reply eq 'ok') { return 'error: '.$reply; }
8584: my $uhome=&homeserver($uname,$udom,'true');
8585: if (($uhome eq '') || ($uhome eq 'no_host')) {
8586: return 'error: no such course';
8587: }
8588: # ----------------------------------------------------------------- Course made
8589: # log existence
8590: my $now = time;
8591: my $newcourse = {
8592: $udom.'_'.$uname => {
8593: description => $description,
8594: inst_code => $inst_code,
8595: owner => $course_owner,
8596: type => $crstype,
8597: creator => $env{'user.name'}.':'.
8598: $env{'user.domain'},
8599: created => $now,
8600: context => $context,
8601: },
8602: };
8603: &courseidput($udom,$newcourse,$uhome,'notime');
8604: # set toplevel url
8605: my $topurl=$url;
8606: unless ($nonstandard) {
8607: # ------------------------------------------ For standard courses, make top url
8608: my $mapurl=&clutter($url);
8609: if ($mapurl eq '/res/') { $mapurl=''; }
8610: $env{'form.initmap'}=(<<ENDINITMAP);
8611: <map>
8612: <resource id="1" type="start"></resource>
8613: <resource id="2" src="$mapurl"></resource>
8614: <resource id="3" type="finish"></resource>
8615: <link index="1" from="1" to="2"></link>
8616: <link index="2" from="2" to="3"></link>
8617: </map>
8618: ENDINITMAP
8619: $topurl=&declutter(
8620: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
8621: );
8622: }
8623: # ----------------------------------------------------------- Write preferences
8624: &writecoursepref($udom.'_'.$uname,
8625: ('description' => $description,
8626: 'url' => $topurl,
8627: 'internal.creator' => $env{'user.name'}.':'.
8628: $env{'user.domain'},
8629: 'internal.created' => $now,
8630: 'internal.creationcontext' => $context)
8631: );
8632: return '/'.$udom.'/'.$uname;
8633: }
8634:
8635: # ------------------------------------------------------------------- Create ID
8636: sub generate_coursenum {
8637: my ($udom,$crstype) = @_;
8638: my $domdesc = &domain($udom);
8639: return 'error: invalid domain' if ($domdesc eq '');
8640: my $first;
8641: if ($crstype eq 'Community') {
8642: $first = '0';
8643: } else {
8644: $first = int(1+rand(9));
8645: }
8646: my $uname=$first.
8647: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8648: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8649: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8650: # ----------------------------------------------- Make sure that does not exist
8651: my $uhome=&homeserver($uname,$udom,'true');
8652: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8653: if ($crstype eq 'Community') {
8654: $first = '0';
8655: } else {
8656: $first = int(1+rand(9));
8657: }
8658: $uname=$first.
8659: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8660: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8661: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8662: $uhome=&homeserver($uname,$udom,'true');
8663: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8664: return 'error: unable to generate unique course-ID';
8665: }
8666: }
8667: return $uname;
8668: }
8669:
8670: sub is_course {
8671: my ($cdom, $cnum) = scalar(@_) == 1 ?
8672: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8673:
8674: return unless $cdom and $cnum;
8675:
8676: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8677: '.');
8678:
8679: return unless exists($courses{$cdom.'_'.$cnum});
8680: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
8681: }
8682:
8683: sub store_userdata {
8684: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
8685: my $result;
8686: if ($datakey ne '') {
8687: if (ref($storehash) eq 'HASH') {
8688: if ($udom eq '' || $uname eq '') {
8689: $udom = $env{'user.domain'};
8690: $uname = $env{'user.name'};
8691: }
8692: my $uhome=&homeserver($uname,$udom);
8693: if (($uhome eq '') || ($uhome eq 'no_host')) {
8694: $result = 'error: no_host';
8695: } else {
8696: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8697: $storehash->{'host'} = $perlvar{'lonHostID'};
8698:
8699: my $namevalue='';
8700: foreach my $key (keys(%{$storehash})) {
8701: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8702: }
8703: $namevalue=~s/\&$//;
8704: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8705: $namevalue,$uhome);
8706: }
8707: } else {
8708: $result = 'error: data to store was not a hash reference';
8709: }
8710: } else {
8711: $result= 'error: invalid requestkey';
8712: }
8713: return $result;
8714: }
8715:
8716: # ---------------------------------------------------------- Assign Custom Role
8717:
8718: sub assigncustomrole {
8719: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
8720: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
8721: $end,$start,$deleteflag,$selfenroll,$context);
8722: }
8723:
8724: # ----------------------------------------------------------------- Revoke Role
8725:
8726: sub revokerole {
8727: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
8728: my $now=time;
8729: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
8730: }
8731:
8732: # ---------------------------------------------------------- Revoke Custom Role
8733:
8734: sub revokecustomrole {
8735: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
8736: my $now=time;
8737: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
8738: $deleteflag,$selfenroll,$context);
8739: }
8740:
8741: # ------------------------------------------------------------ Disk usage
8742: sub diskusage {
8743: my ($udom,$uname,$directorypath,$getpropath)=@_;
8744: $directorypath =~ s/\/$//;
8745: my $listing=&reply('du2:'.&escape($directorypath).':'
8746: .&escape($getpropath).':'.&escape($uname).':'
8747: .&escape($udom),homeserver($uname,$udom));
8748: if ($listing eq 'unknown_cmd') {
8749: if ($getpropath) {
8750: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8751: }
8752: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8753: }
8754: return $listing;
8755: }
8756:
8757: sub is_locked {
8758: my ($file_name, $domain, $user, $which) = @_;
8759: my @check;
8760: my $is_locked;
8761: push (@check,$file_name);
8762: my %locked = &get('file_permissions',\@check,
8763: $env{'user.domain'},$env{'user.name'});
8764: my ($tmp)=keys(%locked);
8765: if ($tmp=~/^error:/) { undef(%locked); }
8766:
8767: if (ref($locked{$file_name}) eq 'ARRAY') {
8768: $is_locked = 'false';
8769: foreach my $entry (@{$locked{$file_name}}) {
8770: if (ref($entry) eq 'ARRAY') {
8771: $is_locked = 'true';
8772: if (ref($which) eq 'ARRAY') {
8773: push(@{$which},$entry);
8774: } else {
8775: last;
8776: }
8777: }
8778: }
8779: } else {
8780: $is_locked = 'false';
8781: }
8782: return $is_locked;
8783: }
8784:
8785: sub declutter_portfile {
8786: my ($file) = @_;
8787: $file =~ s{^(/portfolio/|portfolio/)}{/};
8788: return $file;
8789: }
8790:
8791: # ------------------------------------------------------------- Mark as Read Only
8792:
8793: sub mark_as_readonly {
8794: my ($domain,$user,$files,$what) = @_;
8795: my %current_permissions = &dump('file_permissions',$domain,$user);
8796: my ($tmp)=keys(%current_permissions);
8797: if ($tmp=~/^error:/) { undef(%current_permissions); }
8798: foreach my $file (@{$files}) {
8799: $file = &declutter_portfile($file);
8800: push(@{$current_permissions{$file}},$what);
8801: }
8802: &put('file_permissions',\%current_permissions,$domain,$user);
8803: return;
8804: }
8805:
8806: # ------------------------------------------------------------Save Selected Files
8807:
8808: sub save_selected_files {
8809: my ($user, $path, @files) = @_;
8810: my $filename = $user."savedfiles";
8811: my @other_files = &files_not_in_path($user, $path);
8812: open (OUT, '>'.$tmpdir.$filename);
8813: foreach my $file (@files) {
8814: print (OUT $env{'form.currentpath'}.$file."\n");
8815: }
8816: foreach my $file (@other_files) {
8817: print (OUT $file."\n");
8818: }
8819: close (OUT);
8820: return 'ok';
8821: }
8822:
8823: sub clear_selected_files {
8824: my ($user) = @_;
8825: my $filename = $user."savedfiles";
8826: open (OUT, '>'.LONCAPA::tempdir().$filename);
8827: print (OUT undef);
8828: close (OUT);
8829: return ("ok");
8830: }
8831:
8832: sub files_in_path {
8833: my ($user, $path) = @_;
8834: my $filename = $user."savedfiles";
8835: my %return_files;
8836: open (IN, '<'.LONCAPA::tempdir().$filename);
8837: while (my $line_in = <IN>) {
8838: chomp ($line_in);
8839: my @paths_and_file = split (m!/!, $line_in);
8840: my $file_part = pop (@paths_and_file);
8841: my $path_part = join ('/', @paths_and_file);
8842: $path_part.='/';
8843: my $path_and_file = $path_part.$file_part;
8844: if ($path_part eq $path) {
8845: $return_files{$file_part}= 'selected';
8846: }
8847: }
8848: close (IN);
8849: return (\%return_files);
8850: }
8851:
8852: # called in portfolio select mode, to show files selected NOT in current directory
8853: sub files_not_in_path {
8854: my ($user, $path) = @_;
8855: my $filename = $user."savedfiles";
8856: my @return_files;
8857: my $path_part;
8858: open(IN, '<'.LONCAPA::.$filename);
8859: while (my $line = <IN>) {
8860: #ok, I know it's clunky, but I want it to work
8861: my @paths_and_file = split(m|/|, $line);
8862: my $file_part = pop(@paths_and_file);
8863: chomp($file_part);
8864: my $path_part = join('/', @paths_and_file);
8865: $path_part .= '/';
8866: my $path_and_file = $path_part.$file_part;
8867: if ($path_part ne $path) {
8868: push(@return_files, ($path_and_file));
8869: }
8870: }
8871: close(OUT);
8872: return (@return_files);
8873: }
8874:
8875: #----------------------------------------------Get portfolio file permissions
8876:
8877: sub get_portfile_permissions {
8878: my ($domain,$user) = @_;
8879: my %current_permissions = &dump('file_permissions',$domain,$user);
8880: my ($tmp)=keys(%current_permissions);
8881: if ($tmp=~/^error:/) { undef(%current_permissions); }
8882: return \%current_permissions;
8883: }
8884:
8885: #---------------------------------------------Get portfolio file access controls
8886:
8887: sub get_access_controls {
8888: my ($current_permissions,$group,$file) = @_;
8889: my %access;
8890: my $real_file = $file;
8891: $file =~ s/\.meta$//;
8892: if (defined($file)) {
8893: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
8894: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
8895: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
8896: }
8897: }
8898: } else {
8899: foreach my $key (keys(%{$current_permissions})) {
8900: if ($key =~ /\0accesscontrol$/) {
8901: if (defined($group)) {
8902: if ($key !~ m-^\Q$group\E/-) {
8903: next;
8904: }
8905: }
8906: my ($fullpath) = split(/\0/,$key);
8907: if (ref($$current_permissions{$key}) eq 'HASH') {
8908: foreach my $control (keys(%{$$current_permissions{$key}})) {
8909: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
8910: }
8911: }
8912: }
8913: }
8914: }
8915: return %access;
8916: }
8917:
8918: sub modify_access_controls {
8919: my ($file_name,$changes,$domain,$user)=@_;
8920: my ($outcome,$deloutcome);
8921: my %store_permissions;
8922: my %new_values;
8923: my %new_control;
8924: my %translation;
8925: my @deletions = ();
8926: my $now = time;
8927: if (exists($$changes{'activate'})) {
8928: if (ref($$changes{'activate'}) eq 'HASH') {
8929: my @newitems = sort(keys(%{$$changes{'activate'}}));
8930: my $numnew = scalar(@newitems);
8931: for (my $i=0; $i<$numnew; $i++) {
8932: my $newkey = $newitems[$i];
8933: my $newid = &Apache::loncommon::get_cgi_id();
8934: if ($newkey =~ /^\d+:/) {
8935: $newkey =~ s/^(\d+)/$newid/;
8936: $translation{$1} = $newid;
8937: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
8938: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
8939: $translation{$1} = $newid;
8940: }
8941: $new_values{$file_name."\0".$newkey} =
8942: $$changes{'activate'}{$newitems[$i]};
8943: $new_control{$newkey} = $now;
8944: }
8945: }
8946: }
8947: my %todelete;
8948: my %changed_items;
8949: foreach my $action ('delete','update') {
8950: if (exists($$changes{$action})) {
8951: if (ref($$changes{$action}) eq 'HASH') {
8952: foreach my $key (keys(%{$$changes{$action}})) {
8953: my ($itemnum) = ($key =~ /^([^:]+):/);
8954: if ($action eq 'delete') {
8955: $todelete{$itemnum} = 1;
8956: } else {
8957: $changed_items{$itemnum} = $key;
8958: }
8959: }
8960: }
8961: }
8962: }
8963: # get lock on access controls for file.
8964: my $lockhash = {
8965: $file_name."\0".'locked_access_records' => $env{'user.name'}.
8966: ':'.$env{'user.domain'},
8967: };
8968: my $tries = 0;
8969: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8970:
8971: while (($gotlock ne 'ok') && $tries <3) {
8972: $tries ++;
8973: sleep 1;
8974: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8975: }
8976: if ($gotlock eq 'ok') {
8977: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
8978: my ($tmp)=keys(%curr_permissions);
8979: if ($tmp=~/^error:/) { undef(%curr_permissions); }
8980: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
8981: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
8982: if (ref($curr_controls) eq 'HASH') {
8983: foreach my $control_item (keys(%{$curr_controls})) {
8984: my ($itemnum) = ($control_item =~ /^([^:]+):/);
8985: if (defined($todelete{$itemnum})) {
8986: push(@deletions,$file_name."\0".$control_item);
8987: } else {
8988: if (defined($changed_items{$itemnum})) {
8989: $new_control{$changed_items{$itemnum}} = $now;
8990: push(@deletions,$file_name."\0".$control_item);
8991: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
8992: } else {
8993: $new_control{$control_item} = $$curr_controls{$control_item};
8994: }
8995: }
8996: }
8997: }
8998: }
8999: my ($group);
9000: if (&is_course($domain,$user)) {
9001: ($group,my $file) = split(/\//,$file_name,2);
9002: }
9003: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9004: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9005: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9006: # remove lock
9007: my @del_lock = ($file_name."\0".'locked_access_records');
9008: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
9009: my $sqlresult =
9010: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
9011: $group);
9012: } else {
9013: $outcome = "error: could not obtain lockfile\n";
9014: }
9015: return ($outcome,$deloutcome,\%new_values,\%translation);
9016: }
9017:
9018: sub make_public_indefinitely {
9019: my ($requrl) = @_;
9020: my $now = time;
9021: my $action = 'activate';
9022: my $aclnum = 0;
9023: if (&is_portfolio_url($requrl)) {
9024: my (undef,$udom,$unum,$file_name,$group) =
9025: &parse_portfolio_url($requrl);
9026: my $current_perms = &get_portfile_permissions($udom,$unum);
9027: my %access_controls = &get_access_controls($current_perms,
9028: $group,$file_name);
9029: foreach my $key (keys(%{$access_controls{$file_name}})) {
9030: my ($num,$scope,$end,$start) =
9031: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9032: if ($scope eq 'public') {
9033: if ($start <= $now && $end == 0) {
9034: $action = 'none';
9035: } else {
9036: $action = 'update';
9037: $aclnum = $num;
9038: }
9039: last;
9040: }
9041: }
9042: if ($action eq 'none') {
9043: return 'ok';
9044: } else {
9045: my %changes;
9046: my $newend = 0;
9047: my $newstart = $now;
9048: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9049: $changes{$action}{$newkey} = {
9050: type => 'public',
9051: time => {
9052: start => $newstart,
9053: end => $newend,
9054: },
9055: };
9056: my ($outcome,$deloutcome,$new_values,$translation) =
9057: &modify_access_controls($file_name,\%changes,$udom,$unum);
9058: return $outcome;
9059: }
9060: } else {
9061: return 'invalid';
9062: }
9063: }
9064:
9065: #------------------------------------------------------Get Marked as Read Only
9066:
9067: sub get_marked_as_readonly {
9068: my ($domain,$user,$what,$group) = @_;
9069: my $current_permissions = &get_portfile_permissions($domain,$user);
9070: my @readonly_files;
9071: my $cmp1=$what;
9072: if (ref($what)) { $cmp1=join('',@{$what}) };
9073: while (my ($file_name,$value) = each(%{$current_permissions})) {
9074: if (defined($group)) {
9075: if ($file_name !~ m-^\Q$group\E/-) {
9076: next;
9077: }
9078: }
9079: if (ref($value) eq "ARRAY"){
9080: foreach my $stored_what (@{$value}) {
9081: my $cmp2=$stored_what;
9082: if (ref($stored_what) eq 'ARRAY') {
9083: $cmp2=join('',@{$stored_what});
9084: }
9085: if ($cmp1 eq $cmp2) {
9086: push(@readonly_files, $file_name);
9087: last;
9088: } elsif (!defined($what)) {
9089: push(@readonly_files, $file_name);
9090: last;
9091: }
9092: }
9093: }
9094: }
9095: return @readonly_files;
9096: }
9097: #-----------------------------------------------------------Get Marked as Read Only Hash
9098:
9099: sub get_marked_as_readonly_hash {
9100: my ($current_permissions,$group,$what) = @_;
9101: my %readonly_files;
9102: while (my ($file_name,$value) = each(%{$current_permissions})) {
9103: if (defined($group)) {
9104: if ($file_name !~ m-^\Q$group\E/-) {
9105: next;
9106: }
9107: }
9108: if (ref($value) eq "ARRAY"){
9109: foreach my $stored_what (@{$value}) {
9110: if (ref($stored_what) eq 'ARRAY') {
9111: foreach my $lock_descriptor(@{$stored_what}) {
9112: if ($lock_descriptor eq 'graded') {
9113: $readonly_files{$file_name} = 'graded';
9114: } elsif ($lock_descriptor eq 'handback') {
9115: $readonly_files{$file_name} = 'handback';
9116: } else {
9117: if (!exists($readonly_files{$file_name})) {
9118: $readonly_files{$file_name} = 'locked';
9119: }
9120: }
9121: }
9122: }
9123: }
9124: }
9125: }
9126: return %readonly_files;
9127: }
9128: # ------------------------------------------------------------ Unmark as Read Only
9129:
9130: sub unmark_as_readonly {
9131: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9132: # for portfolio submissions, $what contains [$symb,$crsid]
9133: my ($domain,$user,$what,$file_name,$group) = @_;
9134: $file_name = &declutter_portfile($file_name);
9135: my $symb_crs = $what;
9136: if (ref($what)) { $symb_crs=join('',@$what); }
9137: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
9138: my ($tmp)=keys(%current_permissions);
9139: if ($tmp=~/^error:/) { undef(%current_permissions); }
9140: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
9141: foreach my $file (@readonly_files) {
9142: my $clean_file = &declutter_portfile($file);
9143: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
9144: my $current_locks = $current_permissions{$file};
9145: my @new_locks;
9146: my @del_keys;
9147: if (ref($current_locks) eq "ARRAY"){
9148: foreach my $locker (@{$current_locks}) {
9149: my $compare=$locker;
9150: if (ref($locker) eq 'ARRAY') {
9151: $compare=join('',@{$locker});
9152: if ($compare ne $symb_crs) {
9153: push(@new_locks, $locker);
9154: }
9155: }
9156: }
9157: if (scalar(@new_locks) > 0) {
9158: $current_permissions{$file} = \@new_locks;
9159: } else {
9160: push(@del_keys, $file);
9161: &del('file_permissions',\@del_keys, $domain, $user);
9162: delete($current_permissions{$file});
9163: }
9164: }
9165: }
9166: &put('file_permissions',\%current_permissions,$domain,$user);
9167: return;
9168: }
9169:
9170: # ------------------------------------------------------------ Directory lister
9171:
9172: sub dirlist {
9173: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
9174: $uri=~s/^\///;
9175: $uri=~s/\/$//;
9176: my ($udom, $uname);
9177: if ($getuserdir) {
9178: $udom = $userdomain;
9179: $uname = $username;
9180: } else {
9181: (undef,$udom,$uname)=split(/\//,$uri);
9182: if(defined($userdomain)) {
9183: $udom = $userdomain;
9184: }
9185: if(defined($username)) {
9186: $uname = $username;
9187: }
9188: }
9189: my ($dirRoot,$listing,@listing_results);
9190:
9191: $dirRoot = $perlvar{'lonDocRoot'};
9192: if (defined($getpropath)) {
9193: $dirRoot = &propath($udom,$uname);
9194: $dirRoot =~ s/\/$//;
9195: } elsif (defined($getuserdir)) {
9196: my $subdir=$uname.'__';
9197: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9198: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9199: ."/$udom/$subdir/$uname";
9200: } elsif (defined($alternateRoot)) {
9201: $dirRoot = $alternateRoot;
9202: }
9203:
9204: if($udom) {
9205: if($uname) {
9206: my $uhome = &homeserver($uname,$udom);
9207: if ($uhome eq 'no_host') {
9208: return ([],'no_host');
9209: }
9210: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
9211: .$getuserdir.':'.&escape($dirRoot)
9212: .':'.&escape($uname).':'.&escape($udom),$uhome);
9213: if ($listing eq 'unknown_cmd') {
9214: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
9215: } else {
9216: @listing_results = map { &unescape($_); } split(/:/,$listing);
9217: }
9218: if ($listing eq 'unknown_cmd') {
9219: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
9220: @listing_results = split(/:/,$listing);
9221: } else {
9222: @listing_results = map { &unescape($_); } split(/:/,$listing);
9223: }
9224: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9225: ($listing eq 'rejected') || ($listing eq 'refused') ||
9226: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9227: return ([],$listing);
9228: } else {
9229: return (\@listing_results);
9230: }
9231: } elsif(!$alternateRoot) {
9232: my (%allusers,%listerror);
9233: my %servers = &get_servers($udom,'library');
9234: foreach my $tryserver (keys(%servers)) {
9235: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9236: &escape($udom),$tryserver);
9237: if ($listing eq 'unknown_cmd') {
9238: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9239: $udom, $tryserver);
9240: } else {
9241: @listing_results = map { &unescape($_); } split(/:/,$listing);
9242: }
9243: if ($listing eq 'unknown_cmd') {
9244: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9245: $udom, $tryserver);
9246: @listing_results = split(/:/,$listing);
9247: } else {
9248: @listing_results =
9249: map { &unescape($_); } split(/:/,$listing);
9250: }
9251: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9252: ($listing eq 'rejected') || ($listing eq 'refused') ||
9253: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9254: $listerror{$tryserver} = $listing;
9255: } else {
9256: foreach my $line (@listing_results) {
9257: my ($entry) = split(/&/,$line,2);
9258: $allusers{$entry} = 1;
9259: }
9260: }
9261: }
9262: my @alluserslist=();
9263: foreach my $user (sort(keys(%allusers))) {
9264: push(@alluserslist,$user.'&user');
9265: }
9266: return (\@alluserslist);
9267: } else {
9268: return ([],'missing username');
9269: }
9270: } elsif(!defined($getpropath)) {
9271: my $path = $perlvar{'lonDocRoot'}.'/res/';
9272: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9273: return (\@all_domains);
9274: } else {
9275: return ([],'missing domain');
9276: }
9277: }
9278:
9279: # --------------------------------------------- GetFileTimestamp
9280: # This function utilizes dirlist and returns the date stamp for
9281: # when it was last modified. It will also return an error of -1
9282: # if an error occurs
9283:
9284: sub GetFileTimestamp {
9285: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
9286: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9287: $studentName = &LONCAPA::clean_username($studentName);
9288: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9289: undef,$getuserdir);
9290: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9291: return -1;
9292: }
9293: if (ref($fileref) eq 'ARRAY') {
9294: my @stats = split('&',$fileref->[0]);
9295: # @stats contains first the filename, then the stat output
9296: return $stats[10]; # so this is 10 instead of 9.
9297: } else {
9298: return -1;
9299: }
9300: }
9301:
9302: sub stat_file {
9303: my ($uri) = @_;
9304: $uri = &clutter_with_no_wrapper($uri);
9305:
9306: my ($udom,$uname,$file);
9307: if ($uri =~ m-^/(uploaded|editupload)/-) {
9308: ($udom,$uname,$file) =
9309: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
9310: $file = 'userfiles/'.$file;
9311: }
9312: if ($uri =~ m-^/res/-) {
9313: ($udom,$uname) =
9314: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
9315: $file = $uri;
9316: }
9317:
9318: if (!$udom || !$uname || !$file) {
9319: # unable to handle the uri
9320: return ();
9321: }
9322: my $getpropath;
9323: if ($file =~ /^userfiles\//) {
9324: $getpropath = 1;
9325: }
9326: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9327: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9328: return ();
9329: } else {
9330: if (ref($listref) eq 'ARRAY') {
9331: my @stats = split('&',$listref->[0]);
9332: shift(@stats); #filename is first
9333: return @stats;
9334: }
9335: }
9336: return ();
9337: }
9338:
9339: # -------------------------------------------------------- Value of a Condition
9340:
9341: # gets the value of a specific preevaluated condition
9342: # stored in the string $env{user.state.<cid>}
9343: # or looks up a condition reference in the bighash and if if hasn't
9344: # already been evaluated recurses into docondval to get the value of
9345: # the condition, then memoizing it to
9346: # $env{user.state.<cid>.<condition>}
9347: sub directcondval {
9348: my $number=shift;
9349: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
9350: &Apache::lonuserstate::evalstate();
9351: }
9352: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9353: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9354: } elsif ($number =~ /^_/) {
9355: my $sub_condition;
9356: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9357: &GDBM_READER(),0640)) {
9358: $sub_condition=$bighash{'conditions'.$number};
9359: untie(%bighash);
9360: }
9361: my $value = &docondval($sub_condition);
9362: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
9363: return $value;
9364: }
9365: if ($env{'user.state.'.$env{'request.course.id'}}) {
9366: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
9367: } else {
9368: return 2;
9369: }
9370: }
9371:
9372: # get the collection of conditions for this resource
9373: sub condval {
9374: my $condidx=shift;
9375: my $allpathcond='';
9376: foreach my $cond (split(/\|/,$condidx)) {
9377: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9378: $allpathcond.=
9379: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9380: }
9381: }
9382: $allpathcond=~s/\|$//;
9383: return &docondval($allpathcond);
9384: }
9385:
9386: #evaluates an expression of conditions
9387: sub docondval {
9388: my ($allpathcond) = @_;
9389: my $result=0;
9390: if ($env{'request.course.id'}
9391: && defined($allpathcond)) {
9392: my $operand='|';
9393: my @stack;
9394: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9395: if ($chunk eq '(') {
9396: push @stack,($operand,$result);
9397: } elsif ($chunk eq ')') {
9398: my $before=pop @stack;
9399: if (pop @stack eq '&') {
9400: $result=$result>$before?$before:$result;
9401: } else {
9402: $result=$result>$before?$result:$before;
9403: }
9404: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9405: $operand=$chunk;
9406: } else {
9407: my $new=directcondval($chunk);
9408: if ($operand eq '&') {
9409: $result=$result>$new?$new:$result;
9410: } else {
9411: $result=$result>$new?$result:$new;
9412: }
9413: }
9414: }
9415: }
9416: return $result;
9417: }
9418:
9419: # ---------------------------------------------------- Devalidate courseresdata
9420:
9421: sub devalidatecourseresdata {
9422: my ($coursenum,$coursedomain)=@_;
9423: my $hashid=$coursenum.':'.$coursedomain;
9424: &devalidate_cache_new('courseres',$hashid);
9425: }
9426:
9427:
9428: # --------------------------------------------------- Course Resourcedata Query
9429: #
9430: # Parameters:
9431: # $coursenum - Number of the course.
9432: # $coursedomain - Domain at which the course was created.
9433: # Returns:
9434: # A hash of the course parameters along (I think) with timestamps
9435: # and version info.
9436:
9437: sub get_courseresdata {
9438: my ($coursenum,$coursedomain)=@_;
9439: my $coursehom=&homeserver($coursenum,$coursedomain);
9440: my $hashid=$coursenum.':'.$coursedomain;
9441: my ($result,$cached)=&is_cached_new('courseres',$hashid);
9442: my %dumpreply;
9443: unless (defined($cached)) {
9444: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
9445: $result=\%dumpreply;
9446: my ($tmp) = keys(%dumpreply);
9447: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9448: &do_cache_new('courseres',$hashid,$result,600);
9449: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9450: return $tmp;
9451: } elsif ($tmp =~ /^(error)/) {
9452: $result=undef;
9453: &do_cache_new('courseres',$hashid,$result,600);
9454: }
9455: }
9456: return $result;
9457: }
9458:
9459: sub devalidateuserresdata {
9460: my ($uname,$udom)=@_;
9461: my $hashid="$udom:$uname";
9462: &devalidate_cache_new('userres',$hashid);
9463: }
9464:
9465: sub get_userresdata {
9466: my ($uname,$udom)=@_;
9467: #most student don\'t have any data set, check if there is some data
9468: if (&EXT_cache_status($udom,$uname)) { return undef; }
9469:
9470: my $hashid="$udom:$uname";
9471: my ($result,$cached)=&is_cached_new('userres',$hashid);
9472: if (!defined($cached)) {
9473: my %resourcedata=&dump('resourcedata',$udom,$uname);
9474: $result=\%resourcedata;
9475: &do_cache_new('userres',$hashid,$result,600);
9476: }
9477: my ($tmp)=keys(%$result);
9478: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9479: return $result;
9480: }
9481: #error 2 occurs when the .db doesn't exist
9482: if ($tmp!~/error: 2 /) {
9483: &logthis("<font color=\"blue\">WARNING:".
9484: " Trying to get resource data for ".
9485: $uname." at ".$udom.": ".
9486: $tmp."</font>");
9487: } elsif ($tmp=~/error: 2 /) {
9488: #&EXT_cache_set($udom,$uname);
9489: &do_cache_new('userres',$hashid,undef,600);
9490: undef($tmp); # not really an error so don't send it back
9491: }
9492: return $tmp;
9493: }
9494: #----------------------------------------------- resdata - return resource data
9495: # Purpose:
9496: # Return resource data for either users or for a course.
9497: # Parameters:
9498: # $name - Course/user name.
9499: # $domain - Name of the domain the user/course is registered on.
9500: # $type - Type of thing $name is (must be 'course' or 'user'
9501: # @which - Array of names of resources desired.
9502: # Returns:
9503: # The value of the first reasource in @which that is found in the
9504: # resource hash.
9505: # Exceptional Conditions:
9506: # If the $type passed in is not valid (not the string 'course' or
9507: # 'user', an undefined reference is returned.
9508: # If none of the resources are found, an undef is returned
9509: sub resdata {
9510: my ($name,$domain,$type,@which)=@_;
9511: my $result;
9512: if ($type eq 'course') {
9513: $result=&get_courseresdata($name,$domain);
9514: } elsif ($type eq 'user') {
9515: $result=&get_userresdata($name,$domain);
9516: }
9517: if (!ref($result)) { return $result; }
9518: foreach my $item (@which) {
9519: if (defined($result->{$item->[0]})) {
9520: return [$result->{$item->[0]},$item->[1]];
9521: }
9522: }
9523: return undef;
9524: }
9525:
9526: #
9527: # EXT resource caching routines
9528: #
9529:
9530: sub clear_EXT_cache_status {
9531: &delenv('cache.EXT.');
9532: }
9533:
9534: sub EXT_cache_status {
9535: my ($target_domain,$target_user) = @_;
9536: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
9537: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
9538: # We know already the user has no data
9539: return 1;
9540: } else {
9541: return 0;
9542: }
9543: }
9544:
9545: sub EXT_cache_set {
9546: my ($target_domain,$target_user) = @_;
9547: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
9548: #&appenv({$cachename => time});
9549: }
9550:
9551: # --------------------------------------------------------- Value of a Variable
9552: sub EXT {
9553:
9554: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
9555: unless ($varname) { return ''; }
9556: #get real user name/domain, courseid and symb
9557: my $courseid;
9558: my $publicuser;
9559: if ($symbparm) {
9560: $symbparm=&get_symb_from_alias($symbparm);
9561: }
9562: if (!($uname && $udom)) {
9563: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
9564: if (!$symbparm) { $symbparm=$cursymb; }
9565: } else {
9566: $courseid=$env{'request.course.id'};
9567: }
9568: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9569: my $rest;
9570: if (defined($therest[0])) {
9571: $rest=join('.',@therest);
9572: } else {
9573: $rest='';
9574: }
9575:
9576: my $qualifierrest=$qualifier;
9577: if ($rest) { $qualifierrest.='.'.$rest; }
9578: my $spacequalifierrest=$space;
9579: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
9580: if ($realm eq 'user') {
9581: # --------------------------------------------------------------- user.resource
9582: if ($space eq 'resource') {
9583: if ( (defined($Apache::lonhomework::parsing_a_problem)
9584: || defined($Apache::lonhomework::parsing_a_task))
9585: &&
9586: ($symbparm eq &symbread()) ) {
9587: # if we are in the middle of processing the resource the
9588: # get the value we are planning on committing
9589: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9590: return $Apache::lonhomework::results{$qualifierrest};
9591: } else {
9592: return $Apache::lonhomework::history{$qualifierrest};
9593: }
9594: } else {
9595: my %restored;
9596: if ($publicuser || $env{'request.state'} eq 'construct') {
9597: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9598: } else {
9599: %restored=&restore($symbparm,$courseid,$udom,$uname);
9600: }
9601: return $restored{$qualifierrest};
9602: }
9603: # ----------------------------------------------------------------- user.access
9604: } elsif ($space eq 'access') {
9605: # FIXME - not supporting calls for a specific user
9606: return &allowed($qualifier,$rest);
9607: # ------------------------------------------ user.preferences, user.environment
9608: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
9609: if (($uname eq $env{'user.name'}) &&
9610: ($udom eq $env{'user.domain'})) {
9611: return $env{join('.',('environment',$qualifierrest))};
9612: } else {
9613: my %returnhash;
9614: if (!$publicuser) {
9615: %returnhash=&userenvironment($udom,$uname,
9616: $qualifierrest);
9617: }
9618: return $returnhash{$qualifierrest};
9619: }
9620: # ----------------------------------------------------------------- user.course
9621: } elsif ($space eq 'course') {
9622: # FIXME - not supporting calls for a specific user
9623: return $env{join('.',('request.course',$qualifier))};
9624: # ------------------------------------------------------------------- user.role
9625: } elsif ($space eq 'role') {
9626: # FIXME - not supporting calls for a specific user
9627: my ($role,$where)=split(/\./,$env{'request.role'});
9628: if ($qualifier eq 'value') {
9629: return $role;
9630: } elsif ($qualifier eq 'extent') {
9631: return $where;
9632: }
9633: # ----------------------------------------------------------------- user.domain
9634: } elsif ($space eq 'domain') {
9635: return $udom;
9636: # ------------------------------------------------------------------- user.name
9637: } elsif ($space eq 'name') {
9638: return $uname;
9639: # ---------------------------------------------------- Any other user namespace
9640: } else {
9641: my %reply;
9642: if (!$publicuser) {
9643: %reply=&get($space,[$qualifierrest],$udom,$uname);
9644: }
9645: return $reply{$qualifierrest};
9646: }
9647: } elsif ($realm eq 'query') {
9648: # ---------------------------------------------- pull stuff out of query string
9649: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9650: [$spacequalifierrest]);
9651: return $env{'form.'.$spacequalifierrest};
9652: } elsif ($realm eq 'request') {
9653: # ------------------------------------------------------------- request.browser
9654: if ($space eq 'browser') {
9655: return $env{'browser.'.$qualifier};
9656: # ------------------------------------------------------------ request.filename
9657: } else {
9658: return $env{'request.'.$spacequalifierrest};
9659: }
9660: } elsif ($realm eq 'course') {
9661: # ---------------------------------------------------------- course.description
9662: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
9663: } elsif ($realm eq 'resource') {
9664:
9665: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
9666: if (!$symbparm) { $symbparm=&symbread(); }
9667: }
9668:
9669: if ($space eq 'title') {
9670: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9671: return &gettitle($symbparm);
9672: }
9673:
9674: if ($space eq 'map') {
9675: my ($map) = &decode_symb($symbparm);
9676: return &symbread($map);
9677: }
9678: if ($space eq 'filename') {
9679: if ($symbparm) {
9680: return &clutter((&decode_symb($symbparm))[2]);
9681: }
9682: return &hreflocation('',$env{'request.filename'});
9683: }
9684:
9685: my ($section, $group, @groups);
9686: my ($courselevelm,$courselevel);
9687: if ($symbparm && defined($courseid) &&
9688: $courseid eq $env{'request.course.id'}) {
9689:
9690: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
9691:
9692: # ----------------------------------------------------- Cascading lookup scheme
9693: my $symbp=$symbparm;
9694: my $mapp=&deversion((&decode_symb($symbp))[0]);
9695:
9696: my $symbparm=$symbp.'.'.$spacequalifierrest;
9697: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9698:
9699: if (($env{'user.name'} eq $uname) &&
9700: ($env{'user.domain'} eq $udom)) {
9701: $section=$env{'request.course.sec'};
9702: @groups = split(/:/,$env{'request.course.groups'});
9703: @groups=&sort_course_groups($courseid,@groups);
9704: } else {
9705: if (! defined($usection)) {
9706: $section=&getsection($udom,$uname,$courseid);
9707: } else {
9708: $section = $usection;
9709: }
9710: @groups = &get_users_groups($udom,$uname,$courseid);
9711: }
9712:
9713: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9714: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9715: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9716:
9717: $courselevel=$courseid.'.'.$spacequalifierrest;
9718: my $courselevelr=$courseid.'.'.$symbparm;
9719: $courselevelm=$courseid.'.'.$mapparm;
9720:
9721: # ----------------------------------------------------------- first, check user
9722:
9723: my $userreply=&resdata($uname,$udom,'user',
9724: ([$courselevelr,'resource'],
9725: [$courselevelm,'map' ],
9726: [$courselevel, 'course' ]));
9727: if (defined($userreply)) { return &get_reply($userreply); }
9728:
9729: # ------------------------------------------------ second, check some of course
9730: my $coursereply;
9731: if (@groups > 0) {
9732: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9733: $mapparm,$spacequalifierrest);
9734: if (defined($coursereply)) { return &get_reply($coursereply); }
9735: }
9736:
9737: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9738: $env{'course.'.$courseid.'.domain'},
9739: 'course',
9740: ([$seclevelr, 'resource'],
9741: [$seclevelm, 'map' ],
9742: [$seclevel, 'course' ],
9743: [$courselevelr,'resource']));
9744: if (defined($coursereply)) { return &get_reply($coursereply); }
9745:
9746: # ------------------------------------------------------ third, check map parms
9747: my %parmhash=();
9748: my $thisparm='';
9749: if (tie(%parmhash,'GDBM_File',
9750: $env{'request.course.fn'}.'_parms.db',
9751: &GDBM_READER(),0640)) {
9752: $thisparm=$parmhash{$symbparm};
9753: untie(%parmhash);
9754: }
9755: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
9756: }
9757: # ------------------------------------------ fourth, look in resource metadata
9758:
9759: $spacequalifierrest=~s/\./\_/;
9760: my $filename;
9761: if (!$symbparm) { $symbparm=&symbread(); }
9762: if ($symbparm) {
9763: $filename=(&decode_symb($symbparm))[2];
9764: } else {
9765: $filename=$env{'request.filename'};
9766: }
9767: my $metadata=&metadata($filename,$spacequalifierrest);
9768: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
9769: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
9770: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
9771:
9772: # ---------------------------------------------- fourth, look in rest of course
9773: if ($symbparm && defined($courseid) &&
9774: $courseid eq $env{'request.course.id'}) {
9775: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9776: $env{'course.'.$courseid.'.domain'},
9777: 'course',
9778: ([$courselevelm,'map' ],
9779: [$courselevel, 'course']));
9780: if (defined($coursereply)) { return &get_reply($coursereply); }
9781: }
9782: # ------------------------------------------------------------------ Cascade up
9783: unless ($space eq '0') {
9784: my @parts=split(/_/,$space);
9785: my $id=pop(@parts);
9786: my $part=join('_',@parts);
9787: if ($part eq '') { $part='0'; }
9788: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
9789: $symbparm,$udom,$uname,$section,1);
9790: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
9791: }
9792: if ($recurse) { return undef; }
9793: my $pack_def=&packages_tab_default($filename,$varname);
9794: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
9795: # ---------------------------------------------------- Any other user namespace
9796: } elsif ($realm eq 'environment') {
9797: # ----------------------------------------------------------------- environment
9798: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
9799: return $env{'environment.'.$spacequalifierrest};
9800: } else {
9801: if ($uname eq 'anonymous' && $udom eq '') {
9802: return '';
9803: }
9804: my %returnhash=&userenvironment($udom,$uname,
9805: $spacequalifierrest);
9806: return $returnhash{$spacequalifierrest};
9807: }
9808: } elsif ($realm eq 'system') {
9809: # ----------------------------------------------------------------- system.time
9810: if ($space eq 'time') {
9811: return time;
9812: }
9813: } elsif ($realm eq 'server') {
9814: # ----------------------------------------------------------------- system.time
9815: if ($space eq 'name') {
9816: return $ENV{'SERVER_NAME'};
9817: }
9818: }
9819: return '';
9820: }
9821:
9822: sub get_reply {
9823: my ($reply_value) = @_;
9824: if (ref($reply_value) eq 'ARRAY') {
9825: if (wantarray) {
9826: return @$reply_value;
9827: }
9828: return $reply_value->[0];
9829: } else {
9830: return $reply_value;
9831: }
9832: }
9833:
9834: sub check_group_parms {
9835: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
9836: my @groupitems = ();
9837: my $resultitem;
9838: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
9839: foreach my $group (@{$groups}) {
9840: foreach my $level (@levels) {
9841: my $item = $courseid.'.['.$group.'].'.$level->[0];
9842: push(@groupitems,[$item,$level->[1]]);
9843: }
9844: }
9845: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
9846: $env{'course.'.$courseid.'.domain'},
9847: 'course',@groupitems);
9848: return $coursereply;
9849: }
9850:
9851: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
9852: my ($courseid,@groups) = @_;
9853: @groups = sort(@groups);
9854: return @groups;
9855: }
9856:
9857: sub packages_tab_default {
9858: my ($uri,$varname)=@_;
9859: my (undef,$part,$name)=split(/\./,$varname);
9860:
9861: my (@extension,@specifics,$do_default);
9862: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
9863: my ($pack_type,$pack_part)=split(/_/,$package,2);
9864: if ($pack_type eq 'default') {
9865: $do_default=1;
9866: } elsif ($pack_type eq 'extension') {
9867: push(@extension,[$package,$pack_type,$pack_part]);
9868: } elsif ($pack_part eq $part || $pack_type eq 'part') {
9869: # only look at packages defaults for packages that this id is
9870: push(@specifics,[$package,$pack_type,$pack_part]);
9871: }
9872: }
9873: # first look for a package that matches the requested part id
9874: foreach my $package (@specifics) {
9875: my (undef,$pack_type,$pack_part)=@{$package};
9876: next if ($pack_part ne $part);
9877: if (defined($packagetab{"$pack_type&$name&default"})) {
9878: return $packagetab{"$pack_type&$name&default"};
9879: }
9880: }
9881: # look for any possible matching non extension_ package
9882: foreach my $package (@specifics) {
9883: my (undef,$pack_type,$pack_part)=@{$package};
9884: if (defined($packagetab{"$pack_type&$name&default"})) {
9885: return $packagetab{"$pack_type&$name&default"};
9886: }
9887: if ($pack_type eq 'part') { $pack_part='0'; }
9888: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
9889: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
9890: }
9891: }
9892: # look for any posible extension_ match
9893: foreach my $package (@extension) {
9894: my ($package,$pack_type)=@{$package};
9895: if (defined($packagetab{"$pack_type&$name&default"})) {
9896: return $packagetab{"$pack_type&$name&default"};
9897: }
9898: if (defined($packagetab{$package."&$name&default"})) {
9899: return $packagetab{$package."&$name&default"};
9900: }
9901: }
9902: # look for a global default setting
9903: if ($do_default && defined($packagetab{"default&$name&default"})) {
9904: return $packagetab{"default&$name&default"};
9905: }
9906: return undef;
9907: }
9908:
9909: sub add_prefix_and_part {
9910: my ($prefix,$part)=@_;
9911: my $keyroot;
9912: if (defined($prefix) && $prefix !~ /^__/) {
9913: # prefix that has a part already
9914: $keyroot=$prefix;
9915: } elsif (defined($prefix)) {
9916: # prefix that is missing a part
9917: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
9918: } else {
9919: # no prefix at all
9920: if (defined($part)) { $keyroot='_'.$part; }
9921: }
9922: return $keyroot;
9923: }
9924:
9925: # ---------------------------------------------------------------- Get metadata
9926:
9927: my %metaentry;
9928: my %importedpartids;
9929: sub metadata {
9930: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
9931: $uri=&declutter($uri);
9932: # if it is a non metadata possible uri return quickly
9933: if (($uri eq '') ||
9934: (($uri =~ m|^/*adm/|) &&
9935: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
9936: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
9937: return undef;
9938: }
9939: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
9940: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
9941: return undef;
9942: }
9943: my $filename=$uri;
9944: $uri=~s/\.meta$//;
9945: #
9946: # Is the metadata already cached?
9947: # Look at timestamp of caching
9948: # Everything is cached by the main uri, libraries are never directly cached
9949: #
9950: if (!defined($liburi)) {
9951: my ($result,$cached)=&is_cached_new('meta',$uri);
9952: if (defined($cached)) { return $result->{':'.$what}; }
9953: }
9954: {
9955: # Imported parts would go here
9956: my %importedids=();
9957: my @origfileimportpartids=();
9958: my $importedparts=0;
9959: #
9960: # Is this a recursive call for a library?
9961: #
9962: # if (! exists($metacache{$uri})) {
9963: # $metacache{$uri}={};
9964: # }
9965: my $cachetime = 60*60;
9966: if ($liburi) {
9967: $liburi=&declutter($liburi);
9968: $filename=$liburi;
9969: } else {
9970: &devalidate_cache_new('meta',$uri);
9971: undef(%metaentry);
9972: }
9973: my %metathesekeys=();
9974: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
9975: my $metastring;
9976: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
9977: my $which = &hreflocation('','/'.($liburi || $uri));
9978: $metastring =
9979: &Apache::lonnet::ssi_body($which,
9980: ('grade_target' => 'meta'));
9981: $cachetime = 1; # only want this cached in the child not long term
9982: } elsif (($uri !~ m -^(editupload)/-) &&
9983: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
9984: my $file=&filelocation('',&clutter($filename));
9985: #push(@{$metaentry{$uri.'.file'}},$file);
9986: $metastring=&getfile($file);
9987: }
9988: my $parser=HTML::LCParser->new(\$metastring);
9989: my $token;
9990: undef %metathesekeys;
9991: while ($token=$parser->get_token) {
9992: if ($token->[0] eq 'S') {
9993: if (defined($token->[2]->{'package'})) {
9994: #
9995: # This is a package - get package info
9996: #
9997: my $package=$token->[2]->{'package'};
9998: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9999: if (defined($token->[2]->{'id'})) {
10000: $keyroot.='_'.$token->[2]->{'id'};
10001: }
10002: if ($metaentry{':packages'}) {
10003: $metaentry{':packages'}.=','.$package.$keyroot;
10004: } else {
10005: $metaentry{':packages'}=$package.$keyroot;
10006: }
10007: foreach my $pack_entry (keys(%packagetab)) {
10008: my $part=$keyroot;
10009: $part=~s/^\_//;
10010: if ($pack_entry=~/^\Q$package\E\&/ ||
10011: $pack_entry=~/^\Q$package\E_0\&/) {
10012: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10013: # ignore package.tab specified default values
10014: # here &package_tab_default() will fetch those
10015: if ($subp eq 'default') { next; }
10016: my $value=$packagetab{$pack_entry};
10017: my $unikey;
10018: if ($pack =~ /_0$/) {
10019: $unikey='parameter_0_'.$name;
10020: $part=0;
10021: } else {
10022: $unikey='parameter'.$keyroot.'_'.$name;
10023: }
10024: if ($subp eq 'display') {
10025: $value.=' [Part: '.$part.']';
10026: }
10027: $metaentry{':'.$unikey.'.part'}=$part;
10028: $metathesekeys{$unikey}=1;
10029: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10030: $metaentry{':'.$unikey.'.'.$subp}=$value;
10031: }
10032: if (defined($metaentry{':'.$unikey.'.default'})) {
10033: $metaentry{':'.$unikey}=
10034: $metaentry{':'.$unikey.'.default'};
10035: }
10036: }
10037: }
10038: } else {
10039: #
10040: # This is not a package - some other kind of start tag
10041: #
10042: my $entry=$token->[1];
10043: my $unikey='';
10044:
10045: if ($entry eq 'import') {
10046: #
10047: # Importing a library here
10048: #
10049: my $location=$parser->get_text('/import');
10050: my $dir=$filename;
10051: $dir=~s|[^/]*$||;
10052: $location=&filelocation($dir,$location);
10053:
10054: my $importmode=$token->[2]->{'importmode'};
10055: if ($importmode eq 'problem') {
10056: # Import as problem/response
10057: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10058: } elsif ($importmode eq 'part') {
10059: # Import as part(s)
10060: $importedparts=1;
10061: # We need to get the original file and the imported file to get the part order correct
10062: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10063: # Load and inspect original file
10064: if ($#origfileimportpartids<0) {
10065: undef(%importedpartids);
10066: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10067: my $origfile=&getfile($origfilelocation);
10068: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10069: }
10070:
10071: # Load and inspect imported file
10072: my $impfile=&getfile($location);
10073: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10074: if ($#impfilepartids>=0) {
10075: # This problem had parts
10076: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10077: } else {
10078: # Importing by turning a single problem into a problem part
10079: # It gets the import-tags ID as part-ID
10080: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10081: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10082: }
10083: } else {
10084: # Normal import
10085: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10086: if (defined($token->[2]->{'id'})) {
10087: $unikey.='_'.$token->[2]->{'id'};
10088: }
10089: }
10090:
10091: if ($depthcount<20) {
10092: my $metadata =
10093: &metadata($uri,'keys', $location,$unikey,
10094: $depthcount+1);
10095: foreach my $meta (split(',',$metadata)) {
10096: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10097: $metathesekeys{$meta}=1;
10098: }
10099:
10100: }
10101: } else {
10102: #
10103: # Not importing, some other kind of non-package, non-library start tag
10104: #
10105: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10106: if (defined($token->[2]->{'id'})) {
10107: $unikey.='_'.$token->[2]->{'id'};
10108: }
10109: if (defined($token->[2]->{'name'})) {
10110: $unikey.='_'.$token->[2]->{'name'};
10111: }
10112: $metathesekeys{$unikey}=1;
10113: foreach my $param (@{$token->[3]}) {
10114: $metaentry{':'.$unikey.'.'.$param} =
10115: $token->[2]->{$param};
10116: }
10117: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10118: my $default=$metaentry{':'.$unikey.'.default'};
10119: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10120: # only ws inside the tag, and not in default, so use default
10121: # as value
10122: $metaentry{':'.$unikey}=$default;
10123: } elsif ( $internaltext =~ /\S/ ) {
10124: # something interesting inside the tag
10125: $metaentry{':'.$unikey}=$internaltext;
10126: } else {
10127: # no interesting values, don't set a default
10128: }
10129: # end of not-a-package not-a-library import
10130: }
10131: # end of not-a-package start tag
10132: }
10133: # the next is the end of "start tag"
10134: }
10135: }
10136: my ($extension) = ($uri =~ /\.(\w+)$/);
10137: $extension = lc($extension);
10138: if ($extension eq 'htm') { $extension='html'; }
10139:
10140: foreach my $key (keys(%packagetab)) {
10141: #no specific packages #how's our extension
10142: if ($key!~/^extension_\Q$extension\E&/) { next; }
10143: &metadata_create_package_def($uri,$key,'extension_'.$extension,
10144: \%metathesekeys);
10145: }
10146:
10147: if (!exists($metaentry{':packages'})
10148: || $packagetab{"import_defaults&extension_$extension"}) {
10149: foreach my $key (keys(%packagetab)) {
10150: #no specific packages well let's get default then
10151: if ($key!~/^default&/) { next; }
10152: &metadata_create_package_def($uri,$key,'default',
10153: \%metathesekeys);
10154: }
10155: }
10156: # are there custom rights to evaluate
10157: if ($metaentry{':copyright'} eq 'custom') {
10158:
10159: #
10160: # Importing a rights file here
10161: #
10162: unless ($depthcount) {
10163: my $location=$metaentry{':customdistributionfile'};
10164: my $dir=$filename;
10165: $dir=~s|[^/]*$||;
10166: $location=&filelocation($dir,$location);
10167: my $rights_metadata =
10168: &metadata($uri,'keys',$location,'_rights',
10169: $depthcount+1);
10170: foreach my $rights (split(',',$rights_metadata)) {
10171: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10172: $metathesekeys{$rights}=1;
10173: }
10174: }
10175: }
10176: # uniqifiy package listing
10177: my %seen;
10178: my @uniq_packages =
10179: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10180: $metaentry{':packages'} = join(',',@uniq_packages);
10181:
10182: if ($importedparts) {
10183: # We had imported parts and need to rebuild partorder
10184: $metaentry{':partorder'}='';
10185: $metathesekeys{'partorder'}=1;
10186: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10187: if ($origfileimportpartids[$index] eq 'part') {
10188: # original part, part of the problem
10189: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10190: } else {
10191: # we have imported parts at this position
10192: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10193: }
10194: }
10195: $metaentry{':partorder'}=~s/^\,//;
10196: }
10197:
10198: $metaentry{':keys'} = join(',',keys(%metathesekeys));
10199: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10200: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
10201: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
10202: # this is the end of "was not already recently cached
10203: }
10204: return $metaentry{':'.$what};
10205: }
10206:
10207: sub metadata_create_package_def {
10208: my ($uri,$key,$package,$metathesekeys)=@_;
10209: my ($pack,$name,$subp)=split(/\&/,$key);
10210: if ($subp eq 'default') { next; }
10211:
10212: if (defined($metaentry{':packages'})) {
10213: $metaentry{':packages'}.=','.$package;
10214: } else {
10215: $metaentry{':packages'}=$package;
10216: }
10217: my $value=$packagetab{$key};
10218: my $unikey;
10219: $unikey='parameter_0_'.$name;
10220: $metaentry{':'.$unikey.'.part'}=0;
10221: $$metathesekeys{$unikey}=1;
10222: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10223: $metaentry{':'.$unikey.'.'.$subp}=$value;
10224: }
10225: if (defined($metaentry{':'.$unikey.'.default'})) {
10226: $metaentry{':'.$unikey}=
10227: $metaentry{':'.$unikey.'.default'};
10228: }
10229: }
10230:
10231: sub metadata_generate_part0 {
10232: my ($metadata,$metacache,$uri) = @_;
10233: my %allnames;
10234: foreach my $metakey (keys(%$metadata)) {
10235: if ($metakey=~/^parameter\_(.*)/) {
10236: my $part=$$metacache{':'.$metakey.'.part'};
10237: my $name=$$metacache{':'.$metakey.'.name'};
10238: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10239: $allnames{$name}=$part;
10240: }
10241: }
10242: }
10243: foreach my $name (keys(%allnames)) {
10244: $$metadata{"parameter_0_$name"}=1;
10245: my $key=":parameter_0_$name";
10246: $$metacache{"$key.part"}='0';
10247: $$metacache{"$key.name"}=$name;
10248: $$metacache{"$key.type"}=$$metacache{':parameter_'.
10249: $allnames{$name}.'_'.$name.
10250: '.type'};
10251: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10252: '.display'};
10253: my $expr='[Part: '.$allnames{$name}.']';
10254: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10255: $$metacache{"$key.display"}=$olddis;
10256: }
10257: }
10258:
10259: # ------------------------------------------------------ Devalidate title cache
10260:
10261: sub devalidate_title_cache {
10262: my ($url)=@_;
10263: if (!$env{'request.course.id'}) { return; }
10264: my $symb=&symbread($url);
10265: if (!$symb) { return; }
10266: my $key=$env{'request.course.id'}."\0".$symb;
10267: &devalidate_cache_new('title',$key);
10268: }
10269:
10270: # ------------------------------------------------- Get the title of a course
10271:
10272: sub current_course_title {
10273: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10274: }
10275: # ------------------------------------------------- Get the title of a resource
10276:
10277: sub gettitle {
10278: my $urlsymb=shift;
10279: my $symb=&symbread($urlsymb);
10280: if ($symb) {
10281: my $key=$env{'request.course.id'}."\0".$symb;
10282: my ($result,$cached)=&is_cached_new('title',$key);
10283: if (defined($cached)) {
10284: return $result;
10285: }
10286: my ($map,$resid,$url)=&decode_symb($symb);
10287: my $title='';
10288: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10289: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10290: } else {
10291: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10292: &GDBM_READER(),0640)) {
10293: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10294: $title=$bighash{'title_'.$mapid.'.'.$resid};
10295: untie(%bighash);
10296: }
10297: }
10298: $title=~s/\&colon\;/\:/gs;
10299: if ($title) {
10300: # Remember both $symb and $title for dynamic metadata
10301: $accesshash{$symb.'___crstitle'}=$title;
10302: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10303: # Cache this title and then return it
10304: return &do_cache_new('title',$key,$title,600);
10305: }
10306: $urlsymb=$url;
10307: }
10308: my $title=&metadata($urlsymb,'title');
10309: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10310: return $title;
10311: }
10312:
10313: sub getdocspath {
10314: my ($symb) = @_;
10315: my $path;
10316: if ($symb) {
10317: my ($mapurl,$id,$resurl) = &decode_symb($symb);
10318: if ($resurl=~/\.(sequence|page)$/) {
10319: $mapurl=$resurl;
10320: } elsif ($resurl eq 'adm/navmaps') {
10321: $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
10322: }
10323: my $mapresobj;
10324: my $navmap = Apache::lonnavmaps::navmap->new();
10325: if (ref($navmap)) {
10326: $mapresobj = $navmap->getResourceByUrl($mapurl);
10327: }
10328: $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
10329: my $type=$2;
10330: if (ref($mapresobj)) {
10331: my $pcslist = $mapresobj->map_hierarchy();
10332: if ($pcslist ne '') {
10333: foreach my $pc (split(/,/,$pcslist)) {
10334: next if ($pc <= 1);
10335: my $res = $navmap->getByMapPc($pc);
10336: if (ref($res)) {
10337: my $thisurl = $res->src();
10338: $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
10339: my $thistitle = $res->title();
10340: $path .= '&'.
10341: &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
10342: &Apache::lonhtmlcommon::entity_encode($thistitle).
10343: ':'.$res->randompick().
10344: ':'.$res->randomout().
10345: ':'.$res->encrypted().
10346: ':'.$res->randomorder().
10347: ':'.$res->is_page();
10348: }
10349: }
10350: }
10351: $path =~ s/^\&//;
10352: my $maptitle = $mapresobj->title();
10353: if ($mapurl eq 'default') {
10354: $maptitle = 'Main Course Documents';
10355: }
10356: $path .= ($path ne '')? '&' : ''.
10357: &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
10358: &Apache::lonhtmlcommon::entity_encode($maptitle).
10359: ':'.$mapresobj->randompick().
10360: ':'.$mapresobj->randomout().
10361: ':'.$mapresobj->encrypted().
10362: ':'.$mapresobj->randomorder().
10363: ':'.$mapresobj->is_page();
10364: } else {
10365: my $maptitle = &gettitle($mapurl);
10366: my $ispage;
10367: if ($mapurl =~ /\.page$/) {
10368: $ispage = 1;
10369: }
10370: if ($mapurl eq 'default') {
10371: $maptitle = 'Main Course Documents';
10372: }
10373: $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
10374: &Apache::lonhtmlcommon::entity_encode($maptitle).':::::'.$ispage;
10375: }
10376: unless ($mapurl eq 'default') {
10377: $path = 'default&'.
10378: &Apache::lonhtmlcommon::entity_encode('Main Course Documents').
10379: ':::::&'.$path;
10380: }
10381: }
10382: return $path;
10383: }
10384:
10385: sub get_slot {
10386: my ($which,$cnum,$cdom)=@_;
10387: if (!$cnum || !$cdom) {
10388: (undef,my $courseid)=&whichuser();
10389: $cdom=$env{'course.'.$courseid.'.domain'};
10390: $cnum=$env{'course.'.$courseid.'.num'};
10391: }
10392: my $key=join("\0",'slots',$cdom,$cnum,$which);
10393: my %slotinfo;
10394: if (exists($remembered{$key})) {
10395: $slotinfo{$which} = $remembered{$key};
10396: } else {
10397: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10398: &Apache::lonhomework::showhash(%slotinfo);
10399: my ($tmp)=keys(%slotinfo);
10400: if ($tmp=~/^error:/) { return (); }
10401: $remembered{$key} = $slotinfo{$which};
10402: }
10403: if (ref($slotinfo{$which}) eq 'HASH') {
10404: return %{$slotinfo{$which}};
10405: }
10406: return $slotinfo{$which};
10407: }
10408:
10409: sub get_reservable_slots {
10410: my ($cnum,$cdom,$uname,$udom) = @_;
10411: my $now = time;
10412: my $reservable_info;
10413: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10414: if (exists($remembered{$key})) {
10415: $reservable_info = $remembered{$key};
10416: } else {
10417: my %resv;
10418: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10419: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10420: $reservable_info = \%resv;
10421: $remembered{$key} = $reservable_info;
10422: }
10423: return $reservable_info;
10424: }
10425:
10426: sub get_course_slots {
10427: my ($cnum,$cdom) = @_;
10428: my $hashid=$cnum.':'.$cdom;
10429: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10430: if (defined($cached)) {
10431: if (ref($result) eq 'HASH') {
10432: return %{$result};
10433: }
10434: } else {
10435: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10436: my ($tmp) = keys(%slots);
10437: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10438: &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
10439: return %slots;
10440: }
10441: }
10442: return;
10443: }
10444:
10445: sub devalidate_slots_cache {
10446: my ($cnum,$cdom)=@_;
10447: my $hashid=$cnum.':'.$cdom;
10448: &devalidate_cache_new('allslots',$hashid);
10449: }
10450:
10451: sub get_coursechange {
10452: my ($cdom,$cnum) = @_;
10453: if ($cdom eq '' || $cnum eq '') {
10454: return unless ($env{'request.course.id'});
10455: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10456: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10457: }
10458: my $hashid=$cdom.'_'.$cnum;
10459: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10460: if ((defined($cached)) && ($change ne '')) {
10461: return $change;
10462: } else {
10463: my %crshash;
10464: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10465: if ($crshash{'internal.contentchange'} eq '') {
10466: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10467: if ($change eq '') {
10468: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10469: $change = $crshash{'internal.created'};
10470: }
10471: } else {
10472: $change = $crshash{'internal.contentchange'};
10473: }
10474: my $cachetime = 600;
10475: &do_cache_new('crschange',$hashid,$change,$cachetime);
10476: }
10477: return $change;
10478: }
10479:
10480: sub devalidate_coursechange_cache {
10481: my ($cnum,$cdom)=@_;
10482: my $hashid=$cnum.':'.$cdom;
10483: &devalidate_cache_new('crschange',$hashid);
10484: }
10485:
10486: # ------------------------------------------------- Update symbolic store links
10487:
10488: sub symblist {
10489: my ($mapname,%newhash)=@_;
10490: $mapname=&deversion(&declutter($mapname));
10491: my %hash;
10492: if (($env{'request.course.fn'}) && (%newhash)) {
10493: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10494: &GDBM_WRCREAT(),0640)) {
10495: foreach my $url (keys(%newhash)) {
10496: next if ($url eq 'last_known'
10497: && $env{'form.no_update_last_known'});
10498: $hash{declutter($url)}=&encode_symb($mapname,
10499: $newhash{$url}->[1],
10500: $newhash{$url}->[0]);
10501: }
10502: if (untie(%hash)) {
10503: return 'ok';
10504: }
10505: }
10506: }
10507: return 'error';
10508: }
10509:
10510: # --------------------------------------------------------------- Verify a symb
10511:
10512: sub symbverify {
10513: my ($symb,$thisurl,$encstate)=@_;
10514: my $thisfn=$thisurl;
10515: $thisfn=&declutter($thisfn);
10516: # direct jump to resource in page or to a sequence - will construct own symbs
10517: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10518: # check URL part
10519: my ($map,$resid,$url)=&decode_symb($symb);
10520:
10521: unless ($url eq $thisfn) { return 0; }
10522:
10523: $symb=&symbclean($symb);
10524: $thisurl=&deversion($thisurl);
10525: $thisfn=&deversion($thisfn);
10526:
10527: my %bighash;
10528: my $okay=0;
10529:
10530: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10531: &GDBM_READER(),0640)) {
10532: my $noclutter;
10533: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10534: $thisurl =~ s/\?.+$//;
10535: if ($map =~ m{^uploaded/.+\.page$}) {
10536: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10537: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10538: $noclutter = 1;
10539: }
10540: }
10541: my $ids;
10542: if ($noclutter) {
10543: $ids=$bighash{'ids_'.$thisurl};
10544: } else {
10545: $ids=$bighash{'ids_'.&clutter($thisurl)};
10546: }
10547: unless ($ids) {
10548: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
10549: $ids=$bighash{$idkey};
10550: }
10551: if ($ids) {
10552: # ------------------------------------------------------------------- Has ID(s)
10553: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10554: $symb =~ s/\?.+$//;
10555: }
10556: foreach my $id (split(/\,/,$ids)) {
10557: my ($mapid,$resid)=split(/\./,$id);
10558: if (
10559: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10560: eq $symb) {
10561: if (ref($encstate)) {
10562: $$encstate = $bighash{'encrypted_'.$id};
10563: }
10564: if (($env{'request.role.adv'}) ||
10565: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10566: ($thisurl eq '/adm/navmaps')) {
10567: $okay=1;
10568: last;
10569: }
10570: }
10571: }
10572: }
10573: untie(%bighash);
10574: }
10575: return $okay;
10576: }
10577:
10578: # --------------------------------------------------------------- Clean-up symb
10579:
10580: sub symbclean {
10581: my $symb=shift;
10582: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10583: # remove version from map
10584: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10585:
10586: # remove version from URL
10587: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10588:
10589: # remove wrapper
10590:
10591: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10592: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10593: return $symb;
10594: }
10595:
10596: # ---------------------------------------------- Split symb to find map and url
10597:
10598: sub encode_symb {
10599: my ($map,$resid,$url)=@_;
10600: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10601: }
10602:
10603: sub decode_symb {
10604: my $symb=shift;
10605: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10606: my ($map,$resid,$url)=split(/___/,$symb);
10607: return (&fixversion($map),$resid,&fixversion($url));
10608: }
10609:
10610: sub fixversion {
10611: my $fn=shift;
10612: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10613: my %bighash;
10614: my $uri=&clutter($fn);
10615: my $key=$env{'request.course.id'}.'_'.$uri;
10616: # is this cached?
10617: my ($result,$cached)=&is_cached_new('courseresversion',$key);
10618: if (defined($cached)) { return $result; }
10619: # unfortunately not cached, or expired
10620: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10621: &GDBM_READER(),0640)) {
10622: if ($bighash{'version_'.$uri}) {
10623: my $version=$bighash{'version_'.$uri};
10624: unless (($version eq 'mostrecent') ||
10625: ($version==&getversion($uri))) {
10626: $uri=~s/\.(\w+)$/\.$version\.$1/;
10627: }
10628: }
10629: untie %bighash;
10630: }
10631: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10632: }
10633:
10634: sub deversion {
10635: my $url=shift;
10636: $url=~s/\.\d+\.(\w+)$/\.$1/;
10637: return $url;
10638: }
10639:
10640: # ------------------------------------------------------ Return symb list entry
10641:
10642: sub symbread {
10643: my ($thisfn,$donotrecurse)=@_;
10644: my $cache_str;
10645: if ($thisfn ne '') {
10646: $cache_str='request.symbread.cached.'.$thisfn;
10647: if ($env{$cache_str} ne '') {
10648: return $env{$cache_str};
10649: }
10650: } else {
10651: # no filename provided? try from environment
10652: if ($env{'request.symb'}) {
10653: return $env{$cache_str}=&symbclean($env{'request.symb'});
10654: }
10655: $thisfn=$env{'request.filename'};
10656: }
10657: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10658: # is that filename actually a symb? Verify, clean, and return
10659: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10660: if (&symbverify($thisfn,$1)) {
10661: return $env{$cache_str}=&symbclean($thisfn);
10662: }
10663: }
10664: $thisfn=declutter($thisfn);
10665: my %hash;
10666: my %bighash;
10667: my $syval='';
10668: if (($env{'request.course.fn'}) && ($thisfn)) {
10669: my $targetfn = $thisfn;
10670: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10671: $targetfn = 'adm/wrapper/'.$thisfn;
10672: }
10673: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10674: $targetfn=$1;
10675: }
10676: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10677: &GDBM_READER(),0640)) {
10678: $syval=$hash{$targetfn};
10679: untie(%hash);
10680: }
10681: # ---------------------------------------------------------- There was an entry
10682: if ($syval) {
10683: #unless ($syval=~/\_\d+$/) {
10684: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10685: #&appenv({'request.ambiguous' => $thisfn});
10686: #return $env{$cache_str}='';
10687: #}
10688: #$syval.=$1;
10689: #}
10690: } else {
10691: # ------------------------------------------------------- Was not in symb table
10692: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10693: &GDBM_READER(),0640)) {
10694: # ---------------------------------------------- Get ID(s) for current resource
10695: my $ids=$bighash{'ids_'.&clutter($thisfn)};
10696: unless ($ids) {
10697: $ids=$bighash{'ids_/'.$thisfn};
10698: }
10699: unless ($ids) {
10700: # alias?
10701: $ids=$bighash{'mapalias_'.$thisfn};
10702: }
10703: if ($ids) {
10704: # ------------------------------------------------------------------- Has ID(s)
10705: my @possibilities=split(/\,/,$ids);
10706: if ($#possibilities==0) {
10707: # ----------------------------------------------- There is only one possibility
10708: my ($mapid,$resid)=split(/\./,$ids);
10709: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10710: $resid,$thisfn);
10711: } elsif (!$donotrecurse) {
10712: # ------------------------------------------ There is more than one possibility
10713: my $realpossible=0;
10714: foreach my $id (@possibilities) {
10715: my $file=$bighash{'src_'.$id};
10716: if (&allowed('bre',$file)) {
10717: my ($mapid,$resid)=split(/\./,$id);
10718: if ($bighash{'map_type_'.$mapid} ne 'page') {
10719: $realpossible++;
10720: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10721: $resid,$thisfn);
10722: }
10723: }
10724: }
10725: if ($realpossible!=1) { $syval=''; }
10726: } else {
10727: $syval='';
10728: }
10729: }
10730: untie(%bighash)
10731: }
10732: }
10733: if ($syval) {
10734: return $env{$cache_str}=$syval;
10735: }
10736: }
10737: &appenv({'request.ambiguous' => $thisfn});
10738: return $env{$cache_str}='';
10739: }
10740:
10741: # ---------------------------------------------------------- Return random seed
10742:
10743: sub numval {
10744: my $txt=shift;
10745: $txt=~tr/A-J/0-9/;
10746: $txt=~tr/a-j/0-9/;
10747: $txt=~tr/K-T/0-9/;
10748: $txt=~tr/k-t/0-9/;
10749: $txt=~tr/U-Z/0-5/;
10750: $txt=~tr/u-z/0-5/;
10751: $txt=~s/\D//g;
10752: if ($_64bit) { if ($txt > 2**32) { return -1; } }
10753: return int($txt);
10754: }
10755:
10756: sub numval2 {
10757: my $txt=shift;
10758: $txt=~tr/A-J/0-9/;
10759: $txt=~tr/a-j/0-9/;
10760: $txt=~tr/K-T/0-9/;
10761: $txt=~tr/k-t/0-9/;
10762: $txt=~tr/U-Z/0-5/;
10763: $txt=~tr/u-z/0-5/;
10764: $txt=~s/\D//g;
10765: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10766: my $total;
10767: foreach my $val (@txts) { $total+=$val; }
10768: if ($_64bit) { if ($total > 2**32) { return -1; } }
10769: return int($total);
10770: }
10771:
10772: sub numval3 {
10773: use integer;
10774: my $txt=shift;
10775: $txt=~tr/A-J/0-9/;
10776: $txt=~tr/a-j/0-9/;
10777: $txt=~tr/K-T/0-9/;
10778: $txt=~tr/k-t/0-9/;
10779: $txt=~tr/U-Z/0-5/;
10780: $txt=~tr/u-z/0-5/;
10781: $txt=~s/\D//g;
10782: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10783: my $total;
10784: foreach my $val (@txts) { $total+=$val; }
10785: if ($_64bit) { $total=(($total<<32)>>32); }
10786: return $total;
10787: }
10788:
10789: sub digest {
10790: my ($data)=@_;
10791: my $digest=&Digest::MD5::md5($data);
10792: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10793: my ($e,$f);
10794: {
10795: use integer;
10796: $e=($a+$b);
10797: $f=($c+$d);
10798: if ($_64bit) {
10799: $e=(($e<<32)>>32);
10800: $f=(($f<<32)>>32);
10801: }
10802: }
10803: if (wantarray) {
10804: return ($e,$f);
10805: } else {
10806: my $g;
10807: {
10808: use integer;
10809: $g=($e+$f);
10810: if ($_64bit) {
10811: $g=(($g<<32)>>32);
10812: }
10813: }
10814: return $g;
10815: }
10816: }
10817:
10818: sub latest_rnd_algorithm_id {
10819: return '64bit5';
10820: }
10821:
10822: sub get_rand_alg {
10823: my ($courseid)=@_;
10824: if (!$courseid) { $courseid=(&whichuser())[1]; }
10825: if ($courseid) {
10826: return $env{"course.$courseid.rndseed"};
10827: }
10828: return &latest_rnd_algorithm_id();
10829: }
10830:
10831: sub validCODE {
10832: my ($CODE)=@_;
10833: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10834: return 0;
10835: }
10836:
10837: sub getCODE {
10838: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10839: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10840: defined($Apache::lonhomework::parsing_a_task) ) &&
10841: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10842: return $Apache::lonhomework::history{'resource.CODE'};
10843: }
10844: return undef;
10845: }
10846: #
10847: # Determines the random seed for a specific context:
10848: #
10849: # parameters:
10850: # symb - in course context the symb for the seed.
10851: # course_id - The course id of the form domain_coursenum.
10852: # domain - Domain for the user.
10853: # course - Course for the user.
10854: # cenv - environment of the course.
10855: #
10856: # NOTE:
10857: # All parameters are picked out of the environment if missing
10858: # or not defined.
10859: # If a symb cannot be determined the current time is used instead.
10860: #
10861: # For a given well defined symb, courside, domain, username,
10862: # and course environment, the seed is reproducible.
10863: #
10864: sub rndseed {
10865: my ($symb,$courseid,$domain,$username, $cenv)=@_;
10866: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10867: if (!defined($symb)) {
10868: unless ($symb=$wsymb) { return time; }
10869: }
10870: if (!defined $courseid) {
10871: $courseid=$wcourseid;
10872: }
10873: if (!defined $domain) { $domain=$wdomain; }
10874: if (!defined $username) { $username=$wusername }
10875:
10876: my $which;
10877: if (defined($cenv->{'rndseed'})) {
10878: $which = $cenv->{'rndseed'};
10879: } else {
10880: $which =&get_rand_alg($courseid);
10881: }
10882: if (defined(&getCODE())) {
10883:
10884: if ($which eq '64bit5') {
10885: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10886: } elsif ($which eq '64bit4') {
10887: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10888: } else {
10889: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10890: }
10891: } elsif ($which eq '64bit5') {
10892: return &rndseed_64bit5($symb,$courseid,$domain,$username);
10893: } elsif ($which eq '64bit4') {
10894: return &rndseed_64bit4($symb,$courseid,$domain,$username);
10895: } elsif ($which eq '64bit3') {
10896: return &rndseed_64bit3($symb,$courseid,$domain,$username);
10897: } elsif ($which eq '64bit2') {
10898: return &rndseed_64bit2($symb,$courseid,$domain,$username);
10899: } elsif ($which eq '64bit') {
10900: return &rndseed_64bit($symb,$courseid,$domain,$username);
10901: }
10902: return &rndseed_32bit($symb,$courseid,$domain,$username);
10903: }
10904:
10905: sub rndseed_32bit {
10906: my ($symb,$courseid,$domain,$username)=@_;
10907: {
10908: use integer;
10909: my $symbchck=unpack("%32C*",$symb) << 27;
10910: my $symbseed=numval($symb) << 22;
10911: my $namechck=unpack("%32C*",$username) << 17;
10912: my $nameseed=numval($username) << 12;
10913: my $domainseed=unpack("%32C*",$domain) << 7;
10914: my $courseseed=unpack("%32C*",$courseid);
10915: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
10916: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10917: #&logthis("rndseed :$num:$symb");
10918: if ($_64bit) { $num=(($num<<32)>>32); }
10919: return $num;
10920: }
10921: }
10922:
10923: sub rndseed_64bit {
10924: my ($symb,$courseid,$domain,$username)=@_;
10925: {
10926: use integer;
10927: my $symbchck=unpack("%32S*",$symb) << 21;
10928: my $symbseed=numval($symb) << 10;
10929: my $namechck=unpack("%32S*",$username);
10930:
10931: my $nameseed=numval($username) << 21;
10932: my $domainseed=unpack("%32S*",$domain) << 10;
10933: my $courseseed=unpack("%32S*",$courseid);
10934:
10935: my $num1=$symbchck+$symbseed+$namechck;
10936: my $num2=$nameseed+$domainseed+$courseseed;
10937: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10938: #&logthis("rndseed :$num:$symb");
10939: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10940: return "$num1,$num2";
10941: }
10942: }
10943:
10944: sub rndseed_64bit2 {
10945: my ($symb,$courseid,$domain,$username)=@_;
10946: {
10947: use integer;
10948: # strings need to be an even # of cahracters long, it it is odd the
10949: # last characters gets thrown away
10950: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10951: my $symbseed=numval($symb) << 10;
10952: my $namechck=unpack("%32S*",$username.' ');
10953:
10954: my $nameseed=numval($username) << 21;
10955: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10956: my $courseseed=unpack("%32S*",$courseid.' ');
10957:
10958: my $num1=$symbchck+$symbseed+$namechck;
10959: my $num2=$nameseed+$domainseed+$courseseed;
10960: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10961: #&logthis("rndseed :$num:$symb");
10962: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10963: return "$num1,$num2";
10964: }
10965: }
10966:
10967: sub rndseed_64bit3 {
10968: my ($symb,$courseid,$domain,$username)=@_;
10969: {
10970: use integer;
10971: # strings need to be an even # of cahracters long, it it is odd the
10972: # last characters gets thrown away
10973: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10974: my $symbseed=numval2($symb) << 10;
10975: my $namechck=unpack("%32S*",$username.' ');
10976:
10977: my $nameseed=numval2($username) << 21;
10978: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10979: my $courseseed=unpack("%32S*",$courseid.' ');
10980:
10981: my $num1=$symbchck+$symbseed+$namechck;
10982: my $num2=$nameseed+$domainseed+$courseseed;
10983: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10984: #&logthis("rndseed :$num1:$num2:$_64bit");
10985: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10986:
10987: return "$num1:$num2";
10988: }
10989: }
10990:
10991: sub rndseed_64bit4 {
10992: my ($symb,$courseid,$domain,$username)=@_;
10993: {
10994: use integer;
10995: # strings need to be an even # of cahracters long, it it is odd the
10996: # last characters gets thrown away
10997: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10998: my $symbseed=numval3($symb) << 10;
10999: my $namechck=unpack("%32S*",$username.' ');
11000:
11001: my $nameseed=numval3($username) << 21;
11002: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11003: my $courseseed=unpack("%32S*",$courseid.' ');
11004:
11005: my $num1=$symbchck+$symbseed+$namechck;
11006: my $num2=$nameseed+$domainseed+$courseseed;
11007: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11008: #&logthis("rndseed :$num1:$num2:$_64bit");
11009: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11010:
11011: return "$num1:$num2";
11012: }
11013: }
11014:
11015: sub rndseed_64bit5 {
11016: my ($symb,$courseid,$domain,$username)=@_;
11017: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11018: return "$num1:$num2";
11019: }
11020:
11021: sub rndseed_CODE_64bit {
11022: my ($symb,$courseid,$domain,$username)=@_;
11023: {
11024: use integer;
11025: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11026: my $symbseed=numval2($symb);
11027: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11028: my $CODEseed=numval(&getCODE());
11029: my $courseseed=unpack("%32S*",$courseid.' ');
11030: my $num1=$symbseed+$CODEchck;
11031: my $num2=$CODEseed+$courseseed+$symbchck;
11032: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11033: #&logthis("rndseed :$num1:$num2:$symb");
11034: if ($_64bit) { $num1=(($num1<<32)>>32); }
11035: if ($_64bit) { $num2=(($num2<<32)>>32); }
11036: return "$num1:$num2";
11037: }
11038: }
11039:
11040: sub rndseed_CODE_64bit4 {
11041: my ($symb,$courseid,$domain,$username)=@_;
11042: {
11043: use integer;
11044: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11045: my $symbseed=numval3($symb);
11046: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11047: my $CODEseed=numval3(&getCODE());
11048: my $courseseed=unpack("%32S*",$courseid.' ');
11049: my $num1=$symbseed+$CODEchck;
11050: my $num2=$CODEseed+$courseseed+$symbchck;
11051: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11052: #&logthis("rndseed :$num1:$num2:$symb");
11053: if ($_64bit) { $num1=(($num1<<32)>>32); }
11054: if ($_64bit) { $num2=(($num2<<32)>>32); }
11055: return "$num1:$num2";
11056: }
11057: }
11058:
11059: sub rndseed_CODE_64bit5 {
11060: my ($symb,$courseid,$domain,$username)=@_;
11061: my $code = &getCODE();
11062: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11063: return "$num1:$num2";
11064: }
11065:
11066: sub setup_random_from_rndseed {
11067: my ($rndseed)=@_;
11068: if ($rndseed =~/([,:])/) {
11069: my ($num1,$num2)=split(/[,:]/,$rndseed);
11070: &Math::Random::random_set_seed(abs($num1),abs($num2));
11071: } else {
11072: &Math::Random::random_set_seed_from_phrase($rndseed);
11073: }
11074: }
11075:
11076: sub latest_receipt_algorithm_id {
11077: return 'receipt3';
11078: }
11079:
11080: sub recunique {
11081: my $fucourseid=shift;
11082: my $unique;
11083: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11084: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11085: $unique=$env{"course.$fucourseid.internal.encseed"};
11086: } else {
11087: $unique=$perlvar{'lonReceipt'};
11088: }
11089: return unpack("%32C*",$unique);
11090: }
11091:
11092: sub recprefix {
11093: my $fucourseid=shift;
11094: my $prefix;
11095: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11096: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11097: $prefix=$env{"course.$fucourseid.internal.encpref"};
11098: } else {
11099: $prefix=$perlvar{'lonHostID'};
11100: }
11101: return unpack("%32C*",$prefix);
11102: }
11103:
11104: sub ireceipt {
11105: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11106:
11107: my $return =&recprefix($fucourseid).'-';
11108:
11109: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11110: $env{'request.state'} eq 'construct') {
11111: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11112: return $return;
11113: }
11114:
11115: my $cuname=unpack("%32C*",$funame);
11116: my $cudom=unpack("%32C*",$fudom);
11117: my $cucourseid=unpack("%32C*",$fucourseid);
11118: my $cusymb=unpack("%32C*",$fusymb);
11119: my $cunique=&recunique($fucourseid);
11120: my $cpart=unpack("%32S*",$part);
11121: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11122:
11123: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
11124:
11125: $return.= ($cunique%$cuname+
11126: $cunique%$cudom+
11127: $cusymb%$cuname+
11128: $cusymb%$cudom+
11129: $cucourseid%$cuname+
11130: $cucourseid%$cudom+
11131: $cpart%$cuname+
11132: $cpart%$cudom);
11133: } else {
11134: $return.= ($cunique%$cuname+
11135: $cunique%$cudom+
11136: $cusymb%$cuname+
11137: $cusymb%$cudom+
11138: $cucourseid%$cuname+
11139: $cucourseid%$cudom);
11140: }
11141: return $return;
11142: }
11143:
11144: sub receipt {
11145: my ($part)=@_;
11146: my ($symb,$courseid,$domain,$name) = &whichuser();
11147: return &ireceipt($name,$domain,$courseid,$symb,$part);
11148: }
11149:
11150: sub whichuser {
11151: my ($passedsymb)=@_;
11152: my ($symb,$courseid,$domain,$name,$publicuser);
11153: if (defined($env{'form.grade_symb'})) {
11154: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11155: my $allowed=&allowed('vgr',$tmp_courseid);
11156: if (!$allowed &&
11157: exists($env{'request.course.sec'}) &&
11158: $env{'request.course.sec'} !~ /^\s*$/) {
11159: $allowed=&allowed('vgr',$tmp_courseid.
11160: '/'.$env{'request.course.sec'});
11161: }
11162: if ($allowed) {
11163: ($symb)=&get_env_multiple('form.grade_symb');
11164: $courseid=$tmp_courseid;
11165: ($domain)=&get_env_multiple('form.grade_domain');
11166: ($name)=&get_env_multiple('form.grade_username');
11167: return ($symb,$courseid,$domain,$name,$publicuser);
11168: }
11169: }
11170: if (!$passedsymb) {
11171: $symb=&symbread();
11172: } else {
11173: $symb=$passedsymb;
11174: }
11175: $courseid=$env{'request.course.id'};
11176: $domain=$env{'user.domain'};
11177: $name=$env{'user.name'};
11178: if ($name eq 'public' && $domain eq 'public') {
11179: if (!defined($env{'form.username'})) {
11180: $env{'form.username'}.=time.rand(10000000);
11181: }
11182: $name.=$env{'form.username'};
11183: }
11184: return ($symb,$courseid,$domain,$name,$publicuser);
11185:
11186: }
11187:
11188: # ------------------------------------------------------------ Serves up a file
11189: # returns either the contents of the file or
11190: # -1 if the file doesn't exist
11191: #
11192: # if the target is a file that was uploaded via DOCS,
11193: # a check will be made to see if a current copy exists on the local server,
11194: # if it does this will be served, otherwise a copy will be retrieved from
11195: # the home server for the course and stored in /home/httpd/html/userfiles on
11196: # the local server.
11197:
11198: sub getfile {
11199: my ($file) = @_;
11200: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11201: &repcopy($file);
11202: return &readfile($file);
11203: }
11204:
11205: sub repcopy_userfile {
11206: my ($file)=@_;
11207: my $londocroot = $perlvar{'lonDocRoot'};
11208: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11209: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11210: my ($cdom,$cnum,$filename) =
11211: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11212: my $uri="/uploaded/$cdom/$cnum/$filename";
11213: if (-e "$file") {
11214: # we already have a local copy, check it out
11215: my @fileinfo = stat($file);
11216: my $rtncode;
11217: my $info;
11218: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11219: if ($lwpresp ne 'ok') {
11220: # there is no such file anymore, even though we had a local copy
11221: if ($rtncode eq '404') {
11222: unlink($file);
11223: }
11224: return -1;
11225: }
11226: if ($info < $fileinfo[9]) {
11227: # nice, the file we have is up-to-date, just say okay
11228: return 'ok';
11229: } else {
11230: # the file is outdated, get rid of it
11231: unlink($file);
11232: }
11233: }
11234: # one way or the other, at this point, we don't have the file
11235: # construct the correct path for the file
11236: my @parts = ($cdom,$cnum);
11237: if ($filename =~ m|^(.+)/[^/]+$|) {
11238: push @parts, split(/\//,$1);
11239: }
11240: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11241: foreach my $part (@parts) {
11242: $path .= '/'.$part;
11243: if (!-e $path) {
11244: mkdir($path,0770);
11245: }
11246: }
11247: # now the path exists for sure
11248: # get a user agent
11249: my $ua=new LWP::UserAgent;
11250: my $transferfile=$file.'.in.transfer';
11251: # FIXME: this should flock
11252: if (-e $transferfile) { return 'ok'; }
11253: my $request;
11254: $uri=~s/^\///;
11255: my $homeserver = &homeserver($cnum,$cdom);
11256: my $protocol = $protocol{$homeserver};
11257: $protocol = 'http' if ($protocol ne 'https');
11258: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11259: my $response=$ua->request($request,$transferfile);
11260: # did it work?
11261: if ($response->is_error()) {
11262: unlink($transferfile);
11263: &logthis("Userfile repcopy failed for $uri");
11264: return -1;
11265: }
11266: # worked, rename the transfer file
11267: rename($transferfile,$file);
11268: return 'ok';
11269: }
11270:
11271: sub tokenwrapper {
11272: my $uri=shift;
11273: $uri=~s|^https?\://([^/]+)||;
11274: $uri=~s|^/||;
11275: $env{'user.environment'}=~/\/([^\/]+)\.id/;
11276: my $token=$1;
11277: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11278: if ($udom && $uname && $file) {
11279: $file=~s|(\?\.*)*$||;
11280: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11281: my $homeserver = &homeserver($uname,$udom);
11282: my $protocol = $protocol{$homeserver};
11283: $protocol = 'http' if ($protocol ne 'https');
11284: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11285: (($uri=~/\?/)?'&':'?').'token='.$token.
11286: '&tokenissued='.$perlvar{'lonHostID'};
11287: } else {
11288: return '/adm/notfound.html';
11289: }
11290: }
11291:
11292: # call with reqtype HEAD: get last modification time
11293: # call with reqtype GET: get the file contents
11294: # Do not call this with reqtype GET for large files! It loads everything into memory
11295: #
11296: sub getuploaded {
11297: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11298: $uri=~s/^\///;
11299: my $homeserver = &homeserver($cnum,$cdom);
11300: my $protocol = $protocol{$homeserver};
11301: $protocol = 'http' if ($protocol ne 'https');
11302: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11303: my $ua=new LWP::UserAgent;
11304: my $request=new HTTP::Request($reqtype,$uri);
11305: my $response=$ua->request($request);
11306: $$rtncode = $response->code;
11307: if (! $response->is_success()) {
11308: return 'failed';
11309: }
11310: if ($reqtype eq 'HEAD') {
11311: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11312: } elsif ($reqtype eq 'GET') {
11313: $$info = $response->content;
11314: }
11315: return 'ok';
11316: }
11317:
11318: sub readfile {
11319: my $file = shift;
11320: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11321: my $fh;
11322: open($fh,"<$file");
11323: my $a='';
11324: while (my $line = <$fh>) { $a .= $line; }
11325: return $a;
11326: }
11327:
11328: sub filelocation {
11329: my ($dir,$file) = @_;
11330: my $location;
11331: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11332:
11333: if ($file =~ m-^/adm/-) {
11334: $file=~s-^/adm/wrapper/-/-;
11335: $file=~s-^/adm/coursedocs/showdoc/-/-;
11336: }
11337:
11338: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11339: $location = $file;
11340: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11341: my ($udom,$uname,$filename)=
11342: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11343: my $home=&homeserver($uname,$udom);
11344: my $is_me=0;
11345: my @ids=¤t_machine_ids();
11346: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11347: if ($is_me) {
11348: $location=propath($udom,$uname).'/userfiles/'.$filename;
11349: } else {
11350: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11351: $udom.'/'.$uname.'/'.$filename;
11352: }
11353: } elsif ($file =~ m-^/adm/-) {
11354: $location = $perlvar{'lonDocRoot'}.'/'.$file;
11355: } else {
11356: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11357: $file=~s:^/(res|priv)/:/:;
11358: my $space=$1;
11359: if ( !( $file =~ m:^/:) ) {
11360: $location = $dir. '/'.$file;
11361: } else {
11362: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11363: }
11364: }
11365: $location=~s://+:/:g; # remove duplicate /
11366: while ($location=~m{/\.\./}) {
11367: if ($location =~ m{/[^/]+/\.\./}) {
11368: $location=~ s{/[^/]+/\.\./}{/}g;
11369: } else {
11370: $location=~ s{/\.\./}{/}g;
11371: }
11372: } #remove dir/..
11373: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11374: return $location;
11375: }
11376:
11377: sub hreflocation {
11378: my ($dir,$file)=@_;
11379: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11380: $file=filelocation($dir,$file);
11381: } elsif ($file=~m-^/adm/-) {
11382: $file=~s-^/adm/wrapper/-/-;
11383: $file=~s-^/adm/coursedocs/showdoc/-/-;
11384: }
11385: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11386: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11387: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11388: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11389: {/uploaded/$1/$2/}x;
11390: }
11391: if ($file=~ m{^/userfiles/}) {
11392: $file =~ s{^/userfiles/}{/uploaded/};
11393: }
11394: return $file;
11395: }
11396:
11397:
11398:
11399:
11400:
11401: sub current_machine_domains {
11402: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11403: }
11404:
11405: sub machine_domains {
11406: my ($hostname) = @_;
11407: my @domains;
11408: my %hostname = &all_hostnames();
11409: while( my($id, $name) = each(%hostname)) {
11410: # &logthis("-$id-$name-$hostname-");
11411: if ($hostname eq $name) {
11412: push(@domains,&host_domain($id));
11413: }
11414: }
11415: return @domains;
11416: }
11417:
11418: sub current_machine_ids {
11419: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11420: }
11421:
11422: sub machine_ids {
11423: my ($hostname) = @_;
11424: $hostname ||= &hostname($perlvar{'lonHostID'});
11425: my @ids;
11426: my %name_to_host = &all_names();
11427: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11428: return @{ $name_to_host{$hostname} };
11429: }
11430: return;
11431: }
11432:
11433: sub additional_machine_domains {
11434: my @domains;
11435: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11436: while( my $line = <$fh>) {
11437: $line =~ s/\s//g;
11438: push(@domains,$line);
11439: }
11440: return @domains;
11441: }
11442:
11443: sub default_login_domain {
11444: my $domain = $perlvar{'lonDefDomain'};
11445: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11446: foreach my $posdom (¤t_machine_domains(),
11447: &additional_machine_domains()) {
11448: if (lc($posdom) eq lc($testdomain)) {
11449: $domain=$posdom;
11450: last;
11451: }
11452: }
11453: return $domain;
11454: }
11455:
11456: # ------------------------------------------------------------- Declutters URLs
11457:
11458: sub declutter {
11459: my $thisfn=shift;
11460: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11461: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11462: $thisfn=~s/^\///;
11463: $thisfn=~s|^adm/wrapper/||;
11464: $thisfn=~s|^adm/coursedocs/showdoc/||;
11465: $thisfn=~s/^res\///;
11466: $thisfn=~s/^priv\///;
11467: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11468: $thisfn=~s/\?.+$//;
11469: }
11470: return $thisfn;
11471: }
11472:
11473: # ------------------------------------------------------------- Clutter up URLs
11474:
11475: sub clutter {
11476: my $thisfn='/'.&declutter(shift);
11477: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11478: || $thisfn =~ m{^/adm/(includes|pages)} ) {
11479: $thisfn='/res'.$thisfn;
11480: }
11481: if ($thisfn !~m|^/adm|) {
11482: if ($thisfn =~ m|^/ext/|) {
11483: $thisfn='/adm/wrapper'.$thisfn;
11484: } else {
11485: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11486: my $embstyle=&Apache::loncommon::fileembstyle($ext);
11487: if ($embstyle eq 'ssi'
11488: || ($embstyle eq 'hdn')
11489: || ($embstyle eq 'rat')
11490: || ($embstyle eq 'prv')
11491: || ($embstyle eq 'ign')) {
11492: #do nothing with these
11493: } elsif (($embstyle eq 'img')
11494: || ($embstyle eq 'emb')
11495: || ($embstyle eq 'wrp')) {
11496: $thisfn='/adm/wrapper'.$thisfn;
11497: } elsif ($embstyle eq 'unk'
11498: && $thisfn!~/\.(sequence|page)$/) {
11499: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
11500: } else {
11501: # &logthis("Got a blank emb style");
11502: }
11503: }
11504: }
11505: return $thisfn;
11506: }
11507:
11508: sub clutter_with_no_wrapper {
11509: my $uri = &clutter(shift);
11510: if ($uri =~ m-^/adm/-) {
11511: $uri =~ s-^/adm/wrapper/-/-;
11512: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11513: }
11514: return $uri;
11515: }
11516:
11517: sub freeze_escape {
11518: my ($value)=@_;
11519: if (ref($value)) {
11520: $value=&nfreeze($value);
11521: return '__FROZEN__'.&escape($value);
11522: }
11523: return &escape($value);
11524: }
11525:
11526:
11527: sub thaw_unescape {
11528: my ($value)=@_;
11529: if ($value =~ /^__FROZEN__/) {
11530: substr($value,0,10,undef);
11531: $value=&unescape($value);
11532: return &thaw($value);
11533: }
11534: return &unescape($value);
11535: }
11536:
11537: sub correct_line_ends {
11538: my ($result)=@_;
11539: $$result =~s/\r\n/\n/mg;
11540: $$result =~s/\r/\n/mg;
11541: }
11542: # ================================================================ Main Program
11543:
11544: sub goodbye {
11545: &logthis("Starting Shut down");
11546: #not converted to using infrastruture and probably shouldn't be
11547: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11548: #converted
11549: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11550: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11551: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11552: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11553: #1.1 only
11554: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11555: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11556: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11557: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11558: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11559: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11560: &logthis(sprintf("%-20s is %s",'hits',$hits));
11561: &flushcourselogs();
11562: &logthis("Shutting down");
11563: }
11564:
11565: sub get_dns {
11566: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
11567: if (!$ignore_cache) {
11568: my ($content,$cached)=
11569: &Apache::lonnet::is_cached_new('dns',$url);
11570: if ($cached) {
11571: &$func($content,$hashref);
11572: return;
11573: }
11574: }
11575:
11576: my %alldns;
11577: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11578: foreach my $dns (<$config>) {
11579: next if ($dns !~ /^\^(\S*)/x);
11580: my $line = $1;
11581: my ($host,$protocol) = split(/:/,$line);
11582: if ($protocol ne 'https') {
11583: $protocol = 'http';
11584: }
11585: $alldns{$host} = $protocol;
11586: }
11587: while (%alldns) {
11588: my ($dns) = keys(%alldns);
11589: my $ua=new LWP::UserAgent;
11590: $ua->timeout(30);
11591: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11592: my $response=$ua->request($request);
11593: delete($alldns{$dns});
11594: next if ($response->is_error());
11595: my @content = split("\n",$response->content);
11596: unless ($nocache) {
11597: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
11598: }
11599: &$func(\@content,$hashref);
11600: return;
11601: }
11602: close($config);
11603: my $which = (split('/',$url))[3];
11604: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11605: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11606: my @content = <$config>;
11607: &$func(\@content,$hashref);
11608: return;
11609: }
11610:
11611: # ------------------------------------------------------Get DNS checksums file
11612: sub parse_dns_checksums_tab {
11613: my ($lines,$hashref) = @_;
11614: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11615: my $loncaparev = &get_server_loncaparev($machine_dom);
11616: my ($release,$timestamp) = split(/\-/,$loncaparev);
11617: my (%chksum,%revnum);
11618: if (ref($lines) eq 'ARRAY') {
11619: chomp(@{$lines});
11620: my $versions = shift(@{$lines});
11621: my %supported;
11622: if ($versions =~ /^VERSIONS\:([\w\.\,]+)$/) {
11623: my $releaseslist = $1;
11624: if ($releaseslist =~ /,/) {
11625: map { $supported{$_} = 1; } split(/,/,$releaseslist);
11626: } elsif ($releaseslist) {
11627: $supported{$releaseslist} = 1;
11628: }
11629: }
11630: if ($supported{$release}) {
11631: my $matchthis = 0;
11632: foreach my $line (@{$lines}) {
11633: if ($line =~ /^(\d[\w\.]+)$/) {
11634: if ($matchthis) {
11635: last;
11636: } elsif ($1 eq $release) {
11637: $matchthis = 1;
11638: }
11639: } elsif ($matchthis) {
11640: my ($file,$version,$shasum) = split(/,/,$line);
11641: $chksum{$file} = $shasum;
11642: $revnum{$file} = $version;
11643: }
11644: }
11645: if (ref($hashref) eq 'HASH') {
11646: %{$hashref} = (
11647: sums => \%chksum,
11648: versions => \%revnum,
11649: );
11650: }
11651: }
11652: }
11653: return;
11654: }
11655:
11656: sub fetch_dns_checksums {
11657: my %checksums;
11658: &get_dns('/adm/dns/checksums',\&parse_dns_checksums_tab,1,1,
11659: \%checksums);
11660: return \%checksums;
11661: }
11662:
11663: # ------------------------------------------------------------ Read domain file
11664: {
11665: my $loaded;
11666: my %domain;
11667:
11668: sub parse_domain_tab {
11669: my ($lines) = @_;
11670: foreach my $line (@$lines) {
11671: next if ($line =~ /^(\#|\s*$ )/x);
11672:
11673: chomp($line);
11674: my ($name,@elements) = split(/:/,$line,9);
11675: my %this_domain;
11676: foreach my $field ('description', 'auth_def', 'auth_arg_def',
11677: 'lang_def', 'city', 'longi', 'lati',
11678: 'primary') {
11679: $this_domain{$field} = shift(@elements);
11680: }
11681: $domain{$name} = \%this_domain;
11682: }
11683: }
11684:
11685: sub reset_domain_info {
11686: undef($loaded);
11687: undef(%domain);
11688: }
11689:
11690: sub load_domain_tab {
11691: my ($ignore_cache) = @_;
11692: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11693: my $fh;
11694: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11695: my @lines = <$fh>;
11696: &parse_domain_tab(\@lines);
11697: }
11698: close($fh);
11699: $loaded = 1;
11700: }
11701:
11702: sub domain {
11703: &load_domain_tab() if (!$loaded);
11704:
11705: my ($name,$what) = @_;
11706: return if ( !exists($domain{$name}) );
11707:
11708: if (!$what) {
11709: return $domain{$name}{'description'};
11710: }
11711: return $domain{$name}{$what};
11712: }
11713:
11714: sub domain_info {
11715: &load_domain_tab() if (!$loaded);
11716: return %domain;
11717: }
11718:
11719: }
11720:
11721:
11722: # ------------------------------------------------------------- Read hosts file
11723: {
11724: my %hostname;
11725: my %hostdom;
11726: my %libserv;
11727: my $loaded;
11728: my %name_to_host;
11729: my %internetdom;
11730: my %LC_dns_serv;
11731:
11732: sub parse_hosts_tab {
11733: my ($file) = @_;
11734: foreach my $configline (@$file) {
11735: next if ($configline =~ /^(\#|\s*$ )/x);
11736: chomp($configline);
11737: if ($configline =~ /^\^/) {
11738: if ($configline =~ /^\^([\w.\-]+)/) {
11739: $LC_dns_serv{$1} = 1;
11740: }
11741: next;
11742: }
11743: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11744: $name=~s/\s//g;
11745: if ($id && $domain && $role && $name) {
11746: $hostname{$id}=$name;
11747: push(@{$name_to_host{$name}}, $id);
11748: $hostdom{$id}=$domain;
11749: if ($role eq 'library') { $libserv{$id}=$name; }
11750: if (defined($protocol)) {
11751: if ($protocol eq 'https') {
11752: $protocol{$id} = $protocol;
11753: } else {
11754: $protocol{$id} = 'http';
11755: }
11756: } else {
11757: $protocol{$id} = 'http';
11758: }
11759: if (defined($intdom)) {
11760: $internetdom{$id} = $intdom;
11761: }
11762: }
11763: }
11764: }
11765:
11766: sub reset_hosts_info {
11767: &purge_remembered();
11768: &reset_domain_info();
11769: &reset_hosts_ip_info();
11770: undef(%name_to_host);
11771: undef(%hostname);
11772: undef(%hostdom);
11773: undef(%libserv);
11774: undef($loaded);
11775: }
11776:
11777: sub load_hosts_tab {
11778: my ($ignore_cache) = @_;
11779: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11780: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11781: my @config = <$config>;
11782: &parse_hosts_tab(\@config);
11783: close($config);
11784: $loaded=1;
11785: }
11786:
11787: sub hostname {
11788: &load_hosts_tab() if (!$loaded);
11789:
11790: my ($lonid) = @_;
11791: return $hostname{$lonid};
11792: }
11793:
11794: sub all_hostnames {
11795: &load_hosts_tab() if (!$loaded);
11796:
11797: return %hostname;
11798: }
11799:
11800: sub all_names {
11801: &load_hosts_tab() if (!$loaded);
11802:
11803: return %name_to_host;
11804: }
11805:
11806: sub all_host_domain {
11807: &load_hosts_tab() if (!$loaded);
11808: return %hostdom;
11809: }
11810:
11811: sub is_library {
11812: &load_hosts_tab() if (!$loaded);
11813:
11814: return exists($libserv{$_[0]});
11815: }
11816:
11817: sub all_library {
11818: &load_hosts_tab() if (!$loaded);
11819:
11820: return %libserv;
11821: }
11822:
11823: sub unique_library {
11824: #2x reverse removes all hostnames that appear more than once
11825: my %unique = reverse &all_library();
11826: return reverse %unique;
11827: }
11828:
11829: sub get_servers {
11830: &load_hosts_tab() if (!$loaded);
11831:
11832: my ($domain,$type) = @_;
11833: my %possible_hosts = ($type eq 'library') ? %libserv
11834: : %hostname;
11835: my %result;
11836: if (ref($domain) eq 'ARRAY') {
11837: while ( my ($host,$hostname) = each(%possible_hosts)) {
11838: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11839: $result{$host} = $hostname;
11840: }
11841: }
11842: } else {
11843: while ( my ($host,$hostname) = each(%possible_hosts)) {
11844: if ($hostdom{$host} eq $domain) {
11845: $result{$host} = $hostname;
11846: }
11847: }
11848: }
11849: return %result;
11850: }
11851:
11852: sub get_unique_servers {
11853: my %unique = reverse &get_servers(@_);
11854: return reverse %unique;
11855: }
11856:
11857: sub host_domain {
11858: &load_hosts_tab() if (!$loaded);
11859:
11860: my ($lonid) = @_;
11861: return $hostdom{$lonid};
11862: }
11863:
11864: sub all_domains {
11865: &load_hosts_tab() if (!$loaded);
11866:
11867: my %seen;
11868: my @uniq = grep(!$seen{$_}++, values(%hostdom));
11869: return @uniq;
11870: }
11871:
11872: sub internet_dom {
11873: &load_hosts_tab() if (!$loaded);
11874:
11875: my ($lonid) = @_;
11876: return $internetdom{$lonid};
11877: }
11878:
11879: sub is_LC_dns {
11880: &load_hosts_tab() if (!$loaded);
11881:
11882: my ($hostname) = @_;
11883: return exists($LC_dns_serv{$hostname});
11884: }
11885:
11886: }
11887:
11888: {
11889: my %iphost;
11890: my %name_to_ip;
11891: my %lonid_to_ip;
11892:
11893: sub get_hosts_from_ip {
11894: my ($ip) = @_;
11895: my %iphosts = &get_iphost();
11896: if (ref($iphosts{$ip})) {
11897: return @{$iphosts{$ip}};
11898: }
11899: return;
11900: }
11901:
11902: sub reset_hosts_ip_info {
11903: undef(%iphost);
11904: undef(%name_to_ip);
11905: undef(%lonid_to_ip);
11906: }
11907:
11908: sub get_host_ip {
11909: my ($lonid) = @_;
11910: if (exists($lonid_to_ip{$lonid})) {
11911: return $lonid_to_ip{$lonid};
11912: }
11913: my $name=&hostname($lonid);
11914: my $ip = gethostbyname($name);
11915: return if (!$ip || length($ip) ne 4);
11916: $ip=inet_ntoa($ip);
11917: $name_to_ip{$name} = $ip;
11918: $lonid_to_ip{$lonid} = $ip;
11919: return $ip;
11920: }
11921:
11922: sub get_iphost {
11923: my ($ignore_cache) = @_;
11924:
11925: if (!$ignore_cache) {
11926: if (%iphost) {
11927: return %iphost;
11928: }
11929: my ($ip_info,$cached)=
11930: &Apache::lonnet::is_cached_new('iphost','iphost');
11931: if ($cached) {
11932: %iphost = %{$ip_info->[0]};
11933: %name_to_ip = %{$ip_info->[1]};
11934: %lonid_to_ip = %{$ip_info->[2]};
11935: return %iphost;
11936: }
11937: }
11938:
11939: # get yesterday's info for fallback
11940: my %old_name_to_ip;
11941: my ($ip_info,$cached)=
11942: &Apache::lonnet::is_cached_new('iphost','iphost');
11943: if ($cached) {
11944: %old_name_to_ip = %{$ip_info->[1]};
11945: }
11946:
11947: my %name_to_host = &all_names();
11948: foreach my $name (keys(%name_to_host)) {
11949: my $ip;
11950: if (!exists($name_to_ip{$name})) {
11951: $ip = gethostbyname($name);
11952: if (!$ip || length($ip) ne 4) {
11953: if (defined($old_name_to_ip{$name})) {
11954: $ip = $old_name_to_ip{$name};
11955: &logthis("Can't find $name defaulting to old $ip");
11956: } else {
11957: &logthis("Name $name no IP found");
11958: next;
11959: }
11960: } else {
11961: $ip=inet_ntoa($ip);
11962: }
11963: $name_to_ip{$name} = $ip;
11964: } else {
11965: $ip = $name_to_ip{$name};
11966: }
11967: foreach my $id (@{ $name_to_host{$name} }) {
11968: $lonid_to_ip{$id} = $ip;
11969: }
11970: push(@{$iphost{$ip}},@{$name_to_host{$name}});
11971: }
11972: &Apache::lonnet::do_cache_new('iphost','iphost',
11973: [\%iphost,\%name_to_ip,\%lonid_to_ip],
11974: 48*60*60);
11975:
11976: return %iphost;
11977: }
11978:
11979: #
11980: # Given a DNS returns the loncapa host name for that DNS
11981: #
11982: sub host_from_dns {
11983: my ($dns) = @_;
11984: my @hosts;
11985: my $ip;
11986:
11987: if (exists($name_to_ip{$dns})) {
11988: $ip = $name_to_ip{$dns};
11989: }
11990: if (!$ip) {
11991: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11992: if (length($ip) == 4) {
11993: $ip = &IO::Socket::inet_ntoa($ip);
11994: }
11995: }
11996: if ($ip) {
11997: @hosts = get_hosts_from_ip($ip);
11998: return $hosts[0];
11999: }
12000: return undef;
12001: }
12002:
12003: sub get_internet_names {
12004: my ($lonid) = @_;
12005: return if ($lonid eq '');
12006: my ($idnref,$cached)=
12007: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12008: if ($cached) {
12009: return $idnref;
12010: }
12011: my $ip = &get_host_ip($lonid);
12012: my @hosts = &get_hosts_from_ip($ip);
12013: my %iphost = &get_iphost();
12014: my (@idns,%seen);
12015: foreach my $id (@hosts) {
12016: my $dom = &host_domain($id);
12017: my $prim_id = &domain($dom,'primary');
12018: my $prim_ip = &get_host_ip($prim_id);
12019: next if ($seen{$prim_ip});
12020: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12021: foreach my $id (@{$iphost{$prim_ip}}) {
12022: my $intdom = &internet_dom($id);
12023: unless (grep(/^\Q$intdom\E$/,@idns)) {
12024: push(@idns,$intdom);
12025: }
12026: }
12027: }
12028: $seen{$prim_ip} = 1;
12029: }
12030: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12031: }
12032:
12033: }
12034:
12035: sub all_loncaparevs {
12036: 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);
12037: }
12038:
12039: BEGIN {
12040:
12041: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12042: unless ($readit) {
12043: {
12044: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12045: %perlvar = (%perlvar,%{$configvars});
12046: }
12047:
12048:
12049: # ------------------------------------------------------ Read spare server file
12050: {
12051: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12052:
12053: while (my $configline=<$config>) {
12054: chomp($configline);
12055: if ($configline) {
12056: my ($host,$type) = split(':',$configline,2);
12057: if (!defined($type) || $type eq '') { $type = 'default' };
12058: push(@{ $spareid{$type} }, $host);
12059: }
12060: }
12061: close($config);
12062: }
12063: # ------------------------------------------------------------ Read permissions
12064: {
12065: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12066:
12067: while (my $configline=<$config>) {
12068: chomp($configline);
12069: if ($configline) {
12070: my ($role,$perm)=split(/ /,$configline);
12071: if ($perm ne '') { $pr{$role}=$perm; }
12072: }
12073: }
12074: close($config);
12075: }
12076:
12077: # -------------------------------------------- Read plain texts for permissions
12078: {
12079: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12080:
12081: while (my $configline=<$config>) {
12082: chomp($configline);
12083: if ($configline) {
12084: my ($short,@plain)=split(/:/,$configline);
12085: %{$prp{$short}} = ();
12086: if (@plain > 0) {
12087: $prp{$short}{'std'} = $plain[0];
12088: for (my $i=1; $i<@plain; $i++) {
12089: $prp{$short}{'alt'.$i} = $plain[$i];
12090: }
12091: }
12092: }
12093: }
12094: close($config);
12095: }
12096:
12097: # ---------------------------------------------------------- Read package table
12098: {
12099: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12100:
12101: while (my $configline=<$config>) {
12102: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12103: chomp($configline);
12104: my ($short,$plain)=split(/:/,$configline);
12105: my ($pack,$name)=split(/\&/,$short);
12106: if ($plain ne '') {
12107: $packagetab{$pack.'&'.$name.'&name'}=$name;
12108: $packagetab{$short}=$plain;
12109: }
12110: }
12111: close($config);
12112: }
12113:
12114: # ---------------------------------------------------------- Read loncaparev table
12115: {
12116: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12117: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12118: while (my $configline=<$config>) {
12119: chomp($configline);
12120: my ($hostid,$loncaparev)=split(/:/,$configline);
12121: $loncaparevs{$hostid}=$loncaparev;
12122: }
12123: close($config);
12124: }
12125: }
12126: }
12127:
12128: # ---------------------------------------------------------- Read serverhostID table
12129: {
12130: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12131: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12132: while (my $configline=<$config>) {
12133: chomp($configline);
12134: my ($name,$id)=split(/:/,$configline);
12135: $serverhomeIDs{$name}=$id;
12136: }
12137: close($config);
12138: }
12139: }
12140: }
12141:
12142: {
12143: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12144: if (-e $file) {
12145: my $parser = HTML::LCParser->new($file);
12146: while (my $token = $parser->get_token()) {
12147: if ($token->[0] eq 'S') {
12148: my $item = $token->[1];
12149: my $name = $token->[2]{'name'};
12150: my $value = $token->[2]{'value'};
12151: if ($item ne '' && $name ne '' && $value ne '') {
12152: my $release = $parser->get_text();
12153: $release =~ s/(^\s*|\s*$ )//gx;
12154: $needsrelease{$item.':'.$name.':'.$value} = $release;
12155: }
12156: }
12157: }
12158: }
12159: }
12160:
12161: # ---------------------------------------------------------- Read managers table
12162: {
12163: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12164: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12165: while (my $configline=<$config>) {
12166: chomp($configline);
12167: next if ($configline =~ /^\#/);
12168: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12169: $managerstab{$configline} = 1;
12170: }
12171: }
12172: close($config);
12173: }
12174: }
12175: }
12176:
12177: # ------------- set up temporary directory
12178: {
12179: $tmpdir = LONCAPA::tempdir();
12180:
12181: }
12182:
12183: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12184: 'compress_threshold'=> 20_000,
12185: });
12186:
12187: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12188: $dumpcount=0;
12189: $locknum=0;
12190:
12191: &logtouch();
12192: &logthis('<font color="yellow">INFO: Read configuration</font>');
12193: $readit=1;
12194: {
12195: use integer;
12196: my $test=(2**32)+1;
12197: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12198: &logthis(" Detected 64bit platform ($_64bit)");
12199: }
12200:
12201: {
12202: eval {
12203: ($apache) =
12204: (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
12205: };
12206: if ($@) {
12207: $apache = 1.3;
12208: }
12209: }
12210:
12211: }
12212: }
12213:
12214: 1;
12215: __END__
12216:
12217: =pod
12218:
12219: =head1 NAME
12220:
12221: Apache::lonnet - Subroutines to ask questions about things in the network.
12222:
12223: =head1 SYNOPSIS
12224:
12225: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12226:
12227: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12228:
12229: Common parameters:
12230:
12231: =over 4
12232:
12233: =item *
12234:
12235: $uname : an internal username (if $cname expecting a course Id specifically)
12236:
12237: =item *
12238:
12239: $udom : a domain (if $cdom expecting a course's domain specifically)
12240:
12241: =item *
12242:
12243: $symb : a resource instance identifier
12244:
12245: =item *
12246:
12247: $namespace : the name of a .db file that contains the data needed or
12248: being set.
12249:
12250: =back
12251:
12252: =head1 OVERVIEW
12253:
12254: lonnet provides subroutines which interact with the
12255: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12256: about classes, users, and resources.
12257:
12258: For many of these objects you can also use this to store data about
12259: them or modify them in various ways.
12260:
12261: =head2 Symbs
12262:
12263: To identify a specific instance of a resource, LON-CAPA uses symbols
12264: or "symbs"X<symb>. These identifiers are built from the URL of the
12265: map, the resource number of the resource in the map, and the URL of
12266: the resource itself. The latter is somewhat redundant, but might help
12267: if maps change.
12268:
12269: An example is
12270:
12271: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12272:
12273: The respective map entry is
12274:
12275: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12276: title="Problem 2">
12277: </resource>
12278:
12279: Symbs are used by the random number generator, as well as to store and
12280: restore data specific to a certain instance of for example a problem.
12281:
12282: =head2 Storing And Retrieving Data
12283:
12284: X<store()>X<cstore()>X<restore()>Three of the most important functions
12285: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12286: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12287: is is the non-critical message twin of cstore. These functions are for
12288: handlers to store a perl hash to a user's permanent data space in an
12289: easy manner, and to retrieve it again on another call. It is expected
12290: that a handler would use this once at the beginning to retrieve data,
12291: and then again once at the end to send only the new data back.
12292:
12293: The data is stored in the user's data directory on the user's
12294: homeserver under the ID of the course.
12295:
12296: The hash that is returned by restore will have all of the previous
12297: value for all of the elements of the hash.
12298:
12299: Example:
12300:
12301: #creating a hash
12302: my %hash;
12303: $hash{'foo'}='bar';
12304:
12305: #storing it
12306: &Apache::lonnet::cstore(\%hash);
12307:
12308: #changing a value
12309: $hash{'foo'}='notbar';
12310:
12311: #adding a new value
12312: $hash{'bar'}='foo';
12313: &Apache::lonnet::cstore(\%hash);
12314:
12315: #retrieving the hash
12316: my %history=&Apache::lonnet::restore();
12317:
12318: #print the hash
12319: foreach my $key (sort(keys(%history))) {
12320: print("\%history{$key} = $history{$key}");
12321: }
12322:
12323: Will print out:
12324:
12325: %history{1:foo} = bar
12326: %history{1:keys} = foo:timestamp
12327: %history{1:timestamp} = 990455579
12328: %history{2:bar} = foo
12329: %history{2:foo} = notbar
12330: %history{2:keys} = foo:bar:timestamp
12331: %history{2:timestamp} = 990455580
12332: %history{bar} = foo
12333: %history{foo} = notbar
12334: %history{timestamp} = 990455580
12335: %history{version} = 2
12336:
12337: Note that the special hash entries C<keys>, C<version> and
12338: C<timestamp> were added to the hash. C<version> will be equal to the
12339: total number of versions of the data that have been stored. The
12340: C<timestamp> attribute will be the UNIX time the hash was
12341: stored. C<keys> is available in every historical section to list which
12342: keys were added or changed at a specific historical revision of a
12343: hash.
12344:
12345: B<Warning>: do not store the hash that restore returns directly. This
12346: will cause a mess since it will restore the historical keys as if the
12347: were new keys. I.E. 1:foo will become 1:1:foo etc.
12348:
12349: Calling convention:
12350:
12351: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
12352: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
12353:
12354: For more detailed information, see lonnet specific documentation.
12355:
12356: =head1 RETURN MESSAGES
12357:
12358: =over 4
12359:
12360: =item * B<con_lost>: unable to contact remote host
12361:
12362: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12363: when the connection is brought back up
12364:
12365: =item * B<con_failed>: unable to contact remote host and unable to save message
12366: for later delivery
12367:
12368: =item * B<error:>: an error a occurred, a description of the error follows the :
12369:
12370: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12371: that was requested
12372:
12373: =back
12374:
12375: =head1 PUBLIC SUBROUTINES
12376:
12377: =head2 Session Environment Functions
12378:
12379: =over 4
12380:
12381: =item *
12382: X<appenv()>
12383: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12384: the user envirnoment file, and will be restored for each access this
12385: user makes during this session, also modifies the %env for the current
12386: process. Optional rolesarrayref - if defined contains a reference to an array
12387: of roles which are exempt from the restriction on modifying user.role entries
12388: in the user's environment.db and in %env.
12389:
12390: =item *
12391: X<delenv()>
12392: B<delenv($delthis,$regexp)>: removes all items from the session
12393: environment file that begin with $delthis. If the
12394: optional second arg - $regexp - is true, $delthis is treated as a
12395: regular expression, otherwise \Q$delthis\E is used.
12396: The values are also deleted from the current processes %env.
12397:
12398: =item * get_env_multiple($name)
12399:
12400: gets $name from the %env hash, it seemlessly handles the cases where multiple
12401: values may be defined and end up as an array ref.
12402:
12403: returns an array of values
12404:
12405: =back
12406:
12407: =head2 User Information
12408:
12409: =over 4
12410:
12411: =item *
12412: X<queryauthenticate()>
12413: B<queryauthenticate($uname,$udom)>: try to determine user's current
12414: authentication scheme
12415:
12416: =item *
12417: X<authenticate()>
12418: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12419: authenticate user from domain's lib servers (first use the current
12420: one). C<$upass> should be the users password.
12421: $checkdefauth is optional (value is 1 if a check should be made to
12422: authenticate user using default authentication method, and allow
12423: account creation if username does not have account in the domain).
12424: $clientcancheckhost is optional (value is 1 if checking whether the
12425: server can host will occur on the client side in lonauth.pm).
12426:
12427: =item *
12428: X<homeserver()>
12429: B<homeserver($uname,$udom)>: find the server which has
12430: the user's directory and files (there must be only one), this caches
12431: the answer, and also caches if there is a borken connection.
12432:
12433: =item *
12434: X<idget()>
12435: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12436: (IDs are a unique resource in a domain, there must be only 1 ID per
12437: username, and only 1 username per ID in a specific domain) (returns
12438: hash: id=>name,id=>name)
12439:
12440: =item *
12441: X<idrget()>
12442: B<idrget($udom,@unames)>: find the IDs behind a list of
12443: usernames (returns hash: name=>id,name=>id)
12444:
12445: =item *
12446: X<idput()>
12447: B<idput($udom,%ids)>: store away a list of names and associated IDs
12448:
12449: =item *
12450: X<rolesinit()>
12451: B<rolesinit($udom,$username)>: get user privileges.
12452: returns user role, first access and timer interval hashes
12453:
12454: =item *
12455: X<privileged()>
12456: B<privileged($username,$domain)>: returns a true if user has a
12457: privileged and active role (i.e. su or dc), false otherwise.
12458:
12459: =item *
12460: X<getsection()>
12461: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12462: course $cname, return section name/number or '' for "not in course"
12463: and '-1' for "no section"
12464:
12465: =item *
12466: X<userenvironment()>
12467: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12468: passed in @what from the requested user's environment, returns a hash
12469:
12470: =item *
12471: X<userlog_query()>
12472: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12473: activity.log file. %filters defines filters applied when parsing the
12474: log file. These can be start or end timestamps, or the type of action
12475: - log to look for Login or Logout events, check for Checkin or
12476: Checkout, role for role selection. The response is in the form
12477: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12478: escaped strings of the action recorded in the activity.log file.
12479:
12480: =back
12481:
12482: =head2 User Roles
12483:
12484: =over 4
12485:
12486: =item *
12487:
12488: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12489: F: full access
12490: U,I,K: authentication modes (cxx only)
12491: '': forbidden
12492: 1: user needs to choose course
12493: 2: browse allowed
12494: A: passphrase authentication needed
12495:
12496: =item *
12497:
12498: constructaccess($url,$setpriv) : check for access to construction space URL
12499:
12500: See if the owner domain and name in the URL match those in the
12501: expected environment. If so, return three element list
12502: ($ownername,$ownerdomain,$ownerhome).
12503:
12504: Otherwise return the null string.
12505:
12506: If second argument 'setpriv' is true, it assigns the privileges,
12507: and returns the same three element list, unless the owner has
12508: blocked "ad hoc" Domain Coordinator access to the Author Space,
12509: in which case the null string is returned.
12510:
12511: =item *
12512:
12513: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12514: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12515: and course level
12516:
12517: =item *
12518:
12519: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12520: (rolesplain.tab); plain text explanation of a user role term.
12521: $type is Course (default) or Community.
12522: If $forcedefault evaluates to true, text returned will be default
12523: text for $type. Otherwise, if this is a course, the text returned
12524: will be a custom name for the role (if defined in the course's
12525: environment). If no custom name is defined the default is returned.
12526:
12527: =item *
12528:
12529: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
12530: All arguments are optional. Returns a hash of a roles, either for
12531: co-author/assistant author roles for a user's Construction Space
12532: (default), or if $context is 'userroles', roles for the user himself,
12533: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12534: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12535: For each key, value is set to colon-separated start and end times for
12536: the role. If no username and domain are specified, will default to
12537: current user/domain. Types, roles, and roledoms are references to arrays
12538: of role statuses (active, future or previous), roles
12539: (e.g., cc,in, st etc.) and domains of the roles which can be used
12540: to restrict the list of roles reported. If no array ref is
12541: provided for types, will default to return only active roles.
12542:
12543: =item *
12544:
12545: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12546: user: $uname:$udom has a role in the course: $cdom_$cnum.
12547:
12548: Additional optional arguments are: $type (if role checking is to be restricted
12549: to certain user status types -- previous (expired roles), active (currently
12550: available roles) or future (roles available in the future), and
12551: $hideprivileged -- if true will not report course roles for users who
12552: have active Domain Coordinator or Super User roles.
12553:
12554: =back
12555:
12556: =head2 User Modification
12557:
12558: =over 4
12559:
12560: =item *
12561:
12562: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
12563: user for the level given by URL. Optional start and end dates (leave empty
12564: string or zero for "no date")
12565:
12566: =item *
12567:
12568: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12569: change a users, password, possible return values are: ok,
12570: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12571: refused
12572:
12573: =item *
12574:
12575: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
12576:
12577: =item *
12578:
12579: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12580: $forceid,$desiredhome,$email,$inststatus,$candelete) :
12581:
12582: will update user information (firstname,middlename,lastname,generation,
12583: permanentemail), and if forceid is true, student/employee ID also.
12584: A user's institutional affiliation(s) can also be updated.
12585: User information fields will not be overwritten with empty entries
12586: unless the field is included in the $candelete array reference.
12587: This array is included when a single user is modified via "Manage Users",
12588: or when Autoupdate.pl is run by cron in a domain.
12589:
12590: =item *
12591:
12592: modifystudent
12593:
12594: modify a student's enrollment and identification information.
12595: The course id is resolved based on the current users environment.
12596: This means the envoking user must be a course coordinator or otherwise
12597: associated with a course.
12598:
12599: This call is essentially a wrapper for lonnet::modifyuser and
12600: lonnet::modify_student_enrollment
12601:
12602: Inputs:
12603:
12604: =over 4
12605:
12606: =item B<$udom> Student's loncapa domain
12607:
12608: =item B<$uname> Student's loncapa login name
12609:
12610: =item B<$uid> Student/Employee ID
12611:
12612: =item B<$umode> Student's authentication mode
12613:
12614: =item B<$upass> Student's password
12615:
12616: =item B<$first> Student's first name
12617:
12618: =item B<$middle> Student's middle name
12619:
12620: =item B<$last> Student's last name
12621:
12622: =item B<$gene> Student's generation
12623:
12624: =item B<$usec> Student's section in course
12625:
12626: =item B<$end> Unix time of the roles expiration
12627:
12628: =item B<$start> Unix time of the roles start date
12629:
12630: =item B<$forceid> If defined, allow $uid to be changed
12631:
12632: =item B<$desiredhome> server to use as home server for student
12633:
12634: =item B<$email> Student's permanent e-mail address
12635:
12636: =item B<$type> Type of enrollment (auto or manual)
12637:
12638: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
12639:
12640: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
12641:
12642: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
12643:
12644: =item B<$context> role change context (shown in User Management Logs display in a course)
12645:
12646: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12647:
12648: =back
12649:
12650: =item *
12651:
12652: modify_student_enrollment
12653:
12654: Change a students enrollment status in a class. The environment variable
12655: 'role.request.course' must be defined for this function to proceed.
12656:
12657: Inputs:
12658:
12659: =over 4
12660:
12661: =item $udom, students domain
12662:
12663: =item $uname, students name
12664:
12665: =item $uid, students user id
12666:
12667: =item $first, students first name
12668:
12669: =item $middle
12670:
12671: =item $last
12672:
12673: =item $gene
12674:
12675: =item $usec
12676:
12677: =item $end
12678:
12679: =item $start
12680:
12681: =item $type
12682:
12683: =item $locktype
12684:
12685: =item $cid
12686:
12687: =item $selfenroll
12688:
12689: =item $context
12690:
12691: =back
12692:
12693:
12694: =item *
12695:
12696: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12697: custom role; give a custom role to a user for the level given by URL. Specify
12698: name and domain of role author, and role name
12699:
12700: =item *
12701:
12702: revokerole($udom,$uname,$url,$role) : revoke a role for url
12703:
12704: =item *
12705:
12706: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12707:
12708: =back
12709:
12710: =head2 Course Infomation
12711:
12712: =over 4
12713:
12714: =item *
12715:
12716: coursedescription($courseid,$options) : returns a hash of information about the
12717: specified course id, including all environment settings for the
12718: course, the description of the course will be in the hash under the
12719: key 'description'
12720:
12721: $options is an optional parameter that if supplied is a hash reference that controls
12722: what how this function works. It has the following key/values:
12723:
12724: =over 4
12725:
12726: =item freshen_cache
12727:
12728: If defined, and the environment cache for the course is valid, it is
12729: returned in the returned hash.
12730:
12731: =item one_time
12732:
12733: If defined, the last cache time is set to _now_
12734:
12735: =item user
12736:
12737: If defined, the supplied username is used instead of the current user.
12738:
12739:
12740: =back
12741:
12742: =item *
12743:
12744: resdata($name,$domain,$type,@which) : request for current parameter
12745: setting for a specific $type, where $type is either 'course' or 'user',
12746: @what should be a list of parameters to ask about. This routine caches
12747: answers for 5 minutes.
12748:
12749: =item *
12750:
12751: get_courseresdata($courseid, $domain) : dump the entire course resource
12752: data base, returning a hash that is keyed by the resource name and has
12753: values that are the resource value. I believe that the timestamps and
12754: versions are also returned.
12755:
12756: =back
12757:
12758: =head2 Course Modification
12759:
12760: =over 4
12761:
12762: =item *
12763:
12764: writecoursepref($courseid,%prefs) : write preferences (environment
12765: database) for a course
12766:
12767: =item *
12768:
12769: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12770:
12771: =item *
12772:
12773: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
12774:
12775: =item *
12776:
12777: is_course($courseid), is_course($cdom, $cnum)
12778:
12779: Accepts either a combined $courseid (in the form of domain_courseid) or the
12780: two component version $cdom, $cnum. It checks if the specified course exists.
12781:
12782: Returns:
12783: undef if the course doesn't exist, otherwise
12784: in scalar context the combined courseid.
12785: in list context the two components of the course identifier, domain and
12786: courseid.
12787:
12788: =back
12789:
12790: =head2 Resource Subroutines
12791:
12792: =over 4
12793:
12794: =item *
12795:
12796: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12797:
12798: =item *
12799:
12800: repcopy($filename) : subscribes to the requested file, and attempts to
12801: replicate from the owning library server, Might return
12802: 'unavailable', 'not_found', 'forbidden', 'ok', or
12803: 'bad_request', also attempts to grab the metadata for the
12804: resource. Expects the local filesystem pathname
12805: (/home/httpd/html/res/....)
12806:
12807: =back
12808:
12809: =head2 Resource Information
12810:
12811: =over 4
12812:
12813: =item *
12814:
12815: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12816: a vairety of different possible values, $varname should be a request
12817: string, and the other parameters can be used to specify who and what
12818: one is asking about.
12819:
12820: Possible values for $varname are environment.lastname (or other item
12821: from the envirnment hash), user.name (or someother aspect about the
12822: user), resource.0.maxtries (or some other part and parameter of a
12823: resource)
12824:
12825: =item *
12826:
12827: directcondval($number) : get current value of a condition; reads from a state
12828: string
12829:
12830: =item *
12831:
12832: condval($condidx) : value of condition index based on state
12833:
12834: =item *
12835:
12836: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12837: resource's metadata, $what should be either a specific key, or either
12838: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12839: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12840:
12841: this function automatically caches all requests
12842:
12843: =item *
12844:
12845: metadata_query($query,$custom,$customshow) : make a metadata query against the
12846: network of library servers; returns file handle of where SQL and regex results
12847: will be stored for query
12848:
12849: =item *
12850:
12851: symbread($filename) : return symbolic list entry (filename argument optional);
12852: returns the data handle
12853:
12854: =item *
12855:
12856: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
12857: and is a possible symb for the URL in $thisfn, and if is an encrypted
12858: resource that the user accessed using /enc/ returns a 1 on success, 0
12859: on failure, user must be in a course, as it assumes the existence of
12860: the course initial hash, and uses $env('request.course.id'}. The third
12861: arg is an optional reference to a scalar. If this arg is passed in the
12862: call to symbverify, it will be set to 1 if the symb has been set to be
12863: encrypted; otherwise it will be null.
12864:
12865: =item *
12866:
12867: symbclean($symb) : removes versions numbers from a symb, returns the
12868: cleaned symb
12869:
12870: =item *
12871:
12872: is_on_map($uri) : checks if the $uri is somewhere on the current
12873: course map, user must be in a course for it to work.
12874:
12875: =item *
12876:
12877: numval($salt) : return random seed value (addend for rndseed)
12878:
12879: =item *
12880:
12881: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12882: a random seed, all arguments are optional, if they aren't sent it uses the
12883: environment to derive them. Note: if symb isn't sent and it can't get one
12884: from &symbread it will use the current time as its return value
12885:
12886: =item *
12887:
12888: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12889: unfakeable, receipt
12890:
12891: =item *
12892:
12893: receipt() : API to ireceipt working off of env values; given out to users
12894:
12895: =item *
12896:
12897: countacc($url) : count the number of accesses to a given URL
12898:
12899: =item *
12900:
12901: 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
12902:
12903: =item *
12904:
12905: 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)
12906:
12907: =item *
12908:
12909: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
12910:
12911: =item *
12912:
12913: devalidate($symb) : devalidate temporary spreadsheet calculations,
12914: forcing spreadsheet to reevaluate the resource scores next time.
12915:
12916: =item *
12917:
12918: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
12919: when viewing in course context.
12920:
12921: input: six args -- filename (decluttered), course number, course domain,
12922: url, symb (if registered) and group (if this is a
12923: group item -- e.g., bulletin board, group page etc.).
12924:
12925: output: array of five scalars --
12926: $cfile -- url for file editing if editable on current server
12927: $home -- homeserver of resource (i.e., for author if published,
12928: or course if uploaded.).
12929: $switchserver -- 1 if server switch will be needed.
12930: $forceedit -- 1 if icon/link should be to go to edit mode
12931: $forceview -- 1 if icon/link should be to go to view mode
12932:
12933: =item *
12934:
12935: is_course_upload($file,$cnum,$cdom)
12936:
12937: Used in course context to determine if current file was uploaded to
12938: the course (i.e., would be found in /userfiles/docs on the course's
12939: homeserver.
12940:
12941: input: 3 args -- filename (decluttered), course number and course domain.
12942: output: boolean -- 1 if file was uploaded.
12943:
12944: =back
12945:
12946: =head2 Storing/Retreiving Data
12947:
12948: =over 4
12949:
12950: =item *
12951:
12952: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12953: for this url; hashref needs to be given and should be a \%hashname; the
12954: remaining args aren't required and if they aren't passed or are '' they will
12955: be derived from the env
12956:
12957: =item *
12958:
12959: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12960: uses critical subroutine
12961:
12962: =item *
12963:
12964: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12965: all args are optional
12966:
12967: =item *
12968:
12969: dumpstore($namespace,$udom,$uname,$regexp,$range) :
12970: dumps the complete (or key matching regexp) namespace into a hash
12971: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12972: normally &store()ed into
12973:
12974: $range should be either an integer '100' (give me the first 100
12975: matching records)
12976: or be two integers sperated by a - with no spaces
12977: '30-50' (give me the 30th through the 50th matching
12978: records)
12979:
12980:
12981: =item *
12982:
12983: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12984: replaces a &store() version of data with a replacement set of data
12985: for a particular resource in a namespace passed in the $storehash hash
12986: reference
12987:
12988: =item *
12989:
12990: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12991: works very similar to store/cstore, but all data is stored in a
12992: temporary location and can be reset using tmpreset, $storehash should
12993: be a hash reference, returns nothing on success
12994:
12995: =item *
12996:
12997: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12998: similar to restore, but all data is stored in a temporary location and
12999: can be reset using tmpreset. Returns a hash of values on success,
13000: error string otherwise.
13001:
13002: =item *
13003:
13004: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13005: deltes all keys for $symb form the temporary storage hash.
13006:
13007: =item *
13008:
13009: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13010: reference filled in from namesp ($udom and $uname are optional)
13011:
13012: =item *
13013:
13014: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13015: namesp ($udom and $uname are optional)
13016:
13017: =item *
13018:
13019: dump($namespace,$udom,$uname,$regexp,$range) :
13020: dumps the complete (or key matching regexp) namespace into a hash
13021: ($udom, $uname, $regexp, $range are optional)
13022:
13023: $range should be either an integer '100' (give me the first 100
13024: matching records)
13025: or be two integers sperated by a - with no spaces
13026: '30-50' (give me the 30th through the 50th matching
13027: records)
13028: =item *
13029:
13030: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13031: $store can be a scalar, an array reference, or if the amount to be
13032: incremented is > 1, a hash reference.
13033:
13034: ($udom and $uname are optional)
13035:
13036: =item *
13037:
13038: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13039: ($udom and $uname are optional)
13040:
13041: =item *
13042:
13043: cput($namespace,$storehash,$udom,$uname) : critical put
13044: ($udom and $uname are optional)
13045:
13046: =item *
13047:
13048: newput($namespace,$storehash,$udom,$uname) :
13049:
13050: Attempts to store the items in the $storehash, but only if they don't
13051: currently exist, if this succeeds you can be certain that you have
13052: successfully created a new key value pair in the $namespace db.
13053:
13054:
13055: Args:
13056: $namespace: name of database to store values to
13057: $storehash: hashref to store to the db
13058: $udom: (optional) domain of user containing the db
13059: $uname: (optional) name of user caontaining the db
13060:
13061: Returns:
13062: 'ok' -> succeeded in storing all keys of $storehash
13063: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13064: least <key> already existed in the db (other
13065: requested keys may also already exist)
13066: 'error: <msg>' -> unable to tie the DB or other error occurred
13067: 'con_lost' -> unable to contact request server
13068: 'refused' -> action was not allowed by remote machine
13069:
13070:
13071: =item *
13072:
13073: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13074: reference filled in from namesp (encrypts the return communication)
13075: ($udom and $uname are optional)
13076:
13077: =item *
13078:
13079: log($udom,$name,$home,$message) : write to permanent log for user; use
13080: critical subroutine
13081:
13082: =item *
13083:
13084: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13085: array reference filled in from namespace found in domain level on either
13086: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13087:
13088: =item *
13089:
13090: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13091: domain level either on specified domain server ($uhome) or primary domain
13092: server ($udom and $uhome are optional)
13093:
13094: =item *
13095:
13096: get_domain_defaults($target_domain) : returns hash with defaults for
13097: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
13098: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
13099: or localauth), initial password or a kerberos realm, language (e.g., en-us).
13100: Values are retrieved from cache (if current), or from domain's configuration.db
13101: (if available), or lastly from values in lonTabs/dns_domain,tab,
13102: or lonTabs/domain.tab.
13103:
13104: %domdefaults = &get_auth_defaults($target_domain);
13105:
13106: =back
13107:
13108: =head2 Network Status Functions
13109:
13110: =over 4
13111:
13112: =item *
13113:
13114: dirlist() : return directory list based on URI (first arg).
13115:
13116: Inputs: 1 required, 5 optional.
13117:
13118: =over
13119:
13120: =item
13121: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13122:
13123: =item
13124: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13125:
13126: =item
13127: $username - username of user/course to be listed. Extracted from $uri if absent.
13128:
13129: =item
13130: $getpropath - boolean: 1 if prepend path using &propath().
13131:
13132: =item
13133: $getuserdir - boolean: 1 if prepend path for "userfiles".
13134:
13135: =item
13136: $alternateRoot - path to prepend in place of path from $uri.
13137:
13138: =back
13139:
13140: Returns: Array of up to two items.
13141:
13142: =over
13143:
13144: a reference to an array of files/subdirectories
13145:
13146: =over
13147:
13148: Each element in the array of files/subdirectories is a & separated list of
13149: item name and the result of running stat on the item. If dirlist was requested
13150: for a file instead of a directory, the item name will be ''. For a directory
13151: listing, if the item is a metadata file, the element will end &N&M
13152: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13153: default copyright set (1).
13154:
13155: =back
13156:
13157: a scalar containing error condition (if encountered).
13158:
13159: =over
13160:
13161: =item
13162: no_host (no homeserver identified for $username:$domain).
13163:
13164: =item
13165: no_such_host (server contacted for listing not identified as valid host).
13166:
13167: =item
13168: con_lost (connection to remote server failed).
13169:
13170: =item
13171: refused (invalid $username:$domain received on lond side).
13172:
13173: =item
13174: no_such_dir (directory at specified path on lond side does not exist).
13175:
13176: =item
13177: empty (directory at specified path on lond side is empty).
13178:
13179: =over
13180:
13181: This is currently not encountered because the &ls3, &ls2,
13182: &ls (_handler) routines on the lond side do not filter out
13183: . and .. from a directory listing.
13184:
13185: =back
13186:
13187: =back
13188:
13189: =back
13190:
13191: =item *
13192:
13193: spareserver() : find server with least workload from spare.tab
13194:
13195:
13196: =item *
13197:
13198: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13199: if there is no corresponding loncapa host.
13200:
13201: =back
13202:
13203:
13204: =head2 Apache Request
13205:
13206: =over 4
13207:
13208: =item *
13209:
13210: ssi($url,%hash) : server side include, does a complete request cycle on url to
13211: localhost, posts hash
13212:
13213: =back
13214:
13215: =head2 Data to String to Data
13216:
13217: =over 4
13218:
13219: =item *
13220:
13221: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13222: and '&' separators, supports elements that are arrayrefs and hashrefs
13223:
13224: =item *
13225:
13226: hashref2str($hashref) : convert a hashref into a string complete with
13227: escaping and '=' and '&' separators, supports elements that are
13228: arrayrefs and hashrefs
13229:
13230: =item *
13231:
13232: arrayref2str($arrayref) : convert an arrayref into a string complete
13233: with escaping and '&' separators, supports elements that are arrayrefs
13234: and hashrefs
13235:
13236: =item *
13237:
13238: str2hash($string) : convert string to hash using unescaping and
13239: splitting on '=' and '&', supports elements that are arrayrefs and
13240: hashrefs
13241:
13242: =item *
13243:
13244: str2array($string) : convert string to hash using unescaping and
13245: splitting on '&', supports elements that are arrayrefs and hashrefs
13246:
13247: =back
13248:
13249: =head2 Logging Routines
13250:
13251:
13252: These routines allow one to make log messages in the lonnet.log and
13253: lonnet.perm logfiles.
13254:
13255: =over 4
13256:
13257: =item *
13258:
13259: logtouch() : make sure the logfile, lonnet.log, exists
13260:
13261: =item *
13262:
13263: logthis() : append message to the normal lonnet.log file, it gets
13264: preiodically rolled over and deleted.
13265:
13266: =item *
13267:
13268: logperm() : append a permanent message to lonnet.perm.log, this log
13269: file never gets deleted by any automated portion of the system, only
13270: messages of critical importance should go in here.
13271:
13272:
13273: =back
13274:
13275: =head2 General File Helper Routines
13276:
13277: =over 4
13278:
13279: =item *
13280:
13281: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13282: (a) files in /uploaded
13283: (i) If a local copy of the file exists -
13284: compares modification date of local copy with last-modified date for
13285: definitive version stored on home server for course. If local copy is
13286: stale, requests a new version from the home server and stores it.
13287: If the original has been removed from the home server, then local copy
13288: is unlinked.
13289: (ii) If local copy does not exist -
13290: requests the file from the home server and stores it.
13291:
13292: If $caller is 'uploadrep':
13293: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13294: for request for files originally uploaded via DOCS.
13295: - returns 'ok' if fresh local copy now available, -1 otherwise.
13296:
13297: Otherwise:
13298: This indicates a call from the content generation phase of the request.
13299: - returns the entire contents of the file or -1.
13300:
13301: (b) files in /res
13302: - returns the entire contents of a file or -1;
13303: it properly subscribes to and replicates the file if neccessary.
13304:
13305:
13306: =item *
13307:
13308: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13309: reference
13310:
13311: returns either a stat() list of data about the file or an empty list
13312: if the file doesn't exist or couldn't find out about it (connection
13313: problems or user unknown)
13314:
13315: =item *
13316:
13317: filelocation($dir,$file) : returns file system location of a file
13318: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13319: directory that relative $file lookups are to looked in ($dir of /a/dir
13320: and a file of ../bob will become /a/bob)
13321:
13322: =item *
13323:
13324: hreflocation($dir,$file) : returns file system location or a URL; same as
13325: filelocation except for hrefs
13326:
13327: =item *
13328:
13329: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13330:
13331: =back
13332:
13333: =head2 Usererfile file routines (/uploaded*)
13334:
13335: =over 4
13336:
13337: =item *
13338:
13339: userfileupload(): main rotine for putting a file in a user or course's
13340: filespace, arguments are,
13341:
13342: formname - required - this is the name of the element in $env where the
13343: filename, and the contents of the file to create/modifed exist
13344: the filename is in $env{'form.'.$formname.'.filename'} and the
13345: contents of the file is located in $env{'form.'.$formname}
13346: context - if coursedoc, store the file in the course of the active role
13347: of the current user;
13348: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13349: if 'canceloverwrite': delete file in tmp/overwrites directory
13350: subdir - required - subdirectory to put the file in under ../userfiles/
13351: if undefined, it will be placed in "unknown"
13352:
13353: (This routine calls clean_filename() to remove any dangerous
13354: characters from the filename, and then calls finuserfileupload() to
13355: complete the transaction)
13356:
13357: returns either the url of the uploaded file (/uploaded/....) if successful
13358: and /adm/notfound.html if unsuccessful
13359:
13360: =item *
13361:
13362: clean_filename(): routine for cleaing a filename up for storage in
13363: userfile space, argument is:
13364:
13365: filename - proposed filename
13366:
13367: returns: the new clean filename
13368:
13369: =item *
13370:
13371: finishuserfileupload(): routine that creates and sends the file to
13372: userspace, probably shouldn't be called directly
13373:
13374: docuname: username or courseid of destination for the file
13375: docudom: domain of user/course of destination for the file
13376: formname: same as for userfileupload()
13377: fname: filename (including subdirectories) for the file
13378: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13379: allfiles: reference to hash used to store objects found by parser
13380: codebase: reference to hash used for codebases of java objects found by parser
13381: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13382: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13383: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13384: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13385: context: if 'overwrite', will move the uploaded file from its temporary location to
13386: userfiles to facilitate overwriting a previously uploaded file with same name.
13387: mimetype: reference to scalar to accommodate mime type determined
13388: from File::MMagic if $parser = parse.
13389:
13390: returns either the url of the uploaded file (/uploaded/....) if successful
13391: and /adm/notfound.html if unsuccessful (or an error message if context
13392: was 'overwrite').
13393:
13394:
13395: =item *
13396:
13397: renameuserfile(): renames an existing userfile to a new name
13398:
13399: Args:
13400: docuname: username or courseid of destination for the file
13401: docudom: domain of user/course of destination for the file
13402: old: current file name (including any subdirs under userfiles)
13403: new: desired file name (including any subdirs under userfiles)
13404:
13405: =item *
13406:
13407: mkdiruserfile(): creates a directory is a userfiles dir
13408:
13409: Args:
13410: docuname: username or courseid of destination for the file
13411: docudom: domain of user/course of destination for the file
13412: dir: dir to create (including any subdirs under userfiles)
13413:
13414: =item *
13415:
13416: removeuserfile(): removes a file that exists in userfiles
13417:
13418: Args:
13419: docuname: username or courseid of destination for the file
13420: docudom: domain of user/course of destination for the file
13421: fname: filname to delete (including any subdirs under userfiles)
13422:
13423: =item *
13424:
13425: removeuploadedurl(): convience function for removeuserfile()
13426:
13427: Args:
13428: url: a full /uploaded/... url to delete
13429:
13430: =item *
13431:
13432: get_portfile_permissions():
13433: Args:
13434: domain: domain of user or course contain the portfolio files
13435: user: name of user or num of course contain the portfolio files
13436: Returns:
13437: hashref of a dump of the proper file_permissions.db
13438:
13439:
13440: =item *
13441:
13442: get_access_controls():
13443:
13444: Args:
13445: current_permissions: the hash ref returned from get_portfile_permissions()
13446: group: (optional) the group you want the files associated with
13447: file: (optional) the file you want access info on
13448:
13449: Returns:
13450: a hash (keys are file names) of hashes containing
13451: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13452: values are XML containing access control settings (see below)
13453:
13454: Internal notes:
13455:
13456: access controls are stored in file_permissions.db as key=value pairs.
13457: key -> path to file/file_name\0uniqueID:scope_end_start
13458: where scope -> public,guest,course,group,domains or users.
13459: end -> UNIX time for end of access (0 -> no end date)
13460: start -> UNIX time for start of access
13461:
13462: value -> XML description of access control
13463: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13464: <start></start>
13465: <end></end>
13466:
13467: <password></password> for scope type = guest
13468:
13469: <domain></domain> for scope type = course or group
13470: <number></number>
13471: <roles id="">
13472: <role></role>
13473: <access></access>
13474: <section></section>
13475: <group></group>
13476: </roles>
13477:
13478: <dom></dom> for scope type = domains
13479:
13480: <users> for scope type = users
13481: <user>
13482: <uname></uname>
13483: <udom></udom>
13484: </user>
13485: </users>
13486: </scope>
13487:
13488: Access data is also aggregated for each file in an additional key=value pair:
13489: key -> path to file/file_name\0accesscontrol
13490: value -> reference to hash
13491: hash contains key = value pairs
13492: where key = uniqueID:scope_end_start
13493: value = UNIX time record was last updated
13494:
13495: Used to improve speed of look-ups of access controls for each file.
13496:
13497: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13498:
13499: =item *
13500:
13501: modify_access_controls():
13502:
13503: Modifies access controls for a portfolio file
13504: Args
13505: 1. file name
13506: 2. reference to hash of required changes,
13507: 3. domain
13508: 4. username
13509: where domain,username are the domain of the portfolio owner
13510: (either a user or a course)
13511:
13512: Returns:
13513: 1. result of additions or updates ('ok' or 'error', with error message).
13514: 2. result of deletions ('ok' or 'error', with error message).
13515: 3. reference to hash of any new or updated access controls.
13516: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13517: key = integer (inbound ID)
13518: value = uniqueID
13519:
13520: =item *
13521:
13522: get_timebased_id():
13523:
13524: Attempts to get a unique timestamp-based suffix for use with items added to a
13525: course via the Course Editor (e.g., folders, composite pages,
13526: group bulletin boards).
13527:
13528: Args: (first three required; six others optional)
13529:
13530: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13531: docssequence, or name of group
13532:
13533: 2. keyid (alphanumeric): name of temporary locking key in hash,
13534: e.g., num, boardids
13535:
13536: 3. namespace: name of gdbm file used to store suffixes already assigned;
13537: file will be named nohist_namespace.db
13538:
13539: 4. cdom: domain of course; default is current course domain from %env
13540:
13541: 5. cnum: course number; default is current course number from %env
13542:
13543: 6. idtype: set to concat if an additional digit is to be appended to the
13544: unix timestamp to form the suffix, if the plain timestamp is already
13545: in use. Default is to not do this, but simply increment the unix
13546: timestamp by 1 until a unique key is obtained.
13547:
13548: 7. who: holder of locking key; defaults to user:domain for user.
13549:
13550: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
13551: retrying); default is 3.
13552:
13553: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
13554:
13555: Returns:
13556:
13557: 1. suffix obtained (numeric)
13558:
13559: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13560:
13561: 3. error: contains (localized) error message if an error occurred.
13562:
13563:
13564: =back
13565:
13566: =head2 HTTP Helper Routines
13567:
13568: =over 4
13569:
13570: =item *
13571:
13572: escape() : unpack non-word characters into CGI-compatible hex codes
13573:
13574: =item *
13575:
13576: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13577:
13578: =back
13579:
13580: =head1 PRIVATE SUBROUTINES
13581:
13582: =head2 Underlying communication routines (Shouldn't call)
13583:
13584: =over 4
13585:
13586: =item *
13587:
13588: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13589:
13590: =item *
13591:
13592: reply() : uses subreply to send a message to remote machine, logs all failures
13593:
13594: =item *
13595:
13596: critical() : passes a critical message to another server; if cannot
13597: get through then place message in connection buffer directory and
13598: returns con_delayed, if incapable of saving message, returns
13599: con_failed
13600:
13601: =item *
13602:
13603: reconlonc() : tries to reconnect lonc client processes.
13604:
13605: =back
13606:
13607: =head2 Resource Access Logging
13608:
13609: =over 4
13610:
13611: =item *
13612:
13613: flushcourselogs() : flush (save) buffer logs and access logs
13614:
13615: =item *
13616:
13617: courselog($what) : save message for course in hash
13618:
13619: =item *
13620:
13621: courseacclog($what) : save message for course using &courselog(). Perform
13622: special processing for specific resource types (problems, exams, quizzes, etc).
13623:
13624: =item *
13625:
13626: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13627: as a PerlChildExitHandler
13628:
13629: =back
13630:
13631: =head2 Other
13632:
13633: =over 4
13634:
13635: =item *
13636:
13637: symblist($mapname,%newhash) : update symbolic storage links
13638:
13639: =back
13640:
13641: =cut
13642:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>