1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.1056.4.33.2.1 2012/02/01 18:27:09 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: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
80: %managerstab);
81:
82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
83: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
84: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
85: %courseownerbuf, %coursetypebuf,$locknum);
86:
87: use IO::Socket;
88: use GDBM_File;
89: use HTML::LCParser;
90: use Fcntl qw(:flock);
91: use Storable qw(thaw nfreeze);
92: use Time::HiRes qw( gettimeofday tv_interval );
93: use Cache::Memcached;
94: use Digest::MD5;
95: use Math::Random;
96: use File::MMagic;
97: use LONCAPA qw(:DEFAULT :match);
98: use LONCAPA::Configuration;
99: use File::Copy;
100:
101: my $readit;
102: my $max_connection_retries = 10; # Or some such value.
103:
104: require Exporter;
105:
106: our @ISA = qw (Exporter);
107: our @EXPORT = qw(%env);
108:
109:
110: # --------------------------------------------------------------------- Logging
111: {
112: my $logid;
113: sub instructor_log {
114: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
115: if (($cnum eq '') || ($cdom eq '')) {
116: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
117: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
118: }
119: $logid++;
120: my $now = time();
121: my $id=$now.'00000'.$$.'00000'.$logid;
122: return &Apache::lonnet::put('nohist_'.$hash_name,
123: { $id => {
124: 'exe_uname' => $env{'user.name'},
125: 'exe_udom' => $env{'user.domain'},
126: 'exe_time' => $now,
127: 'exe_ip' => $ENV{'REMOTE_ADDR'},
128: 'delflag' => $delflag,
129: 'logentry' => $storehash,
130: 'uname' => $uname,
131: 'udom' => $udom,
132: }
133: },$cdom,$cnum);
134: }
135: }
136:
137: sub logtouch {
138: my $execdir=$perlvar{'lonDaemons'};
139: unless (-e "$execdir/logs/lonnet.log") {
140: open(my $fh,">>$execdir/logs/lonnet.log");
141: close $fh;
142: }
143: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
144: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
145: }
146:
147: sub logthis {
148: my $message=shift;
149: my $execdir=$perlvar{'lonDaemons'};
150: my $now=time;
151: my $local=localtime($now);
152: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
153: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
154: print $fh $logstring;
155: close($fh);
156: }
157: return 1;
158: }
159:
160: sub logperm {
161: my $message=shift;
162: my $execdir=$perlvar{'lonDaemons'};
163: my $now=time;
164: my $local=localtime($now);
165: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
166: print $fh "$now:$message:$local\n";
167: close($fh);
168: }
169: return 1;
170: }
171:
172: sub create_connection {
173: my ($hostname,$lonid) = @_;
174: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
175: Type => SOCK_STREAM,
176: Timeout => 10);
177: return 0 if (!$client);
178: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
179: my $result = <$client>;
180: chomp($result);
181: return 1 if ($result eq 'done');
182: return 0;
183: }
184:
185: sub get_server_timezone {
186: my ($cnum,$cdom) = @_;
187: my $home=&homeserver($cnum,$cdom);
188: if ($home ne 'no_host') {
189: my $cachetime = 24*3600;
190: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
191: if (defined($cached)) {
192: return $timezone;
193: } else {
194: my $timezone = &reply('servertimezone',$home);
195: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
196: }
197: }
198: }
199:
200: sub get_server_distarch {
201: my ($lonhost,$ignore_cache) = @_;
202: if (defined($lonhost)) {
203: if (!defined(&hostname($lonhost))) {
204: return;
205: }
206: my $cachetime = 12*3600;
207: if (!$ignore_cache) {
208: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
209: if (defined($cached)) {
210: return $distarch;
211: }
212: }
213: my $rep = &reply('serverdistarch',$lonhost);
214: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
215: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
216: $rep eq '') {
217: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
218: }
219: }
220: return;
221: }
222:
223: sub get_server_loncaparev {
224: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
225: if (defined($lonhost)) {
226: if (!defined(&hostname($lonhost))) {
227: undef($lonhost);
228: }
229: }
230: if (!defined($lonhost)) {
231: if (defined(&domain($dom,'primary'))) {
232: $lonhost=&domain($dom,'primary');
233: if ($lonhost eq 'no_host') {
234: undef($lonhost);
235: }
236: }
237: }
238: if (defined($lonhost)) {
239: my $cachetime = 12*3600;
240: if (!$ignore_cache) {
241: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
242: if (defined($cached)) {
243: return $loncaparev;
244: }
245: }
246: my ($answer,$loncaparev);
247: my @ids=¤t_machine_ids();
248: if (grep(/^\Q$lonhost\E$/,@ids)) {
249: $answer = $perlvar{'lonVersion'};
250: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
251: $loncaparev = $1;
252: }
253: } else {
254: $answer = &reply('serverloncaparev',$lonhost);
255: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
256: if ($caller eq 'loncron') {
257: my $ua=new LWP::UserAgent;
258: $ua->timeout(4);
259: my $protocol = $protocol{$lonhost};
260: $protocol = 'http' if ($protocol ne 'https');
261: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
262: my $request=new HTTP::Request('GET',$url);
263: my $response=$ua->request($request);
264: unless ($response->is_error()) {
265: my $content = $response->content;
266: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
267: $loncaparev = $1;
268: }
269: }
270: } else {
271: $loncaparev = $loncaparevs{$lonhost};
272: }
273: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
274: $loncaparev = $1;
275: }
276: }
277: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
278: }
279: }
280:
281: sub get_server_homeID {
282: my ($hostname,$ignore_cache,$caller) = @_;
283: unless ($ignore_cache) {
284: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
285: if (defined($cached)) {
286: return $serverhomeID;
287: }
288: }
289: my $cachetime = 12*3600;
290: my $serverhomeID;
291: if ($caller eq 'loncron') {
292: my @machine_ids = &machine_ids($hostname);
293: foreach my $id (@machine_ids) {
294: my $response = &reply('serverhomeID',$id);
295: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
296: $serverhomeID = $response;
297: last;
298: }
299: }
300: if ($serverhomeID eq '') {
301: $serverhomeID = $machine_ids[-1];
302: }
303: } else {
304: $serverhomeID = $serverhomeIDs{$hostname};
305: }
306: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
307: }
308:
309: # -------------------------------------------------- Non-critical communication
310: sub subreply {
311: my ($cmd,$server)=@_;
312: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
313: #
314: # With loncnew process trimming, there's a timing hole between lonc server
315: # process exit and the master server picking up the listen on the AF_UNIX
316: # socket. In that time interval, a lock file will exist:
317:
318: my $lockfile=$peerfile.".lock";
319: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
320: sleep(1);
321: }
322: # At this point, either a loncnew parent is listening or an old lonc
323: # or loncnew child is listening so we can connect or everything's dead.
324: #
325: # We'll give the connection a few tries before abandoning it. If
326: # connection is not possible, we'll con_lost back to the client.
327: #
328: my $client;
329: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
330: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
331: Type => SOCK_STREAM,
332: Timeout => 10);
333: if ($client) {
334: last; # Connected!
335: } else {
336: &create_connection(&hostname($server),$server);
337: }
338: sleep(1); # Try again later if failed connection.
339: }
340: my $answer;
341: if ($client) {
342: print $client "sethost:$server:$cmd\n";
343: $answer=<$client>;
344: if (!$answer) { $answer="con_lost"; }
345: chomp($answer);
346: } else {
347: $answer = 'con_lost'; # Failed connection.
348: }
349: return $answer;
350: }
351:
352: sub reply {
353: my ($cmd,$server)=@_;
354: unless (defined(&hostname($server))) { return 'no_such_host'; }
355: my $answer=subreply($cmd,$server);
356: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
357: &logthis("<font color=\"blue\">WARNING:".
358: " $cmd to $server returned $answer</font>");
359: }
360: return $answer;
361: }
362:
363: # ----------------------------------------------------------- Send USR1 to lonc
364:
365: sub reconlonc {
366: my ($lonid) = @_;
367: my $hostname = &hostname($lonid);
368: if ($lonid) {
369: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
370: if ($hostname && -e $peerfile) {
371: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
372: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
373: Type => SOCK_STREAM,
374: Timeout => 10);
375: if ($client) {
376: print $client ("reset_retries\n");
377: my $answer=<$client>;
378: #reset just this one.
379: }
380: }
381: return;
382: }
383:
384: &logthis("Trying to reconnect lonc");
385: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
386: if (open(my $fh,"<$loncfile")) {
387: my $loncpid=<$fh>;
388: chomp($loncpid);
389: if (kill 0 => $loncpid) {
390: &logthis("lonc at pid $loncpid responding, sending USR1");
391: kill USR1 => $loncpid;
392: sleep 1;
393: } else {
394: &logthis(
395: "<font color=\"blue\">WARNING:".
396: " lonc at pid $loncpid not responding, giving up</font>");
397: }
398: } else {
399: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
400: }
401: }
402:
403: # ------------------------------------------------------ Critical communication
404:
405: sub critical {
406: my ($cmd,$server)=@_;
407: unless (&hostname($server)) {
408: &logthis("<font color=\"blue\">WARNING:".
409: " Critical message to unknown server ($server)</font>");
410: return 'no_such_host';
411: }
412: my $answer=reply($cmd,$server);
413: if ($answer eq 'con_lost') {
414: &reconlonc("$perlvar{'lonSockDir'}/$server");
415: my $answer=reply($cmd,$server);
416: if ($answer eq 'con_lost') {
417: my $now=time;
418: my $middlename=$cmd;
419: $middlename=substr($middlename,0,16);
420: $middlename=~s/\W//g;
421: my $dfilename=
422: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
423: $dumpcount++;
424: {
425: my $dfh;
426: if (open($dfh,">$dfilename")) {
427: print $dfh "$cmd\n";
428: close($dfh);
429: }
430: }
431: sleep 2;
432: my $wcmd='';
433: {
434: my $dfh;
435: if (open($dfh,"<$dfilename")) {
436: $wcmd=<$dfh>;
437: close($dfh);
438: }
439: }
440: chomp($wcmd);
441: if ($wcmd eq $cmd) {
442: &logthis("<font color=\"blue\">WARNING: ".
443: "Connection buffer $dfilename: $cmd</font>");
444: &logperm("D:$server:$cmd");
445: return 'con_delayed';
446: } else {
447: &logthis("<font color=\"red\">CRITICAL:"
448: ." Critical connection failed: $server $cmd</font>");
449: &logperm("F:$server:$cmd");
450: return 'con_failed';
451: }
452: }
453: }
454: return $answer;
455: }
456:
457: # ------------------------------------------- check if return value is an error
458:
459: sub error {
460: my ($result) = @_;
461: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
462: if ($2 == 2) { return undef; }
463: return $1;
464: }
465: return undef;
466: }
467:
468: sub convert_and_load_session_env {
469: my ($lonidsdir,$handle)=@_;
470: my @profile;
471: {
472: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
473: if (!$opened) {
474: return 0;
475: }
476: flock($idf,LOCK_SH);
477: @profile=<$idf>;
478: close($idf);
479: }
480: my %temp_env;
481: foreach my $line (@profile) {
482: if ($line !~ m/=/) {
483: return 0;
484: }
485: chomp($line);
486: my ($envname,$envvalue)=split(/=/,$line,2);
487: $temp_env{&unescape($envname)} = &unescape($envvalue);
488: }
489: unlink("$lonidsdir/$handle.id");
490: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
491: 0640)) {
492: %disk_env = %temp_env;
493: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
494: untie(%disk_env);
495: }
496: return 1;
497: }
498:
499: # ------------------------------------------- Transfer profile into environment
500: my $env_loaded;
501: sub transfer_profile_to_env {
502: my ($lonidsdir,$handle,$force_transfer) = @_;
503: if (!$force_transfer && $env_loaded) { return; }
504:
505: if (!defined($lonidsdir)) {
506: $lonidsdir = $perlvar{'lonIDsDir'};
507: }
508: if (!defined($handle)) {
509: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
510: }
511:
512: my $convert;
513: {
514: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
515: if (!$opened) {
516: return;
517: }
518: flock($idf,LOCK_SH);
519: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
520: &GDBM_READER(),0640)) {
521: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
522: untie(%disk_env);
523: } else {
524: $convert = 1;
525: }
526: }
527: if ($convert) {
528: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
529: &logthis("Failed to load session, or convert session.");
530: }
531: }
532:
533: my %remove;
534: while ( my $envname = each(%env) ) {
535: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
536: if ($time < time-300) {
537: $remove{$key}++;
538: }
539: }
540: }
541:
542: $env{'user.environment'} = "$lonidsdir/$handle.id";
543: $env_loaded=1;
544: foreach my $expired_key (keys(%remove)) {
545: &delenv($expired_key);
546: }
547: }
548:
549: # ---------------------------------------------------- Check for valid session
550: sub check_for_valid_session {
551: my ($r) = @_;
552: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
553: my $lonid=$cookies{'lonID'};
554: return undef if (!$lonid);
555:
556: my $handle=&LONCAPA::clean_handle($lonid->value);
557: my $lonidsdir=$r->dir_config('lonIDsDir');
558: return undef if (!-e "$lonidsdir/$handle.id");
559:
560: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
561: return undef if (!$opened);
562:
563: flock($idf,LOCK_SH);
564: my %disk_env;
565: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
566: &GDBM_READER(),0640)) {
567: return undef;
568: }
569:
570: if (!defined($disk_env{'user.name'})
571: || !defined($disk_env{'user.domain'})) {
572: return undef;
573: }
574: return $handle;
575: }
576:
577: sub timed_flock {
578: my ($file,$lock_type) = @_;
579: my $failed=0;
580: eval {
581: local $SIG{__DIE__}='DEFAULT';
582: local $SIG{ALRM}=sub {
583: $failed=1;
584: die("failed lock");
585: };
586: alarm(13);
587: flock($file,$lock_type);
588: alarm(0);
589: };
590: if ($failed) {
591: return undef;
592: } else {
593: return 1;
594: }
595: }
596:
597: # ---------------------------------------------------------- Append Environment
598:
599: sub appenv {
600: my ($newenv,$roles) = @_;
601: if (ref($newenv) eq 'HASH') {
602: foreach my $key (keys(%{$newenv})) {
603: my $refused = 0;
604: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
605: $refused = 1;
606: if (ref($roles) eq 'ARRAY') {
607: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
608: if (grep(/^\Q$role\E$/,@{$roles})) {
609: $refused = 0;
610: }
611: }
612: }
613: if ($refused) {
614: &logthis("<font color=\"blue\">WARNING: ".
615: "Attempt to modify environment ".$key." to ".$newenv->{$key}
616: .'</font>');
617: delete($newenv->{$key});
618: } else {
619: $env{$key}=$newenv->{$key};
620: }
621: }
622: my $opened = open(my $env_file,'+<',$env{'user.environment'});
623: if ($opened
624: && &timed_flock($env_file,LOCK_EX)
625: &&
626: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
627: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
628: while (my ($key,$value) = each(%{$newenv})) {
629: $disk_env{$key} = $value;
630: }
631: untie(%disk_env);
632: }
633: }
634: return 'ok';
635: }
636: # ----------------------------------------------------- Delete from Environment
637:
638: sub delenv {
639: my ($delthis,$regexp) = @_;
640: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
641: &logthis("<font color=\"blue\">WARNING: ".
642: "Attempt to delete from environment ".$delthis);
643: return 'error';
644: }
645: my $opened = open(my $env_file,'+<',$env{'user.environment'});
646: if ($opened
647: && &timed_flock($env_file,LOCK_EX)
648: &&
649: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
650: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
651: foreach my $key (keys(%disk_env)) {
652: if ($regexp) {
653: if ($key=~/^$delthis/) {
654: delete($env{$key});
655: delete($disk_env{$key});
656: }
657: } else {
658: if ($key=~/^\Q$delthis\E/) {
659: delete($env{$key});
660: delete($disk_env{$key});
661: }
662: }
663: }
664: untie(%disk_env);
665: }
666: return 'ok';
667: }
668:
669: sub get_env_multiple {
670: my ($name) = @_;
671: my @values;
672: if (defined($env{$name})) {
673: # exists is it an array
674: if (ref($env{$name})) {
675: @values=@{ $env{$name} };
676: } else {
677: $values[0]=$env{$name};
678: }
679: }
680: return(@values);
681: }
682:
683: # ------------------------------------------------------------------- Locking
684:
685: sub set_lock {
686: my ($text)=@_;
687: $locknum++;
688: my $id=$$.'-'.$locknum;
689: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
690: 'session.lock.'.$id => $text});
691: return $id;
692: }
693:
694: sub get_locks {
695: my $num=0;
696: my %texts=();
697: foreach my $lock (split(/\,/,$env{'session.locks'})) {
698: if ($lock=~/\w/) {
699: $num++;
700: $texts{$lock}=$env{'session.lock.'.$lock};
701: }
702: }
703: return ($num,%texts);
704: }
705:
706: sub remove_lock {
707: my ($id)=@_;
708: my $newlocks='';
709: foreach my $lock (split(/\,/,$env{'session.locks'})) {
710: if (($lock=~/\w/) && ($lock ne $id)) {
711: $newlocks.=','.$lock;
712: }
713: }
714: &appenv({'session.locks' => $newlocks});
715: &delenv('session.lock.'.$id);
716: }
717:
718: sub remove_all_locks {
719: my $activelocks=$env{'session.locks'};
720: foreach my $lock (split(/\,/,$env{'session.locks'})) {
721: if ($lock=~/\w/) {
722: &remove_lock($lock);
723: }
724: }
725: }
726:
727:
728: # ------------------------------------------ Find out current server userload
729: sub userload {
730: my $numusers=0;
731: {
732: opendir(LONIDS,$perlvar{'lonIDsDir'});
733: my $filename;
734: my $curtime=time;
735: while ($filename=readdir(LONIDS)) {
736: next if ($filename eq '.' || $filename eq '..');
737: next if ($filename =~ /publicuser_\d+\.id/);
738: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
739: if ($curtime-$mtime < 1800) { $numusers++; }
740: }
741: closedir(LONIDS);
742: }
743: my $userloadpercent=0;
744: my $maxuserload=$perlvar{'lonUserLoadLim'};
745: if ($maxuserload) {
746: $userloadpercent=100*$numusers/$maxuserload;
747: }
748: $userloadpercent=sprintf("%.2f",$userloadpercent);
749: return $userloadpercent;
750: }
751:
752: # ------------------------------------------ Fight off request when overloaded
753:
754: sub overloaderror {
755: my ($r,$checkserver)=@_;
756: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
757: my $loadavg;
758: if ($checkserver eq $perlvar{'lonHostID'}) {
759: open(my $loadfile,'/proc/loadavg');
760: $loadavg=<$loadfile>;
761: $loadavg =~ s/\s.*//g;
762: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
763: close($loadfile);
764: } else {
765: $loadavg=&reply('load',$checkserver);
766: }
767: my $overload=$loadavg-100;
768: if ($overload>0) {
769: $r->err_headers_out->{'Retry-After'}=$overload;
770: $r->log_error('Overload of '.$overload.' on '.$checkserver);
771: return 413;
772: }
773: return '';
774: }
775:
776: # ------------------------------ Find server with least workload from spare.tab
777:
778: sub spareserver {
779: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
780: my $spare_server;
781: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
782: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
783: : $userloadpercent;
784: my ($uint_dom,$remotesessions);
785: if (($udom ne '') && (&domain($udom) ne '')) {
786: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
787: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
788: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
789: $remotesessions = $udomdefaults{'remotesessions'};
790: }
791: foreach my $try_server (@{ $spareid{'primary'} }) {
792: if ($uint_dom) {
793: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
794: $try_server));
795: }
796: ($spare_server, $lowest_load) =
797: &compare_server_load($try_server, $spare_server, $lowest_load);
798: }
799:
800: my $found_server = ($spare_server ne '' && $lowest_load < 100);
801:
802: if (!$found_server) {
803: foreach my $try_server (@{ $spareid{'default'} }) {
804: if ($uint_dom) {
805: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
806: $try_server));
807: }
808: ($spare_server, $lowest_load) =
809: &compare_server_load($try_server, $spare_server, $lowest_load);
810: }
811: }
812:
813: if (!$want_server_name) {
814: my $protocol = 'http';
815: if ($protocol{$spare_server} eq 'https') {
816: $protocol = $protocol{$spare_server};
817: }
818: if (defined($spare_server)) {
819: my $hostname = &hostname($spare_server);
820: if (defined($hostname)) {
821: $spare_server = $protocol.'://'.$hostname;
822: }
823: }
824: }
825: return $spare_server;
826: }
827:
828: sub compare_server_load {
829: my ($try_server, $spare_server, $lowest_load) = @_;
830:
831: my $loadans = &reply('load', $try_server);
832: my $userloadans = &reply('userload',$try_server);
833:
834: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
835: return ($spare_server, $lowest_load); #didn't get a number from the server
836: }
837:
838: my $load;
839: if ($loadans =~ /\d/) {
840: if ($userloadans =~ /\d/) {
841: #both are numbers, pick the bigger one
842: $load = ($loadans > $userloadans) ? $loadans
843: : $userloadans;
844: } else {
845: $load = $loadans;
846: }
847: } else {
848: $load = $userloadans;
849: }
850:
851: if (($load =~ /\d/) && ($load < $lowest_load)) {
852: $spare_server = $try_server;
853: $lowest_load = $load;
854: }
855: return ($spare_server,$lowest_load);
856: }
857:
858: # --------------------------- ask offload servers if user already has a session
859: sub find_existing_session {
860: my ($udom,$uname) = @_;
861: foreach my $try_server (@{ $spareid{'primary'} },
862: @{ $spareid{'default'} }) {
863: return $try_server if (&has_user_session($try_server, $udom, $uname));
864: }
865: return;
866: }
867:
868: # -------------------------------- ask if server already has a session for user
869: sub has_user_session {
870: my ($lonid,$udom,$uname) = @_;
871: my $result = &reply(join(':','userhassession',
872: map {&escape($_)} ($udom,$uname)),$lonid);
873: return 1 if ($result eq 'ok');
874:
875: return 0;
876: }
877:
878: # --------- determine least loaded server in a user's domain which allows login
879:
880: sub choose_server {
881: my ($udom,$checkloginvia) = @_;
882: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
883: my %servers = &get_servers($udom);
884: my $lowest_load = 30000;
885: my ($login_host,$hostname,$portal_path,$isredirect);
886: foreach my $lonhost (keys(%servers)) {
887: my $loginvia;
888: if ($checkloginvia) {
889: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
890: if ($loginvia) {
891: my ($server,$path) = split(/:/,$loginvia);
892: ($login_host, $lowest_load) =
893: &compare_server_load($lonhost, $login_host, $lowest_load);
894: if ($login_host eq $server) {
895: $portal_path = $path;
896: $isredirect = 1;
897: }
898: } else {
899: ($login_host, $lowest_load) =
900: &compare_server_load($lonhost, $login_host, $lowest_load);
901: if ($login_host eq $lonhost) {
902: $portal_path = '';
903: $isredirect = '';
904: }
905: }
906: } else {
907: ($login_host, $lowest_load) =
908: &compare_server_load($lonhost, $login_host, $lowest_load);
909: }
910: }
911: if ($login_host ne '') {
912: $hostname = &hostname($login_host);
913: }
914: return ($login_host,$hostname,$portal_path,$isredirect);
915: }
916:
917: # --------------------------------------------- Try to change a user's password
918:
919: sub changepass {
920: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
921: $currentpass = &escape($currentpass);
922: $newpass = &escape($newpass);
923: my $lonhost = $perlvar{'lonHostID'};
924: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
925: $server);
926: if (! $answer) {
927: &logthis("No reply on password change request to $server ".
928: "by $uname in domain $udom.");
929: } elsif ($answer =~ "^ok") {
930: &logthis("$uname in $udom successfully changed their password ".
931: "on $server.");
932: } elsif ($answer =~ "^pwchange_failure") {
933: &logthis("$uname in $udom was unable to change their password ".
934: "on $server. The action was blocked by either lcpasswd ".
935: "or pwchange");
936: } elsif ($answer =~ "^non_authorized") {
937: &logthis("$uname in $udom did not get their password correct when ".
938: "attempting to change it on $server.");
939: } elsif ($answer =~ "^auth_mode_error") {
940: &logthis("$uname in $udom attempted to change their password despite ".
941: "not being locally or internally authenticated on $server.");
942: } elsif ($answer =~ "^unknown_user") {
943: &logthis("$uname in $udom attempted to change their password ".
944: "on $server but were unable to because $server is not ".
945: "their home server.");
946: } elsif ($answer =~ "^refused") {
947: &logthis("$server refused to change $uname in $udom password because ".
948: "it was sent an unencrypted request to change the password.");
949: } elsif ($answer =~ "invalid_client") {
950: &logthis("$server refused to change $uname in $udom password because ".
951: "it was a reset by e-mail originating from an invalid server.");
952: }
953: return $answer;
954: }
955:
956: # ----------------------- Try to determine user's current authentication scheme
957:
958: sub queryauthenticate {
959: my ($uname,$udom)=@_;
960: my $uhome=&homeserver($uname,$udom);
961: if (!$uhome) {
962: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
963: return 'no_host';
964: }
965: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
966: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
967: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
968: }
969: return $answer;
970: }
971:
972: # --------- Try to authenticate user from domain's lib servers (first this one)
973:
974: sub authenticate {
975: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
976: $upass=&escape($upass);
977: $uname= &LONCAPA::clean_username($uname);
978: my $uhome=&homeserver($uname,$udom,1);
979: my $newhome;
980: if ((!$uhome) || ($uhome eq 'no_host')) {
981: # Maybe the machine was offline and only re-appeared again recently?
982: &reconlonc();
983: # One more
984: $uhome=&homeserver($uname,$udom,1);
985: if (($uhome eq 'no_host') && $checkdefauth) {
986: if (defined(&domain($udom,'primary'))) {
987: $newhome=&domain($udom,'primary');
988: }
989: if ($newhome ne '') {
990: $uhome = $newhome;
991: }
992: }
993: if ((!$uhome) || ($uhome eq 'no_host')) {
994: &logthis("User $uname at $udom is unknown in authenticate");
995: return 'no_host';
996: }
997: }
998: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
999: if ($answer eq 'authorized') {
1000: if ($newhome) {
1001: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1002: return 'no_account_on_host';
1003: } else {
1004: &logthis("User $uname at $udom authorized by $uhome");
1005: return $uhome;
1006: }
1007: }
1008: if ($answer eq 'non_authorized') {
1009: &logthis("User $uname at $udom rejected by $uhome");
1010: return 'no_host';
1011: }
1012: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1013: return 'no_host';
1014: }
1015:
1016: sub can_host_session {
1017: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1018: my $canhost = 1;
1019: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1020: if (ref($remotesessions) eq 'HASH') {
1021: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1022: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1023: $canhost = 0;
1024: } else {
1025: $canhost = 1;
1026: }
1027: }
1028: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1029: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1030: $canhost = 1;
1031: } else {
1032: $canhost = 0;
1033: }
1034: }
1035: if ($canhost) {
1036: if ($remotesessions->{'version'} ne '') {
1037: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1038: if ($reqmajor ne '' && $reqminor ne '') {
1039: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1040: my $major = $1;
1041: my $minor = $2;
1042: if (($major < $reqmajor ) ||
1043: (($major == $reqmajor) && ($minor < $reqminor))) {
1044: $canhost = 0;
1045: }
1046: } else {
1047: $canhost = 0;
1048: }
1049: }
1050: }
1051: }
1052: }
1053: if ($canhost) {
1054: if (ref($hostedsessions) eq 'HASH') {
1055: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1056: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1057: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1058: if (($uint_dom ne '') &&
1059: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1060: $canhost = 0;
1061: } else {
1062: $canhost = 1;
1063: }
1064: }
1065: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1066: if (($uint_dom ne '') &&
1067: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1068: $canhost = 1;
1069: } else {
1070: $canhost = 0;
1071: }
1072: }
1073: }
1074: }
1075: return $canhost;
1076: }
1077:
1078: sub spare_can_host {
1079: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1080: my $canhost=1;
1081: my @intdoms;
1082: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1083: if (ref($internet_names) eq 'ARRAY') {
1084: @intdoms = @{$internet_names};
1085: }
1086: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1087: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1088: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1089: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1090: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1091: $canhost = &can_host_session($udom,$try_server,$remoterev,
1092: $remotesessions,
1093: $defdomdefaults{'hostedsessions'});
1094: }
1095: return $canhost;
1096: }
1097:
1098: # ---------------------- Find the homebase for a user from domain's lib servers
1099:
1100: my %homecache;
1101: sub homeserver {
1102: my ($uname,$udom,$ignoreBadCache)=@_;
1103: my $index="$uname:$udom";
1104:
1105: if (exists($homecache{$index})) { return $homecache{$index}; }
1106:
1107: my %servers = &get_servers($udom,'library');
1108: foreach my $tryserver (keys(%servers)) {
1109: next if ($ignoreBadCache ne 'true' &&
1110: exists($badServerCache{$tryserver}));
1111:
1112: my $answer=reply("home:$udom:$uname",$tryserver);
1113: if ($answer eq 'found') {
1114: delete($badServerCache{$tryserver});
1115: return $homecache{$index}=$tryserver;
1116: } elsif ($answer eq 'no_host') {
1117: $badServerCache{$tryserver}=1;
1118: }
1119: }
1120: return 'no_host';
1121: }
1122:
1123: # ------------------------------------- Find the usernames behind a list of IDs
1124:
1125: sub idget {
1126: my ($udom,@ids)=@_;
1127: my %returnhash=();
1128:
1129: my %servers = &get_servers($udom,'library');
1130: foreach my $tryserver (keys(%servers)) {
1131: my $idlist=join('&',@ids);
1132: $idlist=~tr/A-Z/a-z/;
1133: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1134: my @answer=();
1135: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1136: @answer=split(/\&/,$reply);
1137: } ;
1138: my $i;
1139: for ($i=0;$i<=$#ids;$i++) {
1140: if ($answer[$i]) {
1141: $returnhash{$ids[$i]}=$answer[$i];
1142: }
1143: }
1144: }
1145: return %returnhash;
1146: }
1147:
1148: # ------------------------------------- Find the IDs behind a list of usernames
1149:
1150: sub idrget {
1151: my ($udom,@unames)=@_;
1152: my %returnhash=();
1153: foreach my $uname (@unames) {
1154: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1155: }
1156: return %returnhash;
1157: }
1158:
1159: # ------------------------------- Store away a list of names and associated IDs
1160:
1161: sub idput {
1162: my ($udom,%ids)=@_;
1163: my %servers=();
1164: foreach my $uname (keys(%ids)) {
1165: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1166: my $uhom=&homeserver($uname,$udom);
1167: if ($uhom ne 'no_host') {
1168: my $id=&escape($ids{$uname});
1169: $id=~tr/A-Z/a-z/;
1170: my $esc_unam=&escape($uname);
1171: if ($servers{$uhom}) {
1172: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1173: } else {
1174: $servers{$uhom}=$id.'='.$esc_unam;
1175: }
1176: }
1177: }
1178: foreach my $server (keys(%servers)) {
1179: &critical('idput:'.$udom.':'.$servers{$server},$server);
1180: }
1181: }
1182:
1183: # ------------------------------dump from db file owned by domainconfig user
1184: sub dump_dom {
1185: my ($namespace,$udom,$regexp,$range)=@_;
1186: if (!$udom) {
1187: $udom=$env{'user.domain'};
1188: }
1189: my %returnhash;
1190: if ($udom) {
1191: my $uname = &get_domainconfiguser($udom);
1192: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1193: }
1194: return %returnhash;
1195: }
1196:
1197: # ------------------------------------------ get items from domain db files
1198:
1199: sub get_dom {
1200: my ($namespace,$storearr,$udom,$uhome)=@_;
1201: my $items='';
1202: foreach my $item (@$storearr) {
1203: $items.=&escape($item).'&';
1204: }
1205: $items=~s/\&$//;
1206: if (!$udom) {
1207: $udom=$env{'user.domain'};
1208: if (defined(&domain($udom,'primary'))) {
1209: $uhome=&domain($udom,'primary');
1210: } else {
1211: undef($uhome);
1212: }
1213: } else {
1214: if (!$uhome) {
1215: if (defined(&domain($udom,'primary'))) {
1216: $uhome=&domain($udom,'primary');
1217: }
1218: }
1219: }
1220: if ($udom && $uhome && ($uhome ne 'no_host')) {
1221: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1222: my %returnhash;
1223: if ($rep eq '' || $rep =~ /^error: 2 /) {
1224: return %returnhash;
1225: }
1226: my @pairs=split(/\&/,$rep);
1227: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1228: return @pairs;
1229: }
1230: my $i=0;
1231: foreach my $item (@$storearr) {
1232: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1233: $i++;
1234: }
1235: return %returnhash;
1236: } else {
1237: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1238: }
1239: }
1240:
1241: # -------------------------------------------- put items in domain db files
1242:
1243: sub put_dom {
1244: my ($namespace,$storehash,$udom,$uhome)=@_;
1245: if (!$udom) {
1246: $udom=$env{'user.domain'};
1247: if (defined(&domain($udom,'primary'))) {
1248: $uhome=&domain($udom,'primary');
1249: } else {
1250: undef($uhome);
1251: }
1252: } else {
1253: if (!$uhome) {
1254: if (defined(&domain($udom,'primary'))) {
1255: $uhome=&domain($udom,'primary');
1256: }
1257: }
1258: }
1259: if ($udom && $uhome && ($uhome ne 'no_host')) {
1260: my $items='';
1261: foreach my $item (keys(%$storehash)) {
1262: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1263: }
1264: $items=~s/\&$//;
1265: return &reply("putdom:$udom:$namespace:$items",$uhome);
1266: } else {
1267: &logthis("put_dom failed - no homeserver and/or domain");
1268: }
1269: }
1270:
1271: # --------------------- newput for items in db file owned by domainconfig user
1272: sub newput_dom {
1273: my ($namespace,$storehash,$udom) = @_;
1274: my $result;
1275: if (!$udom) {
1276: $udom=$env{'user.domain'};
1277: }
1278: if ($udom) {
1279: my $uname = &get_domainconfiguser($udom);
1280: $result = &newput($namespace,$storehash,$udom,$uname);
1281: }
1282: return $result;
1283: }
1284:
1285: # --------------------- delete for items in db file owned by domainconfig user
1286: sub del_dom {
1287: my ($namespace,$storearr,$udom)=@_;
1288: if (ref($storearr) eq 'ARRAY') {
1289: if (!$udom) {
1290: $udom=$env{'user.domain'};
1291: }
1292: if ($udom) {
1293: my $uname = &get_domainconfiguser($udom);
1294: return &del($namespace,$storearr,$udom,$uname);
1295: }
1296: }
1297: }
1298:
1299: # ----------------------------------construct domainconfig user for a domain
1300: sub get_domainconfiguser {
1301: my ($udom) = @_;
1302: return $udom.'-domainconfig';
1303: }
1304:
1305: sub retrieve_inst_usertypes {
1306: my ($udom) = @_;
1307: my (%returnhash,@order);
1308: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1309: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1310: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1311: %returnhash = %{$domdefs{'inststatustypes'}};
1312: @order = @{$domdefs{'inststatusorder'}};
1313: } else {
1314: if (defined(&domain($udom,'primary'))) {
1315: my $uhome=&domain($udom,'primary');
1316: my $rep=&reply("inst_usertypes:$udom",$uhome);
1317: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1318: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1319: return (\%returnhash,\@order);
1320: }
1321: my ($hashitems,$orderitems) = split(/:/,$rep);
1322: my @pairs=split(/\&/,$hashitems);
1323: foreach my $item (@pairs) {
1324: my ($key,$value)=split(/=/,$item,2);
1325: $key = &unescape($key);
1326: next if ($key =~ /^error: 2 /);
1327: $returnhash{$key}=&thaw_unescape($value);
1328: }
1329: my @esc_order = split(/\&/,$orderitems);
1330: foreach my $item (@esc_order) {
1331: push(@order,&unescape($item));
1332: }
1333: } else {
1334: &logthis("get_dom failed - no primary domain server for $udom");
1335: }
1336: }
1337: return (\%returnhash,\@order);
1338: }
1339:
1340: sub is_domainimage {
1341: my ($url) = @_;
1342: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1343: if (&domain($1) ne '') {
1344: return '1';
1345: }
1346: }
1347: return;
1348: }
1349:
1350: sub inst_directory_query {
1351: my ($srch) = @_;
1352: my $udom = $srch->{'srchdomain'};
1353: my %results;
1354: my $homeserver = &domain($udom,'primary');
1355: my $outcome;
1356: if ($homeserver ne '') {
1357: my $queryid=&reply("querysend:instdirsearch:".
1358: &escape($srch->{'srchby'}).':'.
1359: &escape($srch->{'srchterm'}).':'.
1360: &escape($srch->{'srchtype'}),$homeserver);
1361: my $host=&hostname($homeserver);
1362: if ($queryid !~/^\Q$host\E\_/) {
1363: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1364: return;
1365: }
1366: my $response = &get_query_reply($queryid);
1367: my $maxtries = 5;
1368: my $tries = 1;
1369: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1370: $response = &get_query_reply($queryid);
1371: $tries ++;
1372: }
1373:
1374: if (!&error($response) && $response ne 'refused') {
1375: if ($response eq 'unavailable') {
1376: $outcome = $response;
1377: } else {
1378: $outcome = 'ok';
1379: my @matches = split(/\n/,$response);
1380: foreach my $match (@matches) {
1381: my ($key,$value) = split(/=/,$match);
1382: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1383: }
1384: }
1385: }
1386: }
1387: return ($outcome,%results);
1388: }
1389:
1390: sub usersearch {
1391: my ($srch) = @_;
1392: my $dom = $srch->{'srchdomain'};
1393: my %results;
1394: my %libserv = &all_library();
1395: my $query = 'usersearch';
1396: foreach my $tryserver (keys(%libserv)) {
1397: if (&host_domain($tryserver) eq $dom) {
1398: my $host=&hostname($tryserver);
1399: my $queryid=
1400: &reply("querysend:".&escape($query).':'.
1401: &escape($srch->{'srchby'}).':'.
1402: &escape($srch->{'srchtype'}).':'.
1403: &escape($srch->{'srchterm'}),$tryserver);
1404: if ($queryid !~/^\Q$host\E\_/) {
1405: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1406: next;
1407: }
1408: my $reply = &get_query_reply($queryid);
1409: my $maxtries = 1;
1410: my $tries = 1;
1411: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1412: $reply = &get_query_reply($queryid);
1413: $tries ++;
1414: }
1415: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1416: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1417: } else {
1418: my @matches;
1419: if ($reply =~ /\n/) {
1420: @matches = split(/\n/,$reply);
1421: } else {
1422: @matches = split(/\&/,$reply);
1423: }
1424: foreach my $match (@matches) {
1425: my ($uname,$udom,%userhash);
1426: foreach my $entry (split(/:/,$match)) {
1427: my ($key,$value) =
1428: map {&unescape($_);} split(/=/,$entry);
1429: $userhash{$key} = $value;
1430: if ($key eq 'username') {
1431: $uname = $value;
1432: } elsif ($key eq 'domain') {
1433: $udom = $value;
1434: }
1435: }
1436: $results{$uname.':'.$udom} = \%userhash;
1437: }
1438: }
1439: }
1440: }
1441: return %results;
1442: }
1443:
1444: sub get_instuser {
1445: my ($udom,$uname,$id) = @_;
1446: my $homeserver = &domain($udom,'primary');
1447: my ($outcome,%results);
1448: if ($homeserver ne '') {
1449: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1450: &escape($id).':'.&escape($udom),$homeserver);
1451: my $host=&hostname($homeserver);
1452: if ($queryid !~/^\Q$host\E\_/) {
1453: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1454: return;
1455: }
1456: my $response = &get_query_reply($queryid);
1457: my $maxtries = 5;
1458: my $tries = 1;
1459: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1460: $response = &get_query_reply($queryid);
1461: $tries ++;
1462: }
1463: if (!&error($response) && $response ne 'refused') {
1464: if ($response eq 'unavailable') {
1465: $outcome = $response;
1466: } else {
1467: $outcome = 'ok';
1468: my @matches = split(/\n/,$response);
1469: foreach my $match (@matches) {
1470: my ($key,$value) = split(/=/,$match);
1471: $results{&unescape($key)} = &thaw_unescape($value);
1472: }
1473: }
1474: }
1475: }
1476: my %userinfo;
1477: if (ref($results{$uname}) eq 'HASH') {
1478: %userinfo = %{$results{$uname}};
1479: }
1480: return ($outcome,%userinfo);
1481: }
1482:
1483: sub inst_rulecheck {
1484: my ($udom,$uname,$id,$item,$rules) = @_;
1485: my %returnhash;
1486: if ($udom ne '') {
1487: if (ref($rules) eq 'ARRAY') {
1488: @{$rules} = map {&escape($_);} (@{$rules});
1489: my $rulestr = join(':',@{$rules});
1490: my $homeserver=&domain($udom,'primary');
1491: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1492: my $response;
1493: if ($item eq 'username') {
1494: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1495: ':'.&escape($uname).':'.$rulestr,
1496: $homeserver));
1497: } elsif ($item eq 'id') {
1498: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1499: ':'.&escape($id).':'.$rulestr,
1500: $homeserver));
1501: } elsif ($item eq 'selfcreate') {
1502: $response=&unescape(&reply('instselfcreatecheck:'.
1503: &escape($udom).':'.&escape($uname).
1504: ':'.$rulestr,$homeserver));
1505: }
1506: if ($response ne 'refused') {
1507: my @pairs=split(/\&/,$response);
1508: foreach my $item (@pairs) {
1509: my ($key,$value)=split(/=/,$item,2);
1510: $key = &unescape($key);
1511: next if ($key =~ /^error: 2 /);
1512: $returnhash{$key}=&thaw_unescape($value);
1513: }
1514: }
1515: }
1516: }
1517: }
1518: return %returnhash;
1519: }
1520:
1521: sub inst_userrules {
1522: my ($udom,$check) = @_;
1523: my (%ruleshash,@ruleorder);
1524: if ($udom ne '') {
1525: my $homeserver=&domain($udom,'primary');
1526: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1527: my $response;
1528: if ($check eq 'id') {
1529: $response=&reply('instidrules:'.&escape($udom),
1530: $homeserver);
1531: } elsif ($check eq 'email') {
1532: $response=&reply('instemailrules:'.&escape($udom),
1533: $homeserver);
1534: } else {
1535: $response=&reply('instuserrules:'.&escape($udom),
1536: $homeserver);
1537: }
1538: if (($response ne 'refused') && ($response ne 'error') &&
1539: ($response ne 'unknown_cmd') &&
1540: ($response ne 'no_such_host')) {
1541: my ($hashitems,$orderitems) = split(/:/,$response);
1542: my @pairs=split(/\&/,$hashitems);
1543: foreach my $item (@pairs) {
1544: my ($key,$value)=split(/=/,$item,2);
1545: $key = &unescape($key);
1546: next if ($key =~ /^error: 2 /);
1547: $ruleshash{$key}=&thaw_unescape($value);
1548: }
1549: my @esc_order = split(/\&/,$orderitems);
1550: foreach my $item (@esc_order) {
1551: push(@ruleorder,&unescape($item));
1552: }
1553: }
1554: }
1555: }
1556: return (\%ruleshash,\@ruleorder);
1557: }
1558:
1559: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1560:
1561: sub get_domain_defaults {
1562: my ($domain) = @_;
1563: my $cachetime = 60*60*24;
1564: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1565: if (defined($cached)) {
1566: if (ref($result) eq 'HASH') {
1567: return %{$result};
1568: }
1569: }
1570: my %domdefaults;
1571: my %domconfig =
1572: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1573: 'requestcourses','inststatus',
1574: 'coursedefaults','usersessions'],$domain);
1575: if (ref($domconfig{'defaults'}) eq 'HASH') {
1576: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1577: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1578: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1579: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1580: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1581: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1582: } else {
1583: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1584: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1585: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1586: }
1587: if (ref($domconfig{'quotas'}) eq 'HASH') {
1588: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1589: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1590: } else {
1591: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1592: }
1593: my @usertools = ('aboutme','blog','portfolio');
1594: foreach my $item (@usertools) {
1595: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1596: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1597: }
1598: }
1599: }
1600: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1601: foreach my $item ('official','unofficial','community') {
1602: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1603: }
1604: }
1605: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1606: foreach my $item ('inststatustypes','inststatusorder') {
1607: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1608: }
1609: }
1610: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1611: foreach my $item ('canuse_pdfforms') {
1612: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1613: }
1614: }
1615: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1616: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1617: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1618: }
1619: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1620: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1621: }
1622: }
1623: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1624: $cachetime);
1625: return %domdefaults;
1626: }
1627:
1628: # --------------------------------------------------- Assign a key to a student
1629:
1630: sub assign_access_key {
1631: #
1632: # a valid key looks like uname:udom#comments
1633: # comments are being appended
1634: #
1635: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1636: $kdom=
1637: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1638: $knum=
1639: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1640: $cdom=
1641: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1642: $cnum=
1643: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1644: $udom=$env{'user.name'} unless (defined($udom));
1645: $uname=$env{'user.domain'} unless (defined($uname));
1646: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1647: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1648: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1649: # assigned to this person
1650: # - this should not happen,
1651: # unless something went wrong
1652: # the first time around
1653: # ready to assign
1654: $logentry=$1.'; '.$logentry;
1655: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1656: $kdom,$knum) eq 'ok') {
1657: # key now belongs to user
1658: my $envkey='key.'.$cdom.'_'.$cnum;
1659: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1660: &appenv({'environment.'.$envkey => $ckey});
1661: return 'ok';
1662: } else {
1663: return
1664: 'error: Count not permanently assign key, will need to be re-entered later.';
1665: }
1666: } else {
1667: return 'error: Could not assign key, try again later.';
1668: }
1669: } elsif (!$existing{$ckey}) {
1670: # the key does not exist
1671: return 'error: The key does not exist';
1672: } else {
1673: # the key is somebody else's
1674: return 'error: The key is already in use';
1675: }
1676: }
1677:
1678: # ------------------------------------------ put an additional comment on a key
1679:
1680: sub comment_access_key {
1681: #
1682: # a valid key looks like uname:udom#comments
1683: # comments are being appended
1684: #
1685: my ($ckey,$cdom,$cnum,$logentry)=@_;
1686: $cdom=
1687: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1688: $cnum=
1689: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1690: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1691: if ($existing{$ckey}) {
1692: $existing{$ckey}.='; '.$logentry;
1693: # ready to assign
1694: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1695: $cdom,$cnum) eq 'ok') {
1696: return 'ok';
1697: } else {
1698: return 'error: Count not store comment.';
1699: }
1700: } else {
1701: # the key does not exist
1702: return 'error: The key does not exist';
1703: }
1704: }
1705:
1706: # ------------------------------------------------------ Generate a set of keys
1707:
1708: sub generate_access_keys {
1709: my ($number,$cdom,$cnum,$logentry)=@_;
1710: $cdom=
1711: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1712: $cnum=
1713: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1714: unless (&allowed('mky',$cdom)) { return 0; }
1715: unless (($cdom) && ($cnum)) { return 0; }
1716: if ($number>10000) { return 0; }
1717: sleep(2); # make sure don't get same seed twice
1718: srand(time()^($$+($$<<15))); # from "Programming Perl"
1719: my $total=0;
1720: for (my $i=1;$i<=$number;$i++) {
1721: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1722: sprintf("%lx",int(100000*rand)).'-'.
1723: sprintf("%lx",int(100000*rand));
1724: $newkey=~s/1/g/g; # folks mix up 1 and l
1725: $newkey=~s/0/h/g; # and also 0 and O
1726: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1727: if ($existing{$newkey}) {
1728: $i--;
1729: } else {
1730: if (&put('accesskeys',
1731: { $newkey => '# generated '.localtime().
1732: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1733: '; '.$logentry },
1734: $cdom,$cnum) eq 'ok') {
1735: $total++;
1736: }
1737: }
1738: }
1739: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1740: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1741: return $total;
1742: }
1743:
1744: # ------------------------------------------------------- Validate an accesskey
1745:
1746: sub validate_access_key {
1747: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1748: $cdom=
1749: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1750: $cnum=
1751: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1752: $udom=$env{'user.domain'} unless (defined($udom));
1753: $uname=$env{'user.name'} unless (defined($uname));
1754: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1755: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1756: }
1757:
1758: # ------------------------------------- Find the section of student in a course
1759: sub devalidate_getsection_cache {
1760: my ($udom,$unam,$courseid)=@_;
1761: my $hashid="$udom:$unam:$courseid";
1762: &devalidate_cache_new('getsection',$hashid);
1763: }
1764:
1765: sub courseid_to_courseurl {
1766: my ($courseid) = @_;
1767: #already url style courseid
1768: return $courseid if ($courseid =~ m{^/});
1769:
1770: if (exists($env{'course.'.$courseid.'.num'})) {
1771: my $cnum = $env{'course.'.$courseid.'.num'};
1772: my $cdom = $env{'course.'.$courseid.'.domain'};
1773: return "/$cdom/$cnum";
1774: }
1775:
1776: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1777: if (exists($courseinfo{'num'})) {
1778: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1779: }
1780:
1781: return undef;
1782: }
1783:
1784: sub getsection {
1785: my ($udom,$unam,$courseid)=@_;
1786: my $cachetime=1800;
1787:
1788: my $hashid="$udom:$unam:$courseid";
1789: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1790: if (defined($cached)) { return $result; }
1791:
1792: my %Pending;
1793: my %Expired;
1794: #
1795: # Each role can either have not started yet (pending), be active,
1796: # or have expired.
1797: #
1798: # If there is an active role, we are done.
1799: #
1800: # If there is more than one role which has not started yet,
1801: # choose the one which will start sooner
1802: # If there is one role which has not started yet, return it.
1803: #
1804: # If there is more than one expired role, choose the one which ended last.
1805: # If there is a role which has expired, return it.
1806: #
1807: $courseid = &courseid_to_courseurl($courseid);
1808: my $extra = &freeze_escape({'skipcheck' => 1});
1809: my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1810: foreach my $key (keys(%roleshash)) {
1811: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1812: my $section=$1;
1813: if ($key eq $courseid.'_st') { $section=''; }
1814: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1815: my $now=time;
1816: if (defined($end) && $end && ($now > $end)) {
1817: $Expired{$end}=$section;
1818: next;
1819: }
1820: if (defined($start) && $start && ($now < $start)) {
1821: $Pending{$start}=$section;
1822: next;
1823: }
1824: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1825: }
1826: #
1827: # Presumedly there will be few matching roles from the above
1828: # loop and the sorting time will be negligible.
1829: if (scalar(keys(%Pending))) {
1830: my ($time) = sort {$a <=> $b} keys(%Pending);
1831: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1832: }
1833: if (scalar(keys(%Expired))) {
1834: my @sorted = sort {$a <=> $b} keys(%Expired);
1835: my $time = pop(@sorted);
1836: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1837: }
1838: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1839: }
1840:
1841: sub save_cache {
1842: &purge_remembered();
1843: #&Apache::loncommon::validate_page();
1844: undef(%env);
1845: undef($env_loaded);
1846: }
1847:
1848: my $to_remember=-1;
1849: my %remembered;
1850: my %accessed;
1851: my $kicks=0;
1852: my $hits=0;
1853: sub make_key {
1854: my ($name,$id) = @_;
1855: if (length($id) > 65
1856: && length(&escape($id)) > 200) {
1857: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1858: }
1859: return &escape($name.':'.$id);
1860: }
1861:
1862: sub devalidate_cache_new {
1863: my ($name,$id,$debug) = @_;
1864: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1865: $id=&make_key($name,$id);
1866: $memcache->delete($id);
1867: delete($remembered{$id});
1868: delete($accessed{$id});
1869: }
1870:
1871: sub is_cached_new {
1872: my ($name,$id,$debug) = @_;
1873: $id=&make_key($name,$id);
1874: if (exists($remembered{$id})) {
1875: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1876: $accessed{$id}=[&gettimeofday()];
1877: $hits++;
1878: return ($remembered{$id},1);
1879: }
1880: my $value = $memcache->get($id);
1881: if (!(defined($value))) {
1882: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1883: return (undef,undef);
1884: }
1885: if ($value eq '__undef__') {
1886: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1887: $value=undef;
1888: }
1889: &make_room($id,$value,$debug);
1890: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1891: return ($value,1);
1892: }
1893:
1894: sub do_cache_new {
1895: my ($name,$id,$value,$time,$debug) = @_;
1896: $id=&make_key($name,$id);
1897: my $setvalue=$value;
1898: if (!defined($setvalue)) {
1899: $setvalue='__undef__';
1900: }
1901: if (!defined($time) ) {
1902: $time=600;
1903: }
1904: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1905: my $result = $memcache->set($id,$setvalue,$time);
1906: if (! $result) {
1907: &logthis("caching of id -> $id failed");
1908: $memcache->disconnect_all();
1909: }
1910: # need to make a copy of $value
1911: &make_room($id,$value,$debug);
1912: return $value;
1913: }
1914:
1915: sub make_room {
1916: my ($id,$value,$debug)=@_;
1917:
1918: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1919: : $value;
1920: if ($to_remember<0) { return; }
1921: $accessed{$id}=[&gettimeofday()];
1922: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1923: my $to_kick;
1924: my $max_time=0;
1925: foreach my $other (keys(%accessed)) {
1926: if (&tv_interval($accessed{$other}) > $max_time) {
1927: $to_kick=$other;
1928: $max_time=&tv_interval($accessed{$other});
1929: }
1930: }
1931: delete($remembered{$to_kick});
1932: delete($accessed{$to_kick});
1933: $kicks++;
1934: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1935: return;
1936: }
1937:
1938: sub purge_remembered {
1939: #&logthis("Tossing ".scalar(keys(%remembered)));
1940: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1941: undef(%remembered);
1942: undef(%accessed);
1943: }
1944: # ------------------------------------- Read an entry from a user's environment
1945:
1946: sub userenvironment {
1947: my ($udom,$unam,@what)=@_;
1948: my $items;
1949: foreach my $item (@what) {
1950: $items.=&escape($item).'&';
1951: }
1952: $items=~s/\&$//;
1953: my %returnhash=();
1954: my $uhome = &homeserver($unam,$udom);
1955: unless ($uhome eq 'no_host') {
1956: my @answer=split(/\&/,
1957: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1958: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
1959: return %returnhash;
1960: }
1961: my $i;
1962: for ($i=0;$i<=$#what;$i++) {
1963: $returnhash{$what[$i]}=&unescape($answer[$i]);
1964: }
1965: }
1966: return %returnhash;
1967: }
1968:
1969: # ---------------------------------------------------------- Get a studentphoto
1970: sub studentphoto {
1971: my ($udom,$unam,$ext) = @_;
1972: my $home=&Apache::lonnet::homeserver($unam,$udom);
1973: if (defined($env{'request.course.id'})) {
1974: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1975: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1976: return(&retrievestudentphoto($udom,$unam,$ext));
1977: } else {
1978: my ($result,$perm_reqd)=
1979: &Apache::lonnet::auto_photo_permission($unam,$udom);
1980: if ($result eq 'ok') {
1981: if (!($perm_reqd eq 'yes')) {
1982: return(&retrievestudentphoto($udom,$unam,$ext));
1983: }
1984: }
1985: }
1986: }
1987: } else {
1988: my ($result,$perm_reqd) =
1989: &Apache::lonnet::auto_photo_permission($unam,$udom);
1990: if ($result eq 'ok') {
1991: if (!($perm_reqd eq 'yes')) {
1992: return(&retrievestudentphoto($udom,$unam,$ext));
1993: }
1994: }
1995: }
1996: return '/adm/lonKaputt/lonlogo_broken.gif';
1997: }
1998:
1999: sub retrievestudentphoto {
2000: my ($udom,$unam,$ext,$type) = @_;
2001: my $home=&Apache::lonnet::homeserver($unam,$udom);
2002: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2003: if ($ret eq 'ok') {
2004: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2005: if ($type eq 'thumbnail') {
2006: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2007: }
2008: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2009: return $tokenurl;
2010: } else {
2011: if ($type eq 'thumbnail') {
2012: return '/adm/lonKaputt/genericstudent_tn.gif';
2013: } else {
2014: return '/adm/lonKaputt/lonlogo_broken.gif';
2015: }
2016: }
2017: }
2018:
2019: # -------------------------------------------------------------------- New chat
2020:
2021: sub chatsend {
2022: my ($newentry,$anon,$group)=@_;
2023: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2024: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2025: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
2026: &reply('chatsend:'.$cdom.':'.$cnum.':'.
2027: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
2028: &escape($newentry)).':'.$group,$chome);
2029: }
2030:
2031: # ------------------------------------------ Find current version of a resource
2032:
2033: sub getversion {
2034: my $fname=&clutter(shift);
2035: unless ($fname=~/^\/res\//) { return -1; }
2036: return ¤tversion(&filelocation('',$fname));
2037: }
2038:
2039: sub currentversion {
2040: my $fname=shift;
2041: my ($result,$cached)=&is_cached_new('resversion',$fname);
2042: if (defined($cached)) { return $result; }
2043: my $author=$fname;
2044: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2045: my ($udom,$uname)=split(/\//,$author);
2046: my $home=homeserver($uname,$udom);
2047: if ($home eq 'no_host') {
2048: return -1;
2049: }
2050: my $answer=reply("currentversion:$fname",$home);
2051: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2052: return -1;
2053: }
2054: return &do_cache_new('resversion',$fname,$answer,600);
2055: }
2056:
2057: # ----------------------------- Subscribe to a resource, return URL if possible
2058:
2059: sub subscribe {
2060: my $fname=shift;
2061: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
2062: $fname=~s/[\n\r]//g;
2063: my $author=$fname;
2064: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2065: my ($udom,$uname)=split(/\//,$author);
2066: my $home=homeserver($uname,$udom);
2067: if ($home eq 'no_host') {
2068: return 'not_found';
2069: }
2070: my $answer=reply("sub:$fname",$home);
2071: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2072: $answer.=' by '.$home;
2073: }
2074: return $answer;
2075: }
2076:
2077: # -------------------------------------------------------------- Replicate file
2078:
2079: sub repcopy {
2080: my $filename=shift;
2081: $filename=~s/\/+/\//g;
2082: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
2083: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
2084: if ($filename=~m|^/home/httpd/html/userfiles/| or
2085: $filename=~m -^/*(uploaded|editupload)/-) {
2086: return &repcopy_userfile($filename);
2087: }
2088: $filename=~s/[\n\r]//g;
2089: my $transname="$filename.in.transfer";
2090: # FIXME: this should flock
2091: if ((-e $filename) || (-e $transname)) { return 'ok'; }
2092: my $remoteurl=subscribe($filename);
2093: if ($remoteurl =~ /^con_lost by/) {
2094: &logthis("Subscribe returned $remoteurl: $filename");
2095: return 'unavailable';
2096: } elsif ($remoteurl eq 'not_found') {
2097: #&logthis("Subscribe returned not_found: $filename");
2098: return 'not_found';
2099: } elsif ($remoteurl =~ /^rejected by/) {
2100: &logthis("Subscribe returned $remoteurl: $filename");
2101: return 'forbidden';
2102: } elsif ($remoteurl eq 'directory') {
2103: return 'ok';
2104: } else {
2105: my $author=$filename;
2106: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2107: my ($udom,$uname)=split(/\//,$author);
2108: my $home=homeserver($uname,$udom);
2109: unless ($home eq $perlvar{'lonHostID'}) {
2110: my @parts=split(/\//,$filename);
2111: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2112: if ($path ne "$perlvar{'lonDocRoot'}/res") {
2113: &logthis("Malconfiguration for replication: $filename");
2114: return 'bad_request';
2115: }
2116: my $count;
2117: for ($count=5;$count<$#parts;$count++) {
2118: $path.="/$parts[$count]";
2119: if ((-e $path)!=1) {
2120: mkdir($path,0777);
2121: }
2122: }
2123: my $ua=new LWP::UserAgent;
2124: my $request=new HTTP::Request('GET',"$remoteurl");
2125: my $response=$ua->request($request,$transname);
2126: if ($response->is_error()) {
2127: unlink($transname);
2128: my $message=$response->status_line;
2129: &logthis("<font color=\"blue\">WARNING:"
2130: ." LWP get: $message: $filename</font>");
2131: return 'unavailable';
2132: } else {
2133: if ($remoteurl!~/\.meta$/) {
2134: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2135: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2136: if ($mresponse->is_error()) {
2137: unlink($filename.'.meta');
2138: &logthis(
2139: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
2140: }
2141: }
2142: rename($transname,$filename);
2143: return 'ok';
2144: }
2145: }
2146: }
2147: }
2148:
2149: # ------------------------------------------------ Get server side include body
2150: sub ssi_body {
2151: my ($filelink,%form)=@_;
2152: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2153: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2154: }
2155: my $output='';
2156: my $response;
2157: if ($filelink=~/^https?\:/) {
2158: ($output,$response)=&externalssi($filelink);
2159: } else {
2160: $filelink .= $filelink=~/\?/ ? '&' : '?';
2161: $filelink .= 'inhibitmenu=yes';
2162: ($output,$response)=&ssi($filelink,%form);
2163: }
2164: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
2165: $output=~s/^.*?\<body[^\>]*\>//si;
2166: $output=~s/\<\/body\s*\>.*?$//si;
2167: if (wantarray) {
2168: return ($output, $response);
2169: } else {
2170: return $output;
2171: }
2172: }
2173:
2174: # --------------------------------------------------------- Server Side Include
2175:
2176: sub absolute_url {
2177: my ($host_name) = @_;
2178: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2179: if ($host_name eq '') {
2180: $host_name = $ENV{'SERVER_NAME'};
2181: }
2182: return $protocol.$host_name;
2183: }
2184:
2185: #
2186: # Server side include.
2187: # Parameters:
2188: # fn Possibly encrypted resource name/id.
2189: # form Hash that describes how the rendering should be done
2190: # and other things.
2191: # Returns:
2192: # Scalar context: The content of the response.
2193: # Array context: 2 element list of the content and the full response object.
2194: #
2195: sub ssi {
2196:
2197: my ($fn,%form)=@_;
2198: my $ua=new LWP::UserAgent;
2199: my $request;
2200:
2201: $form{'no_update_last_known'}=1;
2202: &Apache::lonenc::check_encrypt(\$fn);
2203: if (%form) {
2204: $request=new HTTP::Request('POST',&absolute_url().$fn);
2205: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
2206: } else {
2207: $request=new HTTP::Request('GET',&absolute_url().$fn);
2208: }
2209:
2210: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2211: my $response=$ua->request($request);
2212:
2213: if (wantarray) {
2214: return ($response->content, $response);
2215: } else {
2216: return $response->content;
2217: }
2218: }
2219:
2220: sub externalssi {
2221: my ($url)=@_;
2222: my $ua=new LWP::UserAgent;
2223: my $request=new HTTP::Request('GET',$url);
2224: my $response=$ua->request($request);
2225: if (wantarray) {
2226: return ($response->content, $response);
2227: } else {
2228: return $response->content;
2229: }
2230: }
2231:
2232: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2233:
2234: sub allowuploaded {
2235: my ($srcurl,$url)=@_;
2236: $url=&clutter(&declutter($url));
2237: my $dir=$url;
2238: $dir=~s/\/[^\/]+$//;
2239: my %httpref=();
2240: my $httpurl=&hreflocation('',$url);
2241: $httpref{'httpref.'.$httpurl}=$srcurl;
2242: &Apache::lonnet::appenv(\%httpref);
2243: }
2244:
2245: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
2246: # input: action, courseID, current domain, intended
2247: # path to file, source of file, instruction to parse file for objects,
2248: # ref to hash for embedded objects,
2249: # ref to hash for codebase of java objects.
2250: # reference to scalar to accommodate mime type determined
2251: # from File::MMagic if $parser = parse.
2252: #
2253: # output: url to file (if action was uploaddoc),
2254: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
2255: #
2256: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2257: # course.
2258: #
2259: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2260: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2261: # course's home server.
2262: #
2263: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2264: # be copied from $source (current location) to
2265: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2266: # and will then be copied to
2267: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2268: # course's home server.
2269: #
2270: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2271: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
2272: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2273: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2274: # in course's home server.
2275: #
2276:
2277: sub process_coursefile {
2278: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2279: $mimetype)=@_;
2280: my $fetchresult;
2281: my $home=&homeserver($docuname,$docudom);
2282: if ($action eq 'propagate') {
2283: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2284: $home);
2285: } else {
2286: my $fpath = '';
2287: my $fname = $file;
2288: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2289: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2290: my $filepath = &build_filepath($fpath);
2291: if ($action eq 'copy') {
2292: if ($source eq '') {
2293: $fetchresult = 'no source file';
2294: return $fetchresult;
2295: } else {
2296: my $destination = $filepath.'/'.$fname;
2297: rename($source,$destination);
2298: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2299: $home);
2300: }
2301: } elsif ($action eq 'uploaddoc') {
2302: open(my $fh,'>'.$filepath.'/'.$fname);
2303: print $fh $env{'form.'.$source};
2304: close($fh);
2305: if ($parser eq 'parse') {
2306: my $mm = new File::MMagic;
2307: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2308: if ($type eq 'text/html') {
2309: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2310: unless ($parse_result eq 'ok') {
2311: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2312: }
2313: }
2314: if (ref($mimetype)) {
2315: $$mimetype = $type;
2316: }
2317: }
2318: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2319: $home);
2320: if ($fetchresult eq 'ok') {
2321: return '/uploaded/'.$fpath.'/'.$fname;
2322: } else {
2323: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2324: ' to host '.$home.': '.$fetchresult);
2325: return '/adm/notfound.html';
2326: }
2327: }
2328: }
2329: unless ( $fetchresult eq 'ok') {
2330: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2331: ' to host '.$home.': '.$fetchresult);
2332: }
2333: return $fetchresult;
2334: }
2335:
2336: sub build_filepath {
2337: my ($fpath) = @_;
2338: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2339: unless ($fpath eq '') {
2340: my @parts=split('/',$fpath);
2341: foreach my $part (@parts) {
2342: $filepath.= '/'.$part;
2343: if ((-e $filepath)!=1) {
2344: mkdir($filepath,0777);
2345: }
2346: }
2347: }
2348: return $filepath;
2349: }
2350:
2351: sub store_edited_file {
2352: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
2353: my $file = $primary_url;
2354: $file =~ s#^/uploaded/$docudom/$docuname/##;
2355: my $fpath = '';
2356: my $fname = $file;
2357: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2358: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2359: my $filepath = &build_filepath($fpath);
2360: open(my $fh,'>'.$filepath.'/'.$fname);
2361: print $fh $content;
2362: close($fh);
2363: my $home=&homeserver($docuname,$docudom);
2364: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2365: $home);
2366: if ($$fetchresult eq 'ok') {
2367: return '/uploaded/'.$fpath.'/'.$fname;
2368: } else {
2369: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2370: ' to host '.$home.': '.$$fetchresult);
2371: return '/adm/notfound.html';
2372: }
2373: }
2374:
2375: sub clean_filename {
2376: my ($fname,$args)=@_;
2377: # Replace Windows backslashes by forward slashes
2378: $fname=~s/\\/\//g;
2379: if (!$args->{'keep_path'}) {
2380: # Get rid of everything but the actual filename
2381: $fname=~s/^.*\/([^\/]+)$/$1/;
2382: }
2383: # Replace spaces by underscores
2384: $fname=~s/\s+/\_/g;
2385: # Replace all other weird characters by nothing
2386: $fname=~s{[^/\w\.\-]}{}g;
2387: # Replace all .\d. sequences with _\d. so they no longer look like version
2388: # numbers
2389: $fname=~s/\.(\d+)(?=\.)/_$1/g;
2390: return $fname;
2391: }
2392: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2393: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2394: # image with the same aspect ratio as the original, but with dimensions which do
2395: # not exceed $resizewidth and $resizeheight.
2396:
2397: sub resizeImage {
2398: my ($img_path,$resizewidth,$resizeheight) = @_;
2399: my $ima = Image::Magick->new;
2400: my $resized;
2401: if (-e $img_path) {
2402: $ima->Read($img_path);
2403: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2404: my $width = $ima->Get('width');
2405: my $height = $ima->Get('height');
2406: if ($width > $resizewidth) {
2407: my $factor = $width/$resizewidth;
2408: my $newheight = $height/$factor;
2409: $ima->Scale(width=>$resizewidth,height=>$newheight);
2410: $resized = 1;
2411: }
2412: }
2413: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2414: my $width = $ima->Get('width');
2415: my $height = $ima->Get('height');
2416: if ($height > $resizeheight) {
2417: my $factor = $height/$resizeheight;
2418: my $newwidth = $width/$factor;
2419: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2420: $resized = 1;
2421: }
2422: }
2423: if ($resized) {
2424: $ima->Write($img_path);
2425: }
2426: }
2427: return;
2428: }
2429:
2430: # --------------- Take an uploaded file and put it into the userfiles directory
2431: # input: $formname - the contents of the file are in $env{"form.$formname"}
2432: # the desired filename is in $env{"form.$formname.filename"}
2433: # $context - possible values: coursedoc, existingfile, overwrite,
2434: # canceloverwrite, or ''.
2435: # if 'coursedoc': upload to the current course
2436: # if 'existingfile': write file to tmp/overwrites directory
2437: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2438: # $context is passed as argument to &finishuserfileupload
2439: # $subdir - directory in userfile to store the file into
2440: # $parser - instruction to parse file for objects ($parser = parse)
2441: # $allfiles - reference to hash for embedded objects
2442: # $codebase - reference to hash for codebase of java objects
2443: # $desuname - username for permanent storage of uploaded file
2444: # $dsetudom - domain for permanaent storage of uploaded file
2445: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2446: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
2447: # $resizewidth - width (pixels) to which to resize uploaded image
2448: # $resizeheight - height (pixels) to which to resize uploaded image
2449: # $mimetype - reference to scalar to accommodate mime type determined
2450: # from File::MMagic if $parser = parse.
2451: #
2452: # output: url of file in userspace, or error: <message>
2453: # or /adm/notfound.html if failure to upload occurse
2454:
2455: sub userfileupload {
2456: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
2457: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
2458: if (!defined($subdir)) { $subdir='unknown'; }
2459: my $fname=$env{'form.'.$formname.'.filename'};
2460: $fname=&clean_filename($fname);
2461: # See if there is anything left
2462: unless ($fname) { return 'error: no uploaded file'; }
2463: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2464: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2465: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2466: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2467: my $now = time;
2468: my $filepath;
2469: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
2470: $filepath = 'tmp/helprequests/'.$now;
2471: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2472: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2473: '_'.$env{'user.domain'}.'/pending';
2474: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2475: my ($docuname,$docudom);
2476: if ($destudom) {
2477: $docudom = $destudom;
2478: } else {
2479: $docudom = $env{'user.domain'};
2480: }
2481: if ($destuname) {
2482: $docuname = $destuname;
2483: } else {
2484: $docuname = $env{'user.name'};
2485: }
2486: if (exists($env{'form.group'})) {
2487: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2488: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2489: }
2490: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2491: if ($context eq 'canceloverwrite') {
2492: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2493: if (-e $tempfile) {
2494: my @info = stat($tempfile);
2495: if ($info[9] eq $env{'form.timestamp'}) {
2496: unlink($tempfile);
2497: }
2498: }
2499: return;
2500: }
2501: }
2502: # Create the directory if not present
2503: my @parts=split(/\//,$filepath);
2504: my $fullpath = $perlvar{'lonDaemons'};
2505: for (my $i=0;$i<@parts;$i++) {
2506: $fullpath .= '/'.$parts[$i];
2507: if ((-e $fullpath)!=1) {
2508: mkdir($fullpath,0777);
2509: }
2510: }
2511: open(my $fh,'>'.$fullpath.'/'.$fname);
2512: print $fh $env{'form.'.$formname};
2513: close($fh);
2514: if ($context eq 'existingfile') {
2515: my @info = stat($fullpath.'/'.$fname);
2516: return ($fullpath.'/'.$fname,$info[9]);
2517: } else {
2518: return $fullpath.'/'.$fname;
2519: }
2520: }
2521: if ($subdir eq 'scantron') {
2522: $fname = 'scantron_orig_'.$fname;
2523: } else {
2524: $fname="$subdir/$fname";
2525: }
2526: if ($context eq 'coursedoc') {
2527: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2528: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2529: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
2530: return &finishuserfileupload($docuname,$docudom,
2531: $formname,$fname,$parser,$allfiles,
2532: $codebase,$thumbwidth,$thumbheight,
2533: $resizewidth,$resizeheight,$context,$mimetype);
2534: } else {
2535: $fname=$env{'form.folder'}.'/'.$fname;
2536: return &process_coursefile('uploaddoc',$docuname,$docudom,
2537: $fname,$formname,$parser,
2538: $allfiles,$codebase,$mimetype);
2539: }
2540: } elsif (defined($destuname)) {
2541: my $docuname=$destuname;
2542: my $docudom=$destudom;
2543: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2544: $parser,$allfiles,$codebase,
2545: $thumbwidth,$thumbheight,
2546: $resizewidth,$resizeheight,$context,$mimetype);
2547: } else {
2548: my $docuname=$env{'user.name'};
2549: my $docudom=$env{'user.domain'};
2550: if (exists($env{'form.group'})) {
2551: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2552: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2553: }
2554: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2555: $parser,$allfiles,$codebase,
2556: $thumbwidth,$thumbheight,
2557: $resizewidth,$resizeheight,$context,$mimetype);
2558: }
2559: }
2560:
2561: sub finishuserfileupload {
2562: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
2563: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
2564: my $path=$docudom.'/'.$docuname.'/';
2565: my $filepath=$perlvar{'lonDocRoot'};
2566:
2567: my ($fnamepath,$file,$fetchthumb);
2568: $file=$fname;
2569: if ($fname=~m|/|) {
2570: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2571: $path.=$fnamepath.'/';
2572: }
2573: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
2574: my $count;
2575: for ($count=4;$count<=$#parts;$count++) {
2576: $filepath.="/$parts[$count]";
2577: if ((-e $filepath)!=1) {
2578: mkdir($filepath,0777);
2579: }
2580: }
2581:
2582: # Save the file
2583: {
2584: if (!open(FH,'>'.$filepath.'/'.$file)) {
2585: &logthis('Failed to create '.$filepath.'/'.$file);
2586: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2587: return '/adm/notfound.html';
2588: }
2589: if ($context eq 'overwrite') {
2590: my $source = $perlvar{'lonDaemons'}.'/tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
2591: my $target = $filepath.'/'.$file;
2592: if (-e $source) {
2593: my @info = stat($source);
2594: if ($info[9] eq $env{'form.timestamp'}) {
2595: unless (&File::Copy::move($source,$target)) {
2596: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2597: return "Moving from $source failed";
2598: }
2599: } else {
2600: return "Temporary file: $source had unexpected date/time for last modification";
2601: }
2602: } else {
2603: return "Temporary file: $source missing";
2604: }
2605: } elsif (!print FH ($env{'form.'.$formname})) {
2606: &logthis('Failed to write to '.$filepath.'/'.$file);
2607: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2608: return '/adm/notfound.html';
2609: }
2610: close(FH);
2611: if ($resizewidth && $resizeheight) {
2612: my $mm = new File::MMagic;
2613: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2614: if ($mime_type =~ m{^image/}) {
2615: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2616: }
2617: }
2618: }
2619: if ($parser eq 'parse') {
2620: my $mm = new File::MMagic;
2621: my $type = $mm->checktype_filename($filepath.'/'.$file);
2622: if ($type eq 'text/html') {
2623: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2624: $allfiles,$codebase);
2625: unless ($parse_result eq 'ok') {
2626: &logthis('Failed to parse '.$filepath.$file.
2627: ' for embedded media: '.$parse_result);
2628: }
2629: }
2630: if (ref($mimetype)) {
2631: $$mimetype = $type;
2632: }
2633: }
2634: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2635: my $input = $filepath.'/'.$file;
2636: my $output = $filepath.'/'.'tn-'.$file;
2637: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2638: system("convert -sample $thumbsize $input $output");
2639: if (-e $filepath.'/'.'tn-'.$file) {
2640: $fetchthumb = 1;
2641: }
2642: }
2643:
2644: # Notify homeserver to grep it
2645: #
2646: my $docuhome=&homeserver($docuname,$docudom);
2647: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
2648: if ($fetchresult eq 'ok') {
2649: if ($fetchthumb) {
2650: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2651: if ($thumbresult ne 'ok') {
2652: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2653: $docuhome.': '.$thumbresult);
2654: }
2655: }
2656: #
2657: # Return the URL to it
2658: return '/uploaded/'.$path.$file;
2659: } else {
2660: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2661: ': '.$fetchresult);
2662: return '/adm/notfound.html';
2663: }
2664: }
2665:
2666: sub extract_embedded_items {
2667: my ($fullpath,$allfiles,$codebase,$content) = @_;
2668: my @state = ();
2669: my %javafiles = (
2670: codebase => '',
2671: code => '',
2672: archive => ''
2673: );
2674: my %mediafiles = (
2675: src => '',
2676: movie => '',
2677: );
2678: my $p;
2679: if ($content) {
2680: $p = HTML::LCParser->new($content);
2681: } else {
2682: $p = HTML::LCParser->new($fullpath);
2683: }
2684: while (my $t=$p->get_token()) {
2685: if ($t->[0] eq 'S') {
2686: my ($tagname, $attr) = ($t->[1],$t->[2]);
2687: push(@state, $tagname);
2688: if (lc($tagname) eq 'allow') {
2689: &add_filetype($allfiles,$attr->{'src'},'src');
2690: }
2691: if (lc($tagname) eq 'img') {
2692: &add_filetype($allfiles,$attr->{'src'},'src');
2693: }
2694: if (lc($tagname) eq 'a') {
2695: &add_filetype($allfiles,$attr->{'href'},'href');
2696: }
2697: if (lc($tagname) eq 'script') {
2698: if ($attr->{'archive'} =~ /\.jar$/i) {
2699: &add_filetype($allfiles,$attr->{'archive'},'archive');
2700: } else {
2701: &add_filetype($allfiles,$attr->{'src'},'src');
2702: }
2703: }
2704: if (lc($tagname) eq 'link') {
2705: if (lc($attr->{'rel'}) eq 'stylesheet') {
2706: &add_filetype($allfiles,$attr->{'href'},'href');
2707: }
2708: }
2709: if (lc($tagname) eq 'object' ||
2710: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2711: foreach my $item (keys(%javafiles)) {
2712: $javafiles{$item} = '';
2713: }
2714: }
2715: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2716: my $name = lc($attr->{'name'});
2717: foreach my $item (keys(%javafiles)) {
2718: if ($name eq $item) {
2719: $javafiles{$item} = $attr->{'value'};
2720: last;
2721: }
2722: }
2723: foreach my $item (keys(%mediafiles)) {
2724: if ($name eq $item) {
2725: &add_filetype($allfiles, $attr->{'value'}, 'value');
2726: last;
2727: }
2728: }
2729: }
2730: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2731: foreach my $item (keys(%javafiles)) {
2732: if ($attr->{$item}) {
2733: $javafiles{$item} = $attr->{$item};
2734: last;
2735: }
2736: }
2737: foreach my $item (keys(%mediafiles)) {
2738: if ($attr->{$item}) {
2739: &add_filetype($allfiles,$attr->{$item},$item);
2740: last;
2741: }
2742: }
2743: }
2744: } elsif ($t->[0] eq 'E') {
2745: my ($tagname) = ($t->[1]);
2746: if ($javafiles{'codebase'} ne '') {
2747: $javafiles{'codebase'} .= '/';
2748: }
2749: if (lc($tagname) eq 'applet' ||
2750: lc($tagname) eq 'object' ||
2751: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2752: ) {
2753: foreach my $item (keys(%javafiles)) {
2754: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2755: my $file=$javafiles{'codebase'}.$javafiles{$item};
2756: &add_filetype($allfiles,$file,$item);
2757: }
2758: }
2759: }
2760: pop @state;
2761: }
2762: }
2763: return 'ok';
2764: }
2765:
2766: sub add_filetype {
2767: my ($allfiles,$file,$type)=@_;
2768: if (exists($allfiles->{$file})) {
2769: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2770: push(@{$allfiles->{$file}}, &escape($type));
2771: }
2772: } else {
2773: @{$allfiles->{$file}} = (&escape($type));
2774: }
2775: }
2776:
2777: sub removeuploadedurl {
2778: my ($url)=@_;
2779: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
2780: return &removeuserfile($uname,$udom,$fname);
2781: }
2782:
2783: sub removeuserfile {
2784: my ($docuname,$docudom,$fname)=@_;
2785: my $home=&homeserver($docuname,$docudom);
2786: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
2787: if ($result eq 'ok') {
2788: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2789: my $metafile = $fname.'.meta';
2790: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
2791: my $url = "/uploaded/$docudom/$docuname/$fname";
2792: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
2793: my $sqlresult =
2794: &update_portfolio_table($docuname,$docudom,$file,
2795: 'portfolio_metadata',$group,
2796: 'delete');
2797: }
2798: }
2799: return $result;
2800: }
2801:
2802: sub mkdiruserfile {
2803: my ($docuname,$docudom,$dir)=@_;
2804: my $home=&homeserver($docuname,$docudom);
2805: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2806: }
2807:
2808: sub renameuserfile {
2809: my ($docuname,$docudom,$old,$new)=@_;
2810: my $home=&homeserver($docuname,$docudom);
2811: my $result = &reply("renameuserfile:$docudom:$docuname:".
2812: &escape("$old").':'.&escape("$new"),$home);
2813: if ($result eq 'ok') {
2814: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2815: my $oldmeta = $old.'.meta';
2816: my $newmeta = $new.'.meta';
2817: my $metaresult =
2818: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
2819: my $url = "/uploaded/$docudom/$docuname/$old";
2820: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
2821: my $sqlresult =
2822: &update_portfolio_table($docuname,$docudom,$file,
2823: 'portfolio_metadata',$group,
2824: 'delete');
2825: }
2826: }
2827: return $result;
2828: }
2829:
2830: # ------------------------------------------------------------------------- Log
2831:
2832: sub log {
2833: my ($dom,$nam,$hom,$what)=@_;
2834: return critical("log:$dom:$nam:$what",$hom);
2835: }
2836:
2837: # ------------------------------------------------------------------ Course Log
2838: #
2839: # This routine flushes several buffers of non-mission-critical nature
2840: #
2841:
2842: sub flushcourselogs {
2843: &logthis('Flushing log buffers');
2844: #
2845: # course logs
2846: # This is a log of all transactions in a course, which can be used
2847: # for data mining purposes
2848: #
2849: # It also collects the courseid database, which lists last transaction
2850: # times and course titles for all courseids
2851: #
2852: my %courseidbuffer=();
2853: foreach my $crsid (keys(%courselogs)) {
2854: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
2855: &escape($courselogs{$crsid}),
2856: $coursehombuf{$crsid}) eq 'ok') {
2857: delete $courselogs{$crsid};
2858: } else {
2859: &logthis('Failed to flush log buffer for '.$crsid);
2860: if (length($courselogs{$crsid})>40000) {
2861: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
2862: " exceeded maximum size, deleting.</font>");
2863: delete $courselogs{$crsid};
2864: }
2865: }
2866: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
2867: 'description' => $coursedescrbuf{$crsid},
2868: 'inst_code' => $courseinstcodebuf{$crsid},
2869: 'type' => $coursetypebuf{$crsid},
2870: 'owner' => $courseownerbuf{$crsid},
2871: };
2872: }
2873: #
2874: # Write course id database (reverse lookup) to homeserver of courses
2875: # Is used in pickcourse
2876: #
2877: foreach my $crs_home (keys(%courseidbuffer)) {
2878: my $response = &courseidput(&host_domain($crs_home),
2879: $courseidbuffer{$crs_home},
2880: $crs_home,'timeonly');
2881: }
2882: #
2883: # File accesses
2884: # Writes to the dynamic metadata of resources to get hit counts, etc.
2885: #
2886: foreach my $entry (keys(%accesshash)) {
2887: if ($entry =~ /___count$/) {
2888: my ($dom,$name);
2889: ($dom,$name,undef)=
2890: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
2891: if (! defined($dom) || $dom eq '' ||
2892: ! defined($name) || $name eq '') {
2893: my $cid = $env{'request.course.id'};
2894: $dom = $env{'request.'.$cid.'.domain'};
2895: $name = $env{'request.'.$cid.'.num'};
2896: }
2897: my $value = $accesshash{$entry};
2898: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2899: my %temphash=($url => $value);
2900: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2901: if ($result eq 'ok') {
2902: delete $accesshash{$entry};
2903: } elsif ($result eq 'unknown_cmd') {
2904: # Target server has old code running on it.
2905: my %temphash=($entry => $value);
2906: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2907: delete $accesshash{$entry};
2908: }
2909: }
2910: } else {
2911: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
2912: my %temphash=($entry => $accesshash{$entry});
2913: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2914: delete $accesshash{$entry};
2915: }
2916: }
2917: }
2918: #
2919: # Roles
2920: # Reverse lookup of user roles for course faculty/staff and co-authorship
2921: #
2922: foreach my $entry (keys(%userrolehash)) {
2923: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
2924: split(/\:/,$entry);
2925: if (&Apache::lonnet::put('nohist_userroles',
2926: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
2927: $rudom,$runame) eq 'ok') {
2928: delete $userrolehash{$entry};
2929: }
2930: }
2931: #
2932: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2933: #
2934: my %domrolebuffer = ();
2935: foreach my $entry (keys(%domainrolehash)) {
2936: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
2937: if ($domrolebuffer{$rudom}) {
2938: $domrolebuffer{$rudom}.='&'.&escape($entry).
2939: '='.&escape($domainrolehash{$entry});
2940: } else {
2941: $domrolebuffer{$rudom}.=&escape($entry).
2942: '='.&escape($domainrolehash{$entry});
2943: }
2944: delete $domainrolehash{$entry};
2945: }
2946: foreach my $dom (keys(%domrolebuffer)) {
2947: my %servers = &get_servers($dom,'library');
2948: foreach my $tryserver (keys(%servers)) {
2949: unless (&reply('domroleput:'.$dom.':'.
2950: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2951: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2952: }
2953: }
2954: }
2955: $dumpcount++;
2956: }
2957:
2958: sub courselog {
2959: my $what=shift;
2960: $what=time.':'.$what;
2961: unless ($env{'request.course.id'}) { return ''; }
2962: $coursedombuf{$env{'request.course.id'}}=
2963: $env{'course.'.$env{'request.course.id'}.'.domain'};
2964: $coursenumbuf{$env{'request.course.id'}}=
2965: $env{'course.'.$env{'request.course.id'}.'.num'};
2966: $coursehombuf{$env{'request.course.id'}}=
2967: $env{'course.'.$env{'request.course.id'}.'.home'};
2968: $coursedescrbuf{$env{'request.course.id'}}=
2969: $env{'course.'.$env{'request.course.id'}.'.description'};
2970: $courseinstcodebuf{$env{'request.course.id'}}=
2971: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2972: $courseownerbuf{$env{'request.course.id'}}=
2973: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
2974: $coursetypebuf{$env{'request.course.id'}}=
2975: $env{'course.'.$env{'request.course.id'}.'.type'};
2976: if (defined $courselogs{$env{'request.course.id'}}) {
2977: $courselogs{$env{'request.course.id'}}.='&'.$what;
2978: } else {
2979: $courselogs{$env{'request.course.id'}}.=$what;
2980: }
2981: if (length($courselogs{$env{'request.course.id'}})>4048) {
2982: &flushcourselogs();
2983: }
2984: }
2985:
2986: sub courseacclog {
2987: my $fnsymb=shift;
2988: unless ($env{'request.course.id'}) { return ''; }
2989: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
2990: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
2991: $what.=':POST';
2992: # FIXME: Probably ought to escape things....
2993: foreach my $key (keys(%env)) {
2994: if ($key=~/^form\.(.*)/) {
2995: my $formitem = $1;
2996: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2997: $what.=':'.$formitem.'='.$env{$key};
2998: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2999: $what.=':'.$formitem.'='.$env{$key};
3000: }
3001: }
3002: }
3003: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3004: # FIXME: We should not be depending on a form parameter that someone
3005: # editing lonsearchcat.pm might change in the future.
3006: if ($env{'form.phase'} eq 'course_search') {
3007: $what.= ':POST';
3008: # FIXME: Probably ought to escape things....
3009: foreach my $element ('courseexp','crsfulltext','crsrelated',
3010: 'crsdiscuss') {
3011: $what.=':'.$element.'='.$env{'form.'.$element};
3012: }
3013: }
3014: }
3015: &courselog($what);
3016: }
3017:
3018: sub countacc {
3019: my $url=&declutter(shift);
3020: return if (! defined($url) || $url eq '');
3021: unless ($env{'request.course.id'}) { return ''; }
3022: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
3023: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
3024: $accesshash{$key}++;
3025: }
3026:
3027: sub linklog {
3028: my ($from,$to)=@_;
3029: $from=&declutter($from);
3030: $to=&declutter($to);
3031: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3032: $accesshash{$to.'___'.$from.'___goto'}=1;
3033: }
3034:
3035: sub userrolelog {
3036: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
3037: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
3038: ($trole=~/^in/) || ($trole=~/^cc/) ||
3039: ($trole=~/^ep/) || ($trole=~/^cr/) ||
3040: ($trole=~/^ta/) || ($trole=~/^co/)) {
3041: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3042: $userrolehash
3043: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3044: =$tend.':'.$tstart;
3045: }
3046: if (($env{'request.role'} =~ /dc\./) &&
3047: (($trole=~/^au/) || ($trole=~/^in/) ||
3048: ($trole=~/^cc/) || ($trole=~/^ep/) ||
3049: ($trole=~/^cr/) || ($trole=~/^ta/) ||
3050: ($trole=~/^co/))) {
3051: $userrolehash
3052: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3053: =$tend.':'.$tstart;
3054: }
3055: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
3056: ($trole=~/^li/) || ($trole=~/^li/) ||
3057: ($trole=~/^au/) || ($trole=~/^dg/) ||
3058: ($trole=~/^sc/)) {
3059: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3060: $domainrolehash
3061: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3062: = $tend.':'.$tstart;
3063: }
3064: }
3065:
3066: sub courserolelog {
3067: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3068: if (($trole eq 'cc') || ($trole eq 'in') ||
3069: ($trole eq 'ep') || ($trole eq 'ad') ||
3070: ($trole eq 'ta') || ($trole eq 'st') ||
3071: ($trole=~/^cr/) || ($trole eq 'gr') ||
3072: ($trole eq 'co')) {
3073: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3074: my $cdom = $1;
3075: my $cnum = $2;
3076: my $sec = $3;
3077: my $namespace = 'rolelog';
3078: my %storehash = (
3079: role => $trole,
3080: start => $tstart,
3081: end => $tend,
3082: selfenroll => $selfenroll,
3083: context => $context,
3084: );
3085: if ($trole eq 'gr') {
3086: $namespace = 'groupslog';
3087: $storehash{'group'} = $sec;
3088: } else {
3089: $storehash{'section'} = $sec;
3090: }
3091: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
3092: if (($trole ne 'st') || ($sec ne '')) {
3093: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3094: }
3095: }
3096: }
3097: return;
3098: }
3099:
3100: sub get_course_adv_roles {
3101: my ($cid,$codes) = @_;
3102: $cid=$env{'request.course.id'} unless (defined($cid));
3103: my %coursehash=&coursedescription($cid);
3104: my $crstype = &Apache::loncommon::course_type($cid);
3105: my %nothide=();
3106: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3107: if ($user !~ /:/) {
3108: $nothide{join(':',split(/[\@]/,$user))}=1;
3109: } else {
3110: $nothide{$user}=1;
3111: }
3112: }
3113: my %returnhash=();
3114: my %dumphash=
3115: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3116: my $now=time;
3117: my %privileged;
3118: foreach my $entry (keys(%dumphash)) {
3119: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3120: if (($tstart) && ($tstart<0)) { next; }
3121: if (($tend) && ($tend<$now)) { next; }
3122: if (($tstart) && ($now<$tstart)) { next; }
3123: my ($role,$username,$domain,$section)=split(/\:/,$entry);
3124: if ($username eq '' || $domain eq '') { next; }
3125: unless (ref($privileged{$domain}) eq 'HASH') {
3126: my %dompersonnel =
3127: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3128: $privileged{$domain} = {};
3129: foreach my $server (keys(%dompersonnel)) {
3130: if (ref($dompersonnel{$server}) eq 'HASH') {
3131: foreach my $user (keys(%{$dompersonnel{$server}})) {
3132: my ($trole,$uname,$udom) = split(/:/,$user);
3133: $privileged{$udom}{$uname} = 1;
3134: }
3135: }
3136: }
3137: }
3138: if ((exists($privileged{$domain}{$username})) &&
3139: (!$nothide{$username.':'.$domain})) { next; }
3140: if ($role eq 'cr') { next; }
3141: if ($codes) {
3142: if ($section) { $role .= ':'.$section; }
3143: if ($returnhash{$role}) {
3144: $returnhash{$role}.=','.$username.':'.$domain;
3145: } else {
3146: $returnhash{$role}=$username.':'.$domain;
3147: }
3148: } else {
3149: my $key=&plaintext($role,$crstype);
3150: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
3151: if ($returnhash{$key}) {
3152: $returnhash{$key}.=','.$username.':'.$domain;
3153: } else {
3154: $returnhash{$key}=$username.':'.$domain;
3155: }
3156: }
3157: }
3158: return %returnhash;
3159: }
3160:
3161: sub get_my_roles {
3162: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
3163: unless (defined($uname)) { $uname=$env{'user.name'}; }
3164: unless (defined($udom)) { $udom=$env{'user.domain'}; }
3165: my (%dumphash,%nothide);
3166: if ($context eq 'userroles') {
3167: my $extra = &freeze_escape({'skipcheck' => 1});
3168: %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
3169: } else {
3170: %dumphash=
3171: &dump('nohist_userroles',$udom,$uname);
3172: if ($hidepriv) {
3173: my %coursehash=&coursedescription($udom.'_'.$uname);
3174: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3175: if ($user !~ /:/) {
3176: $nothide{join(':',split(/[\@]/,$user))} = 1;
3177: } else {
3178: $nothide{$user} = 1;
3179: }
3180: }
3181: }
3182: }
3183: my %returnhash=();
3184: my $now=time;
3185: my %privileged;
3186: foreach my $entry (keys(%dumphash)) {
3187: my ($role,$tend,$tstart);
3188: if ($context eq 'userroles') {
3189: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3190: } else {
3191: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3192: }
3193: if (($tstart) && ($tstart<0)) { next; }
3194: my $status = 'active';
3195: if (($tend) && ($tend<=$now)) {
3196: $status = 'previous';
3197: }
3198: if (($tstart) && ($now<$tstart)) {
3199: $status = 'future';
3200: }
3201: if (ref($types) eq 'ARRAY') {
3202: if (!grep(/^\Q$status\E$/,@{$types})) {
3203: next;
3204: }
3205: } else {
3206: if ($status ne 'active') {
3207: next;
3208: }
3209: }
3210: my ($rolecode,$username,$domain,$section,$area);
3211: if ($context eq 'userroles') {
3212: ($area,$rolecode) = split(/_/,$entry);
3213: (undef,$domain,$username,$section) = split(/\//,$area);
3214: } else {
3215: ($role,$username,$domain,$section) = split(/\:/,$entry);
3216: }
3217: if (ref($roledoms) eq 'ARRAY') {
3218: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3219: next;
3220: }
3221: }
3222: if (ref($roles) eq 'ARRAY') {
3223: if (!grep(/^\Q$role\E$/,@{$roles})) {
3224: if ($role =~ /^cr\//) {
3225: if (!grep(/^cr$/,@{$roles})) {
3226: next;
3227: }
3228: } else {
3229: next;
3230: }
3231: }
3232: }
3233: if ($hidepriv) {
3234: if ($context eq 'userroles') {
3235: if ((&privileged($username,$domain)) &&
3236: (!$nothide{$username.':'.$domain})) {
3237: next;
3238: }
3239: } else {
3240: unless (ref($privileged{$domain}) eq 'HASH') {
3241: my %dompersonnel =
3242: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3243: $privileged{$domain} = {};
3244: if (keys(%dompersonnel)) {
3245: foreach my $server (keys(%dompersonnel)) {
3246: if (ref($dompersonnel{$server}) eq 'HASH') {
3247: foreach my $user (keys(%{$dompersonnel{$server}})) {
3248: my ($trole,$uname,$udom) = split(/:/,$user);
3249: $privileged{$udom}{$uname} = $trole;
3250: }
3251: }
3252: }
3253: }
3254: }
3255: if (exists($privileged{$domain}{$username})) {
3256: if (!$nothide{$username.':'.$domain}) {
3257: next;
3258: }
3259: }
3260: }
3261: }
3262: if ($withsec) {
3263: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3264: $tstart.':'.$tend;
3265: } else {
3266: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3267: }
3268: }
3269: return %returnhash;
3270: }
3271:
3272: # ----------------------------------------------------- Frontpage Announcements
3273: #
3274: #
3275:
3276: sub postannounce {
3277: my ($server,$text)=@_;
3278: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
3279: unless ($text=~/\w/) { $text=''; }
3280: return &reply('setannounce:'.&escape($text),$server);
3281: }
3282:
3283: sub getannounce {
3284:
3285: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
3286: my $announcement='';
3287: while (my $line = <$fh>) { $announcement .= $line; }
3288: close($fh);
3289: if ($announcement=~/\w/) {
3290: return
3291: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
3292: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
3293: } else {
3294: return '';
3295: }
3296: } else {
3297: return '';
3298: }
3299: }
3300:
3301: # ---------------------------------------------------------- Course ID routines
3302: # Deal with domain's nohist_courseid.db files
3303: #
3304:
3305: sub courseidput {
3306: my ($domain,$storehash,$coursehome,$caller) = @_;
3307: return unless (ref($storehash) eq 'HASH');
3308: my $outcome;
3309: if ($caller eq 'timeonly') {
3310: my $cids = '';
3311: foreach my $item (keys(%$storehash)) {
3312: $cids.=&escape($item).'&';
3313: }
3314: $cids=~s/\&$//;
3315: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3316: $coursehome);
3317: } else {
3318: my $items = '';
3319: foreach my $item (keys(%$storehash)) {
3320: $items.= &escape($item).'='.
3321: &freeze_escape($$storehash{$item}).'&';
3322: }
3323: $items=~s/\&$//;
3324: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3325: $coursehome);
3326: }
3327: if ($outcome eq 'unknown_cmd') {
3328: my $what;
3329: foreach my $cid (keys(%$storehash)) {
3330: $what .= &escape($cid).'=';
3331: foreach my $item ('description','inst_code','owner','type') {
3332: $what .= &escape($storehash->{$cid}{$item}).':';
3333: }
3334: $what =~ s/\:$/&/;
3335: }
3336: $what =~ s/\&$//;
3337: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3338: } else {
3339: return $outcome;
3340: }
3341: }
3342:
3343: sub courseiddump {
3344: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
3345: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
3346: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
3347: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
3348: my $as_hash = 1;
3349: my %returnhash;
3350: if (!$domfilter) { $domfilter=''; }
3351: my %libserv = &all_library();
3352: foreach my $tryserver (keys(%libserv)) {
3353: if ( ( $hostidflag == 1
3354: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3355: || (!defined($hostidflag)) ) {
3356:
3357: if (($domfilter eq '') ||
3358: (&host_domain($tryserver) eq $domfilter)) {
3359: my $rep =
3360: &reply('courseiddump:'.&host_domain($tryserver).':'.
3361: $sincefilter.':'.&escape($descfilter).':'.
3362: &escape($instcodefilter).':'.&escape($ownerfilter).
3363: ':'.&escape($coursefilter).':'.&escape($typefilter).
3364: ':'.&escape($regexp_ok).':'.$as_hash.':'.
3365: &escape($selfenrollonly).':'.&escape($catfilter).':'.
3366: $showhidden.':'.$caller.':'.&escape($cloner).':'.
3367: &escape($cc_clone).':'.$cloneonly.':'.
3368: &escape($createdbefore).':'.&escape($createdafter).':'.
3369: &escape($creationcontext).':'.$domcloner,
3370: $tryserver);
3371: my @pairs=split(/\&/,$rep);
3372: foreach my $item (@pairs) {
3373: my ($key,$value)=split(/\=/,$item,2);
3374: $key = &unescape($key);
3375: next if ($key =~ /^error: 2 /);
3376: my $result = &thaw_unescape($value);
3377: if (ref($result) eq 'HASH') {
3378: $returnhash{$key}=$result;
3379: } else {
3380: my @responses = split(/:/,$value);
3381: my @items = ('description','inst_code','owner','type');
3382: for (my $i=0; $i<@responses; $i++) {
3383: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
3384: }
3385: }
3386: }
3387: }
3388: }
3389: }
3390: return %returnhash;
3391: }
3392:
3393: sub courselastaccess {
3394: my ($cdom,$cnum,$hostidref) = @_;
3395: my %returnhash;
3396: if ($cdom && $cnum) {
3397: my $chome = &homeserver($cnum,$cdom);
3398: if ($chome ne 'no_host') {
3399: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3400: &extract_lastaccess(\%returnhash,$rep);
3401: }
3402: } else {
3403: if (!$cdom) { $cdom=''; }
3404: my %libserv = &all_library();
3405: foreach my $tryserver (keys(%libserv)) {
3406: if (ref($hostidref) eq 'ARRAY') {
3407: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3408: }
3409: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3410: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3411: &extract_lastaccess(\%returnhash,$rep);
3412: }
3413: }
3414: }
3415: return %returnhash;
3416: }
3417:
3418: sub extract_lastaccess {
3419: my ($returnhash,$rep) = @_;
3420: if (ref($returnhash) eq 'HASH') {
3421: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3422: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3423: $rep eq '') {
3424: my @pairs=split(/\&/,$rep);
3425: foreach my $item (@pairs) {
3426: my ($key,$value)=split(/\=/,$item,2);
3427: $key = &unescape($key);
3428: next if ($key =~ /^error: 2 /);
3429: $returnhash->{$key} = &thaw_unescape($value);
3430: }
3431: }
3432: }
3433: return;
3434: }
3435:
3436: # ---------------------------------------------------------- DC e-mail
3437:
3438: sub dcmailput {
3439: my ($domain,$msgid,$message,$server)=@_;
3440: my $status = &Apache::lonnet::critical(
3441: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3442: &escape($message),$server);
3443: return $status;
3444: }
3445:
3446: sub dcmaildump {
3447: my ($dom,$startdate,$enddate,$senders) = @_;
3448: my %returnhash=();
3449:
3450: if (defined(&domain($dom,'primary'))) {
3451: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3452: &escape($enddate).':';
3453: my @esc_senders=map { &escape($_)} @$senders;
3454: $cmd.=&escape(join('&',@esc_senders));
3455: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
3456: my ($key,$value) = split(/\=/,$line,2);
3457: if (($key) && ($value)) {
3458: $returnhash{&unescape($key)} = &unescape($value);
3459: }
3460: }
3461: }
3462: return %returnhash;
3463: }
3464: # ---------------------------------------------------------- Domain roles
3465:
3466: sub get_domain_roles {
3467: my ($dom,$roles,$startdate,$enddate)=@_;
3468: if ((!defined($startdate)) || ($startdate eq '')) {
3469: $startdate = '.';
3470: }
3471: if ((!defined($enddate)) || ($enddate eq '')) {
3472: $enddate = '.';
3473: }
3474: my $rolelist;
3475: if (ref($roles) eq 'ARRAY') {
3476: $rolelist = join(':',@{$roles});
3477: }
3478: my %personnel = ();
3479:
3480: my %servers = &get_servers($dom,'library');
3481: foreach my $tryserver (keys(%servers)) {
3482: %{$personnel{$tryserver}}=();
3483: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3484: &escape($startdate).':'.
3485: &escape($enddate).':'.
3486: &escape($rolelist), $tryserver))) {
3487: my ($key,$value) = split(/\=/,$line,2);
3488: if (($key) && ($value)) {
3489: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3490: }
3491: }
3492: }
3493: return %personnel;
3494: }
3495:
3496: # ----------------------------------------------------------- Check out an item
3497:
3498: sub get_first_access {
3499: my ($type,$argsymb)=@_;
3500: my ($symb,$courseid,$udom,$uname)=&whichuser();
3501: if ($argsymb) { $symb=$argsymb; }
3502: my ($map,$id,$res)=&decode_symb($symb);
3503: if ($type eq 'course') {
3504: $res='course';
3505: } elsif ($type eq 'map') {
3506: $res=&symbread($map);
3507: } else {
3508: $res=$symb;
3509: }
3510: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3511: return $times{"$courseid\0$res"};
3512: }
3513:
3514: sub set_first_access {
3515: my ($type)=@_;
3516: my ($symb,$courseid,$udom,$uname)=&whichuser();
3517: my ($map,$id,$res)=&decode_symb($symb);
3518: if ($type eq 'course') {
3519: $res='course';
3520: } elsif ($type eq 'map') {
3521: $res=&symbread($map);
3522: } else {
3523: $res=$symb;
3524: }
3525: my $firstaccess=&get_first_access($type,$symb);
3526: if (!$firstaccess) {
3527: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
3528: }
3529: return 'already_set';
3530: }
3531:
3532: sub checkout {
3533: my ($symb,$tuname,$tudom,$tcrsid)=@_;
3534: my $now=time;
3535: my $lonhost=$perlvar{'lonHostID'};
3536: my $infostr=&escape(
3537: 'CHECKOUTTOKEN&'.
3538: $tuname.'&'.
3539: $tudom.'&'.
3540: $tcrsid.'&'.
3541: $symb.'&'.
3542: $now.'&'.$ENV{'REMOTE_ADDR'});
3543: my $token=&reply('tmpput:'.$infostr,$lonhost);
3544: if ($token=~/^error\:/) {
3545: &logthis("<font color=\"blue\">WARNING: ".
3546: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
3547: "</font>");
3548: return '';
3549: }
3550:
3551: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
3552: $token=~tr/a-z/A-Z/;
3553:
3554: my %infohash=('resource.0.outtoken' => $token,
3555: 'resource.0.checkouttime' => $now,
3556: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
3557:
3558: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3559: return '';
3560: } else {
3561: &logthis("<font color=\"blue\">WARNING: ".
3562: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
3563: "</font>");
3564: }
3565:
3566: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3567: &escape('Checkout '.$infostr.' - '.
3568: $token)) ne 'ok') {
3569: return '';
3570: } else {
3571: &logthis("<font color=\"blue\">WARNING: ".
3572: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
3573: "</font>");
3574: }
3575: return $token;
3576: }
3577:
3578: # ------------------------------------------------------------ Check in an item
3579:
3580: sub checkin {
3581: my $token=shift;
3582: my $now=time;
3583: my ($ta,$tb,$lonhost)=split(/\*/,$token);
3584: $lonhost=~tr/A-Z/a-z/;
3585: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
3586: $dtoken=~s/\W/\_/g;
3587: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
3588: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
3589:
3590: unless (($tuname) && ($tudom)) {
3591: &logthis('Check in '.$token.' ('.$dtoken.') failed');
3592: return '';
3593: }
3594:
3595: unless (&allowed('mgr',$tcrsid)) {
3596: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
3597: $env{'user.name'}.' - '.$env{'user.domain'});
3598: return '';
3599: }
3600:
3601: my %infohash=('resource.0.intoken' => $token,
3602: 'resource.0.checkintime' => $now,
3603: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
3604:
3605: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3606: return '';
3607: }
3608:
3609: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3610: &escape('Checkin - '.$token)) ne 'ok') {
3611: return '';
3612: }
3613:
3614: return ($symb,$tuname,$tudom,$tcrsid);
3615: }
3616:
3617: # --------------------------------------------- Set Expire Date for Spreadsheet
3618:
3619: sub expirespread {
3620: my ($uname,$udom,$stype,$usymb)=@_;
3621: my $cid=$env{'request.course.id'};
3622: if ($cid) {
3623: my $now=time;
3624: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
3625: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3626: $env{'course.'.$cid.'.num'}.
3627: ':nohist_expirationdates:'.
3628: &escape($key).'='.$now,
3629: $env{'course.'.$cid.'.home'})
3630: }
3631: return 'ok';
3632: }
3633:
3634: # ----------------------------------------------------- Devalidate Spreadsheets
3635:
3636: sub devalidate {
3637: my ($symb,$uname,$udom)=@_;
3638: my $cid=$env{'request.course.id'};
3639: if ($cid) {
3640: # delete the stored spreadsheets for
3641: # - the student level sheet of this user in course's homespace
3642: # - the assessment level sheet for this resource
3643: # for this user in user's homespace
3644: # - current conditional state info
3645: my $key=$uname.':'.$udom.':';
3646: my $status=
3647: &del('nohist_calculatedsheets',
3648: [$key.'studentcalc:'],
3649: $env{'course.'.$cid.'.domain'},
3650: $env{'course.'.$cid.'.num'})
3651: .' '.
3652: &del('nohist_calculatedsheets_'.$cid,
3653: [$key.'assesscalc:'.$symb],$udom,$uname);
3654: unless ($status eq 'ok ok') {
3655: &logthis('Could not devalidate spreadsheet '.
3656: $uname.' at '.$udom.' for '.
3657: $symb.': '.$status);
3658: }
3659: &delenv('user.state.'.$cid);
3660: }
3661: }
3662:
3663: sub get_scalar {
3664: my ($string,$end) = @_;
3665: my $value;
3666: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3667: $value = $1;
3668: } elsif ($$string =~ s/^([^&]*?)&//) {
3669: $value = $1;
3670: }
3671: return &unescape($value);
3672: }
3673:
3674: sub array2str {
3675: my (@array) = @_;
3676: my $result=&arrayref2str(\@array);
3677: $result=~s/^__ARRAY_REF__//;
3678: $result=~s/__END_ARRAY_REF__$//;
3679: return $result;
3680: }
3681:
3682: sub arrayref2str {
3683: my ($arrayref) = @_;
3684: my $result='__ARRAY_REF__';
3685: foreach my $elem (@$arrayref) {
3686: if(ref($elem) eq 'ARRAY') {
3687: $result.=&arrayref2str($elem).'&';
3688: } elsif(ref($elem) eq 'HASH') {
3689: $result.=&hashref2str($elem).'&';
3690: } elsif(ref($elem)) {
3691: #print("Got a ref of ".(ref($elem))." skipping.");
3692: } else {
3693: $result.=&escape($elem).'&';
3694: }
3695: }
3696: $result=~s/\&$//;
3697: $result .= '__END_ARRAY_REF__';
3698: return $result;
3699: }
3700:
3701: sub hash2str {
3702: my (%hash) = @_;
3703: my $result=&hashref2str(\%hash);
3704: $result=~s/^__HASH_REF__//;
3705: $result=~s/__END_HASH_REF__$//;
3706: return $result;
3707: }
3708:
3709: sub hashref2str {
3710: my ($hashref)=@_;
3711: my $result='__HASH_REF__';
3712: foreach my $key (sort(keys(%$hashref))) {
3713: if (ref($key) eq 'ARRAY') {
3714: $result.=&arrayref2str($key).'=';
3715: } elsif (ref($key) eq 'HASH') {
3716: $result.=&hashref2str($key).'=';
3717: } elsif (ref($key)) {
3718: $result.='=';
3719: #print("Got a ref of ".(ref($key))." skipping.");
3720: } else {
3721: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
3722: }
3723:
3724: if(ref($hashref->{$key}) eq 'ARRAY') {
3725: $result.=&arrayref2str($hashref->{$key}).'&';
3726: } elsif(ref($hashref->{$key}) eq 'HASH') {
3727: $result.=&hashref2str($hashref->{$key}).'&';
3728: } elsif(ref($hashref->{$key})) {
3729: $result.='&';
3730: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
3731: } else {
3732: $result.=&escape($hashref->{$key}).'&';
3733: }
3734: }
3735: $result=~s/\&$//;
3736: $result .= '__END_HASH_REF__';
3737: return $result;
3738: }
3739:
3740: sub str2hash {
3741: my ($string)=@_;
3742: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3743: return %$hash;
3744: }
3745:
3746: sub str2hashref {
3747: my ($string) = @_;
3748:
3749: my %hash;
3750:
3751: if($string !~ /^__HASH_REF__/) {
3752: if (! ($string eq '' || !defined($string))) {
3753: $hash{'error'}='Not hash reference';
3754: }
3755: return (\%hash, $string);
3756: }
3757:
3758: $string =~ s/^__HASH_REF__//;
3759:
3760: while($string !~ /^__END_HASH_REF__/) {
3761: #key
3762: my $key='';
3763: if($string =~ /^__HASH_REF__/) {
3764: ($key, $string)=&str2hashref($string);
3765: if(defined($key->{'error'})) {
3766: $hash{'error'}='Bad data';
3767: return (\%hash, $string);
3768: }
3769: } elsif($string =~ /^__ARRAY_REF__/) {
3770: ($key, $string)=&str2arrayref($string);
3771: if($key->[0] eq 'Array reference error') {
3772: $hash{'error'}='Bad data';
3773: return (\%hash, $string);
3774: }
3775: } else {
3776: $string =~ s/^(.*?)=//;
3777: $key=&unescape($1);
3778: }
3779: $string =~ s/^=//;
3780:
3781: #value
3782: my $value='';
3783: if($string =~ /^__HASH_REF__/) {
3784: ($value, $string)=&str2hashref($string);
3785: if(defined($value->{'error'})) {
3786: $hash{'error'}='Bad data';
3787: return (\%hash, $string);
3788: }
3789: } elsif($string =~ /^__ARRAY_REF__/) {
3790: ($value, $string)=&str2arrayref($string);
3791: if($value->[0] eq 'Array reference error') {
3792: $hash{'error'}='Bad data';
3793: return (\%hash, $string);
3794: }
3795: } else {
3796: $value=&get_scalar(\$string,'__END_HASH_REF__');
3797: }
3798: $string =~ s/^&//;
3799:
3800: $hash{$key}=$value;
3801: }
3802:
3803: $string =~ s/^__END_HASH_REF__//;
3804:
3805: return (\%hash, $string);
3806: }
3807:
3808: sub str2array {
3809: my ($string)=@_;
3810: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3811: return @$array;
3812: }
3813:
3814: sub str2arrayref {
3815: my ($string) = @_;
3816: my @array;
3817:
3818: if($string !~ /^__ARRAY_REF__/) {
3819: if (! ($string eq '' || !defined($string))) {
3820: $array[0]='Array reference error';
3821: }
3822: return (\@array, $string);
3823: }
3824:
3825: $string =~ s/^__ARRAY_REF__//;
3826:
3827: while($string !~ /^__END_ARRAY_REF__/) {
3828: my $value='';
3829: if($string =~ /^__HASH_REF__/) {
3830: ($value, $string)=&str2hashref($string);
3831: if(defined($value->{'error'})) {
3832: $array[0] ='Array reference error';
3833: return (\@array, $string);
3834: }
3835: } elsif($string =~ /^__ARRAY_REF__/) {
3836: ($value, $string)=&str2arrayref($string);
3837: if($value->[0] eq 'Array reference error') {
3838: $array[0] ='Array reference error';
3839: return (\@array, $string);
3840: }
3841: } else {
3842: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3843: }
3844: $string =~ s/^&//;
3845:
3846: push(@array, $value);
3847: }
3848:
3849: $string =~ s/^__END_ARRAY_REF__//;
3850:
3851: return (\@array, $string);
3852: }
3853:
3854: # -------------------------------------------------------------------Temp Store
3855:
3856: sub tmpreset {
3857: my ($symb,$namespace,$domain,$stuname) = @_;
3858: if (!$symb) {
3859: $symb=&symbread();
3860: if (!$symb) { $symb= $env{'request.url'}; }
3861: }
3862: $symb=escape($symb);
3863:
3864: if (!$namespace) { $namespace=$env{'request.state'}; }
3865: $namespace=~s/\//\_/g;
3866: $namespace=~s/\W//g;
3867:
3868: if (!$domain) { $domain=$env{'user.domain'}; }
3869: if (!$stuname) { $stuname=$env{'user.name'}; }
3870: if ($domain eq 'public' && $stuname eq 'public') {
3871: $stuname=$ENV{'REMOTE_ADDR'};
3872: }
3873: my $path=$perlvar{'lonDaemons'}.'/tmp';
3874: my %hash;
3875: if (tie(%hash,'GDBM_File',
3876: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
3877: &GDBM_WRCREAT(),0640)) {
3878: foreach my $key (keys(%hash)) {
3879: if ($key=~ /:$symb/) {
3880: delete($hash{$key});
3881: }
3882: }
3883: }
3884: }
3885:
3886: sub tmpstore {
3887: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3888:
3889: if (!$symb) {
3890: $symb=&symbread();
3891: if (!$symb) { $symb= $env{'request.url'}; }
3892: }
3893: $symb=escape($symb);
3894:
3895: if (!$namespace) {
3896: # I don't think we would ever want to store this for a course.
3897: # it seems this will only be used if we don't have a course.
3898: #$namespace=$env{'request.course.id'};
3899: #if (!$namespace) {
3900: $namespace=$env{'request.state'};
3901: #}
3902: }
3903: $namespace=~s/\//\_/g;
3904: $namespace=~s/\W//g;
3905: if (!$domain) { $domain=$env{'user.domain'}; }
3906: if (!$stuname) { $stuname=$env{'user.name'}; }
3907: if ($domain eq 'public' && $stuname eq 'public') {
3908: $stuname=$ENV{'REMOTE_ADDR'};
3909: }
3910: my $now=time;
3911: my %hash;
3912: my $path=$perlvar{'lonDaemons'}.'/tmp';
3913: if (tie(%hash,'GDBM_File',
3914: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
3915: &GDBM_WRCREAT(),0640)) {
3916: $hash{"version:$symb"}++;
3917: my $version=$hash{"version:$symb"};
3918: my $allkeys='';
3919: foreach my $key (keys(%$storehash)) {
3920: $allkeys.=$key.':';
3921: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
3922: }
3923: $hash{"$version:$symb:timestamp"}=$now;
3924: $allkeys.='timestamp';
3925: $hash{"$version:keys:$symb"}=$allkeys;
3926: if (untie(%hash)) {
3927: return 'ok';
3928: } else {
3929: return "error:$!";
3930: }
3931: } else {
3932: return "error:$!";
3933: }
3934: }
3935:
3936: # -----------------------------------------------------------------Temp Restore
3937:
3938: sub tmprestore {
3939: my ($symb,$namespace,$domain,$stuname) = @_;
3940:
3941: if (!$symb) {
3942: $symb=&symbread();
3943: if (!$symb) { $symb= $env{'request.url'}; }
3944: }
3945: $symb=escape($symb);
3946:
3947: if (!$namespace) { $namespace=$env{'request.state'}; }
3948:
3949: if (!$domain) { $domain=$env{'user.domain'}; }
3950: if (!$stuname) { $stuname=$env{'user.name'}; }
3951: if ($domain eq 'public' && $stuname eq 'public') {
3952: $stuname=$ENV{'REMOTE_ADDR'};
3953: }
3954: my %returnhash;
3955: $namespace=~s/\//\_/g;
3956: $namespace=~s/\W//g;
3957: my %hash;
3958: my $path=$perlvar{'lonDaemons'}.'/tmp';
3959: if (tie(%hash,'GDBM_File',
3960: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
3961: &GDBM_READER(),0640)) {
3962: my $version=$hash{"version:$symb"};
3963: $returnhash{'version'}=$version;
3964: my $scope;
3965: for ($scope=1;$scope<=$version;$scope++) {
3966: my $vkeys=$hash{"$scope:keys:$symb"};
3967: my @keys=split(/:/,$vkeys);
3968: my $key;
3969: $returnhash{"$scope:keys"}=$vkeys;
3970: foreach $key (@keys) {
3971: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3972: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3973: }
3974: }
3975: if (!(untie(%hash))) {
3976: return "error:$!";
3977: }
3978: } else {
3979: return "error:$!";
3980: }
3981: return %returnhash;
3982: }
3983:
3984: # ----------------------------------------------------------------------- Store
3985:
3986: sub store {
3987: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3988: my $home='';
3989:
3990: if ($stuname) { $home=&homeserver($stuname,$domain); }
3991:
3992: $symb=&symbclean($symb);
3993: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
3994:
3995: if (!$domain) { $domain=$env{'user.domain'}; }
3996: if (!$stuname) { $stuname=$env{'user.name'}; }
3997:
3998: &devalidate($symb,$stuname,$domain);
3999:
4000: $symb=escape($symb);
4001: if (!$namespace) {
4002: unless ($namespace=$env{'request.course.id'}) {
4003: return '';
4004: }
4005: }
4006: if (!$home) { $home=$env{'user.home'}; }
4007:
4008: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4009: $$storehash{'host'}=$perlvar{'lonHostID'};
4010:
4011: my $namevalue='';
4012: foreach my $key (keys(%$storehash)) {
4013: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4014: }
4015: $namevalue=~s/\&$//;
4016: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
4017: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4018: }
4019:
4020: # -------------------------------------------------------------- Critical Store
4021:
4022: sub cstore {
4023: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4024: my $home='';
4025:
4026: if ($stuname) { $home=&homeserver($stuname,$domain); }
4027:
4028: $symb=&symbclean($symb);
4029: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4030:
4031: if (!$domain) { $domain=$env{'user.domain'}; }
4032: if (!$stuname) { $stuname=$env{'user.name'}; }
4033:
4034: &devalidate($symb,$stuname,$domain);
4035:
4036: $symb=escape($symb);
4037: if (!$namespace) {
4038: unless ($namespace=$env{'request.course.id'}) {
4039: return '';
4040: }
4041: }
4042: if (!$home) { $home=$env{'user.home'}; }
4043:
4044: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4045: $$storehash{'host'}=$perlvar{'lonHostID'};
4046:
4047: my $namevalue='';
4048: foreach my $key (keys(%$storehash)) {
4049: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4050: }
4051: $namevalue=~s/\&$//;
4052: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
4053: return critical
4054: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4055: }
4056:
4057: # --------------------------------------------------------------------- Restore
4058:
4059: sub restore {
4060: my ($symb,$namespace,$domain,$stuname) = @_;
4061: my $home='';
4062:
4063: if ($stuname) { $home=&homeserver($stuname,$domain); }
4064:
4065: if (!$symb) {
4066: unless ($symb=escape(&symbread())) { return ''; }
4067: } else {
4068: $symb=&escape(&symbclean($symb));
4069: }
4070: if (!$namespace) {
4071: unless ($namespace=$env{'request.course.id'}) {
4072: return '';
4073: }
4074: }
4075: if (!$domain) { $domain=$env{'user.domain'}; }
4076: if (!$stuname) { $stuname=$env{'user.name'}; }
4077: if (!$home) { $home=$env{'user.home'}; }
4078: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4079:
4080: my %returnhash=();
4081: foreach my $line (split(/\&/,$answer)) {
4082: my ($name,$value)=split(/\=/,$line);
4083: $returnhash{&unescape($name)}=&thaw_unescape($value);
4084: }
4085: my $version;
4086: for ($version=1;$version<=$returnhash{'version'};$version++) {
4087: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4088: $returnhash{$item}=$returnhash{$version.':'.$item};
4089: }
4090: }
4091: return %returnhash;
4092: }
4093:
4094: # ---------------------------------------------------------- Course Description
4095:
4096: sub coursedescription {
4097: my ($courseid,$args)=@_;
4098: $courseid=~s/^\///;
4099: $courseid=~s/\_/\//g;
4100: my ($cdomain,$cnum)=split(/\//,$courseid);
4101: my $chome=&homeserver($cnum,$cdomain);
4102: my $normalid=$cdomain.'_'.$cnum;
4103: # need to always cache even if we get errors otherwise we keep
4104: # trying and trying and trying to get the course description.
4105: my %envhash=();
4106: my %returnhash=();
4107:
4108: my $expiretime=600;
4109: if ($env{'request.course.id'} eq $normalid) {
4110: $expiretime=120;
4111: }
4112:
4113: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4114: if (!$args->{'freshen_cache'}
4115: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4116: foreach my $key (keys(%env)) {
4117: next if ($key !~ /^\Q$prefix\E(.*)/);
4118: my ($setting) = $1;
4119: $returnhash{$setting} = $env{$key};
4120: }
4121: return %returnhash;
4122: }
4123:
4124: # get the data agin
4125: if (!$args->{'one_time'}) {
4126: $envhash{'course.'.$normalid.'.last_cache'}=time;
4127: }
4128:
4129: if ($chome ne 'no_host') {
4130: %returnhash=&dump('environment',$cdomain,$cnum);
4131: if (!exists($returnhash{'con_lost'})) {
4132: $returnhash{'home'}= $chome;
4133: $returnhash{'domain'} = $cdomain;
4134: $returnhash{'num'} = $cnum;
4135: if (!defined($returnhash{'type'})) {
4136: $returnhash{'type'} = 'Course';
4137: }
4138: while (my ($name,$value) = each %returnhash) {
4139: $envhash{'course.'.$normalid.'.'.$name}=$value;
4140: }
4141: $returnhash{'url'}=&clutter($returnhash{'url'});
4142: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
4143: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
4144: $envhash{'course.'.$normalid.'.home'}=$chome;
4145: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4146: $envhash{'course.'.$normalid.'.num'}=$cnum;
4147: }
4148: }
4149: if (!$args->{'one_time'}) {
4150: &appenv(\%envhash);
4151: }
4152: return %returnhash;
4153: }
4154:
4155: sub update_released_required {
4156: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4157: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4158: $cid = $env{'request.course.id'};
4159: $cdom = $env{'course.'.$cid.'.domain'};
4160: $cnum = $env{'course.'.$cid.'.num'};
4161: $chome = $env{'course.'.$cid.'.home'};
4162: }
4163: if ($needsrelease) {
4164: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4165: my $needsupdate;
4166: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4167: $needsupdate = 1;
4168: } else {
4169: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4170: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4171: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4172: $needsupdate = 1;
4173: }
4174: }
4175: if ($needsupdate) {
4176: my %needshash = (
4177: 'internal.releaserequired' => $needsrelease,
4178: );
4179: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4180: if ($putresult eq 'ok') {
4181: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4182: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4183: if (ref($crsinfo{$cid}) eq 'HASH') {
4184: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4185: &courseidput($cdom,\%crsinfo,$chome,'notime');
4186: }
4187: }
4188: }
4189: }
4190: return;
4191: }
4192:
4193: # -------------------------------------------------See if a user is privileged
4194:
4195: sub privileged {
4196: my ($username,$domain)=@_;
4197: my $rolesdump=&reply("dump:$domain:$username:roles",
4198: &homeserver($username,$domain));
4199: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4200: ($rolesdump =~ /^error:/)) {
4201: return 0;
4202: }
4203: my $now=time;
4204: if ($rolesdump ne '') {
4205: foreach my $entry (split(/&/,$rolesdump)) {
4206: if ($entry!~/^rolesdef_/) {
4207: my ($area,$role)=split(/=/,$entry);
4208: $area=~s/\_\w\w$//;
4209: my ($trole,$tend,$tstart)=split(/_/,$role);
4210: if (($trole eq 'dc') || ($trole eq 'su')) {
4211: my $active=1;
4212: if ($tend) {
4213: if ($tend<$now) { $active=0; }
4214: }
4215: if ($tstart) {
4216: if ($tstart>$now) { $active=0; }
4217: }
4218: if ($active) { return 1; }
4219: }
4220: }
4221: }
4222: }
4223: return 0;
4224: }
4225:
4226: # -------------------------------------------------------- Get user privileges
4227:
4228: sub rolesinit {
4229: my ($domain,$username,$authhost)=@_;
4230: my $now=time;
4231: my %userroles = ('user.login.time' => $now);
4232: my $extra = &freeze_escape({'skipcheck' => 1});
4233: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
4234: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4235: ($rolesdump =~ /^error:/)) {
4236: return \%userroles;
4237: }
4238: my %allroles=();
4239: my %allgroups=();
4240: my $group_privs;
4241:
4242: if ($rolesdump ne '') {
4243: foreach my $entry (split(/&/,$rolesdump)) {
4244: if ($entry!~/^rolesdef_/) {
4245: my ($area,$role)=split(/=/,$entry);
4246: $area=~s/\_\w\w$//;
4247: my ($trole,$tend,$tstart,$group_privs);
4248: if ($role=~/^cr/) {
4249: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4250: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
4251: ($tend,$tstart)=split('_',$trest);
4252: } else {
4253: $trole=$role;
4254: }
4255: } elsif ($role =~ m|^gr/|) {
4256: ($trole,$tend,$tstart) = split(/_/,$role);
4257: ($trole,$group_privs) = split(/\//,$trole);
4258: $group_privs = &unescape($group_privs);
4259: } else {
4260: ($trole,$tend,$tstart)=split(/_/,$role);
4261: }
4262: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4263: $username);
4264: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
4265: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4266: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
4267: if (($area ne '') && ($trole ne '')) {
4268: my $spec=$trole.'.'.$area;
4269: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4270: if ($trole =~ /^cr\//) {
4271: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4272: } elsif ($trole eq 'gr') {
4273: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
4274: } else {
4275: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4276: }
4277: }
4278: }
4279: }
4280: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4281: $userroles{'user.adv'} = $adv;
4282: $userroles{'user.author'} = $author;
4283: $env{'user.adv'}=$adv;
4284: }
4285: return \%userroles;
4286: }
4287:
4288: sub set_arearole {
4289: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4290: # log the associated role with the area
4291: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
4292: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
4293: }
4294:
4295: sub custom_roleprivs {
4296: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4297: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4298: my $homsvr=homeserver($rauthor,$rdomain);
4299: if (&hostname($homsvr) ne '') {
4300: my ($rdummy,$roledef)=
4301: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4302: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4303: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4304: if (defined($syspriv)) {
4305: if ($trest =~ /^$match_community$/) {
4306: $syspriv =~ s/bre\&S//;
4307: }
4308: $$allroles{'cm./'}.=':'.$syspriv;
4309: $$allroles{$spec.'./'}.=':'.$syspriv;
4310: }
4311: if ($tdomain ne '') {
4312: if (defined($dompriv)) {
4313: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4314: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4315: }
4316: if (($trest ne '') && (defined($coursepriv))) {
4317: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4318: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4319: }
4320: }
4321: }
4322: }
4323: }
4324:
4325: sub group_roleprivs {
4326: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4327: my $access = 1;
4328: my $now = time;
4329: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4330: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4331: if ($access) {
4332: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
4333: $$allgroups{$course}{$group} .=':'.$group_privs;
4334: }
4335: }
4336:
4337: sub standard_roleprivs {
4338: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4339: if (defined($pr{$trole.':s'})) {
4340: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4341: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4342: }
4343: if ($tdomain ne '') {
4344: if (defined($pr{$trole.':d'})) {
4345: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4346: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4347: }
4348: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4349: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4350: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4351: }
4352: }
4353: }
4354:
4355: sub set_userprivs {
4356: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
4357: my $author=0;
4358: my $adv=0;
4359: my %grouproles = ();
4360: if (keys(%{$allgroups}) > 0) {
4361: my @groupkeys;
4362: foreach my $role (keys(%{$allroles})) {
4363: push(@groupkeys,$role);
4364: }
4365: if (ref($groups_roles) eq 'HASH') {
4366: foreach my $key (keys(%{$groups_roles})) {
4367: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4368: push(@groupkeys,$key);
4369: }
4370: }
4371: }
4372: if (@groupkeys > 0) {
4373: foreach my $role (@groupkeys) {
4374: my ($trole,$area,$sec,$extendedarea);
4375: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4376: $trole = $1;
4377: $area = $2;
4378: $sec = $3;
4379: $extendedarea = $area.$sec;
4380: if (exists($$allgroups{$area})) {
4381: foreach my $group (keys(%{$$allgroups{$area}})) {
4382: my $spec = $trole.'.'.$extendedarea;
4383: $grouproles{$spec.'.'.$area.'/'.$group} =
4384: $$allgroups{$area}{$group};
4385: }
4386: }
4387: }
4388: }
4389: }
4390: }
4391: foreach my $group (keys(%grouproles)) {
4392: $$allroles{$group} = $grouproles{$group};
4393: }
4394: foreach my $role (keys(%{$allroles})) {
4395: my %thesepriv;
4396: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
4397: foreach my $item (split(/:/,$$allroles{$role})) {
4398: if ($item ne '') {
4399: my ($privilege,$restrictions)=split(/&/,$item);
4400: if ($restrictions eq '') {
4401: $thesepriv{$privilege}='F';
4402: } elsif ($thesepriv{$privilege} ne 'F') {
4403: $thesepriv{$privilege}.=$restrictions;
4404: }
4405: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4406: }
4407: }
4408: my $thesestr='';
4409: foreach my $priv (keys(%thesepriv)) {
4410: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4411: }
4412: $userroles->{'user.priv.'.$role} = $thesestr;
4413: }
4414: return ($author,$adv);
4415: }
4416:
4417: sub role_status {
4418: my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
4419: my @pwhere = ();
4420: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4421: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4422: unless (!defined($$role) || $$role eq '') {
4423: $$where=join('.',@pwhere);
4424: $$trolecode=$$role.'.'.$$where;
4425: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4426: $$tstatus='is';
4427: if ($$tstart && $$tstart>$then) {
4428: $$tstatus='future';
4429: if ($$tstart<$now) {
4430: if ($$tstart && $$tstart>$refresh) {
4431: if (($$where ne '') && ($$role ne '')) {
4432: my (%allroles,%allgroups,$group_privs,
4433: %groups_roles,@rolecodes);
4434: my %userroles = (
4435: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4436: );
4437: @rolecodes = ('cm');
4438: my $spec=$$role.'.'.$$where;
4439: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4440: if ($$role =~ /^cr\//) {
4441: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
4442: push(@rolecodes,'cr');
4443: } elsif ($$role eq 'gr') {
4444: push(@rolecodes,$$role);
4445: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4446: $env{'user.name'});
4447: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
4448: (undef,my $group_privs) = split(/\//,$trole);
4449: $group_privs = &unescape($group_privs);
4450: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
4451: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4452: if (keys(%course_roles) > 0) {
4453: my ($tnum) = ($trest =~ /^($match_courseid)/);
4454: if ($tdomain ne '' && $tnum ne '') {
4455: foreach my $key (keys(%course_roles)) {
4456: if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
4457: my $crsrole = $1;
4458: my $crssec = $2;
4459: if ($crsrole =~ /^cr/) {
4460: unless (grep(/^cr$/,@rolecodes)) {
4461: push(@rolecodes,'cr');
4462: }
4463: } else {
4464: unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
4465: push(@rolecodes,$crsrole);
4466: }
4467: }
4468: my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
4469: if ($crssec ne '') {
4470: $rolekey .= '/'.$crssec;
4471: }
4472: $rolekey .= './';
4473: $groups_roles{$rolekey} = \@rolecodes;
4474: }
4475: }
4476: }
4477: }
4478: } else {
4479: push(@rolecodes,$$role);
4480: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4481: }
4482: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4483: &appenv(\%userroles,\@rolecodes);
4484: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4485: }
4486: }
4487: $$tstatus = 'is';
4488: }
4489: }
4490: if ($$tend) {
4491: if ($$tend<$then) {
4492: $$tstatus='expired';
4493: } elsif ($$tend<$now) {
4494: $$tstatus='will_not';
4495: }
4496: }
4497: }
4498: }
4499: }
4500:
4501: sub check_adhoc_privs {
4502: my ($cdom,$cnum,$then,$refresh,$now,$checkrole,$caller) = @_;
4503: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4504: if ($env{$cckey}) {
4505: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
4506: &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
4507: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
4508: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
4509: }
4510: } else {
4511: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
4512: }
4513: }
4514:
4515: sub set_adhoc_privileges {
4516: # role can be cc or ca
4517: my ($dcdom,$pickedcourse,$role,$caller) = @_;
4518: my $area = '/'.$dcdom.'/'.$pickedcourse;
4519: my $spec = $role.'.'.$area;
4520: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4521: $env{'user.name'});
4522: my %ccrole = ();
4523: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4524: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4525: &appenv(\%userroles,[$role,'cm']);
4526: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4527: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
4528: &appenv( {'request.role' => $spec,
4529: 'request.role.domain' => $dcdom,
4530: 'request.course.sec' => ''
4531: }
4532: );
4533: my $tadv=0;
4534: if (&allowed('adv') eq 'F') { $tadv=1; }
4535: &appenv({'request.role.adv' => $tadv});
4536: }
4537: }
4538:
4539: # --------------------------------------------------------------- get interface
4540:
4541: sub get {
4542: my ($namespace,$storearr,$udomain,$uname)=@_;
4543: my $items='';
4544: foreach my $item (@$storearr) {
4545: $items.=&escape($item).'&';
4546: }
4547: $items=~s/\&$//;
4548: if (!$udomain) { $udomain=$env{'user.domain'}; }
4549: if (!$uname) { $uname=$env{'user.name'}; }
4550: my $uhome=&homeserver($uname,$udomain);
4551:
4552: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
4553: my @pairs=split(/\&/,$rep);
4554: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4555: return @pairs;
4556: }
4557: my %returnhash=();
4558: my $i=0;
4559: foreach my $item (@$storearr) {
4560: $returnhash{$item}=&thaw_unescape($pairs[$i]);
4561: $i++;
4562: }
4563: return %returnhash;
4564: }
4565:
4566: # --------------------------------------------------------------- del interface
4567:
4568: sub del {
4569: my ($namespace,$storearr,$udomain,$uname)=@_;
4570: my $items='';
4571: foreach my $item (@$storearr) {
4572: $items.=&escape($item).'&';
4573: }
4574:
4575: $items=~s/\&$//;
4576: if (!$udomain) { $udomain=$env{'user.domain'}; }
4577: if (!$uname) { $uname=$env{'user.name'}; }
4578: my $uhome=&homeserver($uname,$udomain);
4579: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
4580: }
4581:
4582: # -------------------------------------------------------------- dump interface
4583:
4584: sub dump {
4585: my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
4586: if (!$udomain) { $udomain=$env{'user.domain'}; }
4587: if (!$uname) { $uname=$env{'user.name'}; }
4588: my $uhome=&homeserver($uname,$udomain);
4589: if ($regexp) {
4590: $regexp=&escape($regexp);
4591: } else {
4592: $regexp='.';
4593: }
4594: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
4595: my @pairs=split(/\&/,$rep);
4596: my %returnhash=();
4597: foreach my $item (@pairs) {
4598: my ($key,$value)=split(/=/,$item,2);
4599: $key = &unescape($key);
4600: next if ($key =~ /^error: 2 /);
4601: $returnhash{$key}=&thaw_unescape($value);
4602: }
4603: return %returnhash;
4604: }
4605:
4606: # --------------------------------------------------------- dumpstore interface
4607:
4608: sub dumpstore {
4609: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
4610: if (!$udomain) { $udomain=$env{'user.domain'}; }
4611: if (!$uname) { $uname=$env{'user.name'}; }
4612: my $uhome=&homeserver($uname,$udomain);
4613: if ($regexp) {
4614: $regexp=&escape($regexp);
4615: } else {
4616: $regexp='.';
4617: }
4618: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4619: my @pairs=split(/\&/,$rep);
4620: my %returnhash=();
4621: foreach my $item (@pairs) {
4622: my ($key,$value)=split(/=/,$item,2);
4623: next if ($key =~ /^error: 2 /);
4624: $returnhash{$key}=&thaw_unescape($value);
4625: }
4626: return %returnhash;
4627: }
4628:
4629: # -------------------------------------------------------------- keys interface
4630:
4631: sub getkeys {
4632: my ($namespace,$udomain,$uname)=@_;
4633: if (!$udomain) { $udomain=$env{'user.domain'}; }
4634: if (!$uname) { $uname=$env{'user.name'}; }
4635: my $uhome=&homeserver($uname,$udomain);
4636: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4637: my @keyarray=();
4638: foreach my $key (split(/\&/,$rep)) {
4639: next if ($key =~ /^error: 2 /);
4640: push(@keyarray,&unescape($key));
4641: }
4642: return @keyarray;
4643: }
4644:
4645: # --------------------------------------------------------------- currentdump
4646: sub currentdump {
4647: my ($courseid,$sdom,$sname)=@_;
4648: $courseid = $env{'request.course.id'} if (! defined($courseid));
4649: $sdom = $env{'user.domain'} if (! defined($sdom));
4650: $sname = $env{'user.name'} if (! defined($sname));
4651: my $uhome = &homeserver($sname,$sdom);
4652: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
4653: return if ($rep =~ /^(error:|no_such_host)/);
4654: #
4655: my %returnhash=();
4656: #
4657: if ($rep eq "unknown_cmd") {
4658: # an old lond will not know currentdump
4659: # Do a dump and make it look like a currentdump
4660: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
4661: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4662: my %hash = @tmp;
4663: @tmp=();
4664: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
4665: } else {
4666: my @pairs=split(/\&/,$rep);
4667: foreach my $pair (@pairs) {
4668: my ($key,$value)=split(/=/,$pair,2);
4669: my ($symb,$param) = split(/:/,$key);
4670: $returnhash{&unescape($symb)}->{&unescape($param)} =
4671: &thaw_unescape($value);
4672: }
4673: }
4674: return %returnhash;
4675: }
4676:
4677: sub convert_dump_to_currentdump{
4678: my %hash = %{shift()};
4679: my %returnhash;
4680: # Code ripped from lond, essentially. The only difference
4681: # here is the unescaping done by lonnet::dump(). Conceivably
4682: # we might run in to problems with parameter names =~ /^v\./
4683: while (my ($key,$value) = each(%hash)) {
4684: my ($v,$symb,$param) = split(/:/,$key);
4685: $symb = &unescape($symb);
4686: $param = &unescape($param);
4687: next if ($v eq 'version' || $symb eq 'keys');
4688: next if (exists($returnhash{$symb}) &&
4689: exists($returnhash{$symb}->{$param}) &&
4690: $returnhash{$symb}->{'v.'.$param} > $v);
4691: $returnhash{$symb}->{$param}=$value;
4692: $returnhash{$symb}->{'v.'.$param}=$v;
4693: }
4694: #
4695: # Remove all of the keys in the hashes which keep track of
4696: # the version of the parameter.
4697: while (my ($symb,$param_hash) = each(%returnhash)) {
4698: # use a foreach because we are going to delete from the hash.
4699: foreach my $key (keys(%$param_hash)) {
4700: delete($param_hash->{$key}) if ($key =~ /^v\./);
4701: }
4702: }
4703: return \%returnhash;
4704: }
4705:
4706: # ------------------------------------------------------ critical inc interface
4707:
4708: sub cinc {
4709: return &inc(@_,'critical');
4710: }
4711:
4712: # --------------------------------------------------------------- inc interface
4713:
4714: sub inc {
4715: my ($namespace,$store,$udomain,$uname,$critical) = @_;
4716: if (!$udomain) { $udomain=$env{'user.domain'}; }
4717: if (!$uname) { $uname=$env{'user.name'}; }
4718: my $uhome=&homeserver($uname,$udomain);
4719: my $items='';
4720: if (! ref($store)) {
4721: # got a single value, so use that instead
4722: $items = &escape($store).'=&';
4723: } elsif (ref($store) eq 'SCALAR') {
4724: $items = &escape($$store).'=&';
4725: } elsif (ref($store) eq 'ARRAY') {
4726: $items = join('=&',map {&escape($_);} @{$store});
4727: } elsif (ref($store) eq 'HASH') {
4728: while (my($key,$value) = each(%{$store})) {
4729: $items.= &escape($key).'='.&escape($value).'&';
4730: }
4731: }
4732: $items=~s/\&$//;
4733: if ($critical) {
4734: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4735: } else {
4736: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4737: }
4738: }
4739:
4740: # --------------------------------------------------------------- put interface
4741:
4742: sub put {
4743: my ($namespace,$storehash,$udomain,$uname)=@_;
4744: if (!$udomain) { $udomain=$env{'user.domain'}; }
4745: if (!$uname) { $uname=$env{'user.name'}; }
4746: my $uhome=&homeserver($uname,$udomain);
4747: my $items='';
4748: foreach my $item (keys(%$storehash)) {
4749: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
4750: }
4751: $items=~s/\&$//;
4752: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
4753: }
4754:
4755: # ------------------------------------------------------------ newput interface
4756:
4757: sub newput {
4758: my ($namespace,$storehash,$udomain,$uname)=@_;
4759: if (!$udomain) { $udomain=$env{'user.domain'}; }
4760: if (!$uname) { $uname=$env{'user.name'}; }
4761: my $uhome=&homeserver($uname,$udomain);
4762: my $items='';
4763: foreach my $key (keys(%$storehash)) {
4764: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4765: }
4766: $items=~s/\&$//;
4767: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4768: }
4769:
4770: # --------------------------------------------------------- putstore interface
4771:
4772: sub putstore {
4773: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4774: if (!$udomain) { $udomain=$env{'user.domain'}; }
4775: if (!$uname) { $uname=$env{'user.name'}; }
4776: my $uhome=&homeserver($uname,$udomain);
4777: my $items='';
4778: foreach my $key (keys(%$storehash)) {
4779: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
4780: }
4781: $items=~s/\&$//;
4782: my $esc_symb=&escape($symb);
4783: my $esc_v=&escape($version);
4784: my $reply =
4785: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
4786: $uhome);
4787: if ($reply eq 'unknown_cmd') {
4788: # gfall back to way things use to be done
4789: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4790: $uname);
4791: }
4792: return $reply;
4793: }
4794:
4795: sub old_putstore {
4796: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4797: if (!$udomain) { $udomain=$env{'user.domain'}; }
4798: if (!$uname) { $uname=$env{'user.name'}; }
4799: my $uhome=&homeserver($uname,$udomain);
4800: my %newstorehash;
4801: foreach my $item (keys(%$storehash)) {
4802: my $key = $version.':'.&escape($symb).':'.$item;
4803: $newstorehash{$key} = $storehash->{$item};
4804: }
4805: my $items='';
4806: my %allitems = ();
4807: foreach my $item (keys(%newstorehash)) {
4808: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
4809: my $key = $1.':keys:'.$2;
4810: $allitems{$key} .= $3.':';
4811: }
4812: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
4813: }
4814: foreach my $item (keys(%allitems)) {
4815: $allitems{$item} =~ s/\:$//;
4816: $items.= $item.'='.$allitems{$item}.'&';
4817: }
4818: $items=~s/\&$//;
4819: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
4820: }
4821:
4822: # ------------------------------------------------------ critical put interface
4823:
4824: sub cput {
4825: my ($namespace,$storehash,$udomain,$uname)=@_;
4826: if (!$udomain) { $udomain=$env{'user.domain'}; }
4827: if (!$uname) { $uname=$env{'user.name'}; }
4828: my $uhome=&homeserver($uname,$udomain);
4829: my $items='';
4830: foreach my $item (keys(%$storehash)) {
4831: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
4832: }
4833: $items=~s/\&$//;
4834: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
4835: }
4836:
4837: # -------------------------------------------------------------- eget interface
4838:
4839: sub eget {
4840: my ($namespace,$storearr,$udomain,$uname)=@_;
4841: my $items='';
4842: foreach my $item (@$storearr) {
4843: $items.=&escape($item).'&';
4844: }
4845: $items=~s/\&$//;
4846: if (!$udomain) { $udomain=$env{'user.domain'}; }
4847: if (!$uname) { $uname=$env{'user.name'}; }
4848: my $uhome=&homeserver($uname,$udomain);
4849: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
4850: my @pairs=split(/\&/,$rep);
4851: my %returnhash=();
4852: my $i=0;
4853: foreach my $item (@$storearr) {
4854: $returnhash{$item}=&thaw_unescape($pairs[$i]);
4855: $i++;
4856: }
4857: return %returnhash;
4858: }
4859:
4860: # ------------------------------------------------------------ tmpput interface
4861: sub tmpput {
4862: my ($storehash,$server,$context)=@_;
4863: my $items='';
4864: foreach my $item (keys(%$storehash)) {
4865: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
4866: }
4867: $items=~s/\&$//;
4868: if (defined($context)) {
4869: $items .= ':'.&escape($context);
4870: }
4871: return &reply("tmpput:$items",$server);
4872: }
4873:
4874: # ------------------------------------------------------------ tmpget interface
4875: sub tmpget {
4876: my ($token,$server)=@_;
4877: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4878: my $rep=&reply("tmpget:$token",$server);
4879: my %returnhash;
4880: foreach my $item (split(/\&/,$rep)) {
4881: my ($key,$value)=split(/=/,$item);
4882: next if ($key =~ /^error: 2 /);
4883: $returnhash{&unescape($key)}=&thaw_unescape($value);
4884: }
4885: return %returnhash;
4886: }
4887:
4888: # ------------------------------------------------------------ tmpget interface
4889: sub tmpdel {
4890: my ($token,$server)=@_;
4891: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4892: return &reply("tmpdel:$token",$server);
4893: }
4894:
4895: # -------------------------------------------------- portfolio access checking
4896:
4897: sub portfolio_access {
4898: my ($requrl) = @_;
4899: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4900: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
4901: if ($result) {
4902: my %setters;
4903: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4904: my ($startblock,$endblock) =
4905: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4906: if ($startblock && $endblock) {
4907: return 'B';
4908: }
4909: } else {
4910: my ($startblock,$endblock) =
4911: &Apache::loncommon::blockcheck(\%setters,'port');
4912: if ($startblock && $endblock) {
4913: return 'B';
4914: }
4915: }
4916: }
4917: if ($result eq 'ok') {
4918: return 'F';
4919: } elsif ($result =~ /^[^:]+:guest_/) {
4920: return 'A';
4921: }
4922: return '';
4923: }
4924:
4925: sub get_portfolio_access {
4926: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4927:
4928: if (!ref($access_hash)) {
4929: my $current_perms = &get_portfile_permissions($udom,$unum);
4930: my %access_controls = &get_access_controls($current_perms,$group,
4931: $file_name);
4932: $access_hash = $access_controls{$file_name};
4933: }
4934:
4935: my ($public,$guest,@domains,@users,@courses,@groups);
4936: my $now = time;
4937: if (ref($access_hash) eq 'HASH') {
4938: foreach my $key (keys(%{$access_hash})) {
4939: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4940: if ($start > $now) {
4941: next;
4942: }
4943: if ($end && $end<$now) {
4944: next;
4945: }
4946: if ($scope eq 'public') {
4947: $public = $key;
4948: last;
4949: } elsif ($scope eq 'guest') {
4950: $guest = $key;
4951: } elsif ($scope eq 'domains') {
4952: push(@domains,$key);
4953: } elsif ($scope eq 'users') {
4954: push(@users,$key);
4955: } elsif ($scope eq 'course') {
4956: push(@courses,$key);
4957: } elsif ($scope eq 'group') {
4958: push(@groups,$key);
4959: }
4960: }
4961: if ($public) {
4962: return 'ok';
4963: }
4964: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4965: if ($guest) {
4966: return $guest;
4967: }
4968: } else {
4969: if (@domains > 0) {
4970: foreach my $domkey (@domains) {
4971: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4972: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4973: return 'ok';
4974: }
4975: }
4976: }
4977: }
4978: if (@users > 0) {
4979: foreach my $userkey (@users) {
4980: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4981: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4982: if (ref($item) eq 'HASH') {
4983: if (($item->{'uname'} eq $env{'user.name'}) &&
4984: ($item->{'udom'} eq $env{'user.domain'})) {
4985: return 'ok';
4986: }
4987: }
4988: }
4989: }
4990: }
4991: }
4992: my %roleshash;
4993: my @courses_and_groups = @courses;
4994: push(@courses_and_groups,@groups);
4995: if (@courses_and_groups > 0) {
4996: my (%allgroups,%allroles);
4997: my ($start,$end,$role,$sec,$group);
4998: foreach my $envkey (%env) {
4999: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
5000: my $cid = $2.'_'.$3;
5001: if ($1 eq 'gr') {
5002: $group = $4;
5003: $allgroups{$cid}{$group} = $env{$envkey};
5004: } else {
5005: if ($4 eq '') {
5006: $sec = 'none';
5007: } else {
5008: $sec = $4;
5009: }
5010: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5011: }
5012: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
5013: my $cid = $2.'_'.$3;
5014: if ($4 eq '') {
5015: $sec = 'none';
5016: } else {
5017: $sec = $4;
5018: }
5019: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5020: }
5021: }
5022: if (keys(%allroles) == 0) {
5023: return;
5024: }
5025: foreach my $key (@courses_and_groups) {
5026: my %content = %{$$access_hash{$key}};
5027: my $cnum = $content{'number'};
5028: my $cdom = $content{'domain'};
5029: my $cid = $cdom.'_'.$cnum;
5030: if (!exists($allroles{$cid})) {
5031: next;
5032: }
5033: foreach my $role_id (keys(%{$content{'roles'}})) {
5034: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5035: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5036: my @status = @{$content{'roles'}{$role_id}{'access'}};
5037: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5038: foreach my $role (keys(%{$allroles{$cid}})) {
5039: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5040: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5041: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5042: if (grep/^all$/,@sections) {
5043: return 'ok';
5044: } else {
5045: if (grep/^$sec$/,@sections) {
5046: return 'ok';
5047: }
5048: }
5049: }
5050: }
5051: if (keys(%{$allgroups{$cid}}) == 0) {
5052: if (grep/^none$/,@groups) {
5053: return 'ok';
5054: }
5055: } else {
5056: if (grep/^all$/,@groups) {
5057: return 'ok';
5058: }
5059: foreach my $group (keys(%{$allgroups{$cid}})) {
5060: if (grep/^$group$/,@groups) {
5061: return 'ok';
5062: }
5063: }
5064: }
5065: }
5066: }
5067: }
5068: }
5069: }
5070: if ($guest) {
5071: return $guest;
5072: }
5073: }
5074: }
5075: return;
5076: }
5077:
5078: sub course_group_datechecker {
5079: my ($dates,$now,$status) = @_;
5080: my ($start,$end) = split(/\./,$dates);
5081: if (!$start && !$end) {
5082: return 'ok';
5083: }
5084: if (grep/^active$/,@{$status}) {
5085: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5086: return 'ok';
5087: }
5088: }
5089: if (grep/^previous$/,@{$status}) {
5090: if ($end > $now ) {
5091: return 'ok';
5092: }
5093: }
5094: if (grep/^future$/,@{$status}) {
5095: if ($start > $now) {
5096: return 'ok';
5097: }
5098: }
5099: return;
5100: }
5101:
5102: sub parse_portfolio_url {
5103: my ($url) = @_;
5104:
5105: my ($type,$udom,$unum,$group,$file_name);
5106:
5107: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
5108: $type = 1;
5109: $udom = $1;
5110: $unum = $2;
5111: $file_name = $3;
5112: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
5113: $type = 2;
5114: $udom = $1;
5115: $unum = $2;
5116: $group = $3;
5117: $file_name = $3.'/'.$4;
5118: }
5119: if (wantarray) {
5120: return ($type,$udom,$unum,$file_name,$group);
5121: }
5122: return $type;
5123: }
5124:
5125: sub is_portfolio_url {
5126: my ($url) = @_;
5127: return scalar(&parse_portfolio_url($url));
5128: }
5129:
5130: sub is_portfolio_file {
5131: my ($file) = @_;
5132: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
5133: return 1;
5134: }
5135: return;
5136: }
5137:
5138: sub usertools_access {
5139: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref) = @_;
5140: my ($access,%tools);
5141: if ($context eq '') {
5142: $context = 'tools';
5143: }
5144: if ($context eq 'requestcourses') {
5145: %tools = (
5146: official => 1,
5147: unofficial => 1,
5148: community => 1,
5149: );
5150: } else {
5151: %tools = (
5152: aboutme => 1,
5153: blog => 1,
5154: portfolio => 1,
5155: );
5156: }
5157: return if (!defined($tools{$tool}));
5158:
5159: if ((!defined($udom)) || (!defined($uname))) {
5160: $udom = $env{'user.domain'};
5161: $uname = $env{'user.name'};
5162: }
5163:
5164: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5165: if ($action ne 'reload') {
5166: if ($context eq 'requestcourses') {
5167: return $env{'environment.canrequest.'.$tool};
5168: } else {
5169: return $env{'environment.availabletools.'.$tool};
5170: }
5171: }
5172: }
5173:
5174: my ($toolstatus,$inststatus);
5175:
5176: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5177: ($action ne 'reload')) {
5178: $toolstatus = $env{'environment.'.$context.'.'.$tool};
5179: $inststatus = $env{'environment.inststatus'};
5180: } else {
5181: if (ref($userenvref) eq 'HASH') {
5182: $toolstatus = $userenvref->{$context.'.'.$tool};
5183: $inststatus = $userenvref->{'inststatus'};
5184: } else {
5185: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5186: $toolstatus = $userenv{$context.'.'.$tool};
5187: $inststatus = $userenv{'inststatus'};
5188: }
5189: }
5190:
5191: if ($toolstatus ne '') {
5192: if ($toolstatus) {
5193: $access = 1;
5194: } else {
5195: $access = 0;
5196: }
5197: return $access;
5198: }
5199:
5200: my ($is_adv,%domdef);
5201: if (ref($is_advref) eq 'HASH') {
5202: $is_adv = $is_advref->{'is_adv'};
5203: } else {
5204: $is_adv = &is_advanced_user($udom,$uname);
5205: }
5206: if (ref($domdefref) eq 'HASH') {
5207: %domdef = %{$domdefref};
5208: } else {
5209: %domdef = &get_domain_defaults($udom);
5210: }
5211: if (ref($domdef{$tool}) eq 'HASH') {
5212: if ($is_adv) {
5213: if ($domdef{$tool}{'_LC_adv'} ne '') {
5214: if ($domdef{$tool}{'_LC_adv'}) {
5215: $access = 1;
5216: } else {
5217: $access = 0;
5218: }
5219: return $access;
5220: }
5221: }
5222: if ($inststatus ne '') {
5223: my ($hasaccess,$hasnoaccess);
5224: foreach my $affiliation (split(/:/,$inststatus)) {
5225: if ($domdef{$tool}{$affiliation} ne '') {
5226: if ($domdef{$tool}{$affiliation}) {
5227: $hasaccess = 1;
5228: } else {
5229: $hasnoaccess = 1;
5230: }
5231: }
5232: }
5233: if ($hasaccess || $hasnoaccess) {
5234: if ($hasaccess) {
5235: $access = 1;
5236: } elsif ($hasnoaccess) {
5237: $access = 0;
5238: }
5239: return $access;
5240: }
5241: } else {
5242: if ($domdef{$tool}{'default'} ne '') {
5243: if ($domdef{$tool}{'default'}) {
5244: $access = 1;
5245: } elsif ($domdef{$tool}{'default'} == 0) {
5246: $access = 0;
5247: }
5248: return $access;
5249: }
5250: }
5251: } else {
5252: if ($context eq 'tools') {
5253: $access = 1;
5254: } else {
5255: $access = 0;
5256: }
5257: return $access;
5258: }
5259: }
5260:
5261: sub is_course_owner {
5262: my ($cdom,$cnum,$udom,$uname) = @_;
5263: if (($udom eq '') || ($uname eq '')) {
5264: $udom = $env{'user.domain'};
5265: $uname = $env{'user.name'};
5266: }
5267: unless (($udom eq '') || ($uname eq '')) {
5268: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5269: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5270: return 1;
5271: } else {
5272: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5273: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5274: return 1;
5275: }
5276: }
5277: }
5278: }
5279: return;
5280: }
5281:
5282: sub is_advanced_user {
5283: my ($udom,$uname) = @_;
5284: if ($udom ne '' && $uname ne '') {
5285: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5286: return $env{'user.adv'};
5287: }
5288: }
5289: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5290: my %allroles;
5291: my $is_adv;
5292: foreach my $role (keys(%roleshash)) {
5293: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5294: my $area = '/'.$tdomain.'/'.$trest;
5295: if ($sec ne '') {
5296: $area .= '/'.$sec;
5297: }
5298: if (($area ne '') && ($trole ne '')) {
5299: my $spec=$trole.'.'.$area;
5300: if ($trole =~ /^cr\//) {
5301: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5302: } elsif ($trole ne 'gr') {
5303: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5304: }
5305: }
5306: }
5307: foreach my $role (keys(%allroles)) {
5308: last if ($is_adv);
5309: foreach my $item (split(/:/,$allroles{$role})) {
5310: if ($item ne '') {
5311: my ($privilege,$restrictions)=split(/&/,$item);
5312: if ($privilege eq 'adv') {
5313: $is_adv = 1;
5314: last;
5315: }
5316: }
5317: }
5318: }
5319: return $is_adv;
5320: }
5321:
5322: sub check_can_request {
5323: my ($dom,$can_request,$request_domains) = @_;
5324: my $canreq = 0;
5325: my ($types,$typename) = &Apache::loncommon::course_types();
5326: my @options = ('approval','validate','autolimit');
5327: my $optregex = join('|',@options);
5328: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5329: foreach my $type (@{$types}) {
5330: if (&usertools_access($env{'user.name'},
5331: $env{'user.domain'},
5332: $type,undef,'requestcourses')) {
5333: $canreq ++;
5334: if (ref($request_domains) eq 'HASH') {
5335: push(@{$request_domains->{$type}},$env{'user.domain'});
5336: }
5337: if ($dom eq $env{'user.domain'}) {
5338: $can_request->{$type} = 1;
5339: }
5340: }
5341: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5342: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5343: if (@curr > 0) {
5344: foreach my $item (@curr) {
5345: if (ref($request_domains) eq 'HASH') {
5346: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5347: if ($otherdom ne '') {
5348: if (ref($request_domains->{$type}) eq 'ARRAY') {
5349: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5350: push(@{$request_domains->{$type}},$otherdom);
5351: }
5352: } else {
5353: push(@{$request_domains->{$type}},$otherdom);
5354: }
5355: }
5356: }
5357: }
5358: unless($dom eq $env{'user.domain'}) {
5359: $canreq ++;
5360: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5361: $can_request->{$type} = 1;
5362: }
5363: }
5364: }
5365: }
5366: }
5367: }
5368: return $canreq;
5369: }
5370:
5371: # ---------------------------------------------- Custom access rule evaluation
5372:
5373: sub customaccess {
5374: my ($priv,$uri)=@_;
5375: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
5376: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
5377: $udom = &LONCAPA::clean_domain($udom);
5378: $ucrs = &LONCAPA::clean_username($ucrs);
5379: my $access=0;
5380: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
5381: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5382: if ($type eq 'user') {
5383: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5384: my ($tdom,$tuname)=split(m{/},$scope);
5385: if ($tdom) {
5386: if ($tdom ne $env{'user.domain'}) { next; }
5387: }
5388: if ($tuname) {
5389: if ($tuname ne $env{'user.name'}) { next; }
5390: }
5391: $access=($effect eq 'allow');
5392: last;
5393: }
5394: } else {
5395: if ($role) {
5396: if ($role ne $urole) { next; }
5397: }
5398: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5399: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5400: if ($tdom) {
5401: if ($tdom ne $udom) { next; }
5402: }
5403: if ($tcrs) {
5404: if ($tcrs ne $ucrs) { next; }
5405: }
5406: if ($tsec) {
5407: if ($tsec ne $usec) { next; }
5408: }
5409: $access=($effect eq 'allow');
5410: last;
5411: }
5412: if ($realm eq '' && $role eq '') {
5413: $access=($effect eq 'allow');
5414: }
5415: }
5416: }
5417: return $access;
5418: }
5419:
5420: # ------------------------------------------------- Check for a user privilege
5421:
5422: sub allowed {
5423: my ($priv,$uri,$symb,$role)=@_;
5424: my $ver_orguri=$uri;
5425: $uri=&deversion($uri);
5426: my $orguri=$uri;
5427: $uri=&declutter($uri);
5428:
5429: if ($priv eq 'evb') {
5430: # Evade communication block restrictions for specified role in a course
5431: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5432: return $1;
5433: } else {
5434: return;
5435: }
5436: }
5437:
5438: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
5439: # Free bre access to adm and meta resources
5440: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
5441: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5442: && ($priv eq 'bre')) {
5443: return 'F';
5444: }
5445:
5446: # Free bre access to user's own portfolio contents
5447: my ($space,$domain,$name,@dir)=split('/',$uri);
5448: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
5449: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
5450: my %setters;
5451: my ($startblock,$endblock) =
5452: &Apache::loncommon::blockcheck(\%setters,'port');
5453: if ($startblock && $endblock) {
5454: return 'B';
5455: } else {
5456: return 'F';
5457: }
5458: }
5459:
5460: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
5461: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5462: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5463: if (exists($env{'request.course.id'})) {
5464: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5465: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5466: if (($domain eq $cdom) && ($name eq $cnum)) {
5467: my $courseprivid=$env{'request.course.id'};
5468: $courseprivid=~s/\_/\//;
5469: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5470: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5471: return $1;
5472: } else {
5473: if ($env{'request.course.sec'}) {
5474: $courseprivid.='/'.$env{'request.course.sec'};
5475: }
5476: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5477: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5478: return $2;
5479: }
5480: }
5481: }
5482: }
5483: }
5484:
5485: # Free bre to public access
5486:
5487: if ($priv eq 'bre') {
5488: my $copyright=&metadata($uri,'copyright');
5489: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
5490: return 'F';
5491: }
5492: if ($copyright eq 'priv') {
5493: $uri=~/([^\/]+)\/([^\/]+)\//;
5494: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
5495: return '';
5496: }
5497: }
5498: if ($copyright eq 'domain') {
5499: $uri=~/([^\/]+)\/([^\/]+)\//;
5500: unless (($env{'user.domain'} eq $1) ||
5501: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
5502: return '';
5503: }
5504: }
5505: if ($env{'request.role'}=~ /li\.\//) {
5506: # Library role, so allow browsing of resources in this domain.
5507: return 'F';
5508: }
5509: if ($copyright eq 'custom') {
5510: unless (&customaccess($priv,$uri)) { return ''; }
5511: }
5512: }
5513: # Domain coordinator is trying to create a course
5514: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
5515: # uri is the requested domain in this case.
5516: # comparison to 'request.role.domain' shows if the user has selected
5517: # a role of dc for the domain in question.
5518: return 'F' if ($uri eq $env{'request.role.domain'});
5519: }
5520:
5521: my $thisallowed='';
5522: my $statecond=0;
5523: my $courseprivid='';
5524:
5525: my $ownaccess;
5526: # Community Coordinator or Assistant Co-author browsing resource space.
5527: if (($priv eq 'bro') && ($env{'user.author'})) {
5528: if ($uri eq '') {
5529: $ownaccess = 1;
5530: } else {
5531: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5532: my $udom = $env{'user.domain'};
5533: my $uname = $env{'user.name'};
5534: if ($uri =~ m{^\Q$udom\E/?$}) {
5535: $ownaccess = 1;
5536: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
5537: unless ($uri =~ m{\.\./}) {
5538: $ownaccess = 1;
5539: }
5540: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5541: my $now = time;
5542: if ($uri =~ m{^([^/]+)/?$}) {
5543: my $adom = $1;
5544: foreach my $key (keys(%env)) {
5545: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
5546: my ($start,$end) = split('.',$env{$key});
5547: if (($now >= $start) && (!$end || $end < $now)) {
5548: $ownaccess = 1;
5549: last;
5550: }
5551: }
5552: }
5553: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5554: my $adom = $1;
5555: my $aname = $2;
5556: foreach my $role ('ca','aa') {
5557: if ($env{"user.role.$role./$adom/$aname"}) {
5558: my ($start,$end) =
5559: split('.',$env{"user.role.$role./$adom/$aname"});
5560: if (($now >= $start) && (!$end || $end < $now)) {
5561: $ownaccess = 1;
5562: last;
5563: }
5564: }
5565: }
5566: }
5567: }
5568: }
5569: }
5570: }
5571:
5572: # Course
5573:
5574: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
5575: unless (($priv eq 'bro') && (!$ownaccess)) {
5576: $thisallowed.=$1;
5577: }
5578: }
5579:
5580: # Domain
5581:
5582: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
5583: =~/\Q$priv\E\&([^\:]*)/) {
5584: unless (($priv eq 'bro') && (!$ownaccess)) {
5585: $thisallowed.=$1;
5586: }
5587: }
5588:
5589: # Course: uri itself is a course
5590: my $courseuri=$uri;
5591: $courseuri=~s/\_(\d)/\/$1/;
5592: $courseuri=~s/^([^\/])/\/$1/;
5593:
5594: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
5595: =~/\Q$priv\E\&([^\:]*)/) {
5596: unless (($priv eq 'bro') && (!$ownaccess)) {
5597: $thisallowed.=$1;
5598: }
5599: }
5600:
5601: # URI is an uploaded document for this course, default permissions don't matter
5602: # not allowing 'edit' access (editupload) to uploaded course docs
5603: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
5604: $thisallowed='';
5605: my ($match)=&is_on_map($uri);
5606: if ($match) {
5607: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5608: =~/\Q$priv\E\&([^\:]*)/) {
5609: $thisallowed.=$1;
5610: }
5611: } else {
5612: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
5613: if ($refuri) {
5614: if ($refuri =~ m|^/adm/|) {
5615: $thisallowed='F';
5616: } else {
5617: $refuri=&declutter($refuri);
5618: my ($match) = &is_on_map($refuri);
5619: if ($match) {
5620: $thisallowed='F';
5621: }
5622: }
5623: }
5624: }
5625: }
5626:
5627: if ($priv eq 'bre'
5628: && $thisallowed ne 'F'
5629: && $thisallowed ne '2'
5630: && &is_portfolio_url($uri)) {
5631: $thisallowed = &portfolio_access($uri);
5632: }
5633:
5634: # Full access at system, domain or course-wide level? Exit.
5635: if ($thisallowed=~/F/) {
5636: return 'F';
5637: }
5638:
5639: # If this is generating or modifying users, exit with special codes
5640:
5641: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5642: if (($priv eq 'cca') || ($priv eq 'caa')) {
5643: my ($audom,$auname)=split('/',$uri);
5644: # no author name given, so this just checks on the general right to make a co-author in this domain
5645: unless ($auname) { return $thisallowed; }
5646: # an author name is given, so we are about to actually make a co-author for a certain account
5647: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5648: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5649: ($audom ne $env{'request.role.domain'}))) { return ''; }
5650: }
5651: return $thisallowed;
5652: }
5653: #
5654: # Gathered so far: system, domain and course wide privileges
5655: #
5656: # Course: See if uri or referer is an individual resource that is part of
5657: # the course
5658:
5659: if ($env{'request.course.id'}) {
5660:
5661: $courseprivid=$env{'request.course.id'};
5662: if ($env{'request.course.sec'}) {
5663: $courseprivid.='/'.$env{'request.course.sec'};
5664: }
5665: $courseprivid=~s/\_/\//;
5666: my $checkreferer=1;
5667: my ($match,$cond)=&is_on_map($uri);
5668: if ($match) {
5669: $statecond=$cond;
5670: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
5671: =~/\Q$priv\E\&([^\:]*)/) {
5672: $thisallowed.=$1;
5673: $checkreferer=0;
5674: }
5675: }
5676:
5677: if ($checkreferer) {
5678: my $refuri=$env{'httpref.'.$orguri};
5679: unless ($refuri) {
5680: foreach my $key (keys(%env)) {
5681: if ($key=~/^httpref\..*\*/) {
5682: my $pattern=$key;
5683: $pattern=~s/^httpref\.\/res\///;
5684: $pattern=~s/\*/\[\^\/\]\+/g;
5685: $pattern=~s/\//\\\//g;
5686: if ($orguri=~/$pattern/) {
5687: $refuri=$env{$key};
5688: }
5689: }
5690: }
5691: }
5692:
5693: if ($refuri) {
5694: $refuri=&declutter($refuri);
5695: my ($match,$cond)=&is_on_map($refuri);
5696: if ($match) {
5697: my $refstatecond=$cond;
5698: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
5699: =~/\Q$priv\E\&([^\:]*)/) {
5700: $thisallowed.=$1;
5701: $uri=$refuri;
5702: $statecond=$refstatecond;
5703: }
5704: }
5705: }
5706: }
5707: }
5708:
5709: #
5710: # Gathered now: all privileges that could apply, and condition number
5711: #
5712: #
5713: # Full or no access?
5714: #
5715:
5716: if ($thisallowed=~/F/) {
5717: return 'F';
5718: }
5719:
5720: unless ($thisallowed) {
5721: return '';
5722: }
5723:
5724: # Restrictions exist, deal with them
5725: #
5726: # C:according to course preferences
5727: # R:according to resource settings
5728: # L:unless locked
5729: # X:according to user session state
5730: #
5731:
5732: # Possibly locked functionality, check all courses
5733: # Locks might take effect only after 10 minutes cache expiration for other
5734: # courses, and 2 minutes for current course
5735:
5736: my $envkey;
5737: if ($thisallowed=~/L/) {
5738: foreach $envkey (keys(%env)) {
5739: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5740: my $courseid=$2;
5741: my $roleid=$1.'.'.$2;
5742: $courseid=~s/^\///;
5743: my $expiretime=600;
5744: if ($env{'request.role'} eq $roleid) {
5745: $expiretime=120;
5746: }
5747: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5748: my $prefix='course.'.$cdom.'_'.$cnum.'.';
5749: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
5750: &coursedescription($courseid,{'freshen_cache' => 1});
5751: }
5752: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5753: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5754: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5755: &log($env{'user.domain'},$env{'user.name'},
5756: $env{'user.home'},
5757: 'Locked by res: '.$priv.' for '.$uri.' due to '.
5758: $cdom.'/'.$cnum.'/'.$csec.' expire '.
5759: $env{$prefix.'priv.'.$priv.'.lock.expire'});
5760: return '';
5761: }
5762: }
5763: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5764: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5765: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5766: &log($env{'user.domain'},$env{'user.name'},
5767: $env{'user.home'},
5768: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
5769: $cdom.'/'.$cnum.'/'.$csec.' expire '.
5770: $env{$prefix.'priv.'.$priv.'.lock.expire'});
5771: return '';
5772: }
5773: }
5774: }
5775: }
5776: }
5777:
5778: #
5779: # Rest of the restrictions depend on selected course
5780: #
5781:
5782: unless ($env{'request.course.id'}) {
5783: if ($thisallowed eq 'A') {
5784: return 'A';
5785: } elsif ($thisallowed eq 'B') {
5786: return 'B';
5787: } else {
5788: return '1';
5789: }
5790: }
5791:
5792: #
5793: # Now user is definitely in a course
5794: #
5795:
5796:
5797: # Course preferences
5798:
5799: if ($thisallowed=~/C/) {
5800: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5801: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5802: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
5803: =~/\Q$rolecode\E/) {
5804: if (($priv ne 'pch') && ($priv ne 'plc')) {
5805: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5806: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5807: $env{'request.course.id'});
5808: }
5809: return '';
5810: }
5811:
5812: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
5813: =~/\Q$unamedom\E/) {
5814: if (($priv ne 'pch') && ($priv ne 'plc')) {
5815: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5816: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5817: $env{'request.course.id'});
5818: }
5819: return '';
5820: }
5821: }
5822:
5823: # Resource preferences
5824:
5825: if ($thisallowed=~/R/) {
5826: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5827: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
5828: if (($priv ne 'pch') && ($priv ne 'plc')) {
5829: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5830: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5831: }
5832: return '';
5833: }
5834: }
5835:
5836: # Restricted by state or randomout?
5837:
5838: if ($thisallowed=~/X/) {
5839: if ($env{'acc.randomout'}) {
5840: if (!$symb) { $symb=&symbread($uri,1); }
5841: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
5842: return '';
5843: }
5844: }
5845: if (&condval($statecond)) {
5846: return '2';
5847: } else {
5848: return '';
5849: }
5850: }
5851:
5852: if ($thisallowed eq 'A') {
5853: return 'A';
5854: } elsif ($thisallowed eq 'B') {
5855: return 'B';
5856: }
5857: return 'F';
5858: }
5859:
5860: sub split_uri_for_cond {
5861: my $uri=&deversion(&declutter(shift));
5862: my @uriparts=split(/\//,$uri);
5863: my $filename=pop(@uriparts);
5864: my $pathname=join('/',@uriparts);
5865: return ($pathname,$filename);
5866: }
5867: # --------------------------------------------------- Is a resource on the map?
5868:
5869: sub is_on_map {
5870: my ($pathname,$filename) = &split_uri_for_cond(shift);
5871: #Trying to find the conditional for the file
5872: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
5873: /\&\Q$filename\E\:([\d\|]+)\&/);
5874: if ($match) {
5875: return (1,$1);
5876: } else {
5877: return (0,0);
5878: }
5879: }
5880:
5881: # --------------------------------------------------------- Get symb from alias
5882:
5883: sub get_symb_from_alias {
5884: my $symb=shift;
5885: my ($map,$resid,$url)=&decode_symb($symb);
5886: # Already is a symb
5887: if ($url) { return $symb; }
5888: # Must be an alias
5889: my $aliassymb='';
5890: my %bighash;
5891: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
5892: &GDBM_READER(),0640)) {
5893: my $rid=$bighash{'mapalias_'.$symb};
5894: if ($rid) {
5895: my ($mapid,$resid)=split(/\./,$rid);
5896: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5897: $resid,$bighash{'src_'.$rid});
5898: }
5899: untie %bighash;
5900: }
5901: return $aliassymb;
5902: }
5903:
5904: # ----------------------------------------------------------------- Define Role
5905:
5906: sub definerole {
5907: if (allowed('mcr','/')) {
5908: my ($rolename,$sysrole,$domrole,$courole)=@_;
5909: foreach my $role (split(':',$sysrole)) {
5910: my ($crole,$cqual)=split(/\&/,$role);
5911: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5912: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5913: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
5914: return "refused:s:$crole&$cqual";
5915: }
5916: }
5917: }
5918: foreach my $role (split(':',$domrole)) {
5919: my ($crole,$cqual)=split(/\&/,$role);
5920: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5921: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5922: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
5923: return "refused:d:$crole&$cqual";
5924: }
5925: }
5926: }
5927: foreach my $role (split(':',$courole)) {
5928: my ($crole,$cqual)=split(/\&/,$role);
5929: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5930: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5931: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
5932: return "refused:c:$crole&$cqual";
5933: }
5934: }
5935: }
5936: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5937: "$env{'user.domain'}:$env{'user.name'}:".
5938: "rolesdef_$rolename=".
5939: escape($sysrole.'_'.$domrole.'_'.$courole);
5940: return reply($command,$env{'user.home'});
5941: } else {
5942: return 'refused';
5943: }
5944: }
5945:
5946: # ---------------- Make a metadata query against the network of library servers
5947:
5948: sub metadata_query {
5949: my ($query,$custom,$customshow,$server_array)=@_;
5950: my %rhash;
5951: my %libserv = &all_library();
5952: my @server_list = (defined($server_array) ? @$server_array
5953: : keys(%libserv) );
5954: for my $server (@server_list) {
5955: unless ($custom or $customshow) {
5956: my $reply=&reply("querysend:".&escape($query),$server);
5957: $rhash{$server}=$reply;
5958: }
5959: else {
5960: my $reply=&reply("querysend:".&escape($query).':'.
5961: &escape($custom).':'.&escape($customshow),
5962: $server);
5963: $rhash{$server}=$reply;
5964: }
5965: }
5966: return \%rhash;
5967: }
5968:
5969: # ----------------------------------------- Send log queries and wait for reply
5970:
5971: sub log_query {
5972: my ($uname,$udom,$query,%filters)=@_;
5973: my $uhome=&homeserver($uname,$udom);
5974: if ($uhome eq 'no_host') { return 'error: no_host'; }
5975: my $uhost=&hostname($uhome);
5976: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
5977: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5978: $uhome);
5979: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
5980: return get_query_reply($queryid);
5981: }
5982:
5983: # -------------------------- Update MySQL table for portfolio file
5984:
5985: sub update_portfolio_table {
5986: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
5987: if ($group ne '') {
5988: $file_name =~s /^\Q$group\E//;
5989: }
5990: my $homeserver = &homeserver($uname,$udom);
5991: my $queryid=
5992: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5993: ':'.&escape($file_name).':'.$action,$homeserver);
5994: my $reply = &get_query_reply($queryid);
5995: return $reply;
5996: }
5997:
5998: # -------------------------- Update MySQL allusers table
5999:
6000: sub update_allusers_table {
6001: my ($uname,$udom,$names) = @_;
6002: my $homeserver = &homeserver($uname,$udom);
6003: my $queryid=
6004: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
6005: 'lastname='.&escape($names->{'lastname'}).'%%'.
6006: 'firstname='.&escape($names->{'firstname'}).'%%'.
6007: 'middlename='.&escape($names->{'middlename'}).'%%'.
6008: 'generation='.&escape($names->{'generation'}).'%%'.
6009: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
6010: 'id='.&escape($names->{'id'}),$homeserver);
6011: return;
6012: }
6013:
6014: # ------- Request retrieval of institutional classlists for course(s)
6015:
6016: sub fetch_enrollment_query {
6017: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
6018: my $homeserver;
6019: my $maxtries = 1;
6020: if ($context eq 'automated') {
6021: $homeserver = $perlvar{'lonHostID'};
6022: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
6023: } else {
6024: $homeserver = &homeserver($cnum,$dom);
6025: }
6026: my $host=&hostname($homeserver);
6027: my $cmd = '';
6028: foreach my $affiliate (keys(%{$affiliatesref})) {
6029: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
6030: }
6031: $cmd =~ s/%%$//;
6032: $cmd = &escape($cmd);
6033: my $query = 'fetchenrollment';
6034: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
6035: unless ($queryid=~/^\Q$host\E\_/) {
6036: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
6037: return 'error: '.$queryid;
6038: }
6039: my $reply = &get_query_reply($queryid);
6040: my $tries = 1;
6041: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6042: $reply = &get_query_reply($queryid);
6043: $tries ++;
6044: }
6045: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6046: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6047: } else {
6048: my @responses = split(/:/,$reply);
6049: if ($homeserver eq $perlvar{'lonHostID'}) {
6050: foreach my $line (@responses) {
6051: my ($key,$value) = split(/=/,$line,2);
6052: $$replyref{$key} = $value;
6053: }
6054: } else {
6055: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
6056: foreach my $line (@responses) {
6057: my ($key,$value) = split(/=/,$line);
6058: $$replyref{$key} = $value;
6059: if ($value > 0) {
6060: foreach my $item (@{$$affiliatesref{$key}}) {
6061: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
6062: my $destname = $pathname.'/'.$filename;
6063: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
6064: if ($xml_classlist =~ /^error/) {
6065: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6066: } else {
6067: if ( open(FILE,">$destname") ) {
6068: print FILE &unescape($xml_classlist);
6069: close(FILE);
6070: } else {
6071: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
6072: }
6073: }
6074: }
6075: }
6076: }
6077: }
6078: return 'ok';
6079: }
6080: return 'error';
6081: }
6082:
6083: sub get_query_reply {
6084: my $queryid=shift;
6085: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
6086: my $reply='';
6087: for (1..100) {
6088: sleep 2;
6089: if (-e $replyfile.'.end') {
6090: if (open(my $fh,$replyfile)) {
6091: $reply = join('',<$fh>);
6092: close($fh);
6093: } else { return 'error: reply_file_error'; }
6094: return &unescape($reply);
6095: }
6096: }
6097: return 'timeout:'.$queryid;
6098: }
6099:
6100: sub courselog_query {
6101: #
6102: # possible filters:
6103: # url: url or symb
6104: # username
6105: # domain
6106: # action: view, submit, grade
6107: # start: timestamp
6108: # end: timestamp
6109: #
6110: my (%filters)=@_;
6111: unless ($env{'request.course.id'}) { return 'no_course'; }
6112: if ($filters{'url'}) {
6113: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6114: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6115: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6116: }
6117: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6118: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6119: return &log_query($cname,$cdom,'courselog',%filters);
6120: }
6121:
6122: sub userlog_query {
6123: #
6124: # possible filters:
6125: # action: log check role
6126: # start: timestamp
6127: # end: timestamp
6128: #
6129: my ($uname,$udom,%filters)=@_;
6130: return &log_query($uname,$udom,'userlog',%filters);
6131: }
6132:
6133: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6134:
6135: sub auto_run {
6136: my ($cnum,$cdom) = @_;
6137: my $response = 0;
6138: my $settings;
6139: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6140: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6141: $settings = $domconfig{'autoenroll'};
6142: if ($settings->{'run'} eq '1') {
6143: $response = 1;
6144: }
6145: } else {
6146: my $homeserver;
6147: if (&is_course($cdom,$cnum)) {
6148: $homeserver = &homeserver($cnum,$cdom);
6149: } else {
6150: $homeserver = &domain($cdom,'primary');
6151: }
6152: if ($homeserver ne 'no_host') {
6153: $response = &reply('autorun:'.$cdom,$homeserver);
6154: }
6155: }
6156: return $response;
6157: }
6158:
6159: sub auto_get_sections {
6160: my ($cnum,$cdom,$inst_coursecode) = @_;
6161: my $homeserver;
6162: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6163: $homeserver = &homeserver($cnum,$cdom);
6164: }
6165: if (!defined($homeserver)) {
6166: if ($cdom =~ /^$match_domain$/) {
6167: $homeserver = &domain($cdom,'primary');
6168: }
6169: }
6170: my @secs;
6171: if (defined($homeserver)) {
6172: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6173: unless ($response eq 'refused') {
6174: @secs = split(/:/,$response);
6175: }
6176: }
6177: return @secs;
6178: }
6179:
6180: sub auto_new_course {
6181: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
6182: my $homeserver = &homeserver($cnum,$cdom);
6183: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
6184: return $response;
6185: }
6186:
6187: sub auto_validate_courseID {
6188: my ($cnum,$cdom,$inst_course_id) = @_;
6189: my $homeserver = &homeserver($cnum,$cdom);
6190: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
6191: return $response;
6192: }
6193:
6194: sub auto_validate_instcode {
6195: my ($cnum,$cdom,$instcode,$owner) = @_;
6196: my ($homeserver,$response);
6197: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6198: $homeserver = &homeserver($cnum,$cdom);
6199: }
6200: if (!defined($homeserver)) {
6201: if ($cdom =~ /^$match_domain$/) {
6202: $homeserver = &domain($cdom,'primary');
6203: }
6204: }
6205: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6206: &escape($instcode).':'.&escape($owner),$homeserver));
6207: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6208: return ($outcome,$description);
6209: }
6210:
6211: sub auto_create_password {
6212: my ($cnum,$cdom,$authparam,$udom) = @_;
6213: my ($homeserver,$response);
6214: my $create_passwd = 0;
6215: my $authchk = '';
6216: if ($udom =~ /^$match_domain$/) {
6217: $homeserver = &domain($udom,'primary');
6218: }
6219: if ($homeserver eq '') {
6220: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6221: $homeserver = &homeserver($cnum,$cdom);
6222: }
6223: }
6224: if ($homeserver eq '') {
6225: $authchk = 'nodomain';
6226: } else {
6227: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6228: if ($response eq 'refused') {
6229: $authchk = 'refused';
6230: } else {
6231: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
6232: }
6233: }
6234: return ($authparam,$create_passwd,$authchk);
6235: }
6236:
6237: sub auto_photo_permission {
6238: my ($cnum,$cdom,$students) = @_;
6239: my $homeserver = &homeserver($cnum,$cdom);
6240: my ($outcome,$perm_reqd,$conditions) =
6241: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
6242: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6243: return (undef,undef);
6244: }
6245: return ($outcome,$perm_reqd,$conditions);
6246: }
6247:
6248: sub auto_checkphotos {
6249: my ($uname,$udom,$pid) = @_;
6250: my $homeserver = &homeserver($uname,$udom);
6251: my ($result,$resulttype);
6252: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
6253: &escape($uname).':'.&escape($pid),
6254: $homeserver));
6255: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6256: return (undef,undef);
6257: }
6258: if ($outcome) {
6259: ($result,$resulttype) = split(/:/,$outcome);
6260: }
6261: return ($result,$resulttype);
6262: }
6263:
6264: sub auto_photochoice {
6265: my ($cnum,$cdom) = @_;
6266: my $homeserver = &homeserver($cnum,$cdom);
6267: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
6268: &escape($cdom),
6269: $homeserver)));
6270: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6271: return (undef,undef);
6272: }
6273: return ($update,$comment);
6274: }
6275:
6276: sub auto_photoupdate {
6277: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6278: my $homeserver = &homeserver($cnum,$dom);
6279: my $host=&hostname($homeserver);
6280: my $cmd = '';
6281: my $maxtries = 1;
6282: foreach my $affiliate (keys(%{$affiliatesref})) {
6283: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
6284: }
6285: $cmd =~ s/%%$//;
6286: $cmd = &escape($cmd);
6287: my $query = 'institutionalphotos';
6288: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6289: unless ($queryid=~/^\Q$host\E\_/) {
6290: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6291: return 'error: '.$queryid;
6292: }
6293: my $reply = &get_query_reply($queryid);
6294: my $tries = 1;
6295: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6296: $reply = &get_query_reply($queryid);
6297: $tries ++;
6298: }
6299: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6300: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6301: } else {
6302: my @responses = split(/:/,$reply);
6303: my $outcome = shift(@responses);
6304: foreach my $item (@responses) {
6305: my ($key,$value) = split(/=/,$item);
6306: $$photo{$key} = $value;
6307: }
6308: return $outcome;
6309: }
6310: return 'error';
6311: }
6312:
6313: sub auto_instcode_format {
6314: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6315: $cat_order) = @_;
6316: my $courses = '';
6317: my @homeservers;
6318: if ($caller eq 'global') {
6319: my %servers = &get_servers($codedom,'library');
6320: foreach my $tryserver (keys(%servers)) {
6321: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6322: push(@homeservers,$tryserver);
6323: }
6324: }
6325: } elsif ($caller eq 'requests') {
6326: if ($codedom =~ /^$match_domain$/) {
6327: my $chome = &domain($codedom,'primary');
6328: unless ($chome eq 'no_host') {
6329: push(@homeservers,$chome);
6330: }
6331: }
6332: } else {
6333: push(@homeservers,&homeserver($caller,$codedom));
6334: }
6335: foreach my $code (keys(%{$instcodes})) {
6336: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
6337: }
6338: chop($courses);
6339: my $ok_response = 0;
6340: my $response;
6341: while (@homeservers > 0 && $ok_response == 0) {
6342: my $server = shift(@homeservers);
6343: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6344: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6345: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
6346: split(/:/,$response);
6347: %{$codes} = (%{$codes},&str2hash($codes_str));
6348: push(@{$codetitles},&str2array($codetitles_str));
6349: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6350: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6351: $ok_response = 1;
6352: }
6353: }
6354: if ($ok_response) {
6355: return 'ok';
6356: } else {
6357: return $response;
6358: }
6359: }
6360:
6361: sub auto_instcode_defaults {
6362: my ($domain,$returnhash,$code_order) = @_;
6363: my @homeservers;
6364:
6365: my %servers = &get_servers($domain,'library');
6366: foreach my $tryserver (keys(%servers)) {
6367: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6368: push(@homeservers,$tryserver);
6369: }
6370: }
6371:
6372: my $response;
6373: foreach my $server (@homeservers) {
6374: $response=&reply('autoinstcodedefaults:'.$domain,$server);
6375: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6376:
6377: foreach my $pair (split(/\&/,$response)) {
6378: my ($name,$value)=split(/\=/,$pair);
6379: if ($name eq 'code_order') {
6380: @{$code_order} = split(/\&/,&unescape($value));
6381: } else {
6382: $returnhash->{&unescape($name)}=&unescape($value);
6383: }
6384: }
6385: return 'ok';
6386: }
6387:
6388: return $response;
6389: }
6390:
6391: sub auto_possible_instcodes {
6392: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6393: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6394: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6395: return;
6396: }
6397: my (@homeservers,$uhome);
6398: if (defined(&domain($domain,'primary'))) {
6399: $uhome=&domain($domain,'primary');
6400: push(@homeservers,&domain($domain,'primary'));
6401: } else {
6402: my %servers = &get_servers($domain,'library');
6403: foreach my $tryserver (keys(%servers)) {
6404: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6405: push(@homeservers,$tryserver);
6406: }
6407: }
6408: }
6409: my $response;
6410: foreach my $server (@homeservers) {
6411: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6412: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6413: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6414: split(':',$response);
6415: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6416: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
6417: foreach my $item (split('&',$cat_title)) {
6418: my ($name,$value)=split('=',$item);
6419: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
6420: }
6421: foreach my $item (split('&',$cat_order)) {
6422: my ($name,$value)=split('=',$item);
6423: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
6424: }
6425: return 'ok';
6426: }
6427: return $response;
6428: }
6429:
6430: sub auto_courserequest_checks {
6431: my ($dom) = @_;
6432: my ($homeserver,%validations);
6433: if ($dom =~ /^$match_domain$/) {
6434: $homeserver = &domain($dom,'primary');
6435: }
6436: unless ($homeserver eq 'no_host') {
6437: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6438: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6439: my @items = split(/&/,$response);
6440: foreach my $item (@items) {
6441: my ($key,$value) = split('=',$item);
6442: $validations{&unescape($key)} = &thaw_unescape($value);
6443: }
6444: }
6445: }
6446: return %validations;
6447: }
6448:
6449: sub auto_courserequest_validation {
6450: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6451: my ($homeserver,$response);
6452: if ($dom =~ /^$match_domain$/) {
6453: $homeserver = &domain($dom,'primary');
6454: }
6455: unless ($homeserver eq 'no_host') {
6456:
6457: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
6458: ':'.&escape($crstype).':'.&escape($inststatuslist).
6459: ':'.&escape($instcode).':'.&escape($instseclist),
6460: $homeserver));
6461: }
6462: return $response;
6463: }
6464:
6465: sub auto_validate_class_sec {
6466: my ($cdom,$cnum,$owners,$inst_class) = @_;
6467: my $homeserver = &homeserver($cnum,$cdom);
6468: my $ownerlist;
6469: if (ref($owners) eq 'ARRAY') {
6470: $ownerlist = join(',',@{$owners});
6471: } else {
6472: $ownerlist = $owners;
6473: }
6474: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
6475: &escape($ownerlist).':'.$cdom,$homeserver);
6476: return $response;
6477: }
6478:
6479: # ------------------------------------------------------- Course Group routines
6480:
6481: sub get_coursegroups {
6482: my ($cdom,$cnum,$group,$namespace) = @_;
6483: return(&dump($namespace,$cdom,$cnum,$group));
6484: }
6485:
6486: sub modify_coursegroup {
6487: my ($cdom,$cnum,$groupsettings) = @_;
6488: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6489: }
6490:
6491: sub toggle_coursegroup_status {
6492: my ($cdom,$cnum,$group,$action) = @_;
6493: my ($from_namespace,$to_namespace);
6494: if ($action eq 'delete') {
6495: $from_namespace = 'coursegroups';
6496: $to_namespace = 'deleted_groups';
6497: } else {
6498: $from_namespace = 'deleted_groups';
6499: $to_namespace = 'coursegroups';
6500: }
6501: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
6502: if (my $tmp = &error(%curr_group)) {
6503: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6504: return ('read error',$tmp);
6505: } else {
6506: my %savedsettings = %curr_group;
6507: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
6508: my $deloutcome;
6509: if ($result eq 'ok') {
6510: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
6511: } else {
6512: return ('write error',$result);
6513: }
6514: if ($deloutcome eq 'ok') {
6515: return 'ok';
6516: } else {
6517: return ('delete error',$deloutcome);
6518: }
6519: }
6520: }
6521:
6522: sub modify_group_roles {
6523: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
6524: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6525: my $role = 'gr/'.&escape($userprivs);
6526: my ($uname,$udom) = split(/:/,$user);
6527: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
6528: if ($result eq 'ok') {
6529: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6530: }
6531: return $result;
6532: }
6533:
6534: sub modify_coursegroup_membership {
6535: my ($cdom,$cnum,$membership) = @_;
6536: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6537: return $result;
6538: }
6539:
6540: sub get_active_groups {
6541: my ($udom,$uname,$cdom,$cnum) = @_;
6542: my $now = time;
6543: my %groups = ();
6544: foreach my $key (keys(%env)) {
6545: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
6546: my ($start,$end) = split(/\./,$env{$key});
6547: if (($end!=0) && ($end<$now)) { next; }
6548: if (($start!=0) && ($start>$now)) { next; }
6549: if ($1 eq $cdom && $2 eq $cnum) {
6550: $groups{$3} = $env{$key} ;
6551: }
6552: }
6553: }
6554: return %groups;
6555: }
6556:
6557: sub get_group_membership {
6558: my ($cdom,$cnum,$group) = @_;
6559: return(&dump('groupmembership',$cdom,$cnum,$group));
6560: }
6561:
6562: sub get_users_groups {
6563: my ($udom,$uname,$courseid) = @_;
6564: my @usersgroups;
6565: my $cachetime=1800;
6566:
6567: my $hashid="$udom:$uname:$courseid";
6568: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6569: if (defined($cached)) {
6570: @usersgroups = split(/:/,$grouplist);
6571: } else {
6572: $grouplist = '';
6573: my $courseurl = &courseid_to_courseurl($courseid);
6574: my $extra = &freeze_escape({'skipcheck' => 1});
6575: my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
6576: my $access_end = $env{'course.'.$courseid.
6577: '.default_enrollment_end_date'};
6578: my $now = time;
6579: foreach my $key (keys(%roleshash)) {
6580: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6581: my $group = $1;
6582: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6583: my $start = $2;
6584: my $end = $1;
6585: if ($start == -1) { next; } # deleted from group
6586: if (($start!=0) && ($start>$now)) { next; }
6587: if (($end!=0) && ($end<$now)) {
6588: if ($access_end && $access_end < $now) {
6589: if ($access_end - $end < 86400) {
6590: push(@usersgroups,$group);
6591: }
6592: }
6593: next;
6594: }
6595: push(@usersgroups,$group);
6596: }
6597: }
6598: }
6599: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6600: $grouplist = join(':',@usersgroups);
6601: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
6602: }
6603: return @usersgroups;
6604: }
6605:
6606: sub devalidate_getgroups_cache {
6607: my ($udom,$uname,$cdom,$cnum)=@_;
6608: my $courseid = $cdom.'_'.$cnum;
6609:
6610: my $hashid="$udom:$uname:$courseid";
6611: &devalidate_cache_new('getgroups',$hashid);
6612: }
6613:
6614: # ------------------------------------------------------------------ Plain Text
6615:
6616: sub plaintext {
6617: my ($short,$type,$cid,$forcedefault) = @_;
6618: if ($short =~ m{^cr/}) {
6619: return (split('/',$short))[-1];
6620: }
6621: if (!defined($cid)) {
6622: $cid = $env{'request.course.id'};
6623: }
6624: my %rolenames = (
6625: Course => 'std',
6626: Community => 'alt1',
6627: );
6628: if ($cid ne '') {
6629: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6630: unless ($forcedefault) {
6631: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6632: &Apache::lonlocal::mt_escape(\$roletext);
6633: return &Apache::lonlocal::mt($roletext);
6634: }
6635: }
6636: }
6637: if ((defined($type)) && (defined($rolenames{$type})) &&
6638: (defined($rolenames{$type})) &&
6639: (defined($prp{$short}{$rolenames{$type}}))) {
6640: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
6641: } elsif ($cid ne '') {
6642: my $crstype = $env{'course.'.$cid.'.type'};
6643: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6644: (defined($prp{$short}{$rolenames{$crstype}}))) {
6645: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6646: }
6647: }
6648: return &Apache::lonlocal::mt($prp{$short}{'std'});
6649: }
6650:
6651: # ----------------------------------------------------------------- Assign Role
6652:
6653: sub assignrole {
6654: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6655: $context)=@_;
6656: my $mrole;
6657: if ($role =~ /^cr\//) {
6658: my $cwosec=$url;
6659: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
6660: unless (&allowed('ccr',$cwosec)) {
6661: my $refused = 1;
6662: if ($context eq 'requestcourses') {
6663: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6664: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6665: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6666: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6667: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6668: if ($crsenv{'internal.courseowner'} eq
6669: $env{'user.name'}.':'.$env{'user.domain'}) {
6670: $refused = '';
6671: }
6672: }
6673: }
6674: }
6675: }
6676: if ($refused) {
6677: &logthis('Refused custom assignrole: '.
6678: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6679: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6680: return 'refused';
6681: }
6682: }
6683: $mrole='cr';
6684: } elsif ($role =~ /^gr\//) {
6685: my $cwogrp=$url;
6686: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
6687: unless (&allowed('mdg',$cwogrp)) {
6688: &logthis('Refused group assignrole: '.
6689: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6690: $env{'user.name'}.' at '.$env{'user.domain'});
6691: return 'refused';
6692: }
6693: $mrole='gr';
6694: } else {
6695: my $cwosec=$url;
6696: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
6697: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6698: my $refused;
6699: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6700: if (!(&allowed('c'.$role,$url))) {
6701: $refused = 1;
6702: }
6703: } else {
6704: $refused = 1;
6705: }
6706: if ($refused) {
6707: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6708: if (!$selfenroll && $context eq 'course') {
6709: my %crsenv;
6710: if ($role eq 'cc' || $role eq 'co') {
6711: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6712: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
6713: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
6714: if ($crsenv{'internal.courseowner'} eq
6715: $env{'user.name'}.':'.$env{'user.domain'}) {
6716: $refused = '';
6717: }
6718: }
6719: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
6720: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
6721: if ($crsenv{'internal.courseowner'} eq
6722: $env{'user.name'}.':'.$env{'user.domain'}) {
6723: $refused = '';
6724: }
6725: }
6726: }
6727: }
6728: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6729: $refused = '';
6730: } elsif ($context eq 'requestcourses') {
6731: my @possroles = ('st','ta','ep','in','cc','co');
6732: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
6733: my $wrongcc;
6734: if ($cnum =~ /^$match_community$/) {
6735: $wrongcc = 1 if ($role eq 'cc');
6736: } else {
6737: $wrongcc = 1 if ($role eq 'co');
6738: }
6739: unless ($wrongcc) {
6740: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6741: if ($crsenv{'internal.courseowner'} eq
6742: $env{'user.name'}.':'.$env{'user.domain'}) {
6743: $refused = '';
6744: }
6745: }
6746: }
6747: }
6748: if ($refused) {
6749: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6750: ' '.$role.' '.$end.' '.$start.' by '.
6751: $env{'user.name'}.' at '.$env{'user.domain'});
6752: return 'refused';
6753: }
6754: }
6755: } elsif ($role eq 'au') {
6756: if ($url ne '/'.$udom.'/') {
6757: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
6758: ' to assign author role for '.$uname.':'.$udom.
6759: ' in domain: '.$url.' refused (wrong domain).');
6760: return 'refused';
6761: }
6762: }
6763: $mrole=$role;
6764: }
6765: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
6766: "$udom:$uname:$url".'_'."$mrole=$role";
6767: if ($end) { $command.='_'.$end; }
6768: if ($start) {
6769: if ($end) {
6770: $command.='_'.$start;
6771: } else {
6772: $command.='_0_'.$start;
6773: }
6774: }
6775: my $origstart = $start;
6776: my $origend = $end;
6777: my $delflag;
6778: # actually delete
6779: if ($deleteflag) {
6780: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
6781: # modify command to delete the role
6782: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
6783: "$udom:$uname:$url".'_'."$mrole";
6784: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
6785: # set start and finish to negative values for userrolelog
6786: $start=-1;
6787: $end=-1;
6788: $delflag = 1;
6789: }
6790: }
6791: # send command
6792: my $answer=&reply($command,&homeserver($uname,$udom));
6793: # log new user role if status is ok
6794: if ($answer eq 'ok') {
6795: &userrolelog($role,$uname,$udom,$url,$start,$end);
6796: # for course roles, perform group memberships changes triggered by role change.
6797: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
6798: unless ($role =~ /^gr/) {
6799: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
6800: $origstart,$selfenroll,$context);
6801: }
6802: if ($role eq 'cc') {
6803: &autoupdate_coowners($url,$end,$start,$uname,$udom);
6804: }
6805: }
6806: return $answer;
6807: }
6808:
6809: sub autoupdate_coowners {
6810: my ($url,$end,$start,$uname,$udom) = @_;
6811: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
6812: if (($cdom ne '') && ($cnum ne '')) {
6813: my $now = time;
6814: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
6815: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
6816: my %coursehash = &coursedescription($cdom.'_'.$cnum);
6817: my $instcode = $coursehash{'internal.coursecode'};
6818: if ($instcode ne '') {
6819: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
6820: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
6821: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
6822: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
6823: if ($result eq 'valid') {
6824: if ($coursehash{'internal.co-owners'}) {
6825: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6826: push(@newcoowners,$coowner);
6827: }
6828: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
6829: push(@newcoowners,$uname.':'.$udom);
6830: }
6831: @newcoowners = sort(@newcoowners);
6832: } else {
6833: push(@newcoowners,$uname.':'.$udom);
6834: }
6835: } else {
6836: if ($coursehash{'internal.co-owners'}) {
6837: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6838: unless ($coowner eq $uname.':'.$udom) {
6839: push(@newcoowners,$coowner);
6840: }
6841: }
6842: unless (@newcoowners > 0) {
6843: $delcoowners = 1;
6844: $coowners = '';
6845: }
6846: }
6847: }
6848: if (@newcoowners || $delcoowners) {
6849: &store_coowners($cdom,$cnum,$coursehash{'home'},
6850: $delcoowners,@newcoowners);
6851: }
6852: }
6853: }
6854: }
6855: }
6856: }
6857: }
6858:
6859: sub store_coowners {
6860: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
6861: my $cid = $cdom.'_'.$cnum;
6862: my ($coowners,$delresult,$putresult);
6863: if (@newcoowners) {
6864: $coowners = join(',',@newcoowners);
6865: my %coownershash = (
6866: 'internal.co-owners' => $coowners,
6867: );
6868: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
6869: if ($putresult eq 'ok') {
6870: if ($env{'course.'.$cid.'.num'} eq $cnum) {
6871: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
6872: }
6873: }
6874: }
6875: if ($delcoowners) {
6876: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
6877: if ($delresult eq 'ok') {
6878: if ($env{'course.'.$cid.'.internal.co-owners'}) {
6879: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
6880: }
6881: }
6882: }
6883: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
6884: my %crsinfo =
6885: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6886: if (ref($crsinfo{$cid}) eq 'HASH') {
6887: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
6888: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
6889: }
6890: }
6891: }
6892:
6893: # -------------------------------------------------- Modify user authentication
6894: # Overrides without validation
6895:
6896: sub modifyuserauth {
6897: my ($udom,$uname,$umode,$upass)=@_;
6898: my $uhome=&homeserver($uname,$udom);
6899: unless (&allowed('mau',$udom)) { return 'refused'; }
6900: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
6901: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6902: ' in domain '.$env{'request.role.domain'});
6903: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6904: &escape($upass),$uhome);
6905: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
6906: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6907: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6908: &log($udom,,$uname,$uhome,
6909: 'Authentication changed by '.$env{'user.domain'}.', '.
6910: $env{'user.name'}.', '.$umode.
6911: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6912: unless ($reply eq 'ok') {
6913: &logthis('Authentication mode error: '.$reply);
6914: return 'error: '.$reply;
6915: }
6916: return 'ok';
6917: }
6918:
6919: # --------------------------------------------------------------- Modify a user
6920:
6921: sub modifyuser {
6922: my ($udom, $uname, $uid,
6923: $umode, $upass, $first,
6924: $middle, $last, $gene,
6925: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
6926: $udom= &LONCAPA::clean_domain($udom);
6927: $uname=&LONCAPA::clean_username($uname);
6928: my $showcandelete = 'none';
6929: if (ref($candelete) eq 'ARRAY') {
6930: if (@{$candelete} > 0) {
6931: $showcandelete = join(', ',@{$candelete});
6932: }
6933: }
6934: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
6935: $umode.', '.$first.', '.$middle.', '.
6936: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
6937: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6938: ' desiredhome not specified').
6939: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6940: ' in domain '.$env{'request.role.domain'});
6941: my $uhome=&homeserver($uname,$udom,'true');
6942: my $newuser;
6943: if ($uhome eq 'no_host') {
6944: $newuser = 1;
6945: }
6946: # ----------------------------------------------------------------- Create User
6947: if (($uhome eq 'no_host') &&
6948: (($umode && $upass) || ($umode eq 'localauth'))) {
6949: my $unhome='';
6950: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
6951: $unhome = $desiredhome;
6952: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6953: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
6954: } else { # load balancing routine for determining $unhome
6955: my $loadm=10000000;
6956: my %servers = &get_servers($udom,'library');
6957: foreach my $tryserver (keys(%servers)) {
6958: my $answer=reply('load',$tryserver);
6959: if (($answer=~/\d+/) && ($answer<$loadm)) {
6960: $loadm=$answer;
6961: $unhome=$tryserver;
6962: }
6963: }
6964: }
6965: if (($unhome eq '') || ($unhome eq 'no_host')) {
6966: return 'error: unable to find a home server for '.$uname.
6967: ' in domain '.$udom;
6968: }
6969: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6970: &escape($upass),$unhome);
6971: unless ($reply eq 'ok') {
6972: return 'error: '.$reply;
6973: }
6974: $uhome=&homeserver($uname,$udom,'true');
6975: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
6976: return 'error: unable verify users home machine.';
6977: }
6978: } # End of creation of new user
6979: # ---------------------------------------------------------------------- Add ID
6980: if ($uid) {
6981: $uid=~tr/A-Z/a-z/;
6982: my %uidhash=&idrget($udom,$uname);
6983: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6984: && (!$forceid)) {
6985: unless ($uid eq $uidhash{$uname}) {
6986: return 'error: user id "'.$uid.'" does not match '.
6987: 'current user id "'.$uidhash{$uname}.'".';
6988: }
6989: } else {
6990: &idput($udom,($uname => $uid));
6991: }
6992: }
6993: # -------------------------------------------------------------- Add names, etc
6994: my @tmp=&get('environment',
6995: ['firstname','middlename','lastname','generation','id',
6996: 'permanentemail','inststatus'],
6997: $udom,$uname);
6998: my (%names,%oldnames);
6999: if ($tmp[0] =~ m/^error:.*/) {
7000: %names=();
7001: } else {
7002: %names = @tmp;
7003: %oldnames = %names;
7004: }
7005: #
7006: # If name, email and/or uid are blank (e.g., because an uploaded file
7007: # of users did not contain them), do not overwrite existing values
7008: # unless field is in $candelete array ref.
7009: #
7010:
7011: my @fields = ('firstname','middlename','lastname','generation',
7012: 'permanentemail','id');
7013: my %newvalues;
7014: if (ref($candelete) eq 'ARRAY') {
7015: foreach my $field (@fields) {
7016: if (grep(/^\Q$field\E$/,@{$candelete})) {
7017: if ($field eq 'firstname') {
7018: $names{$field} = $first;
7019: } elsif ($field eq 'middlename') {
7020: $names{$field} = $middle;
7021: } elsif ($field eq 'lastname') {
7022: $names{$field} = $last;
7023: } elsif ($field eq 'generation') {
7024: $names{$field} = $gene;
7025: } elsif ($field eq 'permanentemail') {
7026: $names{$field} = $email;
7027: } elsif ($field eq 'id') {
7028: $names{$field} = $uid;
7029: }
7030: }
7031: }
7032: }
7033: if ($first) { $names{'firstname'} = $first; }
7034: if (defined($middle)) { $names{'middlename'} = $middle; }
7035: if ($last) { $names{'lastname'} = $last; }
7036: if (defined($gene)) { $names{'generation'} = $gene; }
7037: if ($email) {
7038: $email=~s/[^\w\@\.\-\,]//gs;
7039: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
7040: }
7041: if ($uid) { $names{'id'} = $uid; }
7042: if (defined($inststatus)) {
7043: $names{'inststatus'} = '';
7044: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
7045: if (ref($usertypes) eq 'HASH') {
7046: my @okstatuses;
7047: foreach my $item (split(/:/,$inststatus)) {
7048: if (defined($usertypes->{$item})) {
7049: push(@okstatuses,$item);
7050: }
7051: }
7052: if (@okstatuses) {
7053: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
7054: }
7055: }
7056: }
7057: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
7058: $umode.', '.$first.', '.$middle.', '.
7059: $last.', '.$gene.', '.$email.', '.$inststatus;
7060: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
7061: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
7062: } else {
7063: $logmsg .= ' during self creation';
7064: }
7065: my $changed;
7066: if ($newuser) {
7067: $changed = 1;
7068: } else {
7069: foreach my $field (@fields) {
7070: if ($names{$field} ne $oldnames{$field}) {
7071: $changed = 1;
7072: last;
7073: }
7074: }
7075: }
7076: unless ($changed) {
7077: $logmsg = 'No changes in user information needed for: '.$logmsg;
7078: &logthis($logmsg);
7079: return 'ok';
7080: }
7081: my $reply = &put('environment', \%names, $udom,$uname);
7082: if ($reply ne 'ok') {
7083: return 'error: '.$reply;
7084: }
7085: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7086: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7087: }
7088: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7089: &devalidate_cache_new('namescache',$uname.':'.$udom);
7090: $logmsg = 'Success modifying user '.$logmsg;
7091: &logthis($logmsg);
7092: return 'ok';
7093: }
7094:
7095: # -------------------------------------------------------------- Modify student
7096:
7097: sub modifystudent {
7098: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
7099: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
7100: $selfenroll,$context,$inststatus)=@_;
7101: if (!$cid) {
7102: unless ($cid=$env{'request.course.id'}) {
7103: return 'not_in_class';
7104: }
7105: }
7106: # --------------------------------------------------------------- Make the user
7107: my $reply=&modifyuser
7108: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
7109: $desiredhome,$email,$inststatus);
7110: unless ($reply eq 'ok') { return $reply; }
7111: # This will cause &modify_student_enrollment to get the uid from the
7112: # students environment
7113: $uid = undef if (!$forceid);
7114: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
7115: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
7116: return $reply;
7117: }
7118:
7119: sub modify_student_enrollment {
7120: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
7121: my ($cdom,$cnum,$chome);
7122: if (!$cid) {
7123: unless ($cid=$env{'request.course.id'}) {
7124: return 'not_in_class';
7125: }
7126: $cdom=$env{'course.'.$cid.'.domain'};
7127: $cnum=$env{'course.'.$cid.'.num'};
7128: } else {
7129: ($cdom,$cnum)=split(/_/,$cid);
7130: }
7131: $chome=$env{'course.'.$cid.'.home'};
7132: if (!$chome) {
7133: $chome=&homeserver($cnum,$cdom);
7134: }
7135: if (!$chome) { return 'unknown_course'; }
7136: # Make sure the user exists
7137: my $uhome=&homeserver($uname,$udom);
7138: if (($uhome eq '') || ($uhome eq 'no_host')) {
7139: return 'error: no such user';
7140: }
7141: # Get student data if we were not given enough information
7142: if (!defined($first) || $first eq '' ||
7143: !defined($last) || $last eq '' ||
7144: !defined($uid) || $uid eq '' ||
7145: !defined($middle) || $middle eq '' ||
7146: !defined($gene) || $gene eq '') {
7147: # They did not supply us with enough data to enroll the student, so
7148: # we need to pick up more information.
7149: my %tmp = &get('environment',
7150: ['firstname','middlename','lastname', 'generation','id']
7151: ,$udom,$uname);
7152:
7153: #foreach my $key (keys(%tmp)) {
7154: # &logthis("key $key = ".$tmp{$key});
7155: #}
7156: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7157: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7158: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
7159: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
7160: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7161: }
7162: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
7163: my $reply=cput('classlist',
7164: {"$uname:$udom" =>
7165: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
7166: $cdom,$cnum);
7167: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
7168: return 'error: '.$reply;
7169: } else {
7170: &devalidate_getsection_cache($udom,$uname,$cid);
7171: }
7172: # Add student role to user
7173: my $uurl='/'.$cid;
7174: $uurl=~s/\_/\//g;
7175: if ($usec) {
7176: $uurl.='/'.$usec;
7177: }
7178: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
7179: }
7180:
7181: sub format_name {
7182: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7183: my $name;
7184: if ($first ne 'lastname') {
7185: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7186: } else {
7187: if ($lastname=~/\S/) {
7188: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7189: $name=~s/\s+,/,/;
7190: } else {
7191: $name.= $firstname.' '.$middlename.' '.$generation;
7192: }
7193: }
7194: $name=~s/^\s+//;
7195: $name=~s/\s+$//;
7196: $name=~s/\s+/ /g;
7197: return $name;
7198: }
7199:
7200: # ------------------------------------------------- Write to course preferences
7201:
7202: sub writecoursepref {
7203: my ($courseid,%prefs)=@_;
7204: $courseid=~s/^\///;
7205: $courseid=~s/\_/\//g;
7206: my ($cdomain,$cnum)=split(/\//,$courseid);
7207: my $chome=homeserver($cnum,$cdomain);
7208: if (($chome eq '') || ($chome eq 'no_host')) {
7209: return 'error: no such course';
7210: }
7211: my $cstring='';
7212: foreach my $pref (keys(%prefs)) {
7213: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
7214: }
7215: $cstring=~s/\&$//;
7216: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7217: }
7218:
7219: # ---------------------------------------------------------- Make/modify course
7220:
7221: sub createcourse {
7222: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
7223: $course_owner,$crstype,$cnum,$context,$category)=@_;
7224: $url=&declutter($url);
7225: my $cid='';
7226: if ($context eq 'requestcourses') {
7227: my $can_create = 0;
7228: my ($ownername,$ownerdom) = split(':',$course_owner);
7229: if ($udom eq $ownerdom) {
7230: if (&usertools_access($ownername,$ownerdom,$category,undef,
7231: $context)) {
7232: $can_create = 1;
7233: }
7234: } else {
7235: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7236: $category);
7237: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7238: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7239: if (@curr > 0) {
7240: my @options = qw(approval validate autolimit);
7241: my $optregex = join('|',@options);
7242: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7243: $can_create = 1;
7244: }
7245: }
7246: }
7247: }
7248: if ($can_create) {
7249: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7250: unless (&allowed('ccc',$udom)) {
7251: return 'refused';
7252: }
7253: }
7254: } else {
7255: return 'refused';
7256: }
7257: } elsif (!&allowed('ccc',$udom)) {
7258: return 'refused';
7259: }
7260: # --------------------------------------------------------------- Get Unique ID
7261: my $uname;
7262: if ($cnum =~ /^$match_courseid$/) {
7263: my $chome=&homeserver($cnum,$udom,'true');
7264: if (($chome eq '') || ($chome eq 'no_host')) {
7265: $uname = $cnum;
7266: } else {
7267: $uname = &generate_coursenum($udom,$crstype);
7268: }
7269: } else {
7270: $uname = &generate_coursenum($udom,$crstype);
7271: }
7272: return $uname if ($uname =~ /^error/);
7273: # -------------------------------------------------- Check supplied server name
7274: if (!defined($course_server)) {
7275: if (defined(&domain($udom,'primary'))) {
7276: $course_server = &domain($udom,'primary');
7277: } else {
7278: $course_server = $env{'user.home'};
7279: }
7280: }
7281: my %host_servers =
7282: &Apache::lonnet::get_servers($udom,'library');
7283: unless ($host_servers{$course_server}) {
7284: return 'error: invalid home server for course: '.$course_server;
7285: }
7286: # ------------------------------------------------------------- Make the course
7287: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
7288: $course_server);
7289: unless ($reply eq 'ok') { return 'error: '.$reply; }
7290: my $uhome=&homeserver($uname,$udom,'true');
7291: if (($uhome eq '') || ($uhome eq 'no_host')) {
7292: return 'error: no such course';
7293: }
7294: # ----------------------------------------------------------------- Course made
7295: # log existence
7296: my $now = time;
7297: my $newcourse = {
7298: $udom.'_'.$uname => {
7299: description => $description,
7300: inst_code => $inst_code,
7301: owner => $course_owner,
7302: type => $crstype,
7303: creator => $env{'user.name'}.':'.
7304: $env{'user.domain'},
7305: created => $now,
7306: context => $context,
7307: },
7308: };
7309: &courseidput($udom,$newcourse,$uhome,'notime');
7310: # set toplevel url
7311: my $topurl=$url;
7312: unless ($nonstandard) {
7313: # ------------------------------------------ For standard courses, make top url
7314: my $mapurl=&clutter($url);
7315: if ($mapurl eq '/res/') { $mapurl=''; }
7316: $env{'form.initmap'}=(<<ENDINITMAP);
7317: <map>
7318: <resource id="1" type="start"></resource>
7319: <resource id="2" src="$mapurl"></resource>
7320: <resource id="3" type="finish"></resource>
7321: <link index="1" from="1" to="2"></link>
7322: <link index="2" from="2" to="3"></link>
7323: </map>
7324: ENDINITMAP
7325: $topurl=&declutter(
7326: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
7327: );
7328: }
7329: # ----------------------------------------------------------- Write preferences
7330: &writecoursepref($udom.'_'.$uname,
7331: ('description' => $description,
7332: 'url' => $topurl,
7333: 'internal.creator' => $env{'user.name'}.':'.
7334: $env{'user.domain'},
7335: 'internal.created' => $now,
7336: 'internal.creationcontext' => $context)
7337: );
7338: return '/'.$udom.'/'.$uname;
7339: }
7340:
7341: # ------------------------------------------------------------------- Create ID
7342: sub generate_coursenum {
7343: my ($udom,$crstype) = @_;
7344: my $domdesc = &domain($udom);
7345: return 'error: invalid domain' if ($domdesc eq '');
7346: my $first;
7347: if ($crstype eq 'Community') {
7348: $first = '0';
7349: } else {
7350: $first = int(1+rand(9));
7351: }
7352: my $uname=$first.
7353: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7354: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7355: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7356: # ----------------------------------------------- Make sure that does not exist
7357: my $uhome=&homeserver($uname,$udom,'true');
7358: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7359: if ($crstype eq 'Community') {
7360: $first = '0';
7361: } else {
7362: $first = int(1+rand(9));
7363: }
7364: $uname=$first.
7365: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7366: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7367: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7368: $uhome=&homeserver($uname,$udom,'true');
7369: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7370: return 'error: unable to generate unique course-ID';
7371: }
7372: }
7373: return $uname;
7374: }
7375:
7376: sub is_course {
7377: my ($cdom,$cnum) = @_;
7378: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
7379: undef,'.');
7380: if (exists($courses{$cdom.'_'.$cnum})) {
7381: return 1;
7382: }
7383: return 0;
7384: }
7385:
7386: sub store_userdata {
7387: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
7388: my $result;
7389: if ($datakey ne '') {
7390: if (ref($storehash) eq 'HASH') {
7391: if ($udom eq '' || $uname eq '') {
7392: $udom = $env{'user.domain'};
7393: $uname = $env{'user.name'};
7394: }
7395: my $uhome=&homeserver($uname,$udom);
7396: if (($uhome eq '') || ($uhome eq 'no_host')) {
7397: $result = 'error: no_host';
7398: } else {
7399: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7400: $storehash->{'host'} = $perlvar{'lonHostID'};
7401:
7402: my $namevalue='';
7403: foreach my $key (keys(%{$storehash})) {
7404: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7405: }
7406: $namevalue=~s/\&$//;
7407: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
7408: $namevalue,$uhome);
7409: }
7410: } else {
7411: $result = 'error: data to store was not a hash reference';
7412: }
7413: } else {
7414: $result= 'error: invalid requestkey';
7415: }
7416: return $result;
7417: }
7418:
7419: # ---------------------------------------------------------- Assign Custom Role
7420:
7421: sub assigncustomrole {
7422: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
7423: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
7424: $end,$start,$deleteflag,$selfenroll,$context);
7425: }
7426:
7427: # ----------------------------------------------------------------- Revoke Role
7428:
7429: sub revokerole {
7430: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
7431: my $now=time;
7432: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
7433: }
7434:
7435: # ---------------------------------------------------------- Revoke Custom Role
7436:
7437: sub revokecustomrole {
7438: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
7439: my $now=time;
7440: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
7441: $deleteflag,$selfenroll,$context);
7442: }
7443:
7444: # ------------------------------------------------------------ Disk usage
7445: sub diskusage {
7446: my ($udom,$uname,$directorypath,$getpropath)=@_;
7447: $directorypath =~ s/\/$//;
7448: my $listing=&reply('du2:'.&escape($directorypath).':'
7449: .&escape($getpropath).':'.&escape($uname).':'
7450: .&escape($udom),homeserver($uname,$udom));
7451: if ($listing eq 'unknown_cmd') {
7452: if ($getpropath) {
7453: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7454: }
7455: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7456: }
7457: return $listing;
7458: }
7459:
7460: sub is_locked {
7461: my ($file_name, $domain, $user, $which) = @_;
7462: my @check;
7463: my $is_locked;
7464: push(@check,$file_name);
7465: my %locked = &get('file_permissions',\@check,
7466: $env{'user.domain'},$env{'user.name'});
7467: my ($tmp)=keys(%locked);
7468: if ($tmp=~/^error:/) { undef(%locked); }
7469:
7470: if (ref($locked{$file_name}) eq 'ARRAY') {
7471: $is_locked = 'false';
7472: foreach my $entry (@{$locked{$file_name}}) {
7473: if (ref($entry) eq 'ARRAY') {
7474: $is_locked = 'true';
7475: if (ref($which) eq 'ARRAY') {
7476: push(@{$which},$entry);
7477: } else {
7478: last;
7479: }
7480: }
7481: }
7482: } else {
7483: $is_locked = 'false';
7484: }
7485: return $is_locked;
7486: }
7487:
7488: sub declutter_portfile {
7489: my ($file) = @_;
7490: $file =~ s{^(/portfolio/|portfolio/)}{/};
7491: return $file;
7492: }
7493:
7494: # ------------------------------------------------------------- Mark as Read Only
7495:
7496: sub mark_as_readonly {
7497: my ($domain,$user,$files,$what) = @_;
7498: my %current_permissions = &dump('file_permissions',$domain,$user);
7499: my ($tmp)=keys(%current_permissions);
7500: if ($tmp=~/^error:/) { undef(%current_permissions); }
7501: foreach my $file (@{$files}) {
7502: $file = &declutter_portfile($file);
7503: push(@{$current_permissions{$file}},$what);
7504: }
7505: &put('file_permissions',\%current_permissions,$domain,$user);
7506: return;
7507: }
7508:
7509: # ------------------------------------------------------------Save Selected Files
7510:
7511: sub save_selected_files {
7512: my ($user, $path, @files) = @_;
7513: my $filename = $user."savedfiles";
7514: my @other_files = &files_not_in_path($user, $path);
7515: open (OUT, '>'.$tmpdir.$filename);
7516: foreach my $file (@files) {
7517: print (OUT $env{'form.currentpath'}.$file."\n");
7518: }
7519: foreach my $file (@other_files) {
7520: print (OUT $file."\n");
7521: }
7522: close (OUT);
7523: return 'ok';
7524: }
7525:
7526: sub clear_selected_files {
7527: my ($user) = @_;
7528: my $filename = $user."savedfiles";
7529: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7530: print (OUT undef);
7531: close (OUT);
7532: return ("ok");
7533: }
7534:
7535: sub files_in_path {
7536: my ($user, $path) = @_;
7537: my $filename = $user."savedfiles";
7538: my %return_files;
7539: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7540: while (my $line_in = <IN>) {
7541: chomp ($line_in);
7542: my @paths_and_file = split (m!/!, $line_in);
7543: my $file_part = pop (@paths_and_file);
7544: my $path_part = join ('/', @paths_and_file);
7545: $path_part.='/';
7546: my $path_and_file = $path_part.$file_part;
7547: if ($path_part eq $path) {
7548: $return_files{$file_part}= 'selected';
7549: }
7550: }
7551: close (IN);
7552: return (\%return_files);
7553: }
7554:
7555: # called in portfolio select mode, to show files selected NOT in current directory
7556: sub files_not_in_path {
7557: my ($user, $path) = @_;
7558: my $filename = $user."savedfiles";
7559: my @return_files;
7560: my $path_part;
7561: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7562: while (my $line = <IN>) {
7563: #ok, I know it's clunky, but I want it to work
7564: my @paths_and_file = split(m|/|, $line);
7565: my $file_part = pop(@paths_and_file);
7566: chomp($file_part);
7567: my $path_part = join('/', @paths_and_file);
7568: $path_part .= '/';
7569: my $path_and_file = $path_part.$file_part;
7570: if ($path_part ne $path) {
7571: push(@return_files, ($path_and_file));
7572: }
7573: }
7574: close(OUT);
7575: return (@return_files);
7576: }
7577:
7578: #----------------------------------------------Get portfolio file permissions
7579:
7580: sub get_portfile_permissions {
7581: my ($domain,$user) = @_;
7582: my %current_permissions = &dump('file_permissions',$domain,$user);
7583: my ($tmp)=keys(%current_permissions);
7584: if ($tmp=~/^error:/) { undef(%current_permissions); }
7585: return \%current_permissions;
7586: }
7587:
7588: #---------------------------------------------Get portfolio file access controls
7589:
7590: sub get_access_controls {
7591: my ($current_permissions,$group,$file) = @_;
7592: my %access;
7593: my $real_file = $file;
7594: $file =~ s/\.meta$//;
7595: if (defined($file)) {
7596: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7597: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
7598: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
7599: }
7600: }
7601: } else {
7602: foreach my $key (keys(%{$current_permissions})) {
7603: if ($key =~ /\0accesscontrol$/) {
7604: if (defined($group)) {
7605: if ($key !~ m-^\Q$group\E/-) {
7606: next;
7607: }
7608: }
7609: my ($fullpath) = split(/\0/,$key);
7610: if (ref($$current_permissions{$key}) eq 'HASH') {
7611: foreach my $control (keys(%{$$current_permissions{$key}})) {
7612: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7613: }
7614: }
7615: }
7616: }
7617: }
7618: return %access;
7619: }
7620:
7621: sub modify_access_controls {
7622: my ($file_name,$changes,$domain,$user)=@_;
7623: my ($outcome,$deloutcome);
7624: my %store_permissions;
7625: my %new_values;
7626: my %new_control;
7627: my %translation;
7628: my @deletions = ();
7629: my $now = time;
7630: if (exists($$changes{'activate'})) {
7631: if (ref($$changes{'activate'}) eq 'HASH') {
7632: my @newitems = sort(keys(%{$$changes{'activate'}}));
7633: my $numnew = scalar(@newitems);
7634: for (my $i=0; $i<$numnew; $i++) {
7635: my $newkey = $newitems[$i];
7636: my $newid = &Apache::loncommon::get_cgi_id();
7637: if ($newkey =~ /^\d+:/) {
7638: $newkey =~ s/^(\d+)/$newid/;
7639: $translation{$1} = $newid;
7640: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7641: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7642: $translation{$1} = $newid;
7643: }
7644: $new_values{$file_name."\0".$newkey} =
7645: $$changes{'activate'}{$newitems[$i]};
7646: $new_control{$newkey} = $now;
7647: }
7648: }
7649: }
7650: my %todelete;
7651: my %changed_items;
7652: foreach my $action ('delete','update') {
7653: if (exists($$changes{$action})) {
7654: if (ref($$changes{$action}) eq 'HASH') {
7655: foreach my $key (keys(%{$$changes{$action}})) {
7656: my ($itemnum) = ($key =~ /^([^:]+):/);
7657: if ($action eq 'delete') {
7658: $todelete{$itemnum} = 1;
7659: } else {
7660: $changed_items{$itemnum} = $key;
7661: }
7662: }
7663: }
7664: }
7665: }
7666: # get lock on access controls for file.
7667: my $lockhash = {
7668: $file_name."\0".'locked_access_records' => $env{'user.name'}.
7669: ':'.$env{'user.domain'},
7670: };
7671: my $tries = 0;
7672: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7673:
7674: while (($gotlock ne 'ok') && $tries <3) {
7675: $tries ++;
7676: sleep 1;
7677: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7678: }
7679: if ($gotlock eq 'ok') {
7680: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
7681: my ($tmp)=keys(%curr_permissions);
7682: if ($tmp=~/^error:/) { undef(%curr_permissions); }
7683: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
7684: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
7685: if (ref($curr_controls) eq 'HASH') {
7686: foreach my $control_item (keys(%{$curr_controls})) {
7687: my ($itemnum) = ($control_item =~ /^([^:]+):/);
7688: if (defined($todelete{$itemnum})) {
7689: push(@deletions,$file_name."\0".$control_item);
7690: } else {
7691: if (defined($changed_items{$itemnum})) {
7692: $new_control{$changed_items{$itemnum}} = $now;
7693: push(@deletions,$file_name."\0".$control_item);
7694: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
7695: } else {
7696: $new_control{$control_item} = $$curr_controls{$control_item};
7697: }
7698: }
7699: }
7700: }
7701: }
7702: my ($group);
7703: if (&is_course($domain,$user)) {
7704: ($group,my $file) = split(/\//,$file_name,2);
7705: }
7706: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
7707: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
7708: $outcome = &put('file_permissions',\%new_values,$domain,$user);
7709: # remove lock
7710: my @del_lock = ($file_name."\0".'locked_access_records');
7711: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
7712: my $sqlresult =
7713: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
7714: $group);
7715: } else {
7716: $outcome = "error: could not obtain lockfile\n";
7717: }
7718: return ($outcome,$deloutcome,\%new_values,\%translation);
7719: }
7720:
7721: sub make_public_indefinitely {
7722: my ($requrl) = @_;
7723: my $now = time;
7724: my $action = 'activate';
7725: my $aclnum = 0;
7726: if (&is_portfolio_url($requrl)) {
7727: my (undef,$udom,$unum,$file_name,$group) =
7728: &parse_portfolio_url($requrl);
7729: my $current_perms = &get_portfile_permissions($udom,$unum);
7730: my %access_controls = &get_access_controls($current_perms,
7731: $group,$file_name);
7732: foreach my $key (keys(%{$access_controls{$file_name}})) {
7733: my ($num,$scope,$end,$start) =
7734: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7735: if ($scope eq 'public') {
7736: if ($start <= $now && $end == 0) {
7737: $action = 'none';
7738: } else {
7739: $action = 'update';
7740: $aclnum = $num;
7741: }
7742: last;
7743: }
7744: }
7745: if ($action eq 'none') {
7746: return 'ok';
7747: } else {
7748: my %changes;
7749: my $newend = 0;
7750: my $newstart = $now;
7751: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
7752: $changes{$action}{$newkey} = {
7753: type => 'public',
7754: time => {
7755: start => $newstart,
7756: end => $newend,
7757: },
7758: };
7759: my ($outcome,$deloutcome,$new_values,$translation) =
7760: &modify_access_controls($file_name,\%changes,$udom,$unum);
7761: return $outcome;
7762: }
7763: } else {
7764: return 'invalid';
7765: }
7766: }
7767:
7768: #------------------------------------------------------Get Marked as Read Only
7769:
7770: sub get_marked_as_readonly {
7771: my ($domain,$user,$what,$group) = @_;
7772: my $current_permissions = &get_portfile_permissions($domain,$user);
7773: my @readonly_files;
7774: my $cmp1=$what;
7775: if (ref($what)) { $cmp1=join('',@{$what}) };
7776: while (my ($file_name,$value) = each(%{$current_permissions})) {
7777: if (defined($group)) {
7778: if ($file_name !~ m-^\Q$group\E/-) {
7779: next;
7780: }
7781: }
7782: if (ref($value) eq "ARRAY"){
7783: foreach my $stored_what (@{$value}) {
7784: my $cmp2=$stored_what;
7785: if (ref($stored_what) eq 'ARRAY') {
7786: $cmp2=join('',@{$stored_what});
7787: }
7788: if ($cmp1 eq $cmp2) {
7789: push(@readonly_files, $file_name);
7790: last;
7791: } elsif (!defined($what)) {
7792: push(@readonly_files, $file_name);
7793: last;
7794: }
7795: }
7796: }
7797: }
7798: return @readonly_files;
7799: }
7800: #-----------------------------------------------------------Get Marked as Read Only Hash
7801:
7802: sub get_marked_as_readonly_hash {
7803: my ($current_permissions,$group,$what) = @_;
7804: my %readonly_files;
7805: while (my ($file_name,$value) = each(%{$current_permissions})) {
7806: if (defined($group)) {
7807: if ($file_name !~ m-^\Q$group\E/-) {
7808: next;
7809: }
7810: }
7811: if (ref($value) eq "ARRAY"){
7812: foreach my $stored_what (@{$value}) {
7813: if (ref($stored_what) eq 'ARRAY') {
7814: foreach my $lock_descriptor(@{$stored_what}) {
7815: if ($lock_descriptor eq 'graded') {
7816: $readonly_files{$file_name} = 'graded';
7817: } elsif ($lock_descriptor eq 'handback') {
7818: $readonly_files{$file_name} = 'handback';
7819: } else {
7820: if (!exists($readonly_files{$file_name})) {
7821: $readonly_files{$file_name} = 'locked';
7822: }
7823: }
7824: }
7825: }
7826: }
7827: }
7828: }
7829: return %readonly_files;
7830: }
7831: # ------------------------------------------------------------ Unmark as Read Only
7832:
7833: sub unmark_as_readonly {
7834: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7835: # for portfolio submissions, $what contains [$symb,$crsid]
7836: my ($domain,$user,$what,$file_name,$group) = @_;
7837: $file_name = &declutter_portfile($file_name);
7838: my $symb_crs = $what;
7839: if (ref($what)) { $symb_crs=join('',@$what); }
7840: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
7841: my ($tmp)=keys(%current_permissions);
7842: if ($tmp=~/^error:/) { undef(%current_permissions); }
7843: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
7844: foreach my $file (@readonly_files) {
7845: my $clean_file = &declutter_portfile($file);
7846: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
7847: my $current_locks = $current_permissions{$file};
7848: my @new_locks;
7849: my @del_keys;
7850: if (ref($current_locks) eq "ARRAY"){
7851: foreach my $locker (@{$current_locks}) {
7852: my $compare=$locker;
7853: if (ref($locker) eq 'ARRAY') {
7854: $compare=join('',@{$locker});
7855: if ($compare ne $symb_crs) {
7856: push(@new_locks, $locker);
7857: }
7858: }
7859: }
7860: if (scalar(@new_locks) > 0) {
7861: $current_permissions{$file} = \@new_locks;
7862: } else {
7863: push(@del_keys, $file);
7864: &del('file_permissions',\@del_keys, $domain, $user);
7865: delete($current_permissions{$file});
7866: }
7867: }
7868: }
7869: &put('file_permissions',\%current_permissions,$domain,$user);
7870: return;
7871: }
7872:
7873: # ------------------------------------------------------------ Directory lister
7874:
7875: sub dirlist {
7876: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
7877: $uri=~s/^\///;
7878: $uri=~s/\/$//;
7879: my ($udom, $uname);
7880: if ($getuserdir) {
7881: $udom = $userdomain;
7882: $uname = $username;
7883: } else {
7884: (undef,$udom,$uname)=split(/\//,$uri);
7885: if(defined($userdomain)) {
7886: $udom = $userdomain;
7887: }
7888: if(defined($username)) {
7889: $uname = $username;
7890: }
7891: }
7892: my ($dirRoot,$listing,@listing_results);
7893:
7894: $dirRoot = $perlvar{'lonDocRoot'};
7895: if (defined($getpropath)) {
7896: $dirRoot = &propath($udom,$uname);
7897: $dirRoot =~ s/\/$//;
7898: } elsif (defined($getuserdir)) {
7899: my $subdir=$uname.'__';
7900: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7901: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7902: ."/$udom/$subdir/$uname";
7903: } elsif (defined($alternateRoot)) {
7904: $dirRoot = $alternateRoot;
7905: }
7906:
7907: if($udom) {
7908: if($uname) {
7909: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
7910: .$getuserdir.':'.&escape($dirRoot)
7911: .':'.&escape($uname).':'.&escape($udom),
7912: &homeserver($uname,$udom));
7913: if ($listing eq 'unknown_cmd') {
7914: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7915: &homeserver($uname,$udom));
7916: } else {
7917: @listing_results = map { &unescape($_); } split(/:/,$listing);
7918: }
7919: if ($listing eq 'unknown_cmd') {
7920: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7921: &homeserver($uname,$udom));
7922: @listing_results = split(/:/,$listing);
7923: } else {
7924: @listing_results = map { &unescape($_); } split(/:/,$listing);
7925: }
7926: return @listing_results;
7927: } elsif(!$alternateRoot) {
7928: my %allusers;
7929: my %servers = &get_servers($udom,'library');
7930: foreach my $tryserver (keys(%servers)) {
7931: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7932: &escape($udom),$tryserver);
7933: if ($listing eq 'unknown_cmd') {
7934: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7935: $udom, $tryserver);
7936: } else {
7937: @listing_results = map { &unescape($_); } split(/:/,$listing);
7938: }
7939: if ($listing eq 'unknown_cmd') {
7940: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7941: $udom, $tryserver);
7942: @listing_results = split(/:/,$listing);
7943: } else {
7944: @listing_results =
7945: map { &unescape($_); } split(/:/,$listing);
7946: }
7947: if ($listing_results[0] ne 'no_such_dir' &&
7948: $listing_results[0] ne 'empty' &&
7949: $listing_results[0] ne 'con_lost') {
7950: foreach my $line (@listing_results) {
7951: my ($entry) = split(/&/,$line,2);
7952: $allusers{$entry} = 1;
7953: }
7954: }
7955: }
7956: my $alluserstr='';
7957: foreach my $user (sort(keys(%allusers))) {
7958: $alluserstr.=$user.'&user:';
7959: }
7960: $alluserstr=~s/:$//;
7961: return split(/:/,$alluserstr);
7962: } else {
7963: return ('missing user name');
7964: }
7965: } elsif(!defined($getpropath)) {
7966: my @all_domains = sort(&all_domains());
7967: foreach my $domain (@all_domains) {
7968: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7969: }
7970: return @all_domains;
7971: } else {
7972: return ('missing domain');
7973: }
7974: }
7975:
7976: # --------------------------------------------- GetFileTimestamp
7977: # This function utilizes dirlist and returns the date stamp for
7978: # when it was last modified. It will also return an error of -1
7979: # if an error occurs
7980:
7981: sub GetFileTimestamp {
7982: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
7983: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7984: $studentName = &LONCAPA::clean_username($studentName);
7985: my ($fileStat) =
7986: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7987: undef,$getuserdir);
7988: my @stats = split('&', $fileStat);
7989: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7990: # @stats contains first the filename, then the stat output
7991: return $stats[10]; # so this is 10 instead of 9.
7992: } else {
7993: return -1;
7994: }
7995: }
7996:
7997: sub stat_file {
7998: my ($uri) = @_;
7999: $uri = &clutter_with_no_wrapper($uri);
8000:
8001: my ($udom,$uname,$file);
8002: if ($uri =~ m-^/(uploaded|editupload)/-) {
8003: ($udom,$uname,$file) =
8004: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
8005: $file = 'userfiles/'.$file;
8006: }
8007: if ($uri =~ m-^/res/-) {
8008: ($udom,$uname) =
8009: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
8010: $file = $uri;
8011: }
8012:
8013: if (!$udom || !$uname || !$file) {
8014: # unable to handle the uri
8015: return ();
8016: }
8017: my $getpropath;
8018: if ($file =~ /^userfiles\//) {
8019: $getpropath = 1;
8020: }
8021: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
8022: my @stats = split('&', $result);
8023:
8024: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
8025: shift(@stats); #filename is first
8026: return @stats;
8027: }
8028: return ();
8029: }
8030:
8031: # -------------------------------------------------------- Value of a Condition
8032:
8033: # gets the value of a specific preevaluated condition
8034: # stored in the string $env{user.state.<cid>}
8035: # or looks up a condition reference in the bighash and if if hasn't
8036: # already been evaluated recurses into docondval to get the value of
8037: # the condition, then memoizing it to
8038: # $env{user.state.<cid>.<condition>}
8039: sub directcondval {
8040: my $number=shift;
8041: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
8042: &Apache::lonuserstate::evalstate();
8043: }
8044: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
8045: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
8046: } elsif ($number =~ /^_/) {
8047: my $sub_condition;
8048: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8049: &GDBM_READER(),0640)) {
8050: $sub_condition=$bighash{'conditions'.$number};
8051: untie(%bighash);
8052: }
8053: my $value = &docondval($sub_condition);
8054: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
8055: return $value;
8056: }
8057: if ($env{'user.state.'.$env{'request.course.id'}}) {
8058: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
8059: } else {
8060: return 2;
8061: }
8062: }
8063:
8064: # get the collection of conditions for this resource
8065: sub condval {
8066: my $condidx=shift;
8067: my $allpathcond='';
8068: foreach my $cond (split(/\|/,$condidx)) {
8069: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8070: $allpathcond.=
8071: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8072: }
8073: }
8074: $allpathcond=~s/\|$//;
8075: return &docondval($allpathcond);
8076: }
8077:
8078: #evaluates an expression of conditions
8079: sub docondval {
8080: my ($allpathcond) = @_;
8081: my $result=0;
8082: if ($env{'request.course.id'}
8083: && defined($allpathcond)) {
8084: my $operand='|';
8085: my @stack;
8086: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8087: if ($chunk eq '(') {
8088: push @stack,($operand,$result);
8089: } elsif ($chunk eq ')') {
8090: my $before=pop @stack;
8091: if (pop @stack eq '&') {
8092: $result=$result>$before?$before:$result;
8093: } else {
8094: $result=$result>$before?$result:$before;
8095: }
8096: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8097: $operand=$chunk;
8098: } else {
8099: my $new=directcondval($chunk);
8100: if ($operand eq '&') {
8101: $result=$result>$new?$new:$result;
8102: } else {
8103: $result=$result>$new?$result:$new;
8104: }
8105: }
8106: }
8107: }
8108: return $result;
8109: }
8110:
8111: # ---------------------------------------------------- Devalidate courseresdata
8112:
8113: sub devalidatecourseresdata {
8114: my ($coursenum,$coursedomain)=@_;
8115: my $hashid=$coursenum.':'.$coursedomain;
8116: &devalidate_cache_new('courseres',$hashid);
8117: }
8118:
8119:
8120: # --------------------------------------------------- Course Resourcedata Query
8121: #
8122: # Parameters:
8123: # $coursenum - Number of the course.
8124: # $coursedomain - Domain at which the course was created.
8125: # Returns:
8126: # A hash of the course parameters along (I think) with timestamps
8127: # and version info.
8128:
8129: sub get_courseresdata {
8130: my ($coursenum,$coursedomain)=@_;
8131: my $coursehom=&homeserver($coursenum,$coursedomain);
8132: my $hashid=$coursenum.':'.$coursedomain;
8133: my ($result,$cached)=&is_cached_new('courseres',$hashid);
8134: my %dumpreply;
8135: unless (defined($cached)) {
8136: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
8137: $result=\%dumpreply;
8138: my ($tmp) = keys(%dumpreply);
8139: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
8140: &do_cache_new('courseres',$hashid,$result,600);
8141: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8142: return $tmp;
8143: } elsif ($tmp =~ /^(error)/) {
8144: $result=undef;
8145: &do_cache_new('courseres',$hashid,$result,600);
8146: }
8147: }
8148: return $result;
8149: }
8150:
8151: sub devalidateuserresdata {
8152: my ($uname,$udom)=@_;
8153: my $hashid="$udom:$uname";
8154: &devalidate_cache_new('userres',$hashid);
8155: }
8156:
8157: sub get_userresdata {
8158: my ($uname,$udom)=@_;
8159: #most student don\'t have any data set, check if there is some data
8160: if (&EXT_cache_status($udom,$uname)) { return undef; }
8161:
8162: my $hashid="$udom:$uname";
8163: my ($result,$cached)=&is_cached_new('userres',$hashid);
8164: if (!defined($cached)) {
8165: my %resourcedata=&dump('resourcedata',$udom,$uname);
8166: $result=\%resourcedata;
8167: &do_cache_new('userres',$hashid,$result,600);
8168: }
8169: my ($tmp)=keys(%$result);
8170: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8171: return $result;
8172: }
8173: #error 2 occurs when the .db doesn't exist
8174: if ($tmp!~/error: 2 /) {
8175: &logthis("<font color=\"blue\">WARNING:".
8176: " Trying to get resource data for ".
8177: $uname." at ".$udom.": ".
8178: $tmp."</font>");
8179: } elsif ($tmp=~/error: 2 /) {
8180: #&EXT_cache_set($udom,$uname);
8181: &do_cache_new('userres',$hashid,undef,600);
8182: undef($tmp); # not really an error so don't send it back
8183: }
8184: return $tmp;
8185: }
8186: #----------------------------------------------- resdata - return resource data
8187: # Purpose:
8188: # Return resource data for either users or for a course.
8189: # Parameters:
8190: # $name - Course/user name.
8191: # $domain - Name of the domain the user/course is registered on.
8192: # $type - Type of thing $name is (must be 'course' or 'user'
8193: # @which - Array of names of resources desired.
8194: # Returns:
8195: # The value of the first reasource in @which that is found in the
8196: # resource hash.
8197: # Exceptional Conditions:
8198: # If the $type passed in is not valid (not the string 'course' or
8199: # 'user', an undefined reference is returned.
8200: # If none of the resources are found, an undef is returned
8201: sub resdata {
8202: my ($name,$domain,$type,@which)=@_;
8203: my $result;
8204: if ($type eq 'course') {
8205: $result=&get_courseresdata($name,$domain);
8206: } elsif ($type eq 'user') {
8207: $result=&get_userresdata($name,$domain);
8208: }
8209: if (!ref($result)) { return $result; }
8210: foreach my $item (@which) {
8211: if (defined($result->{$item->[0]})) {
8212: return [$result->{$item->[0]},$item->[1]];
8213: }
8214: }
8215: return undef;
8216: }
8217:
8218: #
8219: # EXT resource caching routines
8220: #
8221:
8222: sub clear_EXT_cache_status {
8223: &delenv('cache.EXT.');
8224: }
8225:
8226: sub EXT_cache_status {
8227: my ($target_domain,$target_user) = @_;
8228: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
8229: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
8230: # We know already the user has no data
8231: return 1;
8232: } else {
8233: return 0;
8234: }
8235: }
8236:
8237: sub EXT_cache_set {
8238: my ($target_domain,$target_user) = @_;
8239: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
8240: #&appenv({$cachename => time});
8241: }
8242:
8243: # --------------------------------------------------------- Value of a Variable
8244: sub EXT {
8245:
8246: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
8247: unless ($varname) { return ''; }
8248: #get real user name/domain, courseid and symb
8249: my $courseid;
8250: my $publicuser;
8251: if ($symbparm) {
8252: $symbparm=&get_symb_from_alias($symbparm);
8253: }
8254: if (!($uname && $udom)) {
8255: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
8256: if (!$symbparm) { $symbparm=$cursymb; }
8257: } else {
8258: $courseid=$env{'request.course.id'};
8259: }
8260: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8261: my $rest;
8262: if (defined($therest[0])) {
8263: $rest=join('.',@therest);
8264: } else {
8265: $rest='';
8266: }
8267:
8268: my $qualifierrest=$qualifier;
8269: if ($rest) { $qualifierrest.='.'.$rest; }
8270: my $spacequalifierrest=$space;
8271: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
8272: if ($realm eq 'user') {
8273: # --------------------------------------------------------------- user.resource
8274: if ($space eq 'resource') {
8275: if ( (defined($Apache::lonhomework::parsing_a_problem)
8276: || defined($Apache::lonhomework::parsing_a_task))
8277: &&
8278: ($symbparm eq &symbread()) ) {
8279: # if we are in the middle of processing the resource the
8280: # get the value we are planning on committing
8281: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8282: return $Apache::lonhomework::results{$qualifierrest};
8283: } else {
8284: return $Apache::lonhomework::history{$qualifierrest};
8285: }
8286: } else {
8287: my %restored;
8288: if ($publicuser || $env{'request.state'} eq 'construct') {
8289: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8290: } else {
8291: %restored=&restore($symbparm,$courseid,$udom,$uname);
8292: }
8293: return $restored{$qualifierrest};
8294: }
8295: # ----------------------------------------------------------------- user.access
8296: } elsif ($space eq 'access') {
8297: # FIXME - not supporting calls for a specific user
8298: return &allowed($qualifier,$rest);
8299: # ------------------------------------------ user.preferences, user.environment
8300: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
8301: if (($uname eq $env{'user.name'}) &&
8302: ($udom eq $env{'user.domain'})) {
8303: return $env{join('.',('environment',$qualifierrest))};
8304: } else {
8305: my %returnhash;
8306: if (!$publicuser) {
8307: %returnhash=&userenvironment($udom,$uname,
8308: $qualifierrest);
8309: }
8310: return $returnhash{$qualifierrest};
8311: }
8312: # ----------------------------------------------------------------- user.course
8313: } elsif ($space eq 'course') {
8314: # FIXME - not supporting calls for a specific user
8315: return $env{join('.',('request.course',$qualifier))};
8316: # ------------------------------------------------------------------- user.role
8317: } elsif ($space eq 'role') {
8318: # FIXME - not supporting calls for a specific user
8319: my ($role,$where)=split(/\./,$env{'request.role'});
8320: if ($qualifier eq 'value') {
8321: return $role;
8322: } elsif ($qualifier eq 'extent') {
8323: return $where;
8324: }
8325: # ----------------------------------------------------------------- user.domain
8326: } elsif ($space eq 'domain') {
8327: return $udom;
8328: # ------------------------------------------------------------------- user.name
8329: } elsif ($space eq 'name') {
8330: return $uname;
8331: # ---------------------------------------------------- Any other user namespace
8332: } else {
8333: my %reply;
8334: if (!$publicuser) {
8335: %reply=&get($space,[$qualifierrest],$udom,$uname);
8336: }
8337: return $reply{$qualifierrest};
8338: }
8339: } elsif ($realm eq 'query') {
8340: # ---------------------------------------------- pull stuff out of query string
8341: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8342: [$spacequalifierrest]);
8343: return $env{'form.'.$spacequalifierrest};
8344: } elsif ($realm eq 'request') {
8345: # ------------------------------------------------------------- request.browser
8346: if ($space eq 'browser') {
8347: if ($qualifier eq 'textremote') {
8348: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
8349: return 1;
8350: } else {
8351: return 0;
8352: }
8353: } else {
8354: return $env{'browser.'.$qualifier};
8355: }
8356: # ------------------------------------------------------------ request.filename
8357: } else {
8358: return $env{'request.'.$spacequalifierrest};
8359: }
8360: } elsif ($realm eq 'course') {
8361: # ---------------------------------------------------------- course.description
8362: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
8363: } elsif ($realm eq 'resource') {
8364:
8365: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
8366: if (!$symbparm) { $symbparm=&symbread(); }
8367: }
8368:
8369: if ($space eq 'title') {
8370: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8371: return &gettitle($symbparm);
8372: }
8373:
8374: if ($space eq 'map') {
8375: my ($map) = &decode_symb($symbparm);
8376: return &symbread($map);
8377: }
8378: if ($space eq 'filename') {
8379: if ($symbparm) {
8380: return &clutter((&decode_symb($symbparm))[2]);
8381: }
8382: return &hreflocation('',$env{'request.filename'});
8383: }
8384:
8385: my ($section, $group, @groups);
8386: my ($courselevelm,$courselevel);
8387: if ($symbparm && defined($courseid) &&
8388: $courseid eq $env{'request.course.id'}) {
8389:
8390: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
8391:
8392: # ----------------------------------------------------- Cascading lookup scheme
8393: my $symbp=$symbparm;
8394: my $mapp=&deversion((&decode_symb($symbp))[0]);
8395:
8396: my $symbparm=$symbp.'.'.$spacequalifierrest;
8397: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8398:
8399: if (($env{'user.name'} eq $uname) &&
8400: ($env{'user.domain'} eq $udom)) {
8401: $section=$env{'request.course.sec'};
8402: @groups = split(/:/,$env{'request.course.groups'});
8403: @groups=&sort_course_groups($courseid,@groups);
8404: } else {
8405: if (! defined($usection)) {
8406: $section=&getsection($udom,$uname,$courseid);
8407: } else {
8408: $section = $usection;
8409: }
8410: @groups = &get_users_groups($udom,$uname,$courseid);
8411: }
8412:
8413: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8414: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8415: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8416:
8417: $courselevel=$courseid.'.'.$spacequalifierrest;
8418: my $courselevelr=$courseid.'.'.$symbparm;
8419: $courselevelm=$courseid.'.'.$mapparm;
8420:
8421: # ----------------------------------------------------------- first, check user
8422:
8423: my $userreply=&resdata($uname,$udom,'user',
8424: ([$courselevelr,'resource'],
8425: [$courselevelm,'map' ],
8426: [$courselevel, 'course' ]));
8427: if (defined($userreply)) { return &get_reply($userreply); }
8428:
8429: # ------------------------------------------------ second, check some of course
8430: my $coursereply;
8431: if (@groups > 0) {
8432: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8433: $mapparm,$spacequalifierrest);
8434: if (defined($coursereply)) { return &get_reply($coursereply); }
8435: }
8436:
8437: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8438: $env{'course.'.$courseid.'.domain'},
8439: 'course',
8440: ([$seclevelr, 'resource'],
8441: [$seclevelm, 'map' ],
8442: [$seclevel, 'course' ],
8443: [$courselevelr,'resource']));
8444: if (defined($coursereply)) { return &get_reply($coursereply); }
8445:
8446: # ------------------------------------------------------ third, check map parms
8447: my %parmhash=();
8448: my $thisparm='';
8449: if (tie(%parmhash,'GDBM_File',
8450: $env{'request.course.fn'}.'_parms.db',
8451: &GDBM_READER(),0640)) {
8452: $thisparm=$parmhash{$symbparm};
8453: untie(%parmhash);
8454: }
8455: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
8456: }
8457: # ------------------------------------------ fourth, look in resource metadata
8458:
8459: $spacequalifierrest=~s/\./\_/;
8460: my $filename;
8461: if (!$symbparm) { $symbparm=&symbread(); }
8462: if ($symbparm) {
8463: $filename=(&decode_symb($symbparm))[2];
8464: } else {
8465: $filename=$env{'request.filename'};
8466: }
8467: my $metadata=&metadata($filename,$spacequalifierrest);
8468: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
8469: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
8470: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
8471:
8472: # ---------------------------------------------- fourth, look in rest of course
8473: if ($symbparm && defined($courseid) &&
8474: $courseid eq $env{'request.course.id'}) {
8475: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8476: $env{'course.'.$courseid.'.domain'},
8477: 'course',
8478: ([$courselevelm,'map' ],
8479: [$courselevel, 'course']));
8480: if (defined($coursereply)) { return &get_reply($coursereply); }
8481: }
8482: # ------------------------------------------------------------------ Cascade up
8483: unless ($space eq '0') {
8484: my @parts=split(/_/,$space);
8485: my $id=pop(@parts);
8486: my $part=join('_',@parts);
8487: if ($part eq '') { $part='0'; }
8488: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
8489: $symbparm,$udom,$uname,$section,1);
8490: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
8491: }
8492: if ($recurse) { return undef; }
8493: my $pack_def=&packages_tab_default($filename,$varname);
8494: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
8495: # ---------------------------------------------------- Any other user namespace
8496: } elsif ($realm eq 'environment') {
8497: # ----------------------------------------------------------------- environment
8498: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8499: return $env{'environment.'.$spacequalifierrest};
8500: } else {
8501: if ($uname eq 'anonymous' && $udom eq '') {
8502: return '';
8503: }
8504: my %returnhash=&userenvironment($udom,$uname,
8505: $spacequalifierrest);
8506: return $returnhash{$spacequalifierrest};
8507: }
8508: } elsif ($realm eq 'system') {
8509: # ----------------------------------------------------------------- system.time
8510: if ($space eq 'time') {
8511: return time;
8512: }
8513: } elsif ($realm eq 'server') {
8514: # ----------------------------------------------------------------- system.time
8515: if ($space eq 'name') {
8516: return $ENV{'SERVER_NAME'};
8517: }
8518: }
8519: return '';
8520: }
8521:
8522: sub get_reply {
8523: my ($reply_value) = @_;
8524: if (ref($reply_value) eq 'ARRAY') {
8525: if (wantarray) {
8526: return @$reply_value;
8527: }
8528: return $reply_value->[0];
8529: } else {
8530: return $reply_value;
8531: }
8532: }
8533:
8534: sub check_group_parms {
8535: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8536: my @groupitems = ();
8537: my $resultitem;
8538: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
8539: foreach my $group (@{$groups}) {
8540: foreach my $level (@levels) {
8541: my $item = $courseid.'.['.$group.'].'.$level->[0];
8542: push(@groupitems,[$item,$level->[1]]);
8543: }
8544: }
8545: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8546: $env{'course.'.$courseid.'.domain'},
8547: 'course',@groupitems);
8548: return $coursereply;
8549: }
8550:
8551: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
8552: my ($courseid,@groups) = @_;
8553: @groups = sort(@groups);
8554: return @groups;
8555: }
8556:
8557: sub packages_tab_default {
8558: my ($uri,$varname)=@_;
8559: my (undef,$part,$name)=split(/\./,$varname);
8560:
8561: my (@extension,@specifics,$do_default);
8562: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
8563: my ($pack_type,$pack_part)=split(/_/,$package,2);
8564: if ($pack_type eq 'default') {
8565: $do_default=1;
8566: } elsif ($pack_type eq 'extension') {
8567: push(@extension,[$package,$pack_type,$pack_part]);
8568: } elsif ($pack_part eq $part || $pack_type eq 'part') {
8569: # only look at packages defaults for packages that this id is
8570: push(@specifics,[$package,$pack_type,$pack_part]);
8571: }
8572: }
8573: # first look for a package that matches the requested part id
8574: foreach my $package (@specifics) {
8575: my (undef,$pack_type,$pack_part)=@{$package};
8576: next if ($pack_part ne $part);
8577: if (defined($packagetab{"$pack_type&$name&default"})) {
8578: return $packagetab{"$pack_type&$name&default"};
8579: }
8580: }
8581: # look for any possible matching non extension_ package
8582: foreach my $package (@specifics) {
8583: my (undef,$pack_type,$pack_part)=@{$package};
8584: if (defined($packagetab{"$pack_type&$name&default"})) {
8585: return $packagetab{"$pack_type&$name&default"};
8586: }
8587: if ($pack_type eq 'part') { $pack_part='0'; }
8588: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8589: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
8590: }
8591: }
8592: # look for any posible extension_ match
8593: foreach my $package (@extension) {
8594: my ($package,$pack_type)=@{$package};
8595: if (defined($packagetab{"$pack_type&$name&default"})) {
8596: return $packagetab{"$pack_type&$name&default"};
8597: }
8598: if (defined($packagetab{$package."&$name&default"})) {
8599: return $packagetab{$package."&$name&default"};
8600: }
8601: }
8602: # look for a global default setting
8603: if ($do_default && defined($packagetab{"default&$name&default"})) {
8604: return $packagetab{"default&$name&default"};
8605: }
8606: return undef;
8607: }
8608:
8609: sub add_prefix_and_part {
8610: my ($prefix,$part)=@_;
8611: my $keyroot;
8612: if (defined($prefix) && $prefix !~ /^__/) {
8613: # prefix that has a part already
8614: $keyroot=$prefix;
8615: } elsif (defined($prefix)) {
8616: # prefix that is missing a part
8617: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8618: } else {
8619: # no prefix at all
8620: if (defined($part)) { $keyroot='_'.$part; }
8621: }
8622: return $keyroot;
8623: }
8624:
8625: # ---------------------------------------------------------------- Get metadata
8626:
8627: my %metaentry;
8628: sub metadata {
8629: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
8630: $uri=&declutter($uri);
8631: # if it is a non metadata possible uri return quickly
8632: if (($uri eq '') ||
8633: (($uri =~ m|^/*adm/|) &&
8634: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
8635: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
8636: return undef;
8637: }
8638: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8639: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
8640: return undef;
8641: }
8642: my $filename=$uri;
8643: $uri=~s/\.meta$//;
8644: #
8645: # Is the metadata already cached?
8646: # Look at timestamp of caching
8647: # Everything is cached by the main uri, libraries are never directly cached
8648: #
8649: if (!defined($liburi)) {
8650: my ($result,$cached)=&is_cached_new('meta',$uri);
8651: if (defined($cached)) { return $result->{':'.$what}; }
8652: }
8653: {
8654: #
8655: # Is this a recursive call for a library?
8656: #
8657: # if (! exists($metacache{$uri})) {
8658: # $metacache{$uri}={};
8659: # }
8660: my $cachetime = 60*60;
8661: if ($liburi) {
8662: $liburi=&declutter($liburi);
8663: $filename=$liburi;
8664: } else {
8665: &devalidate_cache_new('meta',$uri);
8666: undef(%metaentry);
8667: }
8668: my %metathesekeys=();
8669: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
8670: my $metastring;
8671: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
8672: my $which = &hreflocation('','/'.($liburi || $uri));
8673: $metastring =
8674: &Apache::lonnet::ssi_body($which,
8675: ('grade_target' => 'meta'));
8676: $cachetime = 1; # only want this cached in the child not long term
8677: } elsif (($uri !~ m -^(editupload)/-) &&
8678: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
8679: my $file=&filelocation('',&clutter($filename));
8680: #push(@{$metaentry{$uri.'.file'}},$file);
8681: $metastring=&getfile($file);
8682: }
8683: my $parser=HTML::LCParser->new(\$metastring);
8684: my $token;
8685: undef %metathesekeys;
8686: while ($token=$parser->get_token) {
8687: if ($token->[0] eq 'S') {
8688: if (defined($token->[2]->{'package'})) {
8689: #
8690: # This is a package - get package info
8691: #
8692: my $package=$token->[2]->{'package'};
8693: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8694: if (defined($token->[2]->{'id'})) {
8695: $keyroot.='_'.$token->[2]->{'id'};
8696: }
8697: if ($metaentry{':packages'}) {
8698: $metaentry{':packages'}.=','.$package.$keyroot;
8699: } else {
8700: $metaentry{':packages'}=$package.$keyroot;
8701: }
8702: foreach my $pack_entry (keys(%packagetab)) {
8703: my $part=$keyroot;
8704: $part=~s/^\_//;
8705: if ($pack_entry=~/^\Q$package\E\&/ ||
8706: $pack_entry=~/^\Q$package\E_0\&/) {
8707: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
8708: # ignore package.tab specified default values
8709: # here &package_tab_default() will fetch those
8710: if ($subp eq 'default') { next; }
8711: my $value=$packagetab{$pack_entry};
8712: my $unikey;
8713: if ($pack =~ /_0$/) {
8714: $unikey='parameter_0_'.$name;
8715: $part=0;
8716: } else {
8717: $unikey='parameter'.$keyroot.'_'.$name;
8718: }
8719: if ($subp eq 'display') {
8720: $value.=' [Part: '.$part.']';
8721: }
8722: $metaentry{':'.$unikey.'.part'}=$part;
8723: $metathesekeys{$unikey}=1;
8724: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8725: $metaentry{':'.$unikey.'.'.$subp}=$value;
8726: }
8727: if (defined($metaentry{':'.$unikey.'.default'})) {
8728: $metaentry{':'.$unikey}=
8729: $metaentry{':'.$unikey.'.default'};
8730: }
8731: }
8732: }
8733: } else {
8734: #
8735: # This is not a package - some other kind of start tag
8736: #
8737: my $entry=$token->[1];
8738: my $unikey;
8739: if ($entry eq 'import') {
8740: $unikey='';
8741: } else {
8742: $unikey=$entry;
8743: }
8744: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8745:
8746: if (defined($token->[2]->{'id'})) {
8747: $unikey.='_'.$token->[2]->{'id'};
8748: }
8749:
8750: if ($entry eq 'import') {
8751: #
8752: # Importing a library here
8753: #
8754: if ($depthcount<20) {
8755: my $location=$parser->get_text('/import');
8756: my $dir=$filename;
8757: $dir=~s|[^/]*$||;
8758: $location=&filelocation($dir,$location);
8759: my $metadata =
8760: &metadata($uri,'keys', $location,$unikey,
8761: $depthcount+1);
8762: foreach my $meta (split(',',$metadata)) {
8763: $metaentry{':'.$meta}=$metaentry{':'.$meta};
8764: $metathesekeys{$meta}=1;
8765: }
8766: }
8767: } else {
8768: if (defined($token->[2]->{'name'})) {
8769: $unikey.='_'.$token->[2]->{'name'};
8770: }
8771: $metathesekeys{$unikey}=1;
8772: foreach my $param (@{$token->[3]}) {
8773: $metaentry{':'.$unikey.'.'.$param} =
8774: $token->[2]->{$param};
8775: }
8776: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
8777: my $default=$metaentry{':'.$unikey.'.default'};
8778: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
8779: # only ws inside the tag, and not in default, so use default
8780: # as value
8781: $metaentry{':'.$unikey}=$default;
8782: } elsif ( $internaltext =~ /\S/ ) {
8783: # something interesting inside the tag
8784: $metaentry{':'.$unikey}=$internaltext;
8785: } else {
8786: # no interesting values, don't set a default
8787: }
8788: # end of not-a-package not-a-library import
8789: }
8790: # end of not-a-package start tag
8791: }
8792: # the next is the end of "start tag"
8793: }
8794: }
8795: my ($extension) = ($uri =~ /\.(\w+)$/);
8796: $extension = lc($extension);
8797: if ($extension eq 'htm') { $extension='html'; }
8798:
8799: foreach my $key (keys(%packagetab)) {
8800: #no specific packages #how's our extension
8801: if ($key!~/^extension_\Q$extension\E&/) { next; }
8802: &metadata_create_package_def($uri,$key,'extension_'.$extension,
8803: \%metathesekeys);
8804: }
8805:
8806: if (!exists($metaentry{':packages'})
8807: || $packagetab{"import_defaults&extension_$extension"}) {
8808: foreach my $key (keys(%packagetab)) {
8809: #no specific packages well let's get default then
8810: if ($key!~/^default&/) { next; }
8811: &metadata_create_package_def($uri,$key,'default',
8812: \%metathesekeys);
8813: }
8814: }
8815: # are there custom rights to evaluate
8816: if ($metaentry{':copyright'} eq 'custom') {
8817:
8818: #
8819: # Importing a rights file here
8820: #
8821: unless ($depthcount) {
8822: my $location=$metaentry{':customdistributionfile'};
8823: my $dir=$filename;
8824: $dir=~s|[^/]*$||;
8825: $location=&filelocation($dir,$location);
8826: my $rights_metadata =
8827: &metadata($uri,'keys',$location,'_rights',
8828: $depthcount+1);
8829: foreach my $rights (split(',',$rights_metadata)) {
8830: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8831: $metathesekeys{$rights}=1;
8832: }
8833: }
8834: }
8835: # uniqifiy package listing
8836: my %seen;
8837: my @uniq_packages =
8838: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8839: $metaentry{':packages'} = join(',',@uniq_packages);
8840:
8841: $metaentry{':keys'} = join(',',keys(%metathesekeys));
8842: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8843: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
8844: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
8845: # this is the end of "was not already recently cached
8846: }
8847: return $metaentry{':'.$what};
8848: }
8849:
8850: sub metadata_create_package_def {
8851: my ($uri,$key,$package,$metathesekeys)=@_;
8852: my ($pack,$name,$subp)=split(/\&/,$key);
8853: if ($subp eq 'default') { next; }
8854:
8855: if (defined($metaentry{':packages'})) {
8856: $metaentry{':packages'}.=','.$package;
8857: } else {
8858: $metaentry{':packages'}=$package;
8859: }
8860: my $value=$packagetab{$key};
8861: my $unikey;
8862: $unikey='parameter_0_'.$name;
8863: $metaentry{':'.$unikey.'.part'}=0;
8864: $$metathesekeys{$unikey}=1;
8865: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8866: $metaentry{':'.$unikey.'.'.$subp}=$value;
8867: }
8868: if (defined($metaentry{':'.$unikey.'.default'})) {
8869: $metaentry{':'.$unikey}=
8870: $metaentry{':'.$unikey.'.default'};
8871: }
8872: }
8873:
8874: sub metadata_generate_part0 {
8875: my ($metadata,$metacache,$uri) = @_;
8876: my %allnames;
8877: foreach my $metakey (keys(%$metadata)) {
8878: if ($metakey=~/^parameter\_(.*)/) {
8879: my $part=$$metacache{':'.$metakey.'.part'};
8880: my $name=$$metacache{':'.$metakey.'.name'};
8881: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
8882: $allnames{$name}=$part;
8883: }
8884: }
8885: }
8886: foreach my $name (keys(%allnames)) {
8887: $$metadata{"parameter_0_$name"}=1;
8888: my $key=":parameter_0_$name";
8889: $$metacache{"$key.part"}='0';
8890: $$metacache{"$key.name"}=$name;
8891: $$metacache{"$key.type"}=$$metacache{':parameter_'.
8892: $allnames{$name}.'_'.$name.
8893: '.type'};
8894: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
8895: '.display'};
8896: my $expr='[Part: '.$allnames{$name}.']';
8897: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
8898: $$metacache{"$key.display"}=$olddis;
8899: }
8900: }
8901:
8902: # ------------------------------------------------------ Devalidate title cache
8903:
8904: sub devalidate_title_cache {
8905: my ($url)=@_;
8906: if (!$env{'request.course.id'}) { return; }
8907: my $symb=&symbread($url);
8908: if (!$symb) { return; }
8909: my $key=$env{'request.course.id'}."\0".$symb;
8910: &devalidate_cache_new('title',$key);
8911: }
8912:
8913: # ------------------------------------------------- Get the title of a course
8914:
8915: sub current_course_title {
8916: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8917: }
8918: # ------------------------------------------------- Get the title of a resource
8919:
8920: sub gettitle {
8921: my $urlsymb=shift;
8922: my $symb=&symbread($urlsymb);
8923: if ($symb) {
8924: my $key=$env{'request.course.id'}."\0".$symb;
8925: my ($result,$cached)=&is_cached_new('title',$key);
8926: if (defined($cached)) {
8927: return $result;
8928: }
8929: my ($map,$resid,$url)=&decode_symb($symb);
8930: my $title='';
8931: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8932: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8933: } else {
8934: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8935: &GDBM_READER(),0640)) {
8936: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8937: $title=$bighash{'title_'.$mapid.'.'.$resid};
8938: untie(%bighash);
8939: }
8940: }
8941: $title=~s/\&colon\;/\:/gs;
8942: if ($title) {
8943: return &do_cache_new('title',$key,$title,600);
8944: }
8945: $urlsymb=$url;
8946: }
8947: my $title=&metadata($urlsymb,'title');
8948: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8949: return $title;
8950: }
8951:
8952: sub get_slot {
8953: my ($which,$cnum,$cdom)=@_;
8954: if (!$cnum || !$cdom) {
8955: (undef,my $courseid)=&whichuser();
8956: $cdom=$env{'course.'.$courseid.'.domain'};
8957: $cnum=$env{'course.'.$courseid.'.num'};
8958: }
8959: my $key=join("\0",'slots',$cdom,$cnum,$which);
8960: my %slotinfo;
8961: if (exists($remembered{$key})) {
8962: $slotinfo{$which} = $remembered{$key};
8963: } else {
8964: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8965: &Apache::lonhomework::showhash(%slotinfo);
8966: my ($tmp)=keys(%slotinfo);
8967: if ($tmp=~/^error:/) { return (); }
8968: $remembered{$key} = $slotinfo{$which};
8969: }
8970: if (ref($slotinfo{$which}) eq 'HASH') {
8971: return %{$slotinfo{$which}};
8972: }
8973: return $slotinfo{$which};
8974: }
8975: # ------------------------------------------------- Update symbolic store links
8976:
8977: sub symblist {
8978: my ($mapname,%newhash)=@_;
8979: $mapname=&deversion(&declutter($mapname));
8980: my %hash;
8981: if (($env{'request.course.fn'}) && (%newhash)) {
8982: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
8983: &GDBM_WRCREAT(),0640)) {
8984: foreach my $url (keys(%newhash)) {
8985: next if ($url eq 'last_known'
8986: && $env{'form.no_update_last_known'});
8987: $hash{declutter($url)}=&encode_symb($mapname,
8988: $newhash{$url}->[1],
8989: $newhash{$url}->[0]);
8990: }
8991: if (untie(%hash)) {
8992: return 'ok';
8993: }
8994: }
8995: }
8996: return 'error';
8997: }
8998:
8999: # --------------------------------------------------------------- Verify a symb
9000:
9001: sub symbverify {
9002: my ($symb,$thisurl)=@_;
9003: my $thisfn=$thisurl;
9004: $thisfn=&declutter($thisfn);
9005: # direct jump to resource in page or to a sequence - will construct own symbs
9006: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
9007: # check URL part
9008: my ($map,$resid,$url)=&decode_symb($symb);
9009:
9010: unless ($url eq $thisfn) { return 0; }
9011:
9012: $symb=&symbclean($symb);
9013: $thisurl=&deversion($thisurl);
9014: $thisfn=&deversion($thisfn);
9015:
9016: my %bighash;
9017: my $okay=0;
9018:
9019: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9020: &GDBM_READER(),0640)) {
9021: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
9022: $thisurl =~ s/\?.+$//;
9023: }
9024: my $ids=$bighash{'ids_'.&clutter($thisurl)};
9025: unless ($ids) {
9026: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
9027: $ids=$bighash{$idkey};
9028: }
9029: if ($ids) {
9030: # ------------------------------------------------------------------- Has ID(s)
9031: foreach my $id (split(/\,/,$ids)) {
9032: my ($mapid,$resid)=split(/\./,$id);
9033: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
9034: $symb =~ s/\?.+$//;
9035: }
9036: if (
9037: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
9038: eq $symb) {
9039: if (($env{'request.role.adv'}) ||
9040: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
9041: ($thisurl eq '/adm/navmaps')) {
9042: $okay=1;
9043: }
9044: }
9045: }
9046: }
9047: untie(%bighash);
9048: }
9049: return $okay;
9050: }
9051:
9052: # --------------------------------------------------------------- Clean-up symb
9053:
9054: sub symbclean {
9055: my $symb=shift;
9056: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9057: # remove version from map
9058: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
9059:
9060: # remove version from URL
9061: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
9062:
9063: # remove wrapper
9064:
9065: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
9066: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
9067: return $symb;
9068: }
9069:
9070: # ---------------------------------------------- Split symb to find map and url
9071:
9072: sub encode_symb {
9073: my ($map,$resid,$url)=@_;
9074: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
9075: }
9076:
9077: sub decode_symb {
9078: my $symb=shift;
9079: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9080: my ($map,$resid,$url)=split(/___/,$symb);
9081: return (&fixversion($map),$resid,&fixversion($url));
9082: }
9083:
9084: sub fixversion {
9085: my $fn=shift;
9086: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
9087: my %bighash;
9088: my $uri=&clutter($fn);
9089: my $key=$env{'request.course.id'}.'_'.$uri;
9090: # is this cached?
9091: my ($result,$cached)=&is_cached_new('courseresversion',$key);
9092: if (defined($cached)) { return $result; }
9093: # unfortunately not cached, or expired
9094: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9095: &GDBM_READER(),0640)) {
9096: if ($bighash{'version_'.$uri}) {
9097: my $version=$bighash{'version_'.$uri};
9098: unless (($version eq 'mostrecent') ||
9099: ($version==&getversion($uri))) {
9100: $uri=~s/\.(\w+)$/\.$version\.$1/;
9101: }
9102: }
9103: untie %bighash;
9104: }
9105: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
9106: }
9107:
9108: sub deversion {
9109: my $url=shift;
9110: $url=~s/\.\d+\.(\w+)$/\.$1/;
9111: return $url;
9112: }
9113:
9114: # ------------------------------------------------------ Return symb list entry
9115:
9116: sub symbread {
9117: my ($thisfn,$donotrecurse)=@_;
9118: my $cache_str='request.symbread.cached.'.$thisfn;
9119: if (defined($env{$cache_str})) { return $env{$cache_str}; }
9120: # no filename provided? try from environment
9121: unless ($thisfn) {
9122: if ($env{'request.symb'}) {
9123: return $env{$cache_str}=&symbclean($env{'request.symb'});
9124: }
9125: $thisfn=$env{'request.filename'};
9126: }
9127: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
9128: # is that filename actually a symb? Verify, clean, and return
9129: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
9130: if (&symbverify($thisfn,$1)) {
9131: return $env{$cache_str}=&symbclean($thisfn);
9132: }
9133: }
9134: $thisfn=declutter($thisfn);
9135: my %hash;
9136: my %bighash;
9137: my $syval='';
9138: if (($env{'request.course.fn'}) && ($thisfn)) {
9139: my $targetfn = $thisfn;
9140: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
9141: $targetfn = 'adm/wrapper/'.$thisfn;
9142: }
9143: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9144: $targetfn=$1;
9145: }
9146: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
9147: &GDBM_READER(),0640)) {
9148: $syval=$hash{$targetfn};
9149: untie(%hash);
9150: }
9151: # ---------------------------------------------------------- There was an entry
9152: if ($syval) {
9153: #unless ($syval=~/\_\d+$/) {
9154: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
9155: #&appenv({'request.ambiguous' => $thisfn});
9156: #return $env{$cache_str}='';
9157: #}
9158: #$syval.=$1;
9159: #}
9160: } else {
9161: # ------------------------------------------------------- Was not in symb table
9162: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9163: &GDBM_READER(),0640)) {
9164: # ---------------------------------------------- Get ID(s) for current resource
9165: my $ids=$bighash{'ids_'.&clutter($thisfn)};
9166: unless ($ids) {
9167: $ids=$bighash{'ids_/'.$thisfn};
9168: }
9169: unless ($ids) {
9170: # alias?
9171: $ids=$bighash{'mapalias_'.$thisfn};
9172: }
9173: if ($ids) {
9174: # ------------------------------------------------------------------- Has ID(s)
9175: my @possibilities=split(/\,/,$ids);
9176: if ($#possibilities==0) {
9177: # ----------------------------------------------- There is only one possibility
9178: my ($mapid,$resid)=split(/\./,$ids);
9179: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9180: $resid,$thisfn);
9181: } elsif (!$donotrecurse) {
9182: # ------------------------------------------ There is more than one possibility
9183: my $realpossible=0;
9184: foreach my $id (@possibilities) {
9185: my $file=$bighash{'src_'.$id};
9186: if (&allowed('bre',$file)) {
9187: my ($mapid,$resid)=split(/\./,$id);
9188: if ($bighash{'map_type_'.$mapid} ne 'page') {
9189: $realpossible++;
9190: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9191: $resid,$thisfn);
9192: }
9193: }
9194: }
9195: if ($realpossible!=1) { $syval=''; }
9196: } else {
9197: $syval='';
9198: }
9199: }
9200: untie(%bighash)
9201: }
9202: }
9203: if ($syval) {
9204: return $env{$cache_str}=$syval;
9205: }
9206: }
9207: &appenv({'request.ambiguous' => $thisfn});
9208: return $env{$cache_str}='';
9209: }
9210:
9211: # ---------------------------------------------------------- Return random seed
9212:
9213: sub numval {
9214: my $txt=shift;
9215: $txt=~tr/A-J/0-9/;
9216: $txt=~tr/a-j/0-9/;
9217: $txt=~tr/K-T/0-9/;
9218: $txt=~tr/k-t/0-9/;
9219: $txt=~tr/U-Z/0-5/;
9220: $txt=~tr/u-z/0-5/;
9221: $txt=~s/\D//g;
9222: if ($_64bit) { if ($txt > 2**32) { return -1; } }
9223: return int($txt);
9224: }
9225:
9226: sub numval2 {
9227: my $txt=shift;
9228: $txt=~tr/A-J/0-9/;
9229: $txt=~tr/a-j/0-9/;
9230: $txt=~tr/K-T/0-9/;
9231: $txt=~tr/k-t/0-9/;
9232: $txt=~tr/U-Z/0-5/;
9233: $txt=~tr/u-z/0-5/;
9234: $txt=~s/\D//g;
9235: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9236: my $total;
9237: foreach my $val (@txts) { $total+=$val; }
9238: if ($_64bit) { if ($total > 2**32) { return -1; } }
9239: return int($total);
9240: }
9241:
9242: sub numval3 {
9243: use integer;
9244: my $txt=shift;
9245: $txt=~tr/A-J/0-9/;
9246: $txt=~tr/a-j/0-9/;
9247: $txt=~tr/K-T/0-9/;
9248: $txt=~tr/k-t/0-9/;
9249: $txt=~tr/U-Z/0-5/;
9250: $txt=~tr/u-z/0-5/;
9251: $txt=~s/\D//g;
9252: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9253: my $total;
9254: foreach my $val (@txts) { $total+=$val; }
9255: if ($_64bit) { $total=(($total<<32)>>32); }
9256: return $total;
9257: }
9258:
9259: sub digest {
9260: my ($data)=@_;
9261: my $digest=&Digest::MD5::md5($data);
9262: my ($a,$b,$c,$d)=unpack("iiii",$digest);
9263: my ($e,$f);
9264: {
9265: use integer;
9266: $e=($a+$b);
9267: $f=($c+$d);
9268: if ($_64bit) {
9269: $e=(($e<<32)>>32);
9270: $f=(($f<<32)>>32);
9271: }
9272: }
9273: if (wantarray) {
9274: return ($e,$f);
9275: } else {
9276: my $g;
9277: {
9278: use integer;
9279: $g=($e+$f);
9280: if ($_64bit) {
9281: $g=(($g<<32)>>32);
9282: }
9283: }
9284: return $g;
9285: }
9286: }
9287:
9288: sub latest_rnd_algorithm_id {
9289: return '64bit5';
9290: }
9291:
9292: sub get_rand_alg {
9293: my ($courseid)=@_;
9294: if (!$courseid) { $courseid=(&whichuser())[1]; }
9295: if ($courseid) {
9296: return $env{"course.$courseid.rndseed"};
9297: }
9298: return &latest_rnd_algorithm_id();
9299: }
9300:
9301: sub validCODE {
9302: my ($CODE)=@_;
9303: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9304: return 0;
9305: }
9306:
9307: sub getCODE {
9308: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
9309: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9310: defined($Apache::lonhomework::parsing_a_task) ) &&
9311: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
9312: return $Apache::lonhomework::history{'resource.CODE'};
9313: }
9314: return undef;
9315: }
9316:
9317: sub rndseed {
9318: my ($symb,$courseid,$domain,$username)=@_;
9319: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
9320: if (!defined($symb)) {
9321: unless ($symb=$wsymb) { return time; }
9322: }
9323: if (!$courseid) { $courseid=$wcourseid; }
9324: if (!$domain) { $domain=$wdomain; }
9325: if (!$username) { $username=$wusername }
9326: my $which=&get_rand_alg();
9327:
9328: if (defined(&getCODE())) {
9329: if ($which eq '64bit5') {
9330: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9331: } elsif ($which eq '64bit4') {
9332: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9333: } else {
9334: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9335: }
9336: } elsif ($which eq '64bit5') {
9337: return &rndseed_64bit5($symb,$courseid,$domain,$username);
9338: } elsif ($which eq '64bit4') {
9339: return &rndseed_64bit4($symb,$courseid,$domain,$username);
9340: } elsif ($which eq '64bit3') {
9341: return &rndseed_64bit3($symb,$courseid,$domain,$username);
9342: } elsif ($which eq '64bit2') {
9343: return &rndseed_64bit2($symb,$courseid,$domain,$username);
9344: } elsif ($which eq '64bit') {
9345: return &rndseed_64bit($symb,$courseid,$domain,$username);
9346: }
9347: return &rndseed_32bit($symb,$courseid,$domain,$username);
9348: }
9349:
9350: sub rndseed_32bit {
9351: my ($symb,$courseid,$domain,$username)=@_;
9352: {
9353: use integer;
9354: my $symbchck=unpack("%32C*",$symb) << 27;
9355: my $symbseed=numval($symb) << 22;
9356: my $namechck=unpack("%32C*",$username) << 17;
9357: my $nameseed=numval($username) << 12;
9358: my $domainseed=unpack("%32C*",$domain) << 7;
9359: my $courseseed=unpack("%32C*",$courseid);
9360: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
9361: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9362: #&logthis("rndseed :$num:$symb");
9363: if ($_64bit) { $num=(($num<<32)>>32); }
9364: return $num;
9365: }
9366: }
9367:
9368: sub rndseed_64bit {
9369: my ($symb,$courseid,$domain,$username)=@_;
9370: {
9371: use integer;
9372: my $symbchck=unpack("%32S*",$symb) << 21;
9373: my $symbseed=numval($symb) << 10;
9374: my $namechck=unpack("%32S*",$username);
9375:
9376: my $nameseed=numval($username) << 21;
9377: my $domainseed=unpack("%32S*",$domain) << 10;
9378: my $courseseed=unpack("%32S*",$courseid);
9379:
9380: my $num1=$symbchck+$symbseed+$namechck;
9381: my $num2=$nameseed+$domainseed+$courseseed;
9382: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9383: #&logthis("rndseed :$num:$symb");
9384: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9385: return "$num1,$num2";
9386: }
9387: }
9388:
9389: sub rndseed_64bit2 {
9390: my ($symb,$courseid,$domain,$username)=@_;
9391: {
9392: use integer;
9393: # strings need to be an even # of cahracters long, it it is odd the
9394: # last characters gets thrown away
9395: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9396: my $symbseed=numval($symb) << 10;
9397: my $namechck=unpack("%32S*",$username.' ');
9398:
9399: my $nameseed=numval($username) << 21;
9400: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9401: my $courseseed=unpack("%32S*",$courseid.' ');
9402:
9403: my $num1=$symbchck+$symbseed+$namechck;
9404: my $num2=$nameseed+$domainseed+$courseseed;
9405: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9406: #&logthis("rndseed :$num:$symb");
9407: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9408: return "$num1,$num2";
9409: }
9410: }
9411:
9412: sub rndseed_64bit3 {
9413: my ($symb,$courseid,$domain,$username)=@_;
9414: {
9415: use integer;
9416: # strings need to be an even # of cahracters long, it it is odd the
9417: # last characters gets thrown away
9418: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9419: my $symbseed=numval2($symb) << 10;
9420: my $namechck=unpack("%32S*",$username.' ');
9421:
9422: my $nameseed=numval2($username) << 21;
9423: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9424: my $courseseed=unpack("%32S*",$courseid.' ');
9425:
9426: my $num1=$symbchck+$symbseed+$namechck;
9427: my $num2=$nameseed+$domainseed+$courseseed;
9428: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9429: #&logthis("rndseed :$num1:$num2:$_64bit");
9430: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9431:
9432: return "$num1:$num2";
9433: }
9434: }
9435:
9436: sub rndseed_64bit4 {
9437: my ($symb,$courseid,$domain,$username)=@_;
9438: {
9439: use integer;
9440: # strings need to be an even # of cahracters long, it it is odd the
9441: # last characters gets thrown away
9442: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9443: my $symbseed=numval3($symb) << 10;
9444: my $namechck=unpack("%32S*",$username.' ');
9445:
9446: my $nameseed=numval3($username) << 21;
9447: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9448: my $courseseed=unpack("%32S*",$courseid.' ');
9449:
9450: my $num1=$symbchck+$symbseed+$namechck;
9451: my $num2=$nameseed+$domainseed+$courseseed;
9452: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9453: #&logthis("rndseed :$num1:$num2:$_64bit");
9454: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9455:
9456: return "$num1:$num2";
9457: }
9458: }
9459:
9460: sub rndseed_64bit5 {
9461: my ($symb,$courseid,$domain,$username)=@_;
9462: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9463: return "$num1:$num2";
9464: }
9465:
9466: sub rndseed_CODE_64bit {
9467: my ($symb,$courseid,$domain,$username)=@_;
9468: {
9469: use integer;
9470: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9471: my $symbseed=numval2($symb);
9472: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9473: my $CODEseed=numval(&getCODE());
9474: my $courseseed=unpack("%32S*",$courseid.' ');
9475: my $num1=$symbseed+$CODEchck;
9476: my $num2=$CODEseed+$courseseed+$symbchck;
9477: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9478: #&logthis("rndseed :$num1:$num2:$symb");
9479: if ($_64bit) { $num1=(($num1<<32)>>32); }
9480: if ($_64bit) { $num2=(($num2<<32)>>32); }
9481: return "$num1:$num2";
9482: }
9483: }
9484:
9485: sub rndseed_CODE_64bit4 {
9486: my ($symb,$courseid,$domain,$username)=@_;
9487: {
9488: use integer;
9489: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9490: my $symbseed=numval3($symb);
9491: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9492: my $CODEseed=numval3(&getCODE());
9493: my $courseseed=unpack("%32S*",$courseid.' ');
9494: my $num1=$symbseed+$CODEchck;
9495: my $num2=$CODEseed+$courseseed+$symbchck;
9496: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9497: #&logthis("rndseed :$num1:$num2:$symb");
9498: if ($_64bit) { $num1=(($num1<<32)>>32); }
9499: if ($_64bit) { $num2=(($num2<<32)>>32); }
9500: return "$num1:$num2";
9501: }
9502: }
9503:
9504: sub rndseed_CODE_64bit5 {
9505: my ($symb,$courseid,$domain,$username)=@_;
9506: my $code = &getCODE();
9507: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9508: return "$num1:$num2";
9509: }
9510:
9511: sub setup_random_from_rndseed {
9512: my ($rndseed)=@_;
9513: if ($rndseed =~/([,:])/) {
9514: my ($num1,$num2)=split(/[,:]/,$rndseed);
9515: &Math::Random::random_set_seed(abs($num1),abs($num2));
9516: } else {
9517: &Math::Random::random_set_seed_from_phrase($rndseed);
9518: }
9519: }
9520:
9521: sub latest_receipt_algorithm_id {
9522: return 'receipt3';
9523: }
9524:
9525: sub recunique {
9526: my $fucourseid=shift;
9527: my $unique;
9528: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9529: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
9530: $unique=$env{"course.$fucourseid.internal.encseed"};
9531: } else {
9532: $unique=$perlvar{'lonReceipt'};
9533: }
9534: return unpack("%32C*",$unique);
9535: }
9536:
9537: sub recprefix {
9538: my $fucourseid=shift;
9539: my $prefix;
9540: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9541: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
9542: $prefix=$env{"course.$fucourseid.internal.encpref"};
9543: } else {
9544: $prefix=$perlvar{'lonHostID'};
9545: }
9546: return unpack("%32C*",$prefix);
9547: }
9548:
9549: sub ireceipt {
9550: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
9551:
9552: my $return =&recprefix($fucourseid).'-';
9553:
9554: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9555: $env{'request.state'} eq 'construct') {
9556: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9557: return $return;
9558: }
9559:
9560: my $cuname=unpack("%32C*",$funame);
9561: my $cudom=unpack("%32C*",$fudom);
9562: my $cucourseid=unpack("%32C*",$fucourseid);
9563: my $cusymb=unpack("%32C*",$fusymb);
9564: my $cunique=&recunique($fucourseid);
9565: my $cpart=unpack("%32S*",$part);
9566: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
9567:
9568: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
9569:
9570: $return.= ($cunique%$cuname+
9571: $cunique%$cudom+
9572: $cusymb%$cuname+
9573: $cusymb%$cudom+
9574: $cucourseid%$cuname+
9575: $cucourseid%$cudom+
9576: $cpart%$cuname+
9577: $cpart%$cudom);
9578: } else {
9579: $return.= ($cunique%$cuname+
9580: $cunique%$cudom+
9581: $cusymb%$cuname+
9582: $cusymb%$cudom+
9583: $cucourseid%$cuname+
9584: $cucourseid%$cudom);
9585: }
9586: return $return;
9587: }
9588:
9589: sub receipt {
9590: my ($part)=@_;
9591: my ($symb,$courseid,$domain,$name) = &whichuser();
9592: return &ireceipt($name,$domain,$courseid,$symb,$part);
9593: }
9594:
9595: sub whichuser {
9596: my ($passedsymb)=@_;
9597: my ($symb,$courseid,$domain,$name,$publicuser);
9598: if (defined($env{'form.grade_symb'})) {
9599: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
9600: my $allowed=&allowed('vgr',$tmp_courseid);
9601: if (!$allowed &&
9602: exists($env{'request.course.sec'}) &&
9603: $env{'request.course.sec'} !~ /^\s*$/) {
9604: $allowed=&allowed('vgr',$tmp_courseid.
9605: '/'.$env{'request.course.sec'});
9606: }
9607: if ($allowed) {
9608: ($symb)=&get_env_multiple('form.grade_symb');
9609: $courseid=$tmp_courseid;
9610: ($domain)=&get_env_multiple('form.grade_domain');
9611: ($name)=&get_env_multiple('form.grade_username');
9612: return ($symb,$courseid,$domain,$name,$publicuser);
9613: }
9614: }
9615: if (!$passedsymb) {
9616: $symb=&symbread();
9617: } else {
9618: $symb=$passedsymb;
9619: }
9620: $courseid=$env{'request.course.id'};
9621: $domain=$env{'user.domain'};
9622: $name=$env{'user.name'};
9623: if ($name eq 'public' && $domain eq 'public') {
9624: if (!defined($env{'form.username'})) {
9625: $env{'form.username'}.=time.rand(10000000);
9626: }
9627: $name.=$env{'form.username'};
9628: }
9629: return ($symb,$courseid,$domain,$name,$publicuser);
9630:
9631: }
9632:
9633: # ------------------------------------------------------------ Serves up a file
9634: # returns either the contents of the file or
9635: # -1 if the file doesn't exist
9636: #
9637: # if the target is a file that was uploaded via DOCS,
9638: # a check will be made to see if a current copy exists on the local server,
9639: # if it does this will be served, otherwise a copy will be retrieved from
9640: # the home server for the course and stored in /home/httpd/html/userfiles on
9641: # the local server.
9642:
9643: sub getfile {
9644: my ($file) = @_;
9645: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
9646: &repcopy($file);
9647: return &readfile($file);
9648: }
9649:
9650: sub repcopy_userfile {
9651: my ($file)=@_;
9652: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
9653: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
9654: my ($cdom,$cnum,$filename) =
9655: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
9656: my $uri="/uploaded/$cdom/$cnum/$filename";
9657: if (-e "$file") {
9658: # we already have a local copy, check it out
9659: my @fileinfo = stat($file);
9660: my $rtncode;
9661: my $info;
9662: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
9663: if ($lwpresp ne 'ok') {
9664: # there is no such file anymore, even though we had a local copy
9665: if ($rtncode eq '404') {
9666: unlink($file);
9667: }
9668: return -1;
9669: }
9670: if ($info < $fileinfo[9]) {
9671: # nice, the file we have is up-to-date, just say okay
9672: return 'ok';
9673: } else {
9674: # the file is outdated, get rid of it
9675: unlink($file);
9676: }
9677: }
9678: # one way or the other, at this point, we don't have the file
9679: # construct the correct path for the file
9680: my @parts = ($cdom,$cnum);
9681: if ($filename =~ m|^(.+)/[^/]+$|) {
9682: push @parts, split(/\//,$1);
9683: }
9684: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
9685: foreach my $part (@parts) {
9686: $path .= '/'.$part;
9687: if (!-e $path) {
9688: mkdir($path,0770);
9689: }
9690: }
9691: # now the path exists for sure
9692: # get a user agent
9693: my $ua=new LWP::UserAgent;
9694: my $transferfile=$file.'.in.transfer';
9695: # FIXME: this should flock
9696: if (-e $transferfile) { return 'ok'; }
9697: my $request;
9698: $uri=~s/^\///;
9699: my $homeserver = &homeserver($cnum,$cdom);
9700: my $protocol = $protocol{$homeserver};
9701: $protocol = 'http' if ($protocol ne 'https');
9702: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
9703: my $response=$ua->request($request,$transferfile);
9704: # did it work?
9705: if ($response->is_error()) {
9706: unlink($transferfile);
9707: &logthis("Userfile repcopy failed for $uri");
9708: return -1;
9709: }
9710: # worked, rename the transfer file
9711: rename($transferfile,$file);
9712: return 'ok';
9713: }
9714:
9715: sub tokenwrapper {
9716: my $uri=shift;
9717: $uri=~s|^https?\://([^/]+)||;
9718: $uri=~s|^/||;
9719: $env{'user.environment'}=~/\/([^\/]+)\.id/;
9720: my $token=$1;
9721: my (undef,$udom,$uname,$file)=split('/',$uri,4);
9722: if ($udom && $uname && $file) {
9723: $file=~s|(\?\.*)*$||;
9724: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
9725: my $homeserver = &homeserver($uname,$udom);
9726: my $protocol = $protocol{$homeserver};
9727: $protocol = 'http' if ($protocol ne 'https');
9728: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
9729: (($uri=~/\?/)?'&':'?').'token='.$token.
9730: '&tokenissued='.$perlvar{'lonHostID'};
9731: } else {
9732: return '/adm/notfound.html';
9733: }
9734: }
9735:
9736: # call with reqtype HEAD: get last modification time
9737: # call with reqtype GET: get the file contents
9738: # Do not call this with reqtype GET for large files! It loads everything into memory
9739: #
9740: sub getuploaded {
9741: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
9742: $uri=~s/^\///;
9743: my $homeserver = &homeserver($cnum,$cdom);
9744: my $protocol = $protocol{$homeserver};
9745: $protocol = 'http' if ($protocol ne 'https');
9746: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
9747: my $ua=new LWP::UserAgent;
9748: my $request=new HTTP::Request($reqtype,$uri);
9749: my $response=$ua->request($request);
9750: $$rtncode = $response->code;
9751: if (! $response->is_success()) {
9752: return 'failed';
9753: }
9754: if ($reqtype eq 'HEAD') {
9755: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
9756: } elsif ($reqtype eq 'GET') {
9757: $$info = $response->content;
9758: }
9759: return 'ok';
9760: }
9761:
9762: sub readfile {
9763: my $file = shift;
9764: if ( (! -e $file ) || ($file eq '') ) { return -1; };
9765: my $fh;
9766: open($fh,"<$file");
9767: my $a='';
9768: while (my $line = <$fh>) { $a .= $line; }
9769: return $a;
9770: }
9771:
9772: sub filelocation {
9773: my ($dir,$file) = @_;
9774: my $location;
9775: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
9776:
9777: if ($file =~ m-^/adm/-) {
9778: $file=~s-^/adm/wrapper/-/-;
9779: $file=~s-^/adm/coursedocs/showdoc/-/-;
9780: }
9781:
9782: if ($file=~m:^/~:) { # is a contruction space reference
9783: $location = $file;
9784: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
9785: } elsif ($file=~m{^/home/$match_username/public_html/}) {
9786: # is a correct contruction space reference
9787: $location = $file;
9788: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
9789: $location = $file;
9790: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
9791: my ($udom,$uname,$filename)=
9792: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
9793: my $home=&homeserver($uname,$udom);
9794: my $is_me=0;
9795: my @ids=¤t_machine_ids();
9796: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
9797: if ($is_me) {
9798: $location=&propath($udom,$uname).'/userfiles/'.$filename;
9799: } else {
9800: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
9801: $udom.'/'.$uname.'/'.$filename;
9802: }
9803: } elsif ($file =~ m-^/adm/-) {
9804: $location = $perlvar{'lonDocRoot'}.'/'.$file;
9805: } else {
9806: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9807: $file=~s:^/res/:/:;
9808: if ( !( $file =~ m:^/:) ) {
9809: $location = $dir. '/'.$file;
9810: } else {
9811: $location = '/home/httpd/html/res'.$file;
9812: }
9813: }
9814: $location=~s://+:/:g; # remove duplicate /
9815: while ($location=~m{/\.\./}) {
9816: if ($location =~ m{/[^/]+/\.\./}) {
9817: $location=~ s{/[^/]+/\.\./}{/}g;
9818: } else {
9819: $location=~ s{/\.\./}{/}g;
9820: }
9821: } #remove dir/..
9822: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9823: return $location;
9824: }
9825:
9826: sub hreflocation {
9827: my ($dir,$file)=@_;
9828: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
9829: $file=filelocation($dir,$file);
9830: } elsif ($file=~m-^/adm/-) {
9831: $file=~s-^/adm/wrapper/-/-;
9832: $file=~s-^/adm/coursedocs/showdoc/-/-;
9833: }
9834: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9835: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
9836: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9837: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
9838: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
9839: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
9840: -/uploaded/$1/$2/-x;
9841: }
9842: if ($file=~ m{^/userfiles/}) {
9843: $file =~ s{^/userfiles/}{/uploaded/};
9844: }
9845: return $file;
9846: }
9847:
9848: sub current_machine_domains {
9849: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9850: }
9851:
9852: sub machine_domains {
9853: my ($hostname) = @_;
9854: my @domains;
9855: my %hostname = &all_hostnames();
9856: while( my($id, $name) = each(%hostname)) {
9857: # &logthis("-$id-$name-$hostname-");
9858: if ($hostname eq $name) {
9859: push(@domains,&host_domain($id));
9860: }
9861: }
9862: return @domains;
9863: }
9864:
9865: sub current_machine_ids {
9866: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9867: }
9868:
9869: sub machine_ids {
9870: my ($hostname) = @_;
9871: $hostname ||= &hostname($perlvar{'lonHostID'});
9872: my @ids;
9873: my %name_to_host = &all_names();
9874: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9875: return @{ $name_to_host{$hostname} };
9876: }
9877: return;
9878: }
9879:
9880: sub additional_machine_domains {
9881: my @domains;
9882: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9883: while( my $line = <$fh>) {
9884: $line =~ s/\s//g;
9885: push(@domains,$line);
9886: }
9887: return @domains;
9888: }
9889:
9890: sub default_login_domain {
9891: my $domain = $perlvar{'lonDefDomain'};
9892: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9893: foreach my $posdom (¤t_machine_domains(),
9894: &additional_machine_domains()) {
9895: if (lc($posdom) eq lc($testdomain)) {
9896: $domain=$posdom;
9897: last;
9898: }
9899: }
9900: return $domain;
9901: }
9902:
9903: # ------------------------------------------------------------- Declutters URLs
9904:
9905: sub declutter {
9906: my $thisfn=shift;
9907: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
9908: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9909: $thisfn=~s/^\///;
9910: $thisfn=~s|^adm/wrapper/||;
9911: $thisfn=~s|^adm/coursedocs/showdoc/||;
9912: $thisfn=~s/^res\///;
9913: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
9914: $thisfn=~s/\?.+$//;
9915: }
9916: return $thisfn;
9917: }
9918:
9919: # ------------------------------------------------------------- Clutter up URLs
9920:
9921: sub clutter {
9922: my $thisfn='/'.&declutter(shift);
9923: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
9924: || $thisfn =~ m{^/adm/(includes|pages)} ) {
9925: $thisfn='/res'.$thisfn;
9926: }
9927: if ($thisfn !~m|^/adm|) {
9928: if ($thisfn =~ m|^/ext/|) {
9929: $thisfn='/adm/wrapper'.$thisfn;
9930: } else {
9931: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9932: my $embstyle=&Apache::loncommon::fileembstyle($ext);
9933: if ($embstyle eq 'ssi'
9934: || ($embstyle eq 'hdn')
9935: || ($embstyle eq 'rat')
9936: || ($embstyle eq 'prv')
9937: || ($embstyle eq 'ign')) {
9938: #do nothing with these
9939: } elsif (($embstyle eq 'img')
9940: || ($embstyle eq 'emb')
9941: || ($embstyle eq 'wrp')) {
9942: $thisfn='/adm/wrapper'.$thisfn;
9943: } elsif ($embstyle eq 'unk'
9944: && $thisfn!~/\.(sequence|page)$/) {
9945: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
9946: } else {
9947: # &logthis("Got a blank emb style");
9948: }
9949: }
9950: }
9951: return $thisfn;
9952: }
9953:
9954: sub clutter_with_no_wrapper {
9955: my $uri = &clutter(shift);
9956: if ($uri =~ m-^/adm/-) {
9957: $uri =~ s-^/adm/wrapper/-/-;
9958: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9959: }
9960: return $uri;
9961: }
9962:
9963: sub freeze_escape {
9964: my ($value)=@_;
9965: if (ref($value)) {
9966: $value=&nfreeze($value);
9967: return '__FROZEN__'.&escape($value);
9968: }
9969: return &escape($value);
9970: }
9971:
9972:
9973: sub thaw_unescape {
9974: my ($value)=@_;
9975: if ($value =~ /^__FROZEN__/) {
9976: substr($value,0,10,undef);
9977: $value=&unescape($value);
9978: return &thaw($value);
9979: }
9980: return &unescape($value);
9981: }
9982:
9983: sub correct_line_ends {
9984: my ($result)=@_;
9985: $$result =~s/\r\n/\n/mg;
9986: $$result =~s/\r/\n/mg;
9987: }
9988: # ================================================================ Main Program
9989:
9990: sub goodbye {
9991: &logthis("Starting Shut down");
9992: #not converted to using infrastruture and probably shouldn't be
9993: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
9994: #converted
9995: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
9996: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9997: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9998: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
9999: #1.1 only
10000: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10001: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10002: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10003: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10004: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
10005: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10006: &logthis(sprintf("%-20s is %s",'hits',$hits));
10007: &flushcourselogs();
10008: &logthis("Shutting down");
10009: }
10010:
10011: sub get_dns {
10012: my ($url,$func,$ignore_cache) = @_;
10013: if (!$ignore_cache) {
10014: my ($content,$cached)=
10015: &Apache::lonnet::is_cached_new('dns',$url);
10016: if ($cached) {
10017: &$func($content);
10018: return;
10019: }
10020: }
10021:
10022: my %alldns;
10023: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10024: foreach my $dns (<$config>) {
10025: next if ($dns !~ /^\^(\S*)/x);
10026: my $line = $1;
10027: my ($host,$protocol) = split(/:/,$line);
10028: if ($protocol ne 'https') {
10029: $protocol = 'http';
10030: }
10031: $alldns{$host} = $protocol;
10032: }
10033: while (%alldns) {
10034: my ($dns) = keys(%alldns);
10035: my $ua=new LWP::UserAgent;
10036: $ua->timeout(30);
10037: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
10038: my $response=$ua->request($request);
10039: delete($alldns{$dns});
10040: next if ($response->is_error());
10041: my @content = split("\n",$response->content);
10042: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
10043: &$func(\@content);
10044: return;
10045: }
10046: close($config);
10047: my $which = (split('/',$url))[3];
10048: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10049: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
10050: my @content = <$config>;
10051: &$func(\@content);
10052: return;
10053: }
10054: # ------------------------------------------------------------ Read domain file
10055: {
10056: my $loaded;
10057: my %domain;
10058:
10059: sub parse_domain_tab {
10060: my ($lines) = @_;
10061: foreach my $line (@$lines) {
10062: next if ($line =~ /^(\#|\s*$ )/x);
10063:
10064: chomp($line);
10065: my ($name,@elements) = split(/:/,$line,9);
10066: my %this_domain;
10067: foreach my $field ('description', 'auth_def', 'auth_arg_def',
10068: 'lang_def', 'city', 'longi', 'lati',
10069: 'primary') {
10070: $this_domain{$field} = shift(@elements);
10071: }
10072: $domain{$name} = \%this_domain;
10073: }
10074: }
10075:
10076: sub reset_domain_info {
10077: undef($loaded);
10078: undef(%domain);
10079: }
10080:
10081: sub load_domain_tab {
10082: my ($ignore_cache) = @_;
10083: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
10084: my $fh;
10085: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10086: my @lines = <$fh>;
10087: &parse_domain_tab(\@lines);
10088: }
10089: close($fh);
10090: $loaded = 1;
10091: }
10092:
10093: sub domain {
10094: &load_domain_tab() if (!$loaded);
10095:
10096: my ($name,$what) = @_;
10097: return if ( !exists($domain{$name}) );
10098:
10099: if (!$what) {
10100: return $domain{$name}{'description'};
10101: }
10102: return $domain{$name}{$what};
10103: }
10104:
10105: sub domain_info {
10106: &load_domain_tab() if (!$loaded);
10107: return %domain;
10108: }
10109:
10110: }
10111:
10112:
10113: # ------------------------------------------------------------- Read hosts file
10114: {
10115: my %hostname;
10116: my %hostdom;
10117: my %libserv;
10118: my $loaded;
10119: my %name_to_host;
10120: my %internetdom;
10121: my %LC_dns_serv;
10122:
10123: sub parse_hosts_tab {
10124: my ($file) = @_;
10125: foreach my $configline (@$file) {
10126: next if ($configline =~ /^(\#|\s*$ )/x);
10127: chomp($configline);
10128: if ($configline =~ /^\^/) {
10129: if ($configline =~ /^\^([\w.\-]+)/) {
10130: $LC_dns_serv{$1} = 1;
10131: }
10132: next;
10133: }
10134: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
10135: $name=~s/\s//g;
10136: if ($id && $domain && $role && $name) {
10137: $hostname{$id}=$name;
10138: push(@{$name_to_host{$name}}, $id);
10139: $hostdom{$id}=$domain;
10140: if ($role eq 'library') { $libserv{$id}=$name; }
10141: if (defined($protocol)) {
10142: if ($protocol eq 'https') {
10143: $protocol{$id} = $protocol;
10144: } else {
10145: $protocol{$id} = 'http';
10146: }
10147: } else {
10148: $protocol{$id} = 'http';
10149: }
10150: if (defined($intdom)) {
10151: $internetdom{$id} = $intdom;
10152: }
10153: }
10154: }
10155: }
10156:
10157: sub reset_hosts_info {
10158: &purge_remembered();
10159: &reset_domain_info();
10160: &reset_hosts_ip_info();
10161: undef(%name_to_host);
10162: undef(%hostname);
10163: undef(%hostdom);
10164: undef(%libserv);
10165: undef($loaded);
10166: }
10167:
10168: sub load_hosts_tab {
10169: my ($ignore_cache) = @_;
10170: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
10171: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10172: my @config = <$config>;
10173: &parse_hosts_tab(\@config);
10174: close($config);
10175: $loaded=1;
10176: }
10177:
10178: sub hostname {
10179: &load_hosts_tab() if (!$loaded);
10180:
10181: my ($lonid) = @_;
10182: return $hostname{$lonid};
10183: }
10184:
10185: sub all_hostnames {
10186: &load_hosts_tab() if (!$loaded);
10187:
10188: return %hostname;
10189: }
10190:
10191: sub all_names {
10192: &load_hosts_tab() if (!$loaded);
10193:
10194: return %name_to_host;
10195: }
10196:
10197: sub all_host_domain {
10198: &load_hosts_tab() if (!$loaded);
10199: return %hostdom;
10200: }
10201:
10202: sub is_library {
10203: &load_hosts_tab() if (!$loaded);
10204:
10205: return exists($libserv{$_[0]});
10206: }
10207:
10208: sub all_library {
10209: &load_hosts_tab() if (!$loaded);
10210:
10211: return %libserv;
10212: }
10213:
10214: sub unique_library {
10215: #2x reverse removes all hostnames that appear more than once
10216: my %unique = reverse &all_library();
10217: return reverse %unique;
10218: }
10219:
10220: sub get_servers {
10221: &load_hosts_tab() if (!$loaded);
10222:
10223: my ($domain,$type) = @_;
10224: my %possible_hosts = ($type eq 'library') ? %libserv
10225: : %hostname;
10226: my %result;
10227: if (ref($domain) eq 'ARRAY') {
10228: while ( my ($host,$hostname) = each(%possible_hosts)) {
10229: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
10230: $result{$host} = $hostname;
10231: }
10232: }
10233: } else {
10234: while ( my ($host,$hostname) = each(%possible_hosts)) {
10235: if ($hostdom{$host} eq $domain) {
10236: $result{$host} = $hostname;
10237: }
10238: }
10239: }
10240: return %result;
10241: }
10242:
10243: sub get_unique_servers {
10244: my %unique = reverse &get_servers(@_);
10245: return reverse %unique;
10246: }
10247:
10248: sub host_domain {
10249: &load_hosts_tab() if (!$loaded);
10250:
10251: my ($lonid) = @_;
10252: return $hostdom{$lonid};
10253: }
10254:
10255: sub all_domains {
10256: &load_hosts_tab() if (!$loaded);
10257:
10258: my %seen;
10259: my @uniq = grep(!$seen{$_}++, values(%hostdom));
10260: return @uniq;
10261: }
10262:
10263: sub internet_dom {
10264: &load_hosts_tab() if (!$loaded);
10265:
10266: my ($lonid) = @_;
10267: return $internetdom{$lonid};
10268: }
10269:
10270: sub is_LC_dns {
10271: &load_hosts_tab() if (!$loaded);
10272:
10273: my ($hostname) = @_;
10274: return exists($LC_dns_serv{$hostname});
10275: }
10276:
10277: }
10278:
10279: {
10280: my %iphost;
10281: my %name_to_ip;
10282: my %lonid_to_ip;
10283:
10284: sub get_hosts_from_ip {
10285: my ($ip) = @_;
10286: my %iphosts = &get_iphost();
10287: if (ref($iphosts{$ip})) {
10288: return @{$iphosts{$ip}};
10289: }
10290: return;
10291: }
10292:
10293: sub reset_hosts_ip_info {
10294: undef(%iphost);
10295: undef(%name_to_ip);
10296: undef(%lonid_to_ip);
10297: }
10298:
10299: sub get_host_ip {
10300: my ($lonid) = @_;
10301: if (exists($lonid_to_ip{$lonid})) {
10302: return $lonid_to_ip{$lonid};
10303: }
10304: my $name=&hostname($lonid);
10305: my $ip = gethostbyname($name);
10306: return if (!$ip || length($ip) ne 4);
10307: $ip=inet_ntoa($ip);
10308: $name_to_ip{$name} = $ip;
10309: $lonid_to_ip{$lonid} = $ip;
10310: return $ip;
10311: }
10312:
10313: sub get_iphost {
10314: my ($ignore_cache) = @_;
10315:
10316: if (!$ignore_cache) {
10317: if (%iphost) {
10318: return %iphost;
10319: }
10320: my ($ip_info,$cached)=
10321: &Apache::lonnet::is_cached_new('iphost','iphost');
10322: if ($cached) {
10323: %iphost = %{$ip_info->[0]};
10324: %name_to_ip = %{$ip_info->[1]};
10325: %lonid_to_ip = %{$ip_info->[2]};
10326: return %iphost;
10327: }
10328: }
10329:
10330: # get yesterday's info for fallback
10331: my %old_name_to_ip;
10332: my ($ip_info,$cached)=
10333: &Apache::lonnet::is_cached_new('iphost','iphost');
10334: if ($cached) {
10335: %old_name_to_ip = %{$ip_info->[1]};
10336: }
10337:
10338: my %name_to_host = &all_names();
10339: foreach my $name (keys(%name_to_host)) {
10340: my $ip;
10341: if (!exists($name_to_ip{$name})) {
10342: $ip = gethostbyname($name);
10343: if (!$ip || length($ip) ne 4) {
10344: if (defined($old_name_to_ip{$name})) {
10345: $ip = $old_name_to_ip{$name};
10346: &logthis("Can't find $name defaulting to old $ip");
10347: } else {
10348: &logthis("Name $name no IP found");
10349: next;
10350: }
10351: } else {
10352: $ip=inet_ntoa($ip);
10353: }
10354: $name_to_ip{$name} = $ip;
10355: } else {
10356: $ip = $name_to_ip{$name};
10357: }
10358: foreach my $id (@{ $name_to_host{$name} }) {
10359: $lonid_to_ip{$id} = $ip;
10360: }
10361: push(@{$iphost{$ip}},@{$name_to_host{$name}});
10362: }
10363: &Apache::lonnet::do_cache_new('iphost','iphost',
10364: [\%iphost,\%name_to_ip,\%lonid_to_ip],
10365: 48*60*60);
10366:
10367: return %iphost;
10368: }
10369:
10370: #
10371: # Given a DNS returns the loncapa host name for that DNS
10372: #
10373: sub host_from_dns {
10374: my ($dns) = @_;
10375: my @hosts;
10376: my $ip;
10377:
10378: if (exists($name_to_ip{$dns})) {
10379: $ip = $name_to_ip{$dns};
10380: }
10381: if (!$ip) {
10382: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10383: if (length($ip) == 4) {
10384: $ip = &IO::Socket::inet_ntoa($ip);
10385: }
10386: }
10387: if ($ip) {
10388: @hosts = get_hosts_from_ip($ip);
10389: return $hosts[0];
10390: }
10391: return undef;
10392: }
10393:
10394: sub get_internet_names {
10395: my ($lonid) = @_;
10396: return if ($lonid eq '');
10397: my ($idnref,$cached)=
10398: &Apache::lonnet::is_cached_new('internetnames',$lonid);
10399: if ($cached) {
10400: return $idnref;
10401: }
10402: my $ip = &get_host_ip($lonid);
10403: my @hosts = &get_hosts_from_ip($ip);
10404: my %iphost = &get_iphost();
10405: my (@idns,%seen);
10406: foreach my $id (@hosts) {
10407: my $dom = &host_domain($id);
10408: my $prim_id = &domain($dom,'primary');
10409: my $prim_ip = &get_host_ip($prim_id);
10410: next if ($seen{$prim_ip});
10411: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10412: foreach my $id (@{$iphost{$prim_ip}}) {
10413: my $intdom = &internet_dom($id);
10414: unless (grep(/^\Q$intdom\E$/,@idns)) {
10415: push(@idns,$intdom);
10416: }
10417: }
10418: }
10419: $seen{$prim_ip} = 1;
10420: }
10421: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10422: }
10423:
10424: }
10425:
10426: sub all_loncaparevs {
10427: 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);
10428: }
10429:
10430: BEGIN {
10431:
10432: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10433: unless ($readit) {
10434: {
10435: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10436: %perlvar = (%perlvar,%{$configvars});
10437: }
10438:
10439:
10440: # ------------------------------------------------------ Read spare server file
10441: {
10442: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
10443:
10444: while (my $configline=<$config>) {
10445: chomp($configline);
10446: if ($configline) {
10447: my ($host,$type) = split(':',$configline,2);
10448: if (!defined($type) || $type eq '') { $type = 'default' };
10449: push(@{ $spareid{$type} }, $host);
10450: }
10451: }
10452: close($config);
10453: }
10454: # ------------------------------------------------------------ Read permissions
10455: {
10456: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
10457:
10458: while (my $configline=<$config>) {
10459: chomp($configline);
10460: if ($configline) {
10461: my ($role,$perm)=split(/ /,$configline);
10462: if ($perm ne '') { $pr{$role}=$perm; }
10463: }
10464: }
10465: close($config);
10466: }
10467:
10468: # -------------------------------------------- Read plain texts for permissions
10469: {
10470: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
10471:
10472: while (my $configline=<$config>) {
10473: chomp($configline);
10474: if ($configline) {
10475: my ($short,@plain)=split(/:/,$configline);
10476: %{$prp{$short}} = ();
10477: if (@plain > 0) {
10478: $prp{$short}{'std'} = $plain[0];
10479: for (my $i=1; $i<@plain; $i++) {
10480: $prp{$short}{'alt'.$i} = $plain[$i];
10481: }
10482: }
10483: }
10484: }
10485: close($config);
10486: }
10487:
10488: # ---------------------------------------------------------- Read package table
10489: {
10490: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
10491:
10492: while (my $configline=<$config>) {
10493: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
10494: chomp($configline);
10495: my ($short,$plain)=split(/:/,$configline);
10496: my ($pack,$name)=split(/\&/,$short);
10497: if ($plain ne '') {
10498: $packagetab{$pack.'&'.$name.'&name'}=$name;
10499: $packagetab{$short}=$plain;
10500: }
10501: }
10502: close($config);
10503: }
10504:
10505: # ---------------------------------------------------------- Read loncaparev table
10506: {
10507: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10508: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10509: while (my $configline=<$config>) {
10510: chomp($configline);
10511: my ($hostid,$loncaparev)=split(/:/,$configline);
10512: $loncaparevs{$hostid}=$loncaparev;
10513: }
10514: close($config);
10515: }
10516: }
10517: }
10518:
10519: # ---------------------------------------------------------- Read serverhostID table
10520: {
10521: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10522: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10523: while (my $configline=<$config>) {
10524: chomp($configline);
10525: my ($name,$id)=split(/:/,$configline);
10526: $serverhomeIDs{$name}=$id;
10527: }
10528: close($config);
10529: }
10530: }
10531: }
10532:
10533: {
10534: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
10535: if (-e $file) {
10536: my $parser = HTML::LCParser->new($file);
10537: while (my $token = $parser->get_token()) {
10538: if ($token->[0] eq 'S') {
10539: my $item = $token->[1];
10540: my $name = $token->[2]{'name'};
10541: my $value = $token->[2]{'value'};
10542: if ($item ne '' && $name ne '' && $value ne '') {
10543: my $release = $parser->get_text();
10544: $release =~ s/(^\s*|\s*$ )//gx;
10545: $needsrelease{$item.':'.$name.':'.$value} = $release;
10546: }
10547: }
10548: }
10549: }
10550: }
10551:
10552: # ---------------------------------------------------------- Read managers table
10553: {
10554: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
10555: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
10556: while (my $configline=<$config>) {
10557: chomp($configline);
10558: next if ($configline =~ /^\#/);
10559: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
10560: $managerstab{$configline} = 1;
10561: }
10562: }
10563: close($config);
10564: }
10565: }
10566: }
10567:
10568: # ------------- set up temporary directory
10569: {
10570: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
10571:
10572: }
10573:
10574: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
10575: 'compress_threshold'=> 20_000,
10576: });
10577:
10578: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
10579: $dumpcount=0;
10580: $locknum=0;
10581:
10582: &logtouch();
10583: &logthis('<font color="yellow">INFO: Read configuration</font>');
10584: $readit=1;
10585: {
10586: use integer;
10587: my $test=(2**32)+1;
10588: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
10589: &logthis(" Detected 64bit platform ($_64bit)");
10590: }
10591: }
10592: }
10593:
10594: 1;
10595: __END__
10596:
10597: =pod
10598:
10599: =head1 NAME
10600:
10601: Apache::lonnet - Subroutines to ask questions about things in the network.
10602:
10603: =head1 SYNOPSIS
10604:
10605: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
10606:
10607: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
10608:
10609: Common parameters:
10610:
10611: =over 4
10612:
10613: =item *
10614:
10615: $uname : an internal username (if $cname expecting a course Id specifically)
10616:
10617: =item *
10618:
10619: $udom : a domain (if $cdom expecting a course's domain specifically)
10620:
10621: =item *
10622:
10623: $symb : a resource instance identifier
10624:
10625: =item *
10626:
10627: $namespace : the name of a .db file that contains the data needed or
10628: being set.
10629:
10630: =back
10631:
10632: =head1 OVERVIEW
10633:
10634: lonnet provides subroutines which interact with the
10635: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
10636: about classes, users, and resources.
10637:
10638: For many of these objects you can also use this to store data about
10639: them or modify them in various ways.
10640:
10641: =head2 Symbs
10642:
10643: To identify a specific instance of a resource, LON-CAPA uses symbols
10644: or "symbs"X<symb>. These identifiers are built from the URL of the
10645: map, the resource number of the resource in the map, and the URL of
10646: the resource itself. The latter is somewhat redundant, but might help
10647: if maps change.
10648:
10649: An example is
10650:
10651: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
10652:
10653: The respective map entry is
10654:
10655: <resource id="19" src="/res/msu/korte/tests/part12.problem"
10656: title="Problem 2">
10657: </resource>
10658:
10659: Symbs are used by the random number generator, as well as to store and
10660: restore data specific to a certain instance of for example a problem.
10661:
10662: =head2 Storing And Retrieving Data
10663:
10664: X<store()>X<cstore()>X<restore()>Three of the most important functions
10665: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10666: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10667: is is the non-critical message twin of cstore. These functions are for
10668: handlers to store a perl hash to a user's permanent data space in an
10669: easy manner, and to retrieve it again on another call. It is expected
10670: that a handler would use this once at the beginning to retrieve data,
10671: and then again once at the end to send only the new data back.
10672:
10673: The data is stored in the user's data directory on the user's
10674: homeserver under the ID of the course.
10675:
10676: The hash that is returned by restore will have all of the previous
10677: value for all of the elements of the hash.
10678:
10679: Example:
10680:
10681: #creating a hash
10682: my %hash;
10683: $hash{'foo'}='bar';
10684:
10685: #storing it
10686: &Apache::lonnet::cstore(\%hash);
10687:
10688: #changing a value
10689: $hash{'foo'}='notbar';
10690:
10691: #adding a new value
10692: $hash{'bar'}='foo';
10693: &Apache::lonnet::cstore(\%hash);
10694:
10695: #retrieving the hash
10696: my %history=&Apache::lonnet::restore();
10697:
10698: #print the hash
10699: foreach my $key (sort(keys(%history))) {
10700: print("\%history{$key} = $history{$key}");
10701: }
10702:
10703: Will print out:
10704:
10705: %history{1:foo} = bar
10706: %history{1:keys} = foo:timestamp
10707: %history{1:timestamp} = 990455579
10708: %history{2:bar} = foo
10709: %history{2:foo} = notbar
10710: %history{2:keys} = foo:bar:timestamp
10711: %history{2:timestamp} = 990455580
10712: %history{bar} = foo
10713: %history{foo} = notbar
10714: %history{timestamp} = 990455580
10715: %history{version} = 2
10716:
10717: Note that the special hash entries C<keys>, C<version> and
10718: C<timestamp> were added to the hash. C<version> will be equal to the
10719: total number of versions of the data that have been stored. The
10720: C<timestamp> attribute will be the UNIX time the hash was
10721: stored. C<keys> is available in every historical section to list which
10722: keys were added or changed at a specific historical revision of a
10723: hash.
10724:
10725: B<Warning>: do not store the hash that restore returns directly. This
10726: will cause a mess since it will restore the historical keys as if the
10727: were new keys. I.E. 1:foo will become 1:1:foo etc.
10728:
10729: Calling convention:
10730:
10731: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10732: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
10733:
10734: For more detailed information, see lonnet specific documentation.
10735:
10736: =head1 RETURN MESSAGES
10737:
10738: =over 4
10739:
10740: =item * B<con_lost>: unable to contact remote host
10741:
10742: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10743: when the connection is brought back up
10744:
10745: =item * B<con_failed>: unable to contact remote host and unable to save message
10746: for later delivery
10747:
10748: =item * B<error:>: an error a occurred, a description of the error follows the :
10749:
10750: =item * B<no_such_host>: unable to fund a host associated with the user/domain
10751: that was requested
10752:
10753: =back
10754:
10755: =head1 PUBLIC SUBROUTINES
10756:
10757: =head2 Session Environment Functions
10758:
10759: =over 4
10760:
10761: =item *
10762: X<appenv()>
10763: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
10764: the user envirnoment file, and will be restored for each access this
10765: user makes during this session, also modifies the %env for the current
10766: process. Optional rolesarrayref - if defined contains a reference to an array
10767: of roles which are exempt from the restriction on modifying user.role entries
10768: in the user's environment.db and in %env.
10769:
10770: =item *
10771: X<delenv()>
10772: B<delenv($delthis,$regexp)>: removes all items from the session
10773: environment file that begin with $delthis. If the
10774: optional second arg - $regexp - is true, $delthis is treated as a
10775: regular expression, otherwise \Q$delthis\E is used.
10776: The values are also deleted from the current processes %env.
10777:
10778: =item * get_env_multiple($name)
10779:
10780: gets $name from the %env hash, it seemlessly handles the cases where multiple
10781: values may be defined and end up as an array ref.
10782:
10783: returns an array of values
10784:
10785: =back
10786:
10787: =head2 User Information
10788:
10789: =over 4
10790:
10791: =item *
10792: X<queryauthenticate()>
10793: B<queryauthenticate($uname,$udom)>: try to determine user's current
10794: authentication scheme
10795:
10796: =item *
10797: X<authenticate()>
10798: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
10799: authenticate user from domain's lib servers (first use the current
10800: one). C<$upass> should be the users password.
10801: $checkdefauth is optional (value is 1 if a check should be made to
10802: authenticate user using default authentication method, and allow
10803: account creation if username does not have account in the domain).
10804: $clientcancheckhost is optional (value is 1 if checking whether the
10805: server can host will occur on the client side in lonauth.pm).
10806:
10807: =item *
10808: X<homeserver()>
10809: B<homeserver($uname,$udom)>: find the server which has
10810: the user's directory and files (there must be only one), this caches
10811: the answer, and also caches if there is a borken connection.
10812:
10813: =item *
10814: X<idget()>
10815: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10816: (IDs are a unique resource in a domain, there must be only 1 ID per
10817: username, and only 1 username per ID in a specific domain) (returns
10818: hash: id=>name,id=>name)
10819:
10820: =item *
10821: X<idrget()>
10822: B<idrget($udom,@unames)>: find the IDs behind a list of
10823: usernames (returns hash: name=>id,name=>id)
10824:
10825: =item *
10826: X<idput()>
10827: B<idput($udom,%ids)>: store away a list of names and associated IDs
10828:
10829: =item *
10830: X<rolesinit()>
10831: B<rolesinit($udom,$username,$authhost)>: get user privileges
10832:
10833: =item *
10834: X<getsection()>
10835: B<getsection($udom,$uname,$cname)>: finds the section of student in the
10836: course $cname, return section name/number or '' for "not in course"
10837: and '-1' for "no section"
10838:
10839: =item *
10840: X<userenvironment()>
10841: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
10842: passed in @what from the requested user's environment, returns a hash
10843:
10844: =item *
10845: X<userlog_query()>
10846: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10847: activity.log file. %filters defines filters applied when parsing the
10848: log file. These can be start or end timestamps, or the type of action
10849: - log to look for Login or Logout events, check for Checkin or
10850: Checkout, role for role selection. The response is in the form
10851: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
10852: escaped strings of the action recorded in the activity.log file.
10853:
10854: =back
10855:
10856: =head2 User Roles
10857:
10858: =over 4
10859:
10860: =item *
10861:
10862: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
10863: F: full access
10864: U,I,K: authentication modes (cxx only)
10865: '': forbidden
10866: 1: user needs to choose course
10867: 2: browse allowed
10868: A: passphrase authentication needed
10869:
10870: =item *
10871:
10872: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10873: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10874: and course level
10875:
10876: =item *
10877:
10878: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
10879: (rolesplain.tab); plain text explanation of a user role term.
10880: $type is Course (default) or Community.
10881: If $forcedefault evaluates to true, text returned will be default
10882: text for $type. Otherwise, if this is a course, the text returned
10883: will be a custom name for the role (if defined in the course's
10884: environment). If no custom name is defined the default is returned.
10885:
10886: =item *
10887:
10888: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
10889: All arguments are optional. Returns a hash of a roles, either for
10890: co-author/assistant author roles for a user's Construction Space
10891: (default), or if $context is 'userroles', roles for the user himself,
10892: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10893: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10894: For each key, value is set to colon-separated start and end times for
10895: the role. If no username and domain are specified, will default to
10896: current user/domain. Types, roles, and roledoms are references to arrays
10897: of role statuses (active, future or previous), roles
10898: (e.g., cc,in, st etc.) and domains of the roles which can be used
10899: to restrict the list of roles reported. If no array ref is
10900: provided for types, will default to return only active roles.
10901:
10902: =back
10903:
10904: =head2 User Modification
10905:
10906: =over 4
10907:
10908: =item *
10909:
10910: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
10911: user for the level given by URL. Optional start and end dates (leave empty
10912: string or zero for "no date")
10913:
10914: =item *
10915:
10916: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10917: change a users, password, possible return values are: ok,
10918: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10919: refused
10920:
10921: =item *
10922:
10923: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
10924:
10925: =item *
10926:
10927: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
10928: $forceid,$desiredhome,$email,$inststatus,$candelete) :
10929:
10930: will update user information (firstname,middlename,lastname,generation,
10931: permanentemail), and if forceid is true, student/employee ID also.
10932: A user's institutional affiliation(s) can also be updated.
10933: User information fields will not be overwritten with empty entries
10934: unless the field is included in the $candelete array reference.
10935: This array is included when a single user is modified via "Manage Users",
10936: or when Autoupdate.pl is run by cron in a domain.
10937:
10938: =item *
10939:
10940: modifystudent
10941:
10942: modify a student's enrollment and identification information.
10943: The course id is resolved based on the current users environment.
10944: This means the envoking user must be a course coordinator or otherwise
10945: associated with a course.
10946:
10947: This call is essentially a wrapper for lonnet::modifyuser and
10948: lonnet::modify_student_enrollment
10949:
10950: Inputs:
10951:
10952: =over 4
10953:
10954: =item B<$udom> Student's loncapa domain
10955:
10956: =item B<$uname> Student's loncapa login name
10957:
10958: =item B<$uid> Student/Employee ID
10959:
10960: =item B<$umode> Student's authentication mode
10961:
10962: =item B<$upass> Student's password
10963:
10964: =item B<$first> Student's first name
10965:
10966: =item B<$middle> Student's middle name
10967:
10968: =item B<$last> Student's last name
10969:
10970: =item B<$gene> Student's generation
10971:
10972: =item B<$usec> Student's section in course
10973:
10974: =item B<$end> Unix time of the roles expiration
10975:
10976: =item B<$start> Unix time of the roles start date
10977:
10978: =item B<$forceid> If defined, allow $uid to be changed
10979:
10980: =item B<$desiredhome> server to use as home server for student
10981:
10982: =item B<$email> Student's permanent e-mail address
10983:
10984: =item B<$type> Type of enrollment (auto or manual)
10985:
10986: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10987:
10988: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
10989:
10990: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
10991:
10992: =item B<$context> role change context (shown in User Management Logs display in a course)
10993:
10994: =item B<$inststatus> institutional status of user - : separated string of escaped status types
10995:
10996: =back
10997:
10998: =item *
10999:
11000: modify_student_enrollment
11001:
11002: Change a students enrollment status in a class. The environment variable
11003: 'role.request.course' must be defined for this function to proceed.
11004:
11005: Inputs:
11006:
11007: =over 4
11008:
11009: =item $udom, students domain
11010:
11011: =item $uname, students name
11012:
11013: =item $uid, students user id
11014:
11015: =item $first, students first name
11016:
11017: =item $middle
11018:
11019: =item $last
11020:
11021: =item $gene
11022:
11023: =item $usec
11024:
11025: =item $end
11026:
11027: =item $start
11028:
11029: =item $type
11030:
11031: =item $locktype
11032:
11033: =item $cid
11034:
11035: =item $selfenroll
11036:
11037: =item $context
11038:
11039: =back
11040:
11041:
11042: =item *
11043:
11044: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11045: custom role; give a custom role to a user for the level given by URL. Specify
11046: name and domain of role author, and role name
11047:
11048: =item *
11049:
11050: revokerole($udom,$uname,$url,$role) : revoke a role for url
11051:
11052: =item *
11053:
11054: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11055:
11056: =back
11057:
11058: =head2 Course Infomation
11059:
11060: =over 4
11061:
11062: =item *
11063:
11064: coursedescription($courseid) : returns a hash of information about the
11065: specified course id, including all environment settings for the
11066: course, the description of the course will be in the hash under the
11067: key 'description'
11068:
11069: =item *
11070:
11071: resdata($name,$domain,$type,@which) : request for current parameter
11072: setting for a specific $type, where $type is either 'course' or 'user',
11073: @what should be a list of parameters to ask about. This routine caches
11074: answers for 5 minutes.
11075:
11076: =item *
11077:
11078: get_courseresdata($courseid, $domain) : dump the entire course resource
11079: data base, returning a hash that is keyed by the resource name and has
11080: values that are the resource value. I believe that the timestamps and
11081: versions are also returned.
11082:
11083:
11084: =back
11085:
11086: =head2 Course Modification
11087:
11088: =over 4
11089:
11090: =item *
11091:
11092: writecoursepref($courseid,%prefs) : write preferences (environment
11093: database) for a course
11094:
11095: =item *
11096:
11097: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11098:
11099: =item *
11100:
11101: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
11102:
11103: =back
11104:
11105: =head2 Resource Subroutines
11106:
11107: =over 4
11108:
11109: =item *
11110:
11111: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
11112:
11113: =item *
11114:
11115: repcopy($filename) : subscribes to the requested file, and attempts to
11116: replicate from the owning library server, Might return
11117: 'unavailable', 'not_found', 'forbidden', 'ok', or
11118: 'bad_request', also attempts to grab the metadata for the
11119: resource. Expects the local filesystem pathname
11120: (/home/httpd/html/res/....)
11121:
11122: =back
11123:
11124: =head2 Resource Information
11125:
11126: =over 4
11127:
11128: =item *
11129:
11130: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
11131: a vairety of different possible values, $varname should be a request
11132: string, and the other parameters can be used to specify who and what
11133: one is asking about.
11134:
11135: Possible values for $varname are environment.lastname (or other item
11136: from the envirnment hash), user.name (or someother aspect about the
11137: user), resource.0.maxtries (or some other part and parameter of a
11138: resource)
11139:
11140: =item *
11141:
11142: directcondval($number) : get current value of a condition; reads from a state
11143: string
11144:
11145: =item *
11146:
11147: condval($condidx) : value of condition index based on state
11148:
11149: =item *
11150:
11151: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11152: resource's metadata, $what should be either a specific key, or either
11153: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11154: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11155:
11156: this function automatically caches all requests
11157:
11158: =item *
11159:
11160: metadata_query($query,$custom,$customshow) : make a metadata query against the
11161: network of library servers; returns file handle of where SQL and regex results
11162: will be stored for query
11163:
11164: =item *
11165:
11166: symbread($filename) : return symbolic list entry (filename argument optional);
11167: returns the data handle
11168:
11169: =item *
11170:
11171: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
11172: a possible symb for the URL in $thisfn, and if is an encryypted
11173: resource that the user accessed using /enc/ returns a 1 on success, 0
11174: on failure, user must be in a course, as it assumes the existance of
11175: the course initial hash, and uses $env('request.course.id'}
11176:
11177:
11178: =item *
11179:
11180: symbclean($symb) : removes versions numbers from a symb, returns the
11181: cleaned symb
11182:
11183: =item *
11184:
11185: is_on_map($uri) : checks if the $uri is somewhere on the current
11186: course map, user must be in a course for it to work.
11187:
11188: =item *
11189:
11190: numval($salt) : return random seed value (addend for rndseed)
11191:
11192: =item *
11193:
11194: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11195: a random seed, all arguments are optional, if they aren't sent it uses the
11196: environment to derive them. Note: if symb isn't sent and it can't get one
11197: from &symbread it will use the current time as its return value
11198:
11199: =item *
11200:
11201: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11202: unfakeable, receipt
11203:
11204: =item *
11205:
11206: receipt() : API to ireceipt working off of env values; given out to users
11207:
11208: =item *
11209:
11210: countacc($url) : count the number of accesses to a given URL
11211:
11212: =item *
11213:
11214: 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
11215:
11216: =item *
11217:
11218: 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)
11219:
11220: =item *
11221:
11222: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
11223:
11224: =item *
11225:
11226: devalidate($symb) : devalidate temporary spreadsheet calculations,
11227: forcing spreadsheet to reevaluate the resource scores next time.
11228:
11229: =back
11230:
11231: =head2 Storing/Retreiving Data
11232:
11233: =over 4
11234:
11235: =item *
11236:
11237: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11238: for this url; hashref needs to be given and should be a \%hashname; the
11239: remaining args aren't required and if they aren't passed or are '' they will
11240: be derived from the env
11241:
11242: =item *
11243:
11244: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11245: uses critical subroutine
11246:
11247: =item *
11248:
11249: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11250: all args are optional
11251:
11252: =item *
11253:
11254: dumpstore($namespace,$udom,$uname,$regexp,$range) :
11255: dumps the complete (or key matching regexp) namespace into a hash
11256: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11257: normally &store()ed into
11258:
11259: $range should be either an integer '100' (give me the first 100
11260: matching records)
11261: or be two integers sperated by a - with no spaces
11262: '30-50' (give me the 30th through the 50th matching
11263: records)
11264:
11265:
11266: =item *
11267:
11268: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11269: replaces a &store() version of data with a replacement set of data
11270: for a particular resource in a namespace passed in the $storehash hash
11271: reference
11272:
11273: =item *
11274:
11275: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11276: works very similar to store/cstore, but all data is stored in a
11277: temporary location and can be reset using tmpreset, $storehash should
11278: be a hash reference, returns nothing on success
11279:
11280: =item *
11281:
11282: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11283: similar to restore, but all data is stored in a temporary location and
11284: can be reset using tmpreset. Returns a hash of values on success,
11285: error string otherwise.
11286:
11287: =item *
11288:
11289: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11290: deltes all keys for $symb form the temporary storage hash.
11291:
11292: =item *
11293:
11294: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11295: reference filled in from namesp ($udom and $uname are optional)
11296:
11297: =item *
11298:
11299: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11300: namesp ($udom and $uname are optional)
11301:
11302: =item *
11303:
11304: dump($namespace,$udom,$uname,$regexp,$range) :
11305: dumps the complete (or key matching regexp) namespace into a hash
11306: ($udom, $uname, $regexp, $range are optional)
11307:
11308: $range should be either an integer '100' (give me the first 100
11309: matching records)
11310: or be two integers sperated by a - with no spaces
11311: '30-50' (give me the 30th through the 50th matching
11312: records)
11313: =item *
11314:
11315: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11316: $store can be a scalar, an array reference, or if the amount to be
11317: incremented is > 1, a hash reference.
11318:
11319: ($udom and $uname are optional)
11320:
11321: =item *
11322:
11323: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11324: ($udom and $uname are optional)
11325:
11326: =item *
11327:
11328: cput($namespace,$storehash,$udom,$uname) : critical put
11329: ($udom and $uname are optional)
11330:
11331: =item *
11332:
11333: newput($namespace,$storehash,$udom,$uname) :
11334:
11335: Attempts to store the items in the $storehash, but only if they don't
11336: currently exist, if this succeeds you can be certain that you have
11337: successfully created a new key value pair in the $namespace db.
11338:
11339:
11340: Args:
11341: $namespace: name of database to store values to
11342: $storehash: hashref to store to the db
11343: $udom: (optional) domain of user containing the db
11344: $uname: (optional) name of user caontaining the db
11345:
11346: Returns:
11347: 'ok' -> succeeded in storing all keys of $storehash
11348: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11349: least <key> already existed in the db (other
11350: requested keys may also already exist)
11351: 'error: <msg>' -> unable to tie the DB or other error occurred
11352: 'con_lost' -> unable to contact request server
11353: 'refused' -> action was not allowed by remote machine
11354:
11355:
11356: =item *
11357:
11358: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11359: reference filled in from namesp (encrypts the return communication)
11360: ($udom and $uname are optional)
11361:
11362: =item *
11363:
11364: log($udom,$name,$home,$message) : write to permanent log for user; use
11365: critical subroutine
11366:
11367: =item *
11368:
11369: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11370: array reference filled in from namespace found in domain level on either
11371: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
11372:
11373: =item *
11374:
11375: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11376: domain level either on specified domain server ($uhome) or primary domain
11377: server ($udom and $uhome are optional)
11378:
11379: =item *
11380:
11381: get_domain_defaults($target_domain) : returns hash with defaults for
11382: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11383: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11384: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11385: Values are retrieved from cache (if current), or from domain's configuration.db
11386: (if available), or lastly from values in lonTabs/dns_domain,tab,
11387: or lonTabs/domain.tab.
11388:
11389: %domdefaults = &get_auth_defaults($target_domain);
11390:
11391: =back
11392:
11393: =head2 Network Status Functions
11394:
11395: =over 4
11396:
11397: =item *
11398:
11399: dirlist($uri) : return directory list based on URI
11400:
11401: =item *
11402:
11403: spareserver() : find server with least workload from spare.tab
11404:
11405:
11406: =item *
11407:
11408: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11409: if there is no corresponding loncapa host.
11410:
11411: =back
11412:
11413:
11414: =head2 Apache Request
11415:
11416: =over 4
11417:
11418: =item *
11419:
11420: ssi($url,%hash) : server side include, does a complete request cycle on url to
11421: localhost, posts hash
11422:
11423: =back
11424:
11425: =head2 Data to String to Data
11426:
11427: =over 4
11428:
11429: =item *
11430:
11431: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11432: and '&' separators, supports elements that are arrayrefs and hashrefs
11433:
11434: =item *
11435:
11436: hashref2str($hashref) : convert a hashref into a string complete with
11437: escaping and '=' and '&' separators, supports elements that are
11438: arrayrefs and hashrefs
11439:
11440: =item *
11441:
11442: arrayref2str($arrayref) : convert an arrayref into a string complete
11443: with escaping and '&' separators, supports elements that are arrayrefs
11444: and hashrefs
11445:
11446: =item *
11447:
11448: str2hash($string) : convert string to hash using unescaping and
11449: splitting on '=' and '&', supports elements that are arrayrefs and
11450: hashrefs
11451:
11452: =item *
11453:
11454: str2array($string) : convert string to hash using unescaping and
11455: splitting on '&', supports elements that are arrayrefs and hashrefs
11456:
11457: =back
11458:
11459: =head2 Logging Routines
11460:
11461: These routines allow one to make log messages in the lonnet.log and
11462: lonnet.perm logfiles.
11463:
11464: =over 4
11465:
11466: =item *
11467:
11468: logtouch() : make sure the logfile, lonnet.log, exists
11469:
11470: =item *
11471:
11472: logthis() : append message to the normal lonnet.log file, it gets
11473: preiodically rolled over and deleted.
11474:
11475: =item *
11476:
11477: logperm() : append a permanent message to lonnet.perm.log, this log
11478: file never gets deleted by any automated portion of the system, only
11479: messages of critical importance should go in here.
11480:
11481: =back
11482:
11483: =head2 General File Helper Routines
11484:
11485: =over 4
11486:
11487: =item *
11488:
11489: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
11490: (a) files in /uploaded
11491: (i) If a local copy of the file exists -
11492: compares modification date of local copy with last-modified date for
11493: definitive version stored on home server for course. If local copy is
11494: stale, requests a new version from the home server and stores it.
11495: If the original has been removed from the home server, then local copy
11496: is unlinked.
11497: (ii) If local copy does not exist -
11498: requests the file from the home server and stores it.
11499:
11500: If $caller is 'uploadrep':
11501: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
11502: for request for files originally uploaded via DOCS.
11503: - returns 'ok' if fresh local copy now available, -1 otherwise.
11504:
11505: Otherwise:
11506: This indicates a call from the content generation phase of the request.
11507: - returns the entire contents of the file or -1.
11508:
11509: (b) files in /res
11510: - returns the entire contents of a file or -1;
11511: it properly subscribes to and replicates the file if neccessary.
11512:
11513:
11514: =item *
11515:
11516: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
11517: reference
11518:
11519: returns either a stat() list of data about the file or an empty list
11520: if the file doesn't exist or couldn't find out about it (connection
11521: problems or user unknown)
11522:
11523: =item *
11524:
11525: filelocation($dir,$file) : returns file system location of a file
11526: based on URI; meant to be "fairly clean" absolute reference, $dir is a
11527: directory that relative $file lookups are to looked in ($dir of /a/dir
11528: and a file of ../bob will become /a/bob)
11529:
11530: =item *
11531:
11532: hreflocation($dir,$file) : returns file system location or a URL; same as
11533: filelocation except for hrefs
11534:
11535: =item *
11536:
11537: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
11538:
11539: =back
11540:
11541: =head2 Usererfile file routines (/uploaded*)
11542:
11543: =over 4
11544:
11545: =item *
11546:
11547: userfileupload(): main rotine for putting a file in a user or course's
11548: filespace, arguments are,
11549:
11550: formname - required - this is the name of the element in $env where the
11551: filename, and the contents of the file to create/modifed exist
11552: the filename is in $env{'form.'.$formname.'.filename'} and the
11553: contents of the file is located in $env{'form.'.$formname}
11554: context - if coursedoc, store the file in the course of the active role
11555: of the current user;
11556: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
11557: if 'canceloverwrite': delete file in tmp/overwrites directory
11558: subdir - required - subdirectory to put the file in under ../userfiles/
11559: if undefined, it will be placed in "unknown"
11560:
11561: (This routine calls clean_filename() to remove any dangerous
11562: characters from the filename, and then calls finuserfileupload() to
11563: complete the transaction)
11564:
11565: returns either the url of the uploaded file (/uploaded/....) if successful
11566: and /adm/notfound.html if unsuccessful
11567:
11568: =item *
11569:
11570: clean_filename(): routine for cleaing a filename up for storage in
11571: userfile space, argument is:
11572:
11573: filename - proposed filename
11574:
11575: returns: the new clean filename
11576:
11577: =item *
11578:
11579: finishuserfileupload(): routine that creates and sends the file to
11580: userspace, probably shouldn't be called directly
11581:
11582: docuname: username or courseid of destination for the file
11583: docudom: domain of user/course of destination for the file
11584: formname: same as for userfileupload()
11585: fname: filename (including subdirectories) for the file
11586: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
11587: allfiles: reference to hash used to store objects found by parser
11588: codebase: reference to hash used for codebases of java objects found by parser
11589: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
11590: thumbheight: height (pixels) of thumbnail to be created for uploaded image
11591: resizewidth: width to be used to resize image using resizeImage from ImageMagick
11592: resizeheight: height to be used to resize image using resizeImage from ImageMagick
11593: context: if 'overwrite', will move the uploaded file from its temporary location to
11594: userfiles to facilitate overwriting a previously uploaded file with same name.
11595: mimetype: reference to scalar to accommodate mime type determined
11596: from File::MMagic if $parser = parse.
11597:
11598: returns either the url of the uploaded file (/uploaded/....) if successful
11599: and /adm/notfound.html if unsuccessful (or an error message if context
11600: was 'overwrite').
11601:
11602:
11603: =item *
11604:
11605: renameuserfile(): renames an existing userfile to a new name
11606:
11607: Args:
11608: docuname: username or courseid of destination for the file
11609: docudom: domain of user/course of destination for the file
11610: old: current file name (including any subdirs under userfiles)
11611: new: desired file name (including any subdirs under userfiles)
11612:
11613: =item *
11614:
11615: mkdiruserfile(): creates a directory is a userfiles dir
11616:
11617: Args:
11618: docuname: username or courseid of destination for the file
11619: docudom: domain of user/course of destination for the file
11620: dir: dir to create (including any subdirs under userfiles)
11621:
11622: =item *
11623:
11624: removeuserfile(): removes a file that exists in userfiles
11625:
11626: Args:
11627: docuname: username or courseid of destination for the file
11628: docudom: domain of user/course of destination for the file
11629: fname: filname to delete (including any subdirs under userfiles)
11630:
11631: =item *
11632:
11633: removeuploadedurl(): convience function for removeuserfile()
11634:
11635: Args:
11636: url: a full /uploaded/... url to delete
11637:
11638: =item *
11639:
11640: get_portfile_permissions():
11641: Args:
11642: domain: domain of user or course contain the portfolio files
11643: user: name of user or num of course contain the portfolio files
11644: Returns:
11645: hashref of a dump of the proper file_permissions.db
11646:
11647:
11648: =item *
11649:
11650: get_access_controls():
11651:
11652: Args:
11653: current_permissions: the hash ref returned from get_portfile_permissions()
11654: group: (optional) the group you want the files associated with
11655: file: (optional) the file you want access info on
11656:
11657: Returns:
11658: a hash (keys are file names) of hashes containing
11659: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
11660: values are XML containing access control settings (see below)
11661:
11662: Internal notes:
11663:
11664: access controls are stored in file_permissions.db as key=value pairs.
11665: key -> path to file/file_name\0uniqueID:scope_end_start
11666: where scope -> public,guest,course,group,domains or users.
11667: end -> UNIX time for end of access (0 -> no end date)
11668: start -> UNIX time for start of access
11669:
11670: value -> XML description of access control
11671: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
11672: <start></start>
11673: <end></end>
11674:
11675: <password></password> for scope type = guest
11676:
11677: <domain></domain> for scope type = course or group
11678: <number></number>
11679: <roles id="">
11680: <role></role>
11681: <access></access>
11682: <section></section>
11683: <group></group>
11684: </roles>
11685:
11686: <dom></dom> for scope type = domains
11687:
11688: <users> for scope type = users
11689: <user>
11690: <uname></uname>
11691: <udom></udom>
11692: </user>
11693: </users>
11694: </scope>
11695:
11696: Access data is also aggregated for each file in an additional key=value pair:
11697: key -> path to file/file_name\0accesscontrol
11698: value -> reference to hash
11699: hash contains key = value pairs
11700: where key = uniqueID:scope_end_start
11701: value = UNIX time record was last updated
11702:
11703: Used to improve speed of look-ups of access controls for each file.
11704:
11705: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11706:
11707: modify_access_controls():
11708:
11709: Modifies access controls for a portfolio file
11710: Args
11711: 1. file name
11712: 2. reference to hash of required changes,
11713: 3. domain
11714: 4. username
11715: where domain,username are the domain of the portfolio owner
11716: (either a user or a course)
11717:
11718: Returns:
11719: 1. result of additions or updates ('ok' or 'error', with error message).
11720: 2. result of deletions ('ok' or 'error', with error message).
11721: 3. reference to hash of any new or updated access controls.
11722: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11723: key = integer (inbound ID)
11724: value = uniqueID
11725:
11726: =back
11727:
11728: =head2 HTTP Helper Routines
11729:
11730: =over 4
11731:
11732: =item *
11733:
11734: escape() : unpack non-word characters into CGI-compatible hex codes
11735:
11736: =item *
11737:
11738: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11739:
11740: =back
11741:
11742: =head1 PRIVATE SUBROUTINES
11743:
11744: =head2 Underlying communication routines (Shouldn't call)
11745:
11746: =over 4
11747:
11748: =item *
11749:
11750: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11751:
11752: =item *
11753:
11754: reply() : uses subreply to send a message to remote machine, logs all failures
11755:
11756: =item *
11757:
11758: critical() : passes a critical message to another server; if cannot
11759: get through then place message in connection buffer directory and
11760: returns con_delayed, if incapable of saving message, returns
11761: con_failed
11762:
11763: =item *
11764:
11765: reconlonc() : tries to reconnect lonc client processes.
11766:
11767: =back
11768:
11769: =head2 Resource Access Logging
11770:
11771: =over 4
11772:
11773: =item *
11774:
11775: flushcourselogs() : flush (save) buffer logs and access logs
11776:
11777: =item *
11778:
11779: courselog($what) : save message for course in hash
11780:
11781: =item *
11782:
11783: courseacclog($what) : save message for course using &courselog(). Perform
11784: special processing for specific resource types (problems, exams, quizzes, etc).
11785:
11786: =item *
11787:
11788: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11789: as a PerlChildExitHandler
11790:
11791: =back
11792:
11793: =head2 Other
11794:
11795: =over 4
11796:
11797: =item *
11798:
11799: symblist($mapname,%newhash) : update symbolic storage links
11800:
11801: =back
11802:
11803: =cut
11804:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>