1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.1056.4.33 2011/10/19 16:36:02 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);
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: }
897: } else {
898: ($login_host, $lowest_load) =
899: &compare_server_load($lonhost, $login_host, $lowest_load);
900: if ($login_host eq $lonhost) {
901: $portal_path = '';
902: }
903: }
904: } else {
905: ($login_host, $lowest_load) =
906: &compare_server_load($lonhost, $login_host, $lowest_load);
907: }
908: }
909: if ($login_host ne '') {
910: $hostname = &hostname($login_host);
911: }
912: return ($login_host,$hostname);
913: }
914:
915: # --------------------------------------------- Try to change a user's password
916:
917: sub changepass {
918: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
919: $currentpass = &escape($currentpass);
920: $newpass = &escape($newpass);
921: my $lonhost = $perlvar{'lonHostID'};
922: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
923: $server);
924: if (! $answer) {
925: &logthis("No reply on password change request to $server ".
926: "by $uname in domain $udom.");
927: } elsif ($answer =~ "^ok") {
928: &logthis("$uname in $udom successfully changed their password ".
929: "on $server.");
930: } elsif ($answer =~ "^pwchange_failure") {
931: &logthis("$uname in $udom was unable to change their password ".
932: "on $server. The action was blocked by either lcpasswd ".
933: "or pwchange");
934: } elsif ($answer =~ "^non_authorized") {
935: &logthis("$uname in $udom did not get their password correct when ".
936: "attempting to change it on $server.");
937: } elsif ($answer =~ "^auth_mode_error") {
938: &logthis("$uname in $udom attempted to change their password despite ".
939: "not being locally or internally authenticated on $server.");
940: } elsif ($answer =~ "^unknown_user") {
941: &logthis("$uname in $udom attempted to change their password ".
942: "on $server but were unable to because $server is not ".
943: "their home server.");
944: } elsif ($answer =~ "^refused") {
945: &logthis("$server refused to change $uname in $udom password because ".
946: "it was sent an unencrypted request to change the password.");
947: } elsif ($answer =~ "invalid_client") {
948: &logthis("$server refused to change $uname in $udom password because ".
949: "it was a reset by e-mail originating from an invalid server.");
950: }
951: return $answer;
952: }
953:
954: # ----------------------- Try to determine user's current authentication scheme
955:
956: sub queryauthenticate {
957: my ($uname,$udom)=@_;
958: my $uhome=&homeserver($uname,$udom);
959: if (!$uhome) {
960: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
961: return 'no_host';
962: }
963: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
964: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
965: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
966: }
967: return $answer;
968: }
969:
970: # --------- Try to authenticate user from domain's lib servers (first this one)
971:
972: sub authenticate {
973: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
974: $upass=&escape($upass);
975: $uname= &LONCAPA::clean_username($uname);
976: my $uhome=&homeserver($uname,$udom,1);
977: my $newhome;
978: if ((!$uhome) || ($uhome eq 'no_host')) {
979: # Maybe the machine was offline and only re-appeared again recently?
980: &reconlonc();
981: # One more
982: $uhome=&homeserver($uname,$udom,1);
983: if (($uhome eq 'no_host') && $checkdefauth) {
984: if (defined(&domain($udom,'primary'))) {
985: $newhome=&domain($udom,'primary');
986: }
987: if ($newhome ne '') {
988: $uhome = $newhome;
989: }
990: }
991: if ((!$uhome) || ($uhome eq 'no_host')) {
992: &logthis("User $uname at $udom is unknown in authenticate");
993: return 'no_host';
994: }
995: }
996: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
997: if ($answer eq 'authorized') {
998: if ($newhome) {
999: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1000: return 'no_account_on_host';
1001: } else {
1002: &logthis("User $uname at $udom authorized by $uhome");
1003: return $uhome;
1004: }
1005: }
1006: if ($answer eq 'non_authorized') {
1007: &logthis("User $uname at $udom rejected by $uhome");
1008: return 'no_host';
1009: }
1010: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1011: return 'no_host';
1012: }
1013:
1014: sub can_host_session {
1015: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1016: my $canhost = 1;
1017: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1018: if (ref($remotesessions) eq 'HASH') {
1019: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1020: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1021: $canhost = 0;
1022: } else {
1023: $canhost = 1;
1024: }
1025: }
1026: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1027: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1028: $canhost = 1;
1029: } else {
1030: $canhost = 0;
1031: }
1032: }
1033: if ($canhost) {
1034: if ($remotesessions->{'version'} ne '') {
1035: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1036: if ($reqmajor ne '' && $reqminor ne '') {
1037: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1038: my $major = $1;
1039: my $minor = $2;
1040: if (($major < $reqmajor ) ||
1041: (($major == $reqmajor) && ($minor < $reqminor))) {
1042: $canhost = 0;
1043: }
1044: } else {
1045: $canhost = 0;
1046: }
1047: }
1048: }
1049: }
1050: }
1051: if ($canhost) {
1052: if (ref($hostedsessions) eq 'HASH') {
1053: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1054: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1055: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1056: if (($uint_dom ne '') &&
1057: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1058: $canhost = 0;
1059: } else {
1060: $canhost = 1;
1061: }
1062: }
1063: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1064: if (($uint_dom ne '') &&
1065: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1066: $canhost = 1;
1067: } else {
1068: $canhost = 0;
1069: }
1070: }
1071: }
1072: }
1073: return $canhost;
1074: }
1075:
1076: sub spare_can_host {
1077: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1078: my $canhost=1;
1079: my @intdoms;
1080: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1081: if (ref($internet_names) eq 'ARRAY') {
1082: @intdoms = @{$internet_names};
1083: }
1084: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1085: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1086: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1087: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1088: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1089: $canhost = &can_host_session($udom,$try_server,$remoterev,
1090: $remotesessions,
1091: $defdomdefaults{'hostedsessions'});
1092: }
1093: return $canhost;
1094: }
1095:
1096: # ---------------------- Find the homebase for a user from domain's lib servers
1097:
1098: my %homecache;
1099: sub homeserver {
1100: my ($uname,$udom,$ignoreBadCache)=@_;
1101: my $index="$uname:$udom";
1102:
1103: if (exists($homecache{$index})) { return $homecache{$index}; }
1104:
1105: my %servers = &get_servers($udom,'library');
1106: foreach my $tryserver (keys(%servers)) {
1107: next if ($ignoreBadCache ne 'true' &&
1108: exists($badServerCache{$tryserver}));
1109:
1110: my $answer=reply("home:$udom:$uname",$tryserver);
1111: if ($answer eq 'found') {
1112: delete($badServerCache{$tryserver});
1113: return $homecache{$index}=$tryserver;
1114: } elsif ($answer eq 'no_host') {
1115: $badServerCache{$tryserver}=1;
1116: }
1117: }
1118: return 'no_host';
1119: }
1120:
1121: # ------------------------------------- Find the usernames behind a list of IDs
1122:
1123: sub idget {
1124: my ($udom,@ids)=@_;
1125: my %returnhash=();
1126:
1127: my %servers = &get_servers($udom,'library');
1128: foreach my $tryserver (keys(%servers)) {
1129: my $idlist=join('&',@ids);
1130: $idlist=~tr/A-Z/a-z/;
1131: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1132: my @answer=();
1133: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1134: @answer=split(/\&/,$reply);
1135: } ;
1136: my $i;
1137: for ($i=0;$i<=$#ids;$i++) {
1138: if ($answer[$i]) {
1139: $returnhash{$ids[$i]}=$answer[$i];
1140: }
1141: }
1142: }
1143: return %returnhash;
1144: }
1145:
1146: # ------------------------------------- Find the IDs behind a list of usernames
1147:
1148: sub idrget {
1149: my ($udom,@unames)=@_;
1150: my %returnhash=();
1151: foreach my $uname (@unames) {
1152: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1153: }
1154: return %returnhash;
1155: }
1156:
1157: # ------------------------------- Store away a list of names and associated IDs
1158:
1159: sub idput {
1160: my ($udom,%ids)=@_;
1161: my %servers=();
1162: foreach my $uname (keys(%ids)) {
1163: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1164: my $uhom=&homeserver($uname,$udom);
1165: if ($uhom ne 'no_host') {
1166: my $id=&escape($ids{$uname});
1167: $id=~tr/A-Z/a-z/;
1168: my $esc_unam=&escape($uname);
1169: if ($servers{$uhom}) {
1170: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1171: } else {
1172: $servers{$uhom}=$id.'='.$esc_unam;
1173: }
1174: }
1175: }
1176: foreach my $server (keys(%servers)) {
1177: &critical('idput:'.$udom.':'.$servers{$server},$server);
1178: }
1179: }
1180:
1181: # ------------------------------dump from db file owned by domainconfig user
1182: sub dump_dom {
1183: my ($namespace,$udom,$regexp,$range)=@_;
1184: if (!$udom) {
1185: $udom=$env{'user.domain'};
1186: }
1187: my %returnhash;
1188: if ($udom) {
1189: my $uname = &get_domainconfiguser($udom);
1190: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1191: }
1192: return %returnhash;
1193: }
1194:
1195: # ------------------------------------------ get items from domain db files
1196:
1197: sub get_dom {
1198: my ($namespace,$storearr,$udom,$uhome)=@_;
1199: my $items='';
1200: foreach my $item (@$storearr) {
1201: $items.=&escape($item).'&';
1202: }
1203: $items=~s/\&$//;
1204: if (!$udom) {
1205: $udom=$env{'user.domain'};
1206: if (defined(&domain($udom,'primary'))) {
1207: $uhome=&domain($udom,'primary');
1208: } else {
1209: undef($uhome);
1210: }
1211: } else {
1212: if (!$uhome) {
1213: if (defined(&domain($udom,'primary'))) {
1214: $uhome=&domain($udom,'primary');
1215: }
1216: }
1217: }
1218: if ($udom && $uhome && ($uhome ne 'no_host')) {
1219: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1220: my %returnhash;
1221: if ($rep eq '' || $rep =~ /^error: 2 /) {
1222: return %returnhash;
1223: }
1224: my @pairs=split(/\&/,$rep);
1225: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1226: return @pairs;
1227: }
1228: my $i=0;
1229: foreach my $item (@$storearr) {
1230: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1231: $i++;
1232: }
1233: return %returnhash;
1234: } else {
1235: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1236: }
1237: }
1238:
1239: # -------------------------------------------- put items in domain db files
1240:
1241: sub put_dom {
1242: my ($namespace,$storehash,$udom,$uhome)=@_;
1243: if (!$udom) {
1244: $udom=$env{'user.domain'};
1245: if (defined(&domain($udom,'primary'))) {
1246: $uhome=&domain($udom,'primary');
1247: } else {
1248: undef($uhome);
1249: }
1250: } else {
1251: if (!$uhome) {
1252: if (defined(&domain($udom,'primary'))) {
1253: $uhome=&domain($udom,'primary');
1254: }
1255: }
1256: }
1257: if ($udom && $uhome && ($uhome ne 'no_host')) {
1258: my $items='';
1259: foreach my $item (keys(%$storehash)) {
1260: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1261: }
1262: $items=~s/\&$//;
1263: return &reply("putdom:$udom:$namespace:$items",$uhome);
1264: } else {
1265: &logthis("put_dom failed - no homeserver and/or domain");
1266: }
1267: }
1268:
1269: # --------------------- newput for items in db file owned by domainconfig user
1270: sub newput_dom {
1271: my ($namespace,$storehash,$udom) = @_;
1272: my $result;
1273: if (!$udom) {
1274: $udom=$env{'user.domain'};
1275: }
1276: if ($udom) {
1277: my $uname = &get_domainconfiguser($udom);
1278: $result = &newput($namespace,$storehash,$udom,$uname);
1279: }
1280: return $result;
1281: }
1282:
1283: # --------------------- delete for items in db file owned by domainconfig user
1284: sub del_dom {
1285: my ($namespace,$storearr,$udom)=@_;
1286: if (ref($storearr) eq 'ARRAY') {
1287: if (!$udom) {
1288: $udom=$env{'user.domain'};
1289: }
1290: if ($udom) {
1291: my $uname = &get_domainconfiguser($udom);
1292: return &del($namespace,$storearr,$udom,$uname);
1293: }
1294: }
1295: }
1296:
1297: # ----------------------------------construct domainconfig user for a domain
1298: sub get_domainconfiguser {
1299: my ($udom) = @_;
1300: return $udom.'-domainconfig';
1301: }
1302:
1303: sub retrieve_inst_usertypes {
1304: my ($udom) = @_;
1305: my (%returnhash,@order);
1306: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1307: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1308: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1309: %returnhash = %{$domdefs{'inststatustypes'}};
1310: @order = @{$domdefs{'inststatusorder'}};
1311: } else {
1312: if (defined(&domain($udom,'primary'))) {
1313: my $uhome=&domain($udom,'primary');
1314: my $rep=&reply("inst_usertypes:$udom",$uhome);
1315: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1316: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1317: return (\%returnhash,\@order);
1318: }
1319: my ($hashitems,$orderitems) = split(/:/,$rep);
1320: my @pairs=split(/\&/,$hashitems);
1321: foreach my $item (@pairs) {
1322: my ($key,$value)=split(/=/,$item,2);
1323: $key = &unescape($key);
1324: next if ($key =~ /^error: 2 /);
1325: $returnhash{$key}=&thaw_unescape($value);
1326: }
1327: my @esc_order = split(/\&/,$orderitems);
1328: foreach my $item (@esc_order) {
1329: push(@order,&unescape($item));
1330: }
1331: } else {
1332: &logthis("get_dom failed - no primary domain server for $udom");
1333: }
1334: }
1335: return (\%returnhash,\@order);
1336: }
1337:
1338: sub is_domainimage {
1339: my ($url) = @_;
1340: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1341: if (&domain($1) ne '') {
1342: return '1';
1343: }
1344: }
1345: return;
1346: }
1347:
1348: sub inst_directory_query {
1349: my ($srch) = @_;
1350: my $udom = $srch->{'srchdomain'};
1351: my %results;
1352: my $homeserver = &domain($udom,'primary');
1353: my $outcome;
1354: if ($homeserver ne '') {
1355: my $queryid=&reply("querysend:instdirsearch:".
1356: &escape($srch->{'srchby'}).':'.
1357: &escape($srch->{'srchterm'}).':'.
1358: &escape($srch->{'srchtype'}),$homeserver);
1359: my $host=&hostname($homeserver);
1360: if ($queryid !~/^\Q$host\E\_/) {
1361: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1362: return;
1363: }
1364: my $response = &get_query_reply($queryid);
1365: my $maxtries = 5;
1366: my $tries = 1;
1367: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1368: $response = &get_query_reply($queryid);
1369: $tries ++;
1370: }
1371:
1372: if (!&error($response) && $response ne 'refused') {
1373: if ($response eq 'unavailable') {
1374: $outcome = $response;
1375: } else {
1376: $outcome = 'ok';
1377: my @matches = split(/\n/,$response);
1378: foreach my $match (@matches) {
1379: my ($key,$value) = split(/=/,$match);
1380: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1381: }
1382: }
1383: }
1384: }
1385: return ($outcome,%results);
1386: }
1387:
1388: sub usersearch {
1389: my ($srch) = @_;
1390: my $dom = $srch->{'srchdomain'};
1391: my %results;
1392: my %libserv = &all_library();
1393: my $query = 'usersearch';
1394: foreach my $tryserver (keys(%libserv)) {
1395: if (&host_domain($tryserver) eq $dom) {
1396: my $host=&hostname($tryserver);
1397: my $queryid=
1398: &reply("querysend:".&escape($query).':'.
1399: &escape($srch->{'srchby'}).':'.
1400: &escape($srch->{'srchtype'}).':'.
1401: &escape($srch->{'srchterm'}),$tryserver);
1402: if ($queryid !~/^\Q$host\E\_/) {
1403: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1404: next;
1405: }
1406: my $reply = &get_query_reply($queryid);
1407: my $maxtries = 1;
1408: my $tries = 1;
1409: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1410: $reply = &get_query_reply($queryid);
1411: $tries ++;
1412: }
1413: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1414: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1415: } else {
1416: my @matches;
1417: if ($reply =~ /\n/) {
1418: @matches = split(/\n/,$reply);
1419: } else {
1420: @matches = split(/\&/,$reply);
1421: }
1422: foreach my $match (@matches) {
1423: my ($uname,$udom,%userhash);
1424: foreach my $entry (split(/:/,$match)) {
1425: my ($key,$value) =
1426: map {&unescape($_);} split(/=/,$entry);
1427: $userhash{$key} = $value;
1428: if ($key eq 'username') {
1429: $uname = $value;
1430: } elsif ($key eq 'domain') {
1431: $udom = $value;
1432: }
1433: }
1434: $results{$uname.':'.$udom} = \%userhash;
1435: }
1436: }
1437: }
1438: }
1439: return %results;
1440: }
1441:
1442: sub get_instuser {
1443: my ($udom,$uname,$id) = @_;
1444: my $homeserver = &domain($udom,'primary');
1445: my ($outcome,%results);
1446: if ($homeserver ne '') {
1447: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1448: &escape($id).':'.&escape($udom),$homeserver);
1449: my $host=&hostname($homeserver);
1450: if ($queryid !~/^\Q$host\E\_/) {
1451: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1452: return;
1453: }
1454: my $response = &get_query_reply($queryid);
1455: my $maxtries = 5;
1456: my $tries = 1;
1457: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1458: $response = &get_query_reply($queryid);
1459: $tries ++;
1460: }
1461: if (!&error($response) && $response ne 'refused') {
1462: if ($response eq 'unavailable') {
1463: $outcome = $response;
1464: } else {
1465: $outcome = 'ok';
1466: my @matches = split(/\n/,$response);
1467: foreach my $match (@matches) {
1468: my ($key,$value) = split(/=/,$match);
1469: $results{&unescape($key)} = &thaw_unescape($value);
1470: }
1471: }
1472: }
1473: }
1474: my %userinfo;
1475: if (ref($results{$uname}) eq 'HASH') {
1476: %userinfo = %{$results{$uname}};
1477: }
1478: return ($outcome,%userinfo);
1479: }
1480:
1481: sub inst_rulecheck {
1482: my ($udom,$uname,$id,$item,$rules) = @_;
1483: my %returnhash;
1484: if ($udom ne '') {
1485: if (ref($rules) eq 'ARRAY') {
1486: @{$rules} = map {&escape($_);} (@{$rules});
1487: my $rulestr = join(':',@{$rules});
1488: my $homeserver=&domain($udom,'primary');
1489: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1490: my $response;
1491: if ($item eq 'username') {
1492: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1493: ':'.&escape($uname).':'.$rulestr,
1494: $homeserver));
1495: } elsif ($item eq 'id') {
1496: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1497: ':'.&escape($id).':'.$rulestr,
1498: $homeserver));
1499: } elsif ($item eq 'selfcreate') {
1500: $response=&unescape(&reply('instselfcreatecheck:'.
1501: &escape($udom).':'.&escape($uname).
1502: ':'.$rulestr,$homeserver));
1503: }
1504: if ($response ne 'refused') {
1505: my @pairs=split(/\&/,$response);
1506: foreach my $item (@pairs) {
1507: my ($key,$value)=split(/=/,$item,2);
1508: $key = &unescape($key);
1509: next if ($key =~ /^error: 2 /);
1510: $returnhash{$key}=&thaw_unescape($value);
1511: }
1512: }
1513: }
1514: }
1515: }
1516: return %returnhash;
1517: }
1518:
1519: sub inst_userrules {
1520: my ($udom,$check) = @_;
1521: my (%ruleshash,@ruleorder);
1522: if ($udom ne '') {
1523: my $homeserver=&domain($udom,'primary');
1524: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1525: my $response;
1526: if ($check eq 'id') {
1527: $response=&reply('instidrules:'.&escape($udom),
1528: $homeserver);
1529: } elsif ($check eq 'email') {
1530: $response=&reply('instemailrules:'.&escape($udom),
1531: $homeserver);
1532: } else {
1533: $response=&reply('instuserrules:'.&escape($udom),
1534: $homeserver);
1535: }
1536: if (($response ne 'refused') && ($response ne 'error') &&
1537: ($response ne 'unknown_cmd') &&
1538: ($response ne 'no_such_host')) {
1539: my ($hashitems,$orderitems) = split(/:/,$response);
1540: my @pairs=split(/\&/,$hashitems);
1541: foreach my $item (@pairs) {
1542: my ($key,$value)=split(/=/,$item,2);
1543: $key = &unescape($key);
1544: next if ($key =~ /^error: 2 /);
1545: $ruleshash{$key}=&thaw_unescape($value);
1546: }
1547: my @esc_order = split(/\&/,$orderitems);
1548: foreach my $item (@esc_order) {
1549: push(@ruleorder,&unescape($item));
1550: }
1551: }
1552: }
1553: }
1554: return (\%ruleshash,\@ruleorder);
1555: }
1556:
1557: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1558:
1559: sub get_domain_defaults {
1560: my ($domain) = @_;
1561: my $cachetime = 60*60*24;
1562: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1563: if (defined($cached)) {
1564: if (ref($result) eq 'HASH') {
1565: return %{$result};
1566: }
1567: }
1568: my %domdefaults;
1569: my %domconfig =
1570: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1571: 'requestcourses','inststatus',
1572: 'coursedefaults','usersessions'],$domain);
1573: if (ref($domconfig{'defaults'}) eq 'HASH') {
1574: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1575: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1576: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1577: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1578: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1579: } else {
1580: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1581: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1582: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1583: }
1584: if (ref($domconfig{'quotas'}) eq 'HASH') {
1585: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1586: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1587: } else {
1588: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1589: }
1590: my @usertools = ('aboutme','blog','portfolio');
1591: foreach my $item (@usertools) {
1592: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1593: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1594: }
1595: }
1596: }
1597: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1598: foreach my $item ('official','unofficial','community') {
1599: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1600: }
1601: }
1602: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1603: foreach my $item ('inststatustypes','inststatusorder') {
1604: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1605: }
1606: }
1607: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1608: foreach my $item ('canuse_pdfforms') {
1609: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1610: }
1611: }
1612: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1613: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1614: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1615: }
1616: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1617: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1618: }
1619: }
1620: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1621: $cachetime);
1622: return %domdefaults;
1623: }
1624:
1625: # --------------------------------------------------- Assign a key to a student
1626:
1627: sub assign_access_key {
1628: #
1629: # a valid key looks like uname:udom#comments
1630: # comments are being appended
1631: #
1632: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1633: $kdom=
1634: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1635: $knum=
1636: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1637: $cdom=
1638: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1639: $cnum=
1640: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1641: $udom=$env{'user.name'} unless (defined($udom));
1642: $uname=$env{'user.domain'} unless (defined($uname));
1643: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1644: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1645: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1646: # assigned to this person
1647: # - this should not happen,
1648: # unless something went wrong
1649: # the first time around
1650: # ready to assign
1651: $logentry=$1.'; '.$logentry;
1652: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1653: $kdom,$knum) eq 'ok') {
1654: # key now belongs to user
1655: my $envkey='key.'.$cdom.'_'.$cnum;
1656: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1657: &appenv({'environment.'.$envkey => $ckey});
1658: return 'ok';
1659: } else {
1660: return
1661: 'error: Count not permanently assign key, will need to be re-entered later.';
1662: }
1663: } else {
1664: return 'error: Could not assign key, try again later.';
1665: }
1666: } elsif (!$existing{$ckey}) {
1667: # the key does not exist
1668: return 'error: The key does not exist';
1669: } else {
1670: # the key is somebody else's
1671: return 'error: The key is already in use';
1672: }
1673: }
1674:
1675: # ------------------------------------------ put an additional comment on a key
1676:
1677: sub comment_access_key {
1678: #
1679: # a valid key looks like uname:udom#comments
1680: # comments are being appended
1681: #
1682: my ($ckey,$cdom,$cnum,$logentry)=@_;
1683: $cdom=
1684: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1685: $cnum=
1686: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1687: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1688: if ($existing{$ckey}) {
1689: $existing{$ckey}.='; '.$logentry;
1690: # ready to assign
1691: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1692: $cdom,$cnum) eq 'ok') {
1693: return 'ok';
1694: } else {
1695: return 'error: Count not store comment.';
1696: }
1697: } else {
1698: # the key does not exist
1699: return 'error: The key does not exist';
1700: }
1701: }
1702:
1703: # ------------------------------------------------------ Generate a set of keys
1704:
1705: sub generate_access_keys {
1706: my ($number,$cdom,$cnum,$logentry)=@_;
1707: $cdom=
1708: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1709: $cnum=
1710: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1711: unless (&allowed('mky',$cdom)) { return 0; }
1712: unless (($cdom) && ($cnum)) { return 0; }
1713: if ($number>10000) { return 0; }
1714: sleep(2); # make sure don't get same seed twice
1715: srand(time()^($$+($$<<15))); # from "Programming Perl"
1716: my $total=0;
1717: for (my $i=1;$i<=$number;$i++) {
1718: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1719: sprintf("%lx",int(100000*rand)).'-'.
1720: sprintf("%lx",int(100000*rand));
1721: $newkey=~s/1/g/g; # folks mix up 1 and l
1722: $newkey=~s/0/h/g; # and also 0 and O
1723: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1724: if ($existing{$newkey}) {
1725: $i--;
1726: } else {
1727: if (&put('accesskeys',
1728: { $newkey => '# generated '.localtime().
1729: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1730: '; '.$logentry },
1731: $cdom,$cnum) eq 'ok') {
1732: $total++;
1733: }
1734: }
1735: }
1736: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1737: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1738: return $total;
1739: }
1740:
1741: # ------------------------------------------------------- Validate an accesskey
1742:
1743: sub validate_access_key {
1744: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1745: $cdom=
1746: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1747: $cnum=
1748: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1749: $udom=$env{'user.domain'} unless (defined($udom));
1750: $uname=$env{'user.name'} unless (defined($uname));
1751: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1752: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1753: }
1754:
1755: # ------------------------------------- Find the section of student in a course
1756: sub devalidate_getsection_cache {
1757: my ($udom,$unam,$courseid)=@_;
1758: my $hashid="$udom:$unam:$courseid";
1759: &devalidate_cache_new('getsection',$hashid);
1760: }
1761:
1762: sub courseid_to_courseurl {
1763: my ($courseid) = @_;
1764: #already url style courseid
1765: return $courseid if ($courseid =~ m{^/});
1766:
1767: if (exists($env{'course.'.$courseid.'.num'})) {
1768: my $cnum = $env{'course.'.$courseid.'.num'};
1769: my $cdom = $env{'course.'.$courseid.'.domain'};
1770: return "/$cdom/$cnum";
1771: }
1772:
1773: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1774: if (exists($courseinfo{'num'})) {
1775: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1776: }
1777:
1778: return undef;
1779: }
1780:
1781: sub getsection {
1782: my ($udom,$unam,$courseid)=@_;
1783: my $cachetime=1800;
1784:
1785: my $hashid="$udom:$unam:$courseid";
1786: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1787: if (defined($cached)) { return $result; }
1788:
1789: my %Pending;
1790: my %Expired;
1791: #
1792: # Each role can either have not started yet (pending), be active,
1793: # or have expired.
1794: #
1795: # If there is an active role, we are done.
1796: #
1797: # If there is more than one role which has not started yet,
1798: # choose the one which will start sooner
1799: # If there is one role which has not started yet, return it.
1800: #
1801: # If there is more than one expired role, choose the one which ended last.
1802: # If there is a role which has expired, return it.
1803: #
1804: $courseid = &courseid_to_courseurl($courseid);
1805: my $extra = &freeze_escape({'skipcheck' => 1});
1806: my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1807: foreach my $key (keys(%roleshash)) {
1808: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1809: my $section=$1;
1810: if ($key eq $courseid.'_st') { $section=''; }
1811: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1812: my $now=time;
1813: if (defined($end) && $end && ($now > $end)) {
1814: $Expired{$end}=$section;
1815: next;
1816: }
1817: if (defined($start) && $start && ($now < $start)) {
1818: $Pending{$start}=$section;
1819: next;
1820: }
1821: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1822: }
1823: #
1824: # Presumedly there will be few matching roles from the above
1825: # loop and the sorting time will be negligible.
1826: if (scalar(keys(%Pending))) {
1827: my ($time) = sort {$a <=> $b} keys(%Pending);
1828: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1829: }
1830: if (scalar(keys(%Expired))) {
1831: my @sorted = sort {$a <=> $b} keys(%Expired);
1832: my $time = pop(@sorted);
1833: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1834: }
1835: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1836: }
1837:
1838: sub save_cache {
1839: &purge_remembered();
1840: #&Apache::loncommon::validate_page();
1841: undef(%env);
1842: undef($env_loaded);
1843: }
1844:
1845: my $to_remember=-1;
1846: my %remembered;
1847: my %accessed;
1848: my $kicks=0;
1849: my $hits=0;
1850: sub make_key {
1851: my ($name,$id) = @_;
1852: if (length($id) > 65
1853: && length(&escape($id)) > 200) {
1854: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1855: }
1856: return &escape($name.':'.$id);
1857: }
1858:
1859: sub devalidate_cache_new {
1860: my ($name,$id,$debug) = @_;
1861: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1862: $id=&make_key($name,$id);
1863: $memcache->delete($id);
1864: delete($remembered{$id});
1865: delete($accessed{$id});
1866: }
1867:
1868: sub is_cached_new {
1869: my ($name,$id,$debug) = @_;
1870: $id=&make_key($name,$id);
1871: if (exists($remembered{$id})) {
1872: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1873: $accessed{$id}=[&gettimeofday()];
1874: $hits++;
1875: return ($remembered{$id},1);
1876: }
1877: my $value = $memcache->get($id);
1878: if (!(defined($value))) {
1879: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1880: return (undef,undef);
1881: }
1882: if ($value eq '__undef__') {
1883: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1884: $value=undef;
1885: }
1886: &make_room($id,$value,$debug);
1887: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1888: return ($value,1);
1889: }
1890:
1891: sub do_cache_new {
1892: my ($name,$id,$value,$time,$debug) = @_;
1893: $id=&make_key($name,$id);
1894: my $setvalue=$value;
1895: if (!defined($setvalue)) {
1896: $setvalue='__undef__';
1897: }
1898: if (!defined($time) ) {
1899: $time=600;
1900: }
1901: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1902: my $result = $memcache->set($id,$setvalue,$time);
1903: if (! $result) {
1904: &logthis("caching of id -> $id failed");
1905: $memcache->disconnect_all();
1906: }
1907: # need to make a copy of $value
1908: &make_room($id,$value,$debug);
1909: return $value;
1910: }
1911:
1912: sub make_room {
1913: my ($id,$value,$debug)=@_;
1914:
1915: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1916: : $value;
1917: if ($to_remember<0) { return; }
1918: $accessed{$id}=[&gettimeofday()];
1919: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1920: my $to_kick;
1921: my $max_time=0;
1922: foreach my $other (keys(%accessed)) {
1923: if (&tv_interval($accessed{$other}) > $max_time) {
1924: $to_kick=$other;
1925: $max_time=&tv_interval($accessed{$other});
1926: }
1927: }
1928: delete($remembered{$to_kick});
1929: delete($accessed{$to_kick});
1930: $kicks++;
1931: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1932: return;
1933: }
1934:
1935: sub purge_remembered {
1936: #&logthis("Tossing ".scalar(keys(%remembered)));
1937: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1938: undef(%remembered);
1939: undef(%accessed);
1940: }
1941: # ------------------------------------- Read an entry from a user's environment
1942:
1943: sub userenvironment {
1944: my ($udom,$unam,@what)=@_;
1945: my $items;
1946: foreach my $item (@what) {
1947: $items.=&escape($item).'&';
1948: }
1949: $items=~s/\&$//;
1950: my %returnhash=();
1951: my $uhome = &homeserver($unam,$udom);
1952: unless ($uhome eq 'no_host') {
1953: my @answer=split(/\&/,
1954: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1955: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
1956: return %returnhash;
1957: }
1958: my $i;
1959: for ($i=0;$i<=$#what;$i++) {
1960: $returnhash{$what[$i]}=&unescape($answer[$i]);
1961: }
1962: }
1963: return %returnhash;
1964: }
1965:
1966: # ---------------------------------------------------------- Get a studentphoto
1967: sub studentphoto {
1968: my ($udom,$unam,$ext) = @_;
1969: my $home=&Apache::lonnet::homeserver($unam,$udom);
1970: if (defined($env{'request.course.id'})) {
1971: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1972: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1973: return(&retrievestudentphoto($udom,$unam,$ext));
1974: } else {
1975: my ($result,$perm_reqd)=
1976: &Apache::lonnet::auto_photo_permission($unam,$udom);
1977: if ($result eq 'ok') {
1978: if (!($perm_reqd eq 'yes')) {
1979: return(&retrievestudentphoto($udom,$unam,$ext));
1980: }
1981: }
1982: }
1983: }
1984: } else {
1985: my ($result,$perm_reqd) =
1986: &Apache::lonnet::auto_photo_permission($unam,$udom);
1987: if ($result eq 'ok') {
1988: if (!($perm_reqd eq 'yes')) {
1989: return(&retrievestudentphoto($udom,$unam,$ext));
1990: }
1991: }
1992: }
1993: return '/adm/lonKaputt/lonlogo_broken.gif';
1994: }
1995:
1996: sub retrievestudentphoto {
1997: my ($udom,$unam,$ext,$type) = @_;
1998: my $home=&Apache::lonnet::homeserver($unam,$udom);
1999: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2000: if ($ret eq 'ok') {
2001: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2002: if ($type eq 'thumbnail') {
2003: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2004: }
2005: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2006: return $tokenurl;
2007: } else {
2008: if ($type eq 'thumbnail') {
2009: return '/adm/lonKaputt/genericstudent_tn.gif';
2010: } else {
2011: return '/adm/lonKaputt/lonlogo_broken.gif';
2012: }
2013: }
2014: }
2015:
2016: # -------------------------------------------------------------------- New chat
2017:
2018: sub chatsend {
2019: my ($newentry,$anon,$group)=@_;
2020: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2021: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2022: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
2023: &reply('chatsend:'.$cdom.':'.$cnum.':'.
2024: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
2025: &escape($newentry)).':'.$group,$chome);
2026: }
2027:
2028: # ------------------------------------------ Find current version of a resource
2029:
2030: sub getversion {
2031: my $fname=&clutter(shift);
2032: unless ($fname=~/^\/res\//) { return -1; }
2033: return ¤tversion(&filelocation('',$fname));
2034: }
2035:
2036: sub currentversion {
2037: my $fname=shift;
2038: my ($result,$cached)=&is_cached_new('resversion',$fname);
2039: if (defined($cached)) { return $result; }
2040: my $author=$fname;
2041: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2042: my ($udom,$uname)=split(/\//,$author);
2043: my $home=homeserver($uname,$udom);
2044: if ($home eq 'no_host') {
2045: return -1;
2046: }
2047: my $answer=reply("currentversion:$fname",$home);
2048: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2049: return -1;
2050: }
2051: return &do_cache_new('resversion',$fname,$answer,600);
2052: }
2053:
2054: # ----------------------------- Subscribe to a resource, return URL if possible
2055:
2056: sub subscribe {
2057: my $fname=shift;
2058: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
2059: $fname=~s/[\n\r]//g;
2060: my $author=$fname;
2061: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2062: my ($udom,$uname)=split(/\//,$author);
2063: my $home=homeserver($uname,$udom);
2064: if ($home eq 'no_host') {
2065: return 'not_found';
2066: }
2067: my $answer=reply("sub:$fname",$home);
2068: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2069: $answer.=' by '.$home;
2070: }
2071: return $answer;
2072: }
2073:
2074: # -------------------------------------------------------------- Replicate file
2075:
2076: sub repcopy {
2077: my $filename=shift;
2078: $filename=~s/\/+/\//g;
2079: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
2080: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
2081: if ($filename=~m|^/home/httpd/html/userfiles/| or
2082: $filename=~m -^/*(uploaded|editupload)/-) {
2083: return &repcopy_userfile($filename);
2084: }
2085: $filename=~s/[\n\r]//g;
2086: my $transname="$filename.in.transfer";
2087: # FIXME: this should flock
2088: if ((-e $filename) || (-e $transname)) { return 'ok'; }
2089: my $remoteurl=subscribe($filename);
2090: if ($remoteurl =~ /^con_lost by/) {
2091: &logthis("Subscribe returned $remoteurl: $filename");
2092: return 'unavailable';
2093: } elsif ($remoteurl eq 'not_found') {
2094: #&logthis("Subscribe returned not_found: $filename");
2095: return 'not_found';
2096: } elsif ($remoteurl =~ /^rejected by/) {
2097: &logthis("Subscribe returned $remoteurl: $filename");
2098: return 'forbidden';
2099: } elsif ($remoteurl eq 'directory') {
2100: return 'ok';
2101: } else {
2102: my $author=$filename;
2103: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2104: my ($udom,$uname)=split(/\//,$author);
2105: my $home=homeserver($uname,$udom);
2106: unless ($home eq $perlvar{'lonHostID'}) {
2107: my @parts=split(/\//,$filename);
2108: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2109: if ($path ne "$perlvar{'lonDocRoot'}/res") {
2110: &logthis("Malconfiguration for replication: $filename");
2111: return 'bad_request';
2112: }
2113: my $count;
2114: for ($count=5;$count<$#parts;$count++) {
2115: $path.="/$parts[$count]";
2116: if ((-e $path)!=1) {
2117: mkdir($path,0777);
2118: }
2119: }
2120: my $ua=new LWP::UserAgent;
2121: my $request=new HTTP::Request('GET',"$remoteurl");
2122: my $response=$ua->request($request,$transname);
2123: if ($response->is_error()) {
2124: unlink($transname);
2125: my $message=$response->status_line;
2126: &logthis("<font color=\"blue\">WARNING:"
2127: ." LWP get: $message: $filename</font>");
2128: return 'unavailable';
2129: } else {
2130: if ($remoteurl!~/\.meta$/) {
2131: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2132: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2133: if ($mresponse->is_error()) {
2134: unlink($filename.'.meta');
2135: &logthis(
2136: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
2137: }
2138: }
2139: rename($transname,$filename);
2140: return 'ok';
2141: }
2142: }
2143: }
2144: }
2145:
2146: # ------------------------------------------------ Get server side include body
2147: sub ssi_body {
2148: my ($filelink,%form)=@_;
2149: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2150: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2151: }
2152: my $output='';
2153: my $response;
2154: if ($filelink=~/^https?\:/) {
2155: ($output,$response)=&externalssi($filelink);
2156: } else {
2157: $filelink .= $filelink=~/\?/ ? '&' : '?';
2158: $filelink .= 'inhibitmenu=yes';
2159: ($output,$response)=&ssi($filelink,%form);
2160: }
2161: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
2162: $output=~s/^.*?\<body[^\>]*\>//si;
2163: $output=~s/\<\/body\s*\>.*?$//si;
2164: if (wantarray) {
2165: return ($output, $response);
2166: } else {
2167: return $output;
2168: }
2169: }
2170:
2171: # --------------------------------------------------------- Server Side Include
2172:
2173: sub absolute_url {
2174: my ($host_name) = @_;
2175: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2176: if ($host_name eq '') {
2177: $host_name = $ENV{'SERVER_NAME'};
2178: }
2179: return $protocol.$host_name;
2180: }
2181:
2182: #
2183: # Server side include.
2184: # Parameters:
2185: # fn Possibly encrypted resource name/id.
2186: # form Hash that describes how the rendering should be done
2187: # and other things.
2188: # Returns:
2189: # Scalar context: The content of the response.
2190: # Array context: 2 element list of the content and the full response object.
2191: #
2192: sub ssi {
2193:
2194: my ($fn,%form)=@_;
2195: my $ua=new LWP::UserAgent;
2196: my $request;
2197:
2198: $form{'no_update_last_known'}=1;
2199: &Apache::lonenc::check_encrypt(\$fn);
2200: if (%form) {
2201: $request=new HTTP::Request('POST',&absolute_url().$fn);
2202: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
2203: } else {
2204: $request=new HTTP::Request('GET',&absolute_url().$fn);
2205: }
2206:
2207: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2208: my $response=$ua->request($request);
2209:
2210: if (wantarray) {
2211: return ($response->content, $response);
2212: } else {
2213: return $response->content;
2214: }
2215: }
2216:
2217: sub externalssi {
2218: my ($url)=@_;
2219: my $ua=new LWP::UserAgent;
2220: my $request=new HTTP::Request('GET',$url);
2221: my $response=$ua->request($request);
2222: if (wantarray) {
2223: return ($response->content, $response);
2224: } else {
2225: return $response->content;
2226: }
2227: }
2228:
2229: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2230:
2231: sub allowuploaded {
2232: my ($srcurl,$url)=@_;
2233: $url=&clutter(&declutter($url));
2234: my $dir=$url;
2235: $dir=~s/\/[^\/]+$//;
2236: my %httpref=();
2237: my $httpurl=&hreflocation('',$url);
2238: $httpref{'httpref.'.$httpurl}=$srcurl;
2239: &Apache::lonnet::appenv(\%httpref);
2240: }
2241:
2242: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
2243: # input: action, courseID, current domain, intended
2244: # path to file, source of file, instruction to parse file for objects,
2245: # ref to hash for embedded objects,
2246: # ref to hash for codebase of java objects.
2247: # reference to scalar to accommodate mime type determined
2248: # from File::MMagic if $parser = parse.
2249: #
2250: # output: url to file (if action was uploaddoc),
2251: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
2252: #
2253: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2254: # course.
2255: #
2256: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2257: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2258: # course's home server.
2259: #
2260: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2261: # be copied from $source (current location) to
2262: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2263: # and will then be copied to
2264: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2265: # course's home server.
2266: #
2267: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2268: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
2269: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2270: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2271: # in course's home server.
2272: #
2273:
2274: sub process_coursefile {
2275: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2276: $mimetype)=@_;
2277: my $fetchresult;
2278: my $home=&homeserver($docuname,$docudom);
2279: if ($action eq 'propagate') {
2280: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2281: $home);
2282: } else {
2283: my $fpath = '';
2284: my $fname = $file;
2285: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2286: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2287: my $filepath = &build_filepath($fpath);
2288: if ($action eq 'copy') {
2289: if ($source eq '') {
2290: $fetchresult = 'no source file';
2291: return $fetchresult;
2292: } else {
2293: my $destination = $filepath.'/'.$fname;
2294: rename($source,$destination);
2295: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2296: $home);
2297: }
2298: } elsif ($action eq 'uploaddoc') {
2299: open(my $fh,'>'.$filepath.'/'.$fname);
2300: print $fh $env{'form.'.$source};
2301: close($fh);
2302: if ($parser eq 'parse') {
2303: my $mm = new File::MMagic;
2304: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2305: if ($type eq 'text/html') {
2306: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2307: unless ($parse_result eq 'ok') {
2308: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2309: }
2310: }
2311: if (ref($mimetype)) {
2312: $$mimetype = $type;
2313: }
2314: }
2315: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2316: $home);
2317: if ($fetchresult eq 'ok') {
2318: return '/uploaded/'.$fpath.'/'.$fname;
2319: } else {
2320: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2321: ' to host '.$home.': '.$fetchresult);
2322: return '/adm/notfound.html';
2323: }
2324: }
2325: }
2326: unless ( $fetchresult eq 'ok') {
2327: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2328: ' to host '.$home.': '.$fetchresult);
2329: }
2330: return $fetchresult;
2331: }
2332:
2333: sub build_filepath {
2334: my ($fpath) = @_;
2335: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2336: unless ($fpath eq '') {
2337: my @parts=split('/',$fpath);
2338: foreach my $part (@parts) {
2339: $filepath.= '/'.$part;
2340: if ((-e $filepath)!=1) {
2341: mkdir($filepath,0777);
2342: }
2343: }
2344: }
2345: return $filepath;
2346: }
2347:
2348: sub store_edited_file {
2349: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
2350: my $file = $primary_url;
2351: $file =~ s#^/uploaded/$docudom/$docuname/##;
2352: my $fpath = '';
2353: my $fname = $file;
2354: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2355: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2356: my $filepath = &build_filepath($fpath);
2357: open(my $fh,'>'.$filepath.'/'.$fname);
2358: print $fh $content;
2359: close($fh);
2360: my $home=&homeserver($docuname,$docudom);
2361: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2362: $home);
2363: if ($$fetchresult eq 'ok') {
2364: return '/uploaded/'.$fpath.'/'.$fname;
2365: } else {
2366: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2367: ' to host '.$home.': '.$$fetchresult);
2368: return '/adm/notfound.html';
2369: }
2370: }
2371:
2372: sub clean_filename {
2373: my ($fname,$args)=@_;
2374: # Replace Windows backslashes by forward slashes
2375: $fname=~s/\\/\//g;
2376: if (!$args->{'keep_path'}) {
2377: # Get rid of everything but the actual filename
2378: $fname=~s/^.*\/([^\/]+)$/$1/;
2379: }
2380: # Replace spaces by underscores
2381: $fname=~s/\s+/\_/g;
2382: # Replace all other weird characters by nothing
2383: $fname=~s{[^/\w\.\-]}{}g;
2384: # Replace all .\d. sequences with _\d. so they no longer look like version
2385: # numbers
2386: $fname=~s/\.(\d+)(?=\.)/_$1/g;
2387: return $fname;
2388: }
2389: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2390: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2391: # image with the same aspect ratio as the original, but with dimensions which do
2392: # not exceed $resizewidth and $resizeheight.
2393:
2394: sub resizeImage {
2395: my ($img_path,$resizewidth,$resizeheight) = @_;
2396: my $ima = Image::Magick->new;
2397: my $resized;
2398: if (-e $img_path) {
2399: $ima->Read($img_path);
2400: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2401: my $width = $ima->Get('width');
2402: my $height = $ima->Get('height');
2403: if ($width > $resizewidth) {
2404: my $factor = $width/$resizewidth;
2405: my $newheight = $height/$factor;
2406: $ima->Scale(width=>$resizewidth,height=>$newheight);
2407: $resized = 1;
2408: }
2409: }
2410: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2411: my $width = $ima->Get('width');
2412: my $height = $ima->Get('height');
2413: if ($height > $resizeheight) {
2414: my $factor = $height/$resizeheight;
2415: my $newwidth = $width/$factor;
2416: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2417: $resized = 1;
2418: }
2419: }
2420: if ($resized) {
2421: $ima->Write($img_path);
2422: }
2423: }
2424: return;
2425: }
2426:
2427: # --------------- Take an uploaded file and put it into the userfiles directory
2428: # input: $formname - the contents of the file are in $env{"form.$formname"}
2429: # the desired filename is in $env{"form.$formname.filename"}
2430: # $context - possible values: coursedoc, existingfile, overwrite,
2431: # canceloverwrite, or ''.
2432: # if 'coursedoc': upload to the current course
2433: # if 'existingfile': write file to tmp/overwrites directory
2434: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2435: # $context is passed as argument to &finishuserfileupload
2436: # $subdir - directory in userfile to store the file into
2437: # $parser - instruction to parse file for objects ($parser = parse)
2438: # $allfiles - reference to hash for embedded objects
2439: # $codebase - reference to hash for codebase of java objects
2440: # $desuname - username for permanent storage of uploaded file
2441: # $dsetudom - domain for permanaent storage of uploaded file
2442: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2443: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
2444: # $resizewidth - width (pixels) to which to resize uploaded image
2445: # $resizeheight - height (pixels) to which to resize uploaded image
2446: # $mimetype - reference to scalar to accommodate mime type determined
2447: # from File::MMagic if $parser = parse.
2448: #
2449: # output: url of file in userspace, or error: <message>
2450: # or /adm/notfound.html if failure to upload occurse
2451:
2452: sub userfileupload {
2453: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
2454: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
2455: if (!defined($subdir)) { $subdir='unknown'; }
2456: my $fname=$env{'form.'.$formname.'.filename'};
2457: $fname=&clean_filename($fname);
2458: # See if there is anything left
2459: unless ($fname) { return 'error: no uploaded file'; }
2460: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2461: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2462: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2463: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2464: my $now = time;
2465: my $filepath;
2466: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
2467: $filepath = 'tmp/helprequests/'.$now;
2468: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2469: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2470: '_'.$env{'user.domain'}.'/pending';
2471: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2472: my ($docuname,$docudom);
2473: if ($destudom) {
2474: $docudom = $destudom;
2475: } else {
2476: $docudom = $env{'user.domain'};
2477: }
2478: if ($destuname) {
2479: $docuname = $destuname;
2480: } else {
2481: $docuname = $env{'user.name'};
2482: }
2483: if (exists($env{'form.group'})) {
2484: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2485: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2486: }
2487: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2488: if ($context eq 'canceloverwrite') {
2489: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2490: if (-e $tempfile) {
2491: my @info = stat($tempfile);
2492: if ($info[9] eq $env{'form.timestamp'}) {
2493: unlink($tempfile);
2494: }
2495: }
2496: return;
2497: }
2498: }
2499: # Create the directory if not present
2500: my @parts=split(/\//,$filepath);
2501: my $fullpath = $perlvar{'lonDaemons'};
2502: for (my $i=0;$i<@parts;$i++) {
2503: $fullpath .= '/'.$parts[$i];
2504: if ((-e $fullpath)!=1) {
2505: mkdir($fullpath,0777);
2506: }
2507: }
2508: open(my $fh,'>'.$fullpath.'/'.$fname);
2509: print $fh $env{'form.'.$formname};
2510: close($fh);
2511: if ($context eq 'existingfile') {
2512: my @info = stat($fullpath.'/'.$fname);
2513: return ($fullpath.'/'.$fname,$info[9]);
2514: } else {
2515: return $fullpath.'/'.$fname;
2516: }
2517: }
2518: if ($subdir eq 'scantron') {
2519: $fname = 'scantron_orig_'.$fname;
2520: } else {
2521: $fname="$subdir/$fname";
2522: }
2523: if ($context eq 'coursedoc') {
2524: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2525: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2526: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
2527: return &finishuserfileupload($docuname,$docudom,
2528: $formname,$fname,$parser,$allfiles,
2529: $codebase,$thumbwidth,$thumbheight,
2530: $resizewidth,$resizeheight,$context,$mimetype);
2531: } else {
2532: $fname=$env{'form.folder'}.'/'.$fname;
2533: return &process_coursefile('uploaddoc',$docuname,$docudom,
2534: $fname,$formname,$parser,
2535: $allfiles,$codebase,$mimetype);
2536: }
2537: } elsif (defined($destuname)) {
2538: my $docuname=$destuname;
2539: my $docudom=$destudom;
2540: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2541: $parser,$allfiles,$codebase,
2542: $thumbwidth,$thumbheight,
2543: $resizewidth,$resizeheight,$context,$mimetype);
2544: } else {
2545: my $docuname=$env{'user.name'};
2546: my $docudom=$env{'user.domain'};
2547: if (exists($env{'form.group'})) {
2548: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2549: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2550: }
2551: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2552: $parser,$allfiles,$codebase,
2553: $thumbwidth,$thumbheight,
2554: $resizewidth,$resizeheight,$context,$mimetype);
2555: }
2556: }
2557:
2558: sub finishuserfileupload {
2559: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
2560: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
2561: my $path=$docudom.'/'.$docuname.'/';
2562: my $filepath=$perlvar{'lonDocRoot'};
2563:
2564: my ($fnamepath,$file,$fetchthumb);
2565: $file=$fname;
2566: if ($fname=~m|/|) {
2567: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2568: $path.=$fnamepath.'/';
2569: }
2570: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
2571: my $count;
2572: for ($count=4;$count<=$#parts;$count++) {
2573: $filepath.="/$parts[$count]";
2574: if ((-e $filepath)!=1) {
2575: mkdir($filepath,0777);
2576: }
2577: }
2578:
2579: # Save the file
2580: {
2581: if (!open(FH,'>'.$filepath.'/'.$file)) {
2582: &logthis('Failed to create '.$filepath.'/'.$file);
2583: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2584: return '/adm/notfound.html';
2585: }
2586: if ($context eq 'overwrite') {
2587: my $source = $perlvar{'lonDaemons'}.'/tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
2588: my $target = $filepath.'/'.$file;
2589: if (-e $source) {
2590: my @info = stat($source);
2591: if ($info[9] eq $env{'form.timestamp'}) {
2592: unless (&File::Copy::move($source,$target)) {
2593: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2594: return "Moving from $source failed";
2595: }
2596: } else {
2597: return "Temporary file: $source had unexpected date/time for last modification";
2598: }
2599: } else {
2600: return "Temporary file: $source missing";
2601: }
2602: } elsif (!print FH ($env{'form.'.$formname})) {
2603: &logthis('Failed to write to '.$filepath.'/'.$file);
2604: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2605: return '/adm/notfound.html';
2606: }
2607: close(FH);
2608: if ($resizewidth && $resizeheight) {
2609: my $mm = new File::MMagic;
2610: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2611: if ($mime_type =~ m{^image/}) {
2612: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2613: }
2614: }
2615: }
2616: if ($parser eq 'parse') {
2617: my $mm = new File::MMagic;
2618: my $type = $mm->checktype_filename($filepath.'/'.$file);
2619: if ($type eq 'text/html') {
2620: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2621: $allfiles,$codebase);
2622: unless ($parse_result eq 'ok') {
2623: &logthis('Failed to parse '.$filepath.$file.
2624: ' for embedded media: '.$parse_result);
2625: }
2626: }
2627: if (ref($mimetype)) {
2628: $$mimetype = $type;
2629: }
2630: }
2631: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2632: my $input = $filepath.'/'.$file;
2633: my $output = $filepath.'/'.'tn-'.$file;
2634: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2635: system("convert -sample $thumbsize $input $output");
2636: if (-e $filepath.'/'.'tn-'.$file) {
2637: $fetchthumb = 1;
2638: }
2639: }
2640:
2641: # Notify homeserver to grep it
2642: #
2643: my $docuhome=&homeserver($docuname,$docudom);
2644: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
2645: if ($fetchresult eq 'ok') {
2646: if ($fetchthumb) {
2647: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2648: if ($thumbresult ne 'ok') {
2649: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2650: $docuhome.': '.$thumbresult);
2651: }
2652: }
2653: #
2654: # Return the URL to it
2655: return '/uploaded/'.$path.$file;
2656: } else {
2657: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2658: ': '.$fetchresult);
2659: return '/adm/notfound.html';
2660: }
2661: }
2662:
2663: sub extract_embedded_items {
2664: my ($fullpath,$allfiles,$codebase,$content) = @_;
2665: my @state = ();
2666: my %javafiles = (
2667: codebase => '',
2668: code => '',
2669: archive => ''
2670: );
2671: my %mediafiles = (
2672: src => '',
2673: movie => '',
2674: );
2675: my $p;
2676: if ($content) {
2677: $p = HTML::LCParser->new($content);
2678: } else {
2679: $p = HTML::LCParser->new($fullpath);
2680: }
2681: while (my $t=$p->get_token()) {
2682: if ($t->[0] eq 'S') {
2683: my ($tagname, $attr) = ($t->[1],$t->[2]);
2684: push(@state, $tagname);
2685: if (lc($tagname) eq 'allow') {
2686: &add_filetype($allfiles,$attr->{'src'},'src');
2687: }
2688: if (lc($tagname) eq 'img') {
2689: &add_filetype($allfiles,$attr->{'src'},'src');
2690: }
2691: if (lc($tagname) eq 'a') {
2692: &add_filetype($allfiles,$attr->{'href'},'href');
2693: }
2694: if (lc($tagname) eq 'script') {
2695: if ($attr->{'archive'} =~ /\.jar$/i) {
2696: &add_filetype($allfiles,$attr->{'archive'},'archive');
2697: } else {
2698: &add_filetype($allfiles,$attr->{'src'},'src');
2699: }
2700: }
2701: if (lc($tagname) eq 'link') {
2702: if (lc($attr->{'rel'}) eq 'stylesheet') {
2703: &add_filetype($allfiles,$attr->{'href'},'href');
2704: }
2705: }
2706: if (lc($tagname) eq 'object' ||
2707: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2708: foreach my $item (keys(%javafiles)) {
2709: $javafiles{$item} = '';
2710: }
2711: }
2712: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2713: my $name = lc($attr->{'name'});
2714: foreach my $item (keys(%javafiles)) {
2715: if ($name eq $item) {
2716: $javafiles{$item} = $attr->{'value'};
2717: last;
2718: }
2719: }
2720: foreach my $item (keys(%mediafiles)) {
2721: if ($name eq $item) {
2722: &add_filetype($allfiles, $attr->{'value'}, 'value');
2723: last;
2724: }
2725: }
2726: }
2727: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2728: foreach my $item (keys(%javafiles)) {
2729: if ($attr->{$item}) {
2730: $javafiles{$item} = $attr->{$item};
2731: last;
2732: }
2733: }
2734: foreach my $item (keys(%mediafiles)) {
2735: if ($attr->{$item}) {
2736: &add_filetype($allfiles,$attr->{$item},$item);
2737: last;
2738: }
2739: }
2740: }
2741: } elsif ($t->[0] eq 'E') {
2742: my ($tagname) = ($t->[1]);
2743: if ($javafiles{'codebase'} ne '') {
2744: $javafiles{'codebase'} .= '/';
2745: }
2746: if (lc($tagname) eq 'applet' ||
2747: lc($tagname) eq 'object' ||
2748: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2749: ) {
2750: foreach my $item (keys(%javafiles)) {
2751: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2752: my $file=$javafiles{'codebase'}.$javafiles{$item};
2753: &add_filetype($allfiles,$file,$item);
2754: }
2755: }
2756: }
2757: pop @state;
2758: }
2759: }
2760: return 'ok';
2761: }
2762:
2763: sub add_filetype {
2764: my ($allfiles,$file,$type)=@_;
2765: if (exists($allfiles->{$file})) {
2766: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2767: push(@{$allfiles->{$file}}, &escape($type));
2768: }
2769: } else {
2770: @{$allfiles->{$file}} = (&escape($type));
2771: }
2772: }
2773:
2774: sub removeuploadedurl {
2775: my ($url)=@_;
2776: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
2777: return &removeuserfile($uname,$udom,$fname);
2778: }
2779:
2780: sub removeuserfile {
2781: my ($docuname,$docudom,$fname)=@_;
2782: my $home=&homeserver($docuname,$docudom);
2783: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
2784: if ($result eq 'ok') {
2785: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2786: my $metafile = $fname.'.meta';
2787: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
2788: my $url = "/uploaded/$docudom/$docuname/$fname";
2789: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
2790: my $sqlresult =
2791: &update_portfolio_table($docuname,$docudom,$file,
2792: 'portfolio_metadata',$group,
2793: 'delete');
2794: }
2795: }
2796: return $result;
2797: }
2798:
2799: sub mkdiruserfile {
2800: my ($docuname,$docudom,$dir)=@_;
2801: my $home=&homeserver($docuname,$docudom);
2802: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2803: }
2804:
2805: sub renameuserfile {
2806: my ($docuname,$docudom,$old,$new)=@_;
2807: my $home=&homeserver($docuname,$docudom);
2808: my $result = &reply("renameuserfile:$docudom:$docuname:".
2809: &escape("$old").':'.&escape("$new"),$home);
2810: if ($result eq 'ok') {
2811: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2812: my $oldmeta = $old.'.meta';
2813: my $newmeta = $new.'.meta';
2814: my $metaresult =
2815: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
2816: my $url = "/uploaded/$docudom/$docuname/$old";
2817: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
2818: my $sqlresult =
2819: &update_portfolio_table($docuname,$docudom,$file,
2820: 'portfolio_metadata',$group,
2821: 'delete');
2822: }
2823: }
2824: return $result;
2825: }
2826:
2827: # ------------------------------------------------------------------------- Log
2828:
2829: sub log {
2830: my ($dom,$nam,$hom,$what)=@_;
2831: return critical("log:$dom:$nam:$what",$hom);
2832: }
2833:
2834: # ------------------------------------------------------------------ Course Log
2835: #
2836: # This routine flushes several buffers of non-mission-critical nature
2837: #
2838:
2839: sub flushcourselogs {
2840: &logthis('Flushing log buffers');
2841: #
2842: # course logs
2843: # This is a log of all transactions in a course, which can be used
2844: # for data mining purposes
2845: #
2846: # It also collects the courseid database, which lists last transaction
2847: # times and course titles for all courseids
2848: #
2849: my %courseidbuffer=();
2850: foreach my $crsid (keys(%courselogs)) {
2851: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
2852: &escape($courselogs{$crsid}),
2853: $coursehombuf{$crsid}) eq 'ok') {
2854: delete $courselogs{$crsid};
2855: } else {
2856: &logthis('Failed to flush log buffer for '.$crsid);
2857: if (length($courselogs{$crsid})>40000) {
2858: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
2859: " exceeded maximum size, deleting.</font>");
2860: delete $courselogs{$crsid};
2861: }
2862: }
2863: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
2864: 'description' => $coursedescrbuf{$crsid},
2865: 'inst_code' => $courseinstcodebuf{$crsid},
2866: 'type' => $coursetypebuf{$crsid},
2867: 'owner' => $courseownerbuf{$crsid},
2868: };
2869: }
2870: #
2871: # Write course id database (reverse lookup) to homeserver of courses
2872: # Is used in pickcourse
2873: #
2874: foreach my $crs_home (keys(%courseidbuffer)) {
2875: my $response = &courseidput(&host_domain($crs_home),
2876: $courseidbuffer{$crs_home},
2877: $crs_home,'timeonly');
2878: }
2879: #
2880: # File accesses
2881: # Writes to the dynamic metadata of resources to get hit counts, etc.
2882: #
2883: foreach my $entry (keys(%accesshash)) {
2884: if ($entry =~ /___count$/) {
2885: my ($dom,$name);
2886: ($dom,$name,undef)=
2887: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
2888: if (! defined($dom) || $dom eq '' ||
2889: ! defined($name) || $name eq '') {
2890: my $cid = $env{'request.course.id'};
2891: $dom = $env{'request.'.$cid.'.domain'};
2892: $name = $env{'request.'.$cid.'.num'};
2893: }
2894: my $value = $accesshash{$entry};
2895: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2896: my %temphash=($url => $value);
2897: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2898: if ($result eq 'ok') {
2899: delete $accesshash{$entry};
2900: } elsif ($result eq 'unknown_cmd') {
2901: # Target server has old code running on it.
2902: my %temphash=($entry => $value);
2903: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2904: delete $accesshash{$entry};
2905: }
2906: }
2907: } else {
2908: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
2909: my %temphash=($entry => $accesshash{$entry});
2910: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2911: delete $accesshash{$entry};
2912: }
2913: }
2914: }
2915: #
2916: # Roles
2917: # Reverse lookup of user roles for course faculty/staff and co-authorship
2918: #
2919: foreach my $entry (keys(%userrolehash)) {
2920: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
2921: split(/\:/,$entry);
2922: if (&Apache::lonnet::put('nohist_userroles',
2923: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
2924: $rudom,$runame) eq 'ok') {
2925: delete $userrolehash{$entry};
2926: }
2927: }
2928: #
2929: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2930: #
2931: my %domrolebuffer = ();
2932: foreach my $entry (keys(%domainrolehash)) {
2933: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
2934: if ($domrolebuffer{$rudom}) {
2935: $domrolebuffer{$rudom}.='&'.&escape($entry).
2936: '='.&escape($domainrolehash{$entry});
2937: } else {
2938: $domrolebuffer{$rudom}.=&escape($entry).
2939: '='.&escape($domainrolehash{$entry});
2940: }
2941: delete $domainrolehash{$entry};
2942: }
2943: foreach my $dom (keys(%domrolebuffer)) {
2944: my %servers = &get_servers($dom,'library');
2945: foreach my $tryserver (keys(%servers)) {
2946: unless (&reply('domroleput:'.$dom.':'.
2947: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2948: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2949: }
2950: }
2951: }
2952: $dumpcount++;
2953: }
2954:
2955: sub courselog {
2956: my $what=shift;
2957: $what=time.':'.$what;
2958: unless ($env{'request.course.id'}) { return ''; }
2959: $coursedombuf{$env{'request.course.id'}}=
2960: $env{'course.'.$env{'request.course.id'}.'.domain'};
2961: $coursenumbuf{$env{'request.course.id'}}=
2962: $env{'course.'.$env{'request.course.id'}.'.num'};
2963: $coursehombuf{$env{'request.course.id'}}=
2964: $env{'course.'.$env{'request.course.id'}.'.home'};
2965: $coursedescrbuf{$env{'request.course.id'}}=
2966: $env{'course.'.$env{'request.course.id'}.'.description'};
2967: $courseinstcodebuf{$env{'request.course.id'}}=
2968: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2969: $courseownerbuf{$env{'request.course.id'}}=
2970: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
2971: $coursetypebuf{$env{'request.course.id'}}=
2972: $env{'course.'.$env{'request.course.id'}.'.type'};
2973: if (defined $courselogs{$env{'request.course.id'}}) {
2974: $courselogs{$env{'request.course.id'}}.='&'.$what;
2975: } else {
2976: $courselogs{$env{'request.course.id'}}.=$what;
2977: }
2978: if (length($courselogs{$env{'request.course.id'}})>4048) {
2979: &flushcourselogs();
2980: }
2981: }
2982:
2983: sub courseacclog {
2984: my $fnsymb=shift;
2985: unless ($env{'request.course.id'}) { return ''; }
2986: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
2987: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
2988: $what.=':POST';
2989: # FIXME: Probably ought to escape things....
2990: foreach my $key (keys(%env)) {
2991: if ($key=~/^form\.(.*)/) {
2992: my $formitem = $1;
2993: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2994: $what.=':'.$formitem.'='.$env{$key};
2995: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2996: $what.=':'.$formitem.'='.$env{$key};
2997: }
2998: }
2999: }
3000: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3001: # FIXME: We should not be depending on a form parameter that someone
3002: # editing lonsearchcat.pm might change in the future.
3003: if ($env{'form.phase'} eq 'course_search') {
3004: $what.= ':POST';
3005: # FIXME: Probably ought to escape things....
3006: foreach my $element ('courseexp','crsfulltext','crsrelated',
3007: 'crsdiscuss') {
3008: $what.=':'.$element.'='.$env{'form.'.$element};
3009: }
3010: }
3011: }
3012: &courselog($what);
3013: }
3014:
3015: sub countacc {
3016: my $url=&declutter(shift);
3017: return if (! defined($url) || $url eq '');
3018: unless ($env{'request.course.id'}) { return ''; }
3019: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
3020: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
3021: $accesshash{$key}++;
3022: }
3023:
3024: sub linklog {
3025: my ($from,$to)=@_;
3026: $from=&declutter($from);
3027: $to=&declutter($to);
3028: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3029: $accesshash{$to.'___'.$from.'___goto'}=1;
3030: }
3031:
3032: sub userrolelog {
3033: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
3034: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
3035: ($trole=~/^in/) || ($trole=~/^cc/) ||
3036: ($trole=~/^ep/) || ($trole=~/^cr/) ||
3037: ($trole=~/^ta/) || ($trole=~/^co/)) {
3038: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3039: $userrolehash
3040: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3041: =$tend.':'.$tstart;
3042: }
3043: if (($env{'request.role'} =~ /dc\./) &&
3044: (($trole=~/^au/) || ($trole=~/^in/) ||
3045: ($trole=~/^cc/) || ($trole=~/^ep/) ||
3046: ($trole=~/^cr/) || ($trole=~/^ta/) ||
3047: ($trole=~/^co/))) {
3048: $userrolehash
3049: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3050: =$tend.':'.$tstart;
3051: }
3052: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
3053: ($trole=~/^li/) || ($trole=~/^li/) ||
3054: ($trole=~/^au/) || ($trole=~/^dg/) ||
3055: ($trole=~/^sc/)) {
3056: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3057: $domainrolehash
3058: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3059: = $tend.':'.$tstart;
3060: }
3061: }
3062:
3063: sub courserolelog {
3064: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3065: if (($trole eq 'cc') || ($trole eq 'in') ||
3066: ($trole eq 'ep') || ($trole eq 'ad') ||
3067: ($trole eq 'ta') || ($trole eq 'st') ||
3068: ($trole=~/^cr/) || ($trole eq 'gr') ||
3069: ($trole eq 'co')) {
3070: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3071: my $cdom = $1;
3072: my $cnum = $2;
3073: my $sec = $3;
3074: my $namespace = 'rolelog';
3075: my %storehash = (
3076: role => $trole,
3077: start => $tstart,
3078: end => $tend,
3079: selfenroll => $selfenroll,
3080: context => $context,
3081: );
3082: if ($trole eq 'gr') {
3083: $namespace = 'groupslog';
3084: $storehash{'group'} = $sec;
3085: } else {
3086: $storehash{'section'} = $sec;
3087: }
3088: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
3089: if (($trole ne 'st') || ($sec ne '')) {
3090: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3091: }
3092: }
3093: }
3094: return;
3095: }
3096:
3097: sub get_course_adv_roles {
3098: my ($cid,$codes) = @_;
3099: $cid=$env{'request.course.id'} unless (defined($cid));
3100: my %coursehash=&coursedescription($cid);
3101: my $crstype = &Apache::loncommon::course_type($cid);
3102: my %nothide=();
3103: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3104: if ($user !~ /:/) {
3105: $nothide{join(':',split(/[\@]/,$user))}=1;
3106: } else {
3107: $nothide{$user}=1;
3108: }
3109: }
3110: my %returnhash=();
3111: my %dumphash=
3112: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3113: my $now=time;
3114: my %privileged;
3115: foreach my $entry (keys(%dumphash)) {
3116: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3117: if (($tstart) && ($tstart<0)) { next; }
3118: if (($tend) && ($tend<$now)) { next; }
3119: if (($tstart) && ($now<$tstart)) { next; }
3120: my ($role,$username,$domain,$section)=split(/\:/,$entry);
3121: if ($username eq '' || $domain eq '') { next; }
3122: unless (ref($privileged{$domain}) eq 'HASH') {
3123: my %dompersonnel =
3124: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3125: $privileged{$domain} = {};
3126: foreach my $server (keys(%dompersonnel)) {
3127: if (ref($dompersonnel{$server}) eq 'HASH') {
3128: foreach my $user (keys(%{$dompersonnel{$server}})) {
3129: my ($trole,$uname,$udom) = split(/:/,$user);
3130: $privileged{$udom}{$uname} = 1;
3131: }
3132: }
3133: }
3134: }
3135: if ((exists($privileged{$domain}{$username})) &&
3136: (!$nothide{$username.':'.$domain})) { next; }
3137: if ($role eq 'cr') { next; }
3138: if ($codes) {
3139: if ($section) { $role .= ':'.$section; }
3140: if ($returnhash{$role}) {
3141: $returnhash{$role}.=','.$username.':'.$domain;
3142: } else {
3143: $returnhash{$role}=$username.':'.$domain;
3144: }
3145: } else {
3146: my $key=&plaintext($role,$crstype);
3147: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
3148: if ($returnhash{$key}) {
3149: $returnhash{$key}.=','.$username.':'.$domain;
3150: } else {
3151: $returnhash{$key}=$username.':'.$domain;
3152: }
3153: }
3154: }
3155: return %returnhash;
3156: }
3157:
3158: sub get_my_roles {
3159: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
3160: unless (defined($uname)) { $uname=$env{'user.name'}; }
3161: unless (defined($udom)) { $udom=$env{'user.domain'}; }
3162: my (%dumphash,%nothide);
3163: if ($context eq 'userroles') {
3164: my $extra = &freeze_escape({'skipcheck' => 1});
3165: %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
3166: } else {
3167: %dumphash=
3168: &dump('nohist_userroles',$udom,$uname);
3169: if ($hidepriv) {
3170: my %coursehash=&coursedescription($udom.'_'.$uname);
3171: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3172: if ($user !~ /:/) {
3173: $nothide{join(':',split(/[\@]/,$user))} = 1;
3174: } else {
3175: $nothide{$user} = 1;
3176: }
3177: }
3178: }
3179: }
3180: my %returnhash=();
3181: my $now=time;
3182: my %privileged;
3183: foreach my $entry (keys(%dumphash)) {
3184: my ($role,$tend,$tstart);
3185: if ($context eq 'userroles') {
3186: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3187: } else {
3188: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3189: }
3190: if (($tstart) && ($tstart<0)) { next; }
3191: my $status = 'active';
3192: if (($tend) && ($tend<=$now)) {
3193: $status = 'previous';
3194: }
3195: if (($tstart) && ($now<$tstart)) {
3196: $status = 'future';
3197: }
3198: if (ref($types) eq 'ARRAY') {
3199: if (!grep(/^\Q$status\E$/,@{$types})) {
3200: next;
3201: }
3202: } else {
3203: if ($status ne 'active') {
3204: next;
3205: }
3206: }
3207: my ($rolecode,$username,$domain,$section,$area);
3208: if ($context eq 'userroles') {
3209: ($area,$rolecode) = split(/_/,$entry);
3210: (undef,$domain,$username,$section) = split(/\//,$area);
3211: } else {
3212: ($role,$username,$domain,$section) = split(/\:/,$entry);
3213: }
3214: if (ref($roledoms) eq 'ARRAY') {
3215: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3216: next;
3217: }
3218: }
3219: if (ref($roles) eq 'ARRAY') {
3220: if (!grep(/^\Q$role\E$/,@{$roles})) {
3221: if ($role =~ /^cr\//) {
3222: if (!grep(/^cr$/,@{$roles})) {
3223: next;
3224: }
3225: } else {
3226: next;
3227: }
3228: }
3229: }
3230: if ($hidepriv) {
3231: if ($context eq 'userroles') {
3232: if ((&privileged($username,$domain)) &&
3233: (!$nothide{$username.':'.$domain})) {
3234: next;
3235: }
3236: } else {
3237: unless (ref($privileged{$domain}) eq 'HASH') {
3238: my %dompersonnel =
3239: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3240: $privileged{$domain} = {};
3241: if (keys(%dompersonnel)) {
3242: foreach my $server (keys(%dompersonnel)) {
3243: if (ref($dompersonnel{$server}) eq 'HASH') {
3244: foreach my $user (keys(%{$dompersonnel{$server}})) {
3245: my ($trole,$uname,$udom) = split(/:/,$user);
3246: $privileged{$udom}{$uname} = $trole;
3247: }
3248: }
3249: }
3250: }
3251: }
3252: if (exists($privileged{$domain}{$username})) {
3253: if (!$nothide{$username.':'.$domain}) {
3254: next;
3255: }
3256: }
3257: }
3258: }
3259: if ($withsec) {
3260: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3261: $tstart.':'.$tend;
3262: } else {
3263: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3264: }
3265: }
3266: return %returnhash;
3267: }
3268:
3269: # ----------------------------------------------------- Frontpage Announcements
3270: #
3271: #
3272:
3273: sub postannounce {
3274: my ($server,$text)=@_;
3275: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
3276: unless ($text=~/\w/) { $text=''; }
3277: return &reply('setannounce:'.&escape($text),$server);
3278: }
3279:
3280: sub getannounce {
3281:
3282: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
3283: my $announcement='';
3284: while (my $line = <$fh>) { $announcement .= $line; }
3285: close($fh);
3286: if ($announcement=~/\w/) {
3287: return
3288: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
3289: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
3290: } else {
3291: return '';
3292: }
3293: } else {
3294: return '';
3295: }
3296: }
3297:
3298: # ---------------------------------------------------------- Course ID routines
3299: # Deal with domain's nohist_courseid.db files
3300: #
3301:
3302: sub courseidput {
3303: my ($domain,$storehash,$coursehome,$caller) = @_;
3304: return unless (ref($storehash) eq 'HASH');
3305: my $outcome;
3306: if ($caller eq 'timeonly') {
3307: my $cids = '';
3308: foreach my $item (keys(%$storehash)) {
3309: $cids.=&escape($item).'&';
3310: }
3311: $cids=~s/\&$//;
3312: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3313: $coursehome);
3314: } else {
3315: my $items = '';
3316: foreach my $item (keys(%$storehash)) {
3317: $items.= &escape($item).'='.
3318: &freeze_escape($$storehash{$item}).'&';
3319: }
3320: $items=~s/\&$//;
3321: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3322: $coursehome);
3323: }
3324: if ($outcome eq 'unknown_cmd') {
3325: my $what;
3326: foreach my $cid (keys(%$storehash)) {
3327: $what .= &escape($cid).'=';
3328: foreach my $item ('description','inst_code','owner','type') {
3329: $what .= &escape($storehash->{$cid}{$item}).':';
3330: }
3331: $what =~ s/\:$/&/;
3332: }
3333: $what =~ s/\&$//;
3334: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3335: } else {
3336: return $outcome;
3337: }
3338: }
3339:
3340: sub courseiddump {
3341: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
3342: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
3343: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
3344: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
3345: my $as_hash = 1;
3346: my %returnhash;
3347: if (!$domfilter) { $domfilter=''; }
3348: my %libserv = &all_library();
3349: foreach my $tryserver (keys(%libserv)) {
3350: if ( ( $hostidflag == 1
3351: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3352: || (!defined($hostidflag)) ) {
3353:
3354: if (($domfilter eq '') ||
3355: (&host_domain($tryserver) eq $domfilter)) {
3356: my $rep =
3357: &reply('courseiddump:'.&host_domain($tryserver).':'.
3358: $sincefilter.':'.&escape($descfilter).':'.
3359: &escape($instcodefilter).':'.&escape($ownerfilter).
3360: ':'.&escape($coursefilter).':'.&escape($typefilter).
3361: ':'.&escape($regexp_ok).':'.$as_hash.':'.
3362: &escape($selfenrollonly).':'.&escape($catfilter).':'.
3363: $showhidden.':'.$caller.':'.&escape($cloner).':'.
3364: &escape($cc_clone).':'.$cloneonly.':'.
3365: &escape($createdbefore).':'.&escape($createdafter).':'.
3366: &escape($creationcontext).':'.$domcloner,
3367: $tryserver);
3368: my @pairs=split(/\&/,$rep);
3369: foreach my $item (@pairs) {
3370: my ($key,$value)=split(/\=/,$item,2);
3371: $key = &unescape($key);
3372: next if ($key =~ /^error: 2 /);
3373: my $result = &thaw_unescape($value);
3374: if (ref($result) eq 'HASH') {
3375: $returnhash{$key}=$result;
3376: } else {
3377: my @responses = split(/:/,$value);
3378: my @items = ('description','inst_code','owner','type');
3379: for (my $i=0; $i<@responses; $i++) {
3380: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
3381: }
3382: }
3383: }
3384: }
3385: }
3386: }
3387: return %returnhash;
3388: }
3389:
3390: sub courselastaccess {
3391: my ($cdom,$cnum,$hostidref) = @_;
3392: my %returnhash;
3393: if ($cdom && $cnum) {
3394: my $chome = &homeserver($cnum,$cdom);
3395: if ($chome ne 'no_host') {
3396: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3397: &extract_lastaccess(\%returnhash,$rep);
3398: }
3399: } else {
3400: if (!$cdom) { $cdom=''; }
3401: my %libserv = &all_library();
3402: foreach my $tryserver (keys(%libserv)) {
3403: if (ref($hostidref) eq 'ARRAY') {
3404: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3405: }
3406: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3407: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3408: &extract_lastaccess(\%returnhash,$rep);
3409: }
3410: }
3411: }
3412: return %returnhash;
3413: }
3414:
3415: sub extract_lastaccess {
3416: my ($returnhash,$rep) = @_;
3417: if (ref($returnhash) eq 'HASH') {
3418: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3419: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3420: $rep eq '') {
3421: my @pairs=split(/\&/,$rep);
3422: foreach my $item (@pairs) {
3423: my ($key,$value)=split(/\=/,$item,2);
3424: $key = &unescape($key);
3425: next if ($key =~ /^error: 2 /);
3426: $returnhash->{$key} = &thaw_unescape($value);
3427: }
3428: }
3429: }
3430: return;
3431: }
3432:
3433: # ---------------------------------------------------------- DC e-mail
3434:
3435: sub dcmailput {
3436: my ($domain,$msgid,$message,$server)=@_;
3437: my $status = &Apache::lonnet::critical(
3438: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3439: &escape($message),$server);
3440: return $status;
3441: }
3442:
3443: sub dcmaildump {
3444: my ($dom,$startdate,$enddate,$senders) = @_;
3445: my %returnhash=();
3446:
3447: if (defined(&domain($dom,'primary'))) {
3448: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3449: &escape($enddate).':';
3450: my @esc_senders=map { &escape($_)} @$senders;
3451: $cmd.=&escape(join('&',@esc_senders));
3452: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
3453: my ($key,$value) = split(/\=/,$line,2);
3454: if (($key) && ($value)) {
3455: $returnhash{&unescape($key)} = &unescape($value);
3456: }
3457: }
3458: }
3459: return %returnhash;
3460: }
3461: # ---------------------------------------------------------- Domain roles
3462:
3463: sub get_domain_roles {
3464: my ($dom,$roles,$startdate,$enddate)=@_;
3465: if ((!defined($startdate)) || ($startdate eq '')) {
3466: $startdate = '.';
3467: }
3468: if ((!defined($enddate)) || ($enddate eq '')) {
3469: $enddate = '.';
3470: }
3471: my $rolelist;
3472: if (ref($roles) eq 'ARRAY') {
3473: $rolelist = join(':',@{$roles});
3474: }
3475: my %personnel = ();
3476:
3477: my %servers = &get_servers($dom,'library');
3478: foreach my $tryserver (keys(%servers)) {
3479: %{$personnel{$tryserver}}=();
3480: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3481: &escape($startdate).':'.
3482: &escape($enddate).':'.
3483: &escape($rolelist), $tryserver))) {
3484: my ($key,$value) = split(/\=/,$line,2);
3485: if (($key) && ($value)) {
3486: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3487: }
3488: }
3489: }
3490: return %personnel;
3491: }
3492:
3493: # ----------------------------------------------------------- Check out an item
3494:
3495: sub get_first_access {
3496: my ($type,$argsymb)=@_;
3497: my ($symb,$courseid,$udom,$uname)=&whichuser();
3498: if ($argsymb) { $symb=$argsymb; }
3499: my ($map,$id,$res)=&decode_symb($symb);
3500: if ($type eq 'course') {
3501: $res='course';
3502: } elsif ($type eq 'map') {
3503: $res=&symbread($map);
3504: } else {
3505: $res=$symb;
3506: }
3507: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3508: return $times{"$courseid\0$res"};
3509: }
3510:
3511: sub set_first_access {
3512: my ($type)=@_;
3513: my ($symb,$courseid,$udom,$uname)=&whichuser();
3514: my ($map,$id,$res)=&decode_symb($symb);
3515: if ($type eq 'course') {
3516: $res='course';
3517: } elsif ($type eq 'map') {
3518: $res=&symbread($map);
3519: } else {
3520: $res=$symb;
3521: }
3522: my $firstaccess=&get_first_access($type,$symb);
3523: if (!$firstaccess) {
3524: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
3525: }
3526: return 'already_set';
3527: }
3528:
3529: sub checkout {
3530: my ($symb,$tuname,$tudom,$tcrsid)=@_;
3531: my $now=time;
3532: my $lonhost=$perlvar{'lonHostID'};
3533: my $infostr=&escape(
3534: 'CHECKOUTTOKEN&'.
3535: $tuname.'&'.
3536: $tudom.'&'.
3537: $tcrsid.'&'.
3538: $symb.'&'.
3539: $now.'&'.$ENV{'REMOTE_ADDR'});
3540: my $token=&reply('tmpput:'.$infostr,$lonhost);
3541: if ($token=~/^error\:/) {
3542: &logthis("<font color=\"blue\">WARNING: ".
3543: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
3544: "</font>");
3545: return '';
3546: }
3547:
3548: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
3549: $token=~tr/a-z/A-Z/;
3550:
3551: my %infohash=('resource.0.outtoken' => $token,
3552: 'resource.0.checkouttime' => $now,
3553: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
3554:
3555: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3556: return '';
3557: } else {
3558: &logthis("<font color=\"blue\">WARNING: ".
3559: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
3560: "</font>");
3561: }
3562:
3563: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3564: &escape('Checkout '.$infostr.' - '.
3565: $token)) ne 'ok') {
3566: return '';
3567: } else {
3568: &logthis("<font color=\"blue\">WARNING: ".
3569: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
3570: "</font>");
3571: }
3572: return $token;
3573: }
3574:
3575: # ------------------------------------------------------------ Check in an item
3576:
3577: sub checkin {
3578: my $token=shift;
3579: my $now=time;
3580: my ($ta,$tb,$lonhost)=split(/\*/,$token);
3581: $lonhost=~tr/A-Z/a-z/;
3582: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
3583: $dtoken=~s/\W/\_/g;
3584: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
3585: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
3586:
3587: unless (($tuname) && ($tudom)) {
3588: &logthis('Check in '.$token.' ('.$dtoken.') failed');
3589: return '';
3590: }
3591:
3592: unless (&allowed('mgr',$tcrsid)) {
3593: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
3594: $env{'user.name'}.' - '.$env{'user.domain'});
3595: return '';
3596: }
3597:
3598: my %infohash=('resource.0.intoken' => $token,
3599: 'resource.0.checkintime' => $now,
3600: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
3601:
3602: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3603: return '';
3604: }
3605:
3606: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3607: &escape('Checkin - '.$token)) ne 'ok') {
3608: return '';
3609: }
3610:
3611: return ($symb,$tuname,$tudom,$tcrsid);
3612: }
3613:
3614: # --------------------------------------------- Set Expire Date for Spreadsheet
3615:
3616: sub expirespread {
3617: my ($uname,$udom,$stype,$usymb)=@_;
3618: my $cid=$env{'request.course.id'};
3619: if ($cid) {
3620: my $now=time;
3621: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
3622: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3623: $env{'course.'.$cid.'.num'}.
3624: ':nohist_expirationdates:'.
3625: &escape($key).'='.$now,
3626: $env{'course.'.$cid.'.home'})
3627: }
3628: return 'ok';
3629: }
3630:
3631: # ----------------------------------------------------- Devalidate Spreadsheets
3632:
3633: sub devalidate {
3634: my ($symb,$uname,$udom)=@_;
3635: my $cid=$env{'request.course.id'};
3636: if ($cid) {
3637: # delete the stored spreadsheets for
3638: # - the student level sheet of this user in course's homespace
3639: # - the assessment level sheet for this resource
3640: # for this user in user's homespace
3641: # - current conditional state info
3642: my $key=$uname.':'.$udom.':';
3643: my $status=
3644: &del('nohist_calculatedsheets',
3645: [$key.'studentcalc:'],
3646: $env{'course.'.$cid.'.domain'},
3647: $env{'course.'.$cid.'.num'})
3648: .' '.
3649: &del('nohist_calculatedsheets_'.$cid,
3650: [$key.'assesscalc:'.$symb],$udom,$uname);
3651: unless ($status eq 'ok ok') {
3652: &logthis('Could not devalidate spreadsheet '.
3653: $uname.' at '.$udom.' for '.
3654: $symb.': '.$status);
3655: }
3656: &delenv('user.state.'.$cid);
3657: }
3658: }
3659:
3660: sub get_scalar {
3661: my ($string,$end) = @_;
3662: my $value;
3663: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3664: $value = $1;
3665: } elsif ($$string =~ s/^([^&]*?)&//) {
3666: $value = $1;
3667: }
3668: return &unescape($value);
3669: }
3670:
3671: sub array2str {
3672: my (@array) = @_;
3673: my $result=&arrayref2str(\@array);
3674: $result=~s/^__ARRAY_REF__//;
3675: $result=~s/__END_ARRAY_REF__$//;
3676: return $result;
3677: }
3678:
3679: sub arrayref2str {
3680: my ($arrayref) = @_;
3681: my $result='__ARRAY_REF__';
3682: foreach my $elem (@$arrayref) {
3683: if(ref($elem) eq 'ARRAY') {
3684: $result.=&arrayref2str($elem).'&';
3685: } elsif(ref($elem) eq 'HASH') {
3686: $result.=&hashref2str($elem).'&';
3687: } elsif(ref($elem)) {
3688: #print("Got a ref of ".(ref($elem))." skipping.");
3689: } else {
3690: $result.=&escape($elem).'&';
3691: }
3692: }
3693: $result=~s/\&$//;
3694: $result .= '__END_ARRAY_REF__';
3695: return $result;
3696: }
3697:
3698: sub hash2str {
3699: my (%hash) = @_;
3700: my $result=&hashref2str(\%hash);
3701: $result=~s/^__HASH_REF__//;
3702: $result=~s/__END_HASH_REF__$//;
3703: return $result;
3704: }
3705:
3706: sub hashref2str {
3707: my ($hashref)=@_;
3708: my $result='__HASH_REF__';
3709: foreach my $key (sort(keys(%$hashref))) {
3710: if (ref($key) eq 'ARRAY') {
3711: $result.=&arrayref2str($key).'=';
3712: } elsif (ref($key) eq 'HASH') {
3713: $result.=&hashref2str($key).'=';
3714: } elsif (ref($key)) {
3715: $result.='=';
3716: #print("Got a ref of ".(ref($key))." skipping.");
3717: } else {
3718: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
3719: }
3720:
3721: if(ref($hashref->{$key}) eq 'ARRAY') {
3722: $result.=&arrayref2str($hashref->{$key}).'&';
3723: } elsif(ref($hashref->{$key}) eq 'HASH') {
3724: $result.=&hashref2str($hashref->{$key}).'&';
3725: } elsif(ref($hashref->{$key})) {
3726: $result.='&';
3727: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
3728: } else {
3729: $result.=&escape($hashref->{$key}).'&';
3730: }
3731: }
3732: $result=~s/\&$//;
3733: $result .= '__END_HASH_REF__';
3734: return $result;
3735: }
3736:
3737: sub str2hash {
3738: my ($string)=@_;
3739: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3740: return %$hash;
3741: }
3742:
3743: sub str2hashref {
3744: my ($string) = @_;
3745:
3746: my %hash;
3747:
3748: if($string !~ /^__HASH_REF__/) {
3749: if (! ($string eq '' || !defined($string))) {
3750: $hash{'error'}='Not hash reference';
3751: }
3752: return (\%hash, $string);
3753: }
3754:
3755: $string =~ s/^__HASH_REF__//;
3756:
3757: while($string !~ /^__END_HASH_REF__/) {
3758: #key
3759: my $key='';
3760: if($string =~ /^__HASH_REF__/) {
3761: ($key, $string)=&str2hashref($string);
3762: if(defined($key->{'error'})) {
3763: $hash{'error'}='Bad data';
3764: return (\%hash, $string);
3765: }
3766: } elsif($string =~ /^__ARRAY_REF__/) {
3767: ($key, $string)=&str2arrayref($string);
3768: if($key->[0] eq 'Array reference error') {
3769: $hash{'error'}='Bad data';
3770: return (\%hash, $string);
3771: }
3772: } else {
3773: $string =~ s/^(.*?)=//;
3774: $key=&unescape($1);
3775: }
3776: $string =~ s/^=//;
3777:
3778: #value
3779: my $value='';
3780: if($string =~ /^__HASH_REF__/) {
3781: ($value, $string)=&str2hashref($string);
3782: if(defined($value->{'error'})) {
3783: $hash{'error'}='Bad data';
3784: return (\%hash, $string);
3785: }
3786: } elsif($string =~ /^__ARRAY_REF__/) {
3787: ($value, $string)=&str2arrayref($string);
3788: if($value->[0] eq 'Array reference error') {
3789: $hash{'error'}='Bad data';
3790: return (\%hash, $string);
3791: }
3792: } else {
3793: $value=&get_scalar(\$string,'__END_HASH_REF__');
3794: }
3795: $string =~ s/^&//;
3796:
3797: $hash{$key}=$value;
3798: }
3799:
3800: $string =~ s/^__END_HASH_REF__//;
3801:
3802: return (\%hash, $string);
3803: }
3804:
3805: sub str2array {
3806: my ($string)=@_;
3807: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3808: return @$array;
3809: }
3810:
3811: sub str2arrayref {
3812: my ($string) = @_;
3813: my @array;
3814:
3815: if($string !~ /^__ARRAY_REF__/) {
3816: if (! ($string eq '' || !defined($string))) {
3817: $array[0]='Array reference error';
3818: }
3819: return (\@array, $string);
3820: }
3821:
3822: $string =~ s/^__ARRAY_REF__//;
3823:
3824: while($string !~ /^__END_ARRAY_REF__/) {
3825: my $value='';
3826: if($string =~ /^__HASH_REF__/) {
3827: ($value, $string)=&str2hashref($string);
3828: if(defined($value->{'error'})) {
3829: $array[0] ='Array reference error';
3830: return (\@array, $string);
3831: }
3832: } elsif($string =~ /^__ARRAY_REF__/) {
3833: ($value, $string)=&str2arrayref($string);
3834: if($value->[0] eq 'Array reference error') {
3835: $array[0] ='Array reference error';
3836: return (\@array, $string);
3837: }
3838: } else {
3839: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3840: }
3841: $string =~ s/^&//;
3842:
3843: push(@array, $value);
3844: }
3845:
3846: $string =~ s/^__END_ARRAY_REF__//;
3847:
3848: return (\@array, $string);
3849: }
3850:
3851: # -------------------------------------------------------------------Temp Store
3852:
3853: sub tmpreset {
3854: my ($symb,$namespace,$domain,$stuname) = @_;
3855: if (!$symb) {
3856: $symb=&symbread();
3857: if (!$symb) { $symb= $env{'request.url'}; }
3858: }
3859: $symb=escape($symb);
3860:
3861: if (!$namespace) { $namespace=$env{'request.state'}; }
3862: $namespace=~s/\//\_/g;
3863: $namespace=~s/\W//g;
3864:
3865: if (!$domain) { $domain=$env{'user.domain'}; }
3866: if (!$stuname) { $stuname=$env{'user.name'}; }
3867: if ($domain eq 'public' && $stuname eq 'public') {
3868: $stuname=$ENV{'REMOTE_ADDR'};
3869: }
3870: my $path=$perlvar{'lonDaemons'}.'/tmp';
3871: my %hash;
3872: if (tie(%hash,'GDBM_File',
3873: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
3874: &GDBM_WRCREAT(),0640)) {
3875: foreach my $key (keys(%hash)) {
3876: if ($key=~ /:$symb/) {
3877: delete($hash{$key});
3878: }
3879: }
3880: }
3881: }
3882:
3883: sub tmpstore {
3884: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3885:
3886: if (!$symb) {
3887: $symb=&symbread();
3888: if (!$symb) { $symb= $env{'request.url'}; }
3889: }
3890: $symb=escape($symb);
3891:
3892: if (!$namespace) {
3893: # I don't think we would ever want to store this for a course.
3894: # it seems this will only be used if we don't have a course.
3895: #$namespace=$env{'request.course.id'};
3896: #if (!$namespace) {
3897: $namespace=$env{'request.state'};
3898: #}
3899: }
3900: $namespace=~s/\//\_/g;
3901: $namespace=~s/\W//g;
3902: if (!$domain) { $domain=$env{'user.domain'}; }
3903: if (!$stuname) { $stuname=$env{'user.name'}; }
3904: if ($domain eq 'public' && $stuname eq 'public') {
3905: $stuname=$ENV{'REMOTE_ADDR'};
3906: }
3907: my $now=time;
3908: my %hash;
3909: my $path=$perlvar{'lonDaemons'}.'/tmp';
3910: if (tie(%hash,'GDBM_File',
3911: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
3912: &GDBM_WRCREAT(),0640)) {
3913: $hash{"version:$symb"}++;
3914: my $version=$hash{"version:$symb"};
3915: my $allkeys='';
3916: foreach my $key (keys(%$storehash)) {
3917: $allkeys.=$key.':';
3918: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
3919: }
3920: $hash{"$version:$symb:timestamp"}=$now;
3921: $allkeys.='timestamp';
3922: $hash{"$version:keys:$symb"}=$allkeys;
3923: if (untie(%hash)) {
3924: return 'ok';
3925: } else {
3926: return "error:$!";
3927: }
3928: } else {
3929: return "error:$!";
3930: }
3931: }
3932:
3933: # -----------------------------------------------------------------Temp Restore
3934:
3935: sub tmprestore {
3936: my ($symb,$namespace,$domain,$stuname) = @_;
3937:
3938: if (!$symb) {
3939: $symb=&symbread();
3940: if (!$symb) { $symb= $env{'request.url'}; }
3941: }
3942: $symb=escape($symb);
3943:
3944: if (!$namespace) { $namespace=$env{'request.state'}; }
3945:
3946: if (!$domain) { $domain=$env{'user.domain'}; }
3947: if (!$stuname) { $stuname=$env{'user.name'}; }
3948: if ($domain eq 'public' && $stuname eq 'public') {
3949: $stuname=$ENV{'REMOTE_ADDR'};
3950: }
3951: my %returnhash;
3952: $namespace=~s/\//\_/g;
3953: $namespace=~s/\W//g;
3954: my %hash;
3955: my $path=$perlvar{'lonDaemons'}.'/tmp';
3956: if (tie(%hash,'GDBM_File',
3957: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
3958: &GDBM_READER(),0640)) {
3959: my $version=$hash{"version:$symb"};
3960: $returnhash{'version'}=$version;
3961: my $scope;
3962: for ($scope=1;$scope<=$version;$scope++) {
3963: my $vkeys=$hash{"$scope:keys:$symb"};
3964: my @keys=split(/:/,$vkeys);
3965: my $key;
3966: $returnhash{"$scope:keys"}=$vkeys;
3967: foreach $key (@keys) {
3968: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3969: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3970: }
3971: }
3972: if (!(untie(%hash))) {
3973: return "error:$!";
3974: }
3975: } else {
3976: return "error:$!";
3977: }
3978: return %returnhash;
3979: }
3980:
3981: # ----------------------------------------------------------------------- Store
3982:
3983: sub store {
3984: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3985: my $home='';
3986:
3987: if ($stuname) { $home=&homeserver($stuname,$domain); }
3988:
3989: $symb=&symbclean($symb);
3990: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
3991:
3992: if (!$domain) { $domain=$env{'user.domain'}; }
3993: if (!$stuname) { $stuname=$env{'user.name'}; }
3994:
3995: &devalidate($symb,$stuname,$domain);
3996:
3997: $symb=escape($symb);
3998: if (!$namespace) {
3999: unless ($namespace=$env{'request.course.id'}) {
4000: return '';
4001: }
4002: }
4003: if (!$home) { $home=$env{'user.home'}; }
4004:
4005: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4006: $$storehash{'host'}=$perlvar{'lonHostID'};
4007:
4008: my $namevalue='';
4009: foreach my $key (keys(%$storehash)) {
4010: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4011: }
4012: $namevalue=~s/\&$//;
4013: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
4014: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4015: }
4016:
4017: # -------------------------------------------------------------- Critical Store
4018:
4019: sub cstore {
4020: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4021: my $home='';
4022:
4023: if ($stuname) { $home=&homeserver($stuname,$domain); }
4024:
4025: $symb=&symbclean($symb);
4026: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4027:
4028: if (!$domain) { $domain=$env{'user.domain'}; }
4029: if (!$stuname) { $stuname=$env{'user.name'}; }
4030:
4031: &devalidate($symb,$stuname,$domain);
4032:
4033: $symb=escape($symb);
4034: if (!$namespace) {
4035: unless ($namespace=$env{'request.course.id'}) {
4036: return '';
4037: }
4038: }
4039: if (!$home) { $home=$env{'user.home'}; }
4040:
4041: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4042: $$storehash{'host'}=$perlvar{'lonHostID'};
4043:
4044: my $namevalue='';
4045: foreach my $key (keys(%$storehash)) {
4046: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4047: }
4048: $namevalue=~s/\&$//;
4049: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
4050: return critical
4051: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4052: }
4053:
4054: # --------------------------------------------------------------------- Restore
4055:
4056: sub restore {
4057: my ($symb,$namespace,$domain,$stuname) = @_;
4058: my $home='';
4059:
4060: if ($stuname) { $home=&homeserver($stuname,$domain); }
4061:
4062: if (!$symb) {
4063: unless ($symb=escape(&symbread())) { return ''; }
4064: } else {
4065: $symb=&escape(&symbclean($symb));
4066: }
4067: if (!$namespace) {
4068: unless ($namespace=$env{'request.course.id'}) {
4069: return '';
4070: }
4071: }
4072: if (!$domain) { $domain=$env{'user.domain'}; }
4073: if (!$stuname) { $stuname=$env{'user.name'}; }
4074: if (!$home) { $home=$env{'user.home'}; }
4075: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4076:
4077: my %returnhash=();
4078: foreach my $line (split(/\&/,$answer)) {
4079: my ($name,$value)=split(/\=/,$line);
4080: $returnhash{&unescape($name)}=&thaw_unescape($value);
4081: }
4082: my $version;
4083: for ($version=1;$version<=$returnhash{'version'};$version++) {
4084: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4085: $returnhash{$item}=$returnhash{$version.':'.$item};
4086: }
4087: }
4088: return %returnhash;
4089: }
4090:
4091: # ---------------------------------------------------------- Course Description
4092:
4093: sub coursedescription {
4094: my ($courseid,$args)=@_;
4095: $courseid=~s/^\///;
4096: $courseid=~s/\_/\//g;
4097: my ($cdomain,$cnum)=split(/\//,$courseid);
4098: my $chome=&homeserver($cnum,$cdomain);
4099: my $normalid=$cdomain.'_'.$cnum;
4100: # need to always cache even if we get errors otherwise we keep
4101: # trying and trying and trying to get the course description.
4102: my %envhash=();
4103: my %returnhash=();
4104:
4105: my $expiretime=600;
4106: if ($env{'request.course.id'} eq $normalid) {
4107: $expiretime=120;
4108: }
4109:
4110: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4111: if (!$args->{'freshen_cache'}
4112: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4113: foreach my $key (keys(%env)) {
4114: next if ($key !~ /^\Q$prefix\E(.*)/);
4115: my ($setting) = $1;
4116: $returnhash{$setting} = $env{$key};
4117: }
4118: return %returnhash;
4119: }
4120:
4121: # get the data agin
4122: if (!$args->{'one_time'}) {
4123: $envhash{'course.'.$normalid.'.last_cache'}=time;
4124: }
4125:
4126: if ($chome ne 'no_host') {
4127: %returnhash=&dump('environment',$cdomain,$cnum);
4128: if (!exists($returnhash{'con_lost'})) {
4129: $returnhash{'home'}= $chome;
4130: $returnhash{'domain'} = $cdomain;
4131: $returnhash{'num'} = $cnum;
4132: if (!defined($returnhash{'type'})) {
4133: $returnhash{'type'} = 'Course';
4134: }
4135: while (my ($name,$value) = each %returnhash) {
4136: $envhash{'course.'.$normalid.'.'.$name}=$value;
4137: }
4138: $returnhash{'url'}=&clutter($returnhash{'url'});
4139: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
4140: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
4141: $envhash{'course.'.$normalid.'.home'}=$chome;
4142: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4143: $envhash{'course.'.$normalid.'.num'}=$cnum;
4144: }
4145: }
4146: if (!$args->{'one_time'}) {
4147: &appenv(\%envhash);
4148: }
4149: return %returnhash;
4150: }
4151:
4152: sub update_released_required {
4153: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4154: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4155: $cid = $env{'request.course.id'};
4156: $cdom = $env{'course.'.$cid.'.domain'};
4157: $cnum = $env{'course.'.$cid.'.num'};
4158: $chome = $env{'course.'.$cid.'.home'};
4159: }
4160: if ($needsrelease) {
4161: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4162: my $needsupdate;
4163: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4164: $needsupdate = 1;
4165: } else {
4166: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4167: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4168: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4169: $needsupdate = 1;
4170: }
4171: }
4172: if ($needsupdate) {
4173: my %needshash = (
4174: 'internal.releaserequired' => $needsrelease,
4175: );
4176: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4177: if ($putresult eq 'ok') {
4178: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4179: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4180: if (ref($crsinfo{$cid}) eq 'HASH') {
4181: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4182: &courseidput($cdom,\%crsinfo,$chome,'notime');
4183: }
4184: }
4185: }
4186: }
4187: return;
4188: }
4189:
4190: # -------------------------------------------------See if a user is privileged
4191:
4192: sub privileged {
4193: my ($username,$domain)=@_;
4194: my $rolesdump=&reply("dump:$domain:$username:roles",
4195: &homeserver($username,$domain));
4196: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4197: ($rolesdump =~ /^error:/)) {
4198: return 0;
4199: }
4200: my $now=time;
4201: if ($rolesdump ne '') {
4202: foreach my $entry (split(/&/,$rolesdump)) {
4203: if ($entry!~/^rolesdef_/) {
4204: my ($area,$role)=split(/=/,$entry);
4205: $area=~s/\_\w\w$//;
4206: my ($trole,$tend,$tstart)=split(/_/,$role);
4207: if (($trole eq 'dc') || ($trole eq 'su')) {
4208: my $active=1;
4209: if ($tend) {
4210: if ($tend<$now) { $active=0; }
4211: }
4212: if ($tstart) {
4213: if ($tstart>$now) { $active=0; }
4214: }
4215: if ($active) { return 1; }
4216: }
4217: }
4218: }
4219: }
4220: return 0;
4221: }
4222:
4223: # -------------------------------------------------------- Get user privileges
4224:
4225: sub rolesinit {
4226: my ($domain,$username,$authhost)=@_;
4227: my $now=time;
4228: my %userroles = ('user.login.time' => $now);
4229: my $extra = &freeze_escape({'skipcheck' => 1});
4230: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
4231: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4232: ($rolesdump =~ /^error:/)) {
4233: return \%userroles;
4234: }
4235: my %allroles=();
4236: my %allgroups=();
4237: my $group_privs;
4238:
4239: if ($rolesdump ne '') {
4240: foreach my $entry (split(/&/,$rolesdump)) {
4241: if ($entry!~/^rolesdef_/) {
4242: my ($area,$role)=split(/=/,$entry);
4243: $area=~s/\_\w\w$//;
4244: my ($trole,$tend,$tstart,$group_privs);
4245: if ($role=~/^cr/) {
4246: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4247: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
4248: ($tend,$tstart)=split('_',$trest);
4249: } else {
4250: $trole=$role;
4251: }
4252: } elsif ($role =~ m|^gr/|) {
4253: ($trole,$tend,$tstart) = split(/_/,$role);
4254: ($trole,$group_privs) = split(/\//,$trole);
4255: $group_privs = &unescape($group_privs);
4256: } else {
4257: ($trole,$tend,$tstart)=split(/_/,$role);
4258: }
4259: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4260: $username);
4261: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
4262: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4263: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
4264: if (($area ne '') && ($trole ne '')) {
4265: my $spec=$trole.'.'.$area;
4266: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4267: if ($trole =~ /^cr\//) {
4268: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4269: } elsif ($trole eq 'gr') {
4270: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
4271: } else {
4272: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4273: }
4274: }
4275: }
4276: }
4277: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4278: $userroles{'user.adv'} = $adv;
4279: $userroles{'user.author'} = $author;
4280: $env{'user.adv'}=$adv;
4281: }
4282: return \%userroles;
4283: }
4284:
4285: sub set_arearole {
4286: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4287: # log the associated role with the area
4288: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
4289: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
4290: }
4291:
4292: sub custom_roleprivs {
4293: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4294: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4295: my $homsvr=homeserver($rauthor,$rdomain);
4296: if (&hostname($homsvr) ne '') {
4297: my ($rdummy,$roledef)=
4298: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4299: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4300: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4301: if (defined($syspriv)) {
4302: if ($trest =~ /^$match_community$/) {
4303: $syspriv =~ s/bre\&S//;
4304: }
4305: $$allroles{'cm./'}.=':'.$syspriv;
4306: $$allroles{$spec.'./'}.=':'.$syspriv;
4307: }
4308: if ($tdomain ne '') {
4309: if (defined($dompriv)) {
4310: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4311: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4312: }
4313: if (($trest ne '') && (defined($coursepriv))) {
4314: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4315: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4316: }
4317: }
4318: }
4319: }
4320: }
4321:
4322: sub group_roleprivs {
4323: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4324: my $access = 1;
4325: my $now = time;
4326: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4327: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4328: if ($access) {
4329: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
4330: $$allgroups{$course}{$group} .=':'.$group_privs;
4331: }
4332: }
4333:
4334: sub standard_roleprivs {
4335: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4336: if (defined($pr{$trole.':s'})) {
4337: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4338: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4339: }
4340: if ($tdomain ne '') {
4341: if (defined($pr{$trole.':d'})) {
4342: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4343: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4344: }
4345: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4346: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4347: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4348: }
4349: }
4350: }
4351:
4352: sub set_userprivs {
4353: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
4354: my $author=0;
4355: my $adv=0;
4356: my %grouproles = ();
4357: if (keys(%{$allgroups}) > 0) {
4358: my @groupkeys;
4359: foreach my $role (keys(%{$allroles})) {
4360: push(@groupkeys,$role);
4361: }
4362: if (ref($groups_roles) eq 'HASH') {
4363: foreach my $key (keys(%{$groups_roles})) {
4364: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4365: push(@groupkeys,$key);
4366: }
4367: }
4368: }
4369: if (@groupkeys > 0) {
4370: foreach my $role (@groupkeys) {
4371: my ($trole,$area,$sec,$extendedarea);
4372: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4373: $trole = $1;
4374: $area = $2;
4375: $sec = $3;
4376: $extendedarea = $area.$sec;
4377: if (exists($$allgroups{$area})) {
4378: foreach my $group (keys(%{$$allgroups{$area}})) {
4379: my $spec = $trole.'.'.$extendedarea;
4380: $grouproles{$spec.'.'.$area.'/'.$group} =
4381: $$allgroups{$area}{$group};
4382: }
4383: }
4384: }
4385: }
4386: }
4387: }
4388: foreach my $group (keys(%grouproles)) {
4389: $$allroles{$group} = $grouproles{$group};
4390: }
4391: foreach my $role (keys(%{$allroles})) {
4392: my %thesepriv;
4393: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
4394: foreach my $item (split(/:/,$$allroles{$role})) {
4395: if ($item ne '') {
4396: my ($privilege,$restrictions)=split(/&/,$item);
4397: if ($restrictions eq '') {
4398: $thesepriv{$privilege}='F';
4399: } elsif ($thesepriv{$privilege} ne 'F') {
4400: $thesepriv{$privilege}.=$restrictions;
4401: }
4402: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4403: }
4404: }
4405: my $thesestr='';
4406: foreach my $priv (keys(%thesepriv)) {
4407: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4408: }
4409: $userroles->{'user.priv.'.$role} = $thesestr;
4410: }
4411: return ($author,$adv);
4412: }
4413:
4414: sub role_status {
4415: my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
4416: my @pwhere = ();
4417: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4418: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4419: unless (!defined($$role) || $$role eq '') {
4420: $$where=join('.',@pwhere);
4421: $$trolecode=$$role.'.'.$$where;
4422: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4423: $$tstatus='is';
4424: if ($$tstart && $$tstart>$then) {
4425: $$tstatus='future';
4426: if ($$tstart<$now) {
4427: if ($$tstart && $$tstart>$refresh) {
4428: if (($$where ne '') && ($$role ne '')) {
4429: my (%allroles,%allgroups,$group_privs,
4430: %groups_roles,@rolecodes);
4431: my %userroles = (
4432: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4433: );
4434: @rolecodes = ('cm');
4435: my $spec=$$role.'.'.$$where;
4436: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4437: if ($$role =~ /^cr\//) {
4438: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
4439: push(@rolecodes,'cr');
4440: } elsif ($$role eq 'gr') {
4441: push(@rolecodes,$$role);
4442: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4443: $env{'user.name'});
4444: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
4445: (undef,my $group_privs) = split(/\//,$trole);
4446: $group_privs = &unescape($group_privs);
4447: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
4448: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4449: if (keys(%course_roles) > 0) {
4450: my ($tnum) = ($trest =~ /^($match_courseid)/);
4451: if ($tdomain ne '' && $tnum ne '') {
4452: foreach my $key (keys(%course_roles)) {
4453: if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
4454: my $crsrole = $1;
4455: my $crssec = $2;
4456: if ($crsrole =~ /^cr/) {
4457: unless (grep(/^cr$/,@rolecodes)) {
4458: push(@rolecodes,'cr');
4459: }
4460: } else {
4461: unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
4462: push(@rolecodes,$crsrole);
4463: }
4464: }
4465: my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
4466: if ($crssec ne '') {
4467: $rolekey .= '/'.$crssec;
4468: }
4469: $rolekey .= './';
4470: $groups_roles{$rolekey} = \@rolecodes;
4471: }
4472: }
4473: }
4474: }
4475: } else {
4476: push(@rolecodes,$$role);
4477: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4478: }
4479: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4480: &appenv(\%userroles,\@rolecodes);
4481: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4482: }
4483: }
4484: $$tstatus = 'is';
4485: }
4486: }
4487: if ($$tend) {
4488: if ($$tend<$then) {
4489: $$tstatus='expired';
4490: } elsif ($$tend<$now) {
4491: $$tstatus='will_not';
4492: }
4493: }
4494: }
4495: }
4496: }
4497:
4498: sub check_adhoc_privs {
4499: my ($cdom,$cnum,$then,$refresh,$now,$checkrole,$caller) = @_;
4500: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4501: if ($env{$cckey}) {
4502: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
4503: &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
4504: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
4505: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
4506: }
4507: } else {
4508: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
4509: }
4510: }
4511:
4512: sub set_adhoc_privileges {
4513: # role can be cc or ca
4514: my ($dcdom,$pickedcourse,$role,$caller) = @_;
4515: my $area = '/'.$dcdom.'/'.$pickedcourse;
4516: my $spec = $role.'.'.$area;
4517: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4518: $env{'user.name'});
4519: my %ccrole = ();
4520: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4521: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4522: &appenv(\%userroles,[$role,'cm']);
4523: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4524: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
4525: &appenv( {'request.role' => $spec,
4526: 'request.role.domain' => $dcdom,
4527: 'request.course.sec' => ''
4528: }
4529: );
4530: my $tadv=0;
4531: if (&allowed('adv') eq 'F') { $tadv=1; }
4532: &appenv({'request.role.adv' => $tadv});
4533: }
4534: }
4535:
4536: # --------------------------------------------------------------- get interface
4537:
4538: sub get {
4539: my ($namespace,$storearr,$udomain,$uname)=@_;
4540: my $items='';
4541: foreach my $item (@$storearr) {
4542: $items.=&escape($item).'&';
4543: }
4544: $items=~s/\&$//;
4545: if (!$udomain) { $udomain=$env{'user.domain'}; }
4546: if (!$uname) { $uname=$env{'user.name'}; }
4547: my $uhome=&homeserver($uname,$udomain);
4548:
4549: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
4550: my @pairs=split(/\&/,$rep);
4551: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4552: return @pairs;
4553: }
4554: my %returnhash=();
4555: my $i=0;
4556: foreach my $item (@$storearr) {
4557: $returnhash{$item}=&thaw_unescape($pairs[$i]);
4558: $i++;
4559: }
4560: return %returnhash;
4561: }
4562:
4563: # --------------------------------------------------------------- del interface
4564:
4565: sub del {
4566: my ($namespace,$storearr,$udomain,$uname)=@_;
4567: my $items='';
4568: foreach my $item (@$storearr) {
4569: $items.=&escape($item).'&';
4570: }
4571:
4572: $items=~s/\&$//;
4573: if (!$udomain) { $udomain=$env{'user.domain'}; }
4574: if (!$uname) { $uname=$env{'user.name'}; }
4575: my $uhome=&homeserver($uname,$udomain);
4576: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
4577: }
4578:
4579: # -------------------------------------------------------------- dump interface
4580:
4581: sub dump {
4582: my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
4583: if (!$udomain) { $udomain=$env{'user.domain'}; }
4584: if (!$uname) { $uname=$env{'user.name'}; }
4585: my $uhome=&homeserver($uname,$udomain);
4586: if ($regexp) {
4587: $regexp=&escape($regexp);
4588: } else {
4589: $regexp='.';
4590: }
4591: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
4592: my @pairs=split(/\&/,$rep);
4593: my %returnhash=();
4594: foreach my $item (@pairs) {
4595: my ($key,$value)=split(/=/,$item,2);
4596: $key = &unescape($key);
4597: next if ($key =~ /^error: 2 /);
4598: $returnhash{$key}=&thaw_unescape($value);
4599: }
4600: return %returnhash;
4601: }
4602:
4603: # --------------------------------------------------------- dumpstore interface
4604:
4605: sub dumpstore {
4606: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
4607: if (!$udomain) { $udomain=$env{'user.domain'}; }
4608: if (!$uname) { $uname=$env{'user.name'}; }
4609: my $uhome=&homeserver($uname,$udomain);
4610: if ($regexp) {
4611: $regexp=&escape($regexp);
4612: } else {
4613: $regexp='.';
4614: }
4615: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4616: my @pairs=split(/\&/,$rep);
4617: my %returnhash=();
4618: foreach my $item (@pairs) {
4619: my ($key,$value)=split(/=/,$item,2);
4620: next if ($key =~ /^error: 2 /);
4621: $returnhash{$key}=&thaw_unescape($value);
4622: }
4623: return %returnhash;
4624: }
4625:
4626: # -------------------------------------------------------------- keys interface
4627:
4628: sub getkeys {
4629: my ($namespace,$udomain,$uname)=@_;
4630: if (!$udomain) { $udomain=$env{'user.domain'}; }
4631: if (!$uname) { $uname=$env{'user.name'}; }
4632: my $uhome=&homeserver($uname,$udomain);
4633: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4634: my @keyarray=();
4635: foreach my $key (split(/\&/,$rep)) {
4636: next if ($key =~ /^error: 2 /);
4637: push(@keyarray,&unescape($key));
4638: }
4639: return @keyarray;
4640: }
4641:
4642: # --------------------------------------------------------------- currentdump
4643: sub currentdump {
4644: my ($courseid,$sdom,$sname)=@_;
4645: $courseid = $env{'request.course.id'} if (! defined($courseid));
4646: $sdom = $env{'user.domain'} if (! defined($sdom));
4647: $sname = $env{'user.name'} if (! defined($sname));
4648: my $uhome = &homeserver($sname,$sdom);
4649: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
4650: return if ($rep =~ /^(error:|no_such_host)/);
4651: #
4652: my %returnhash=();
4653: #
4654: if ($rep eq "unknown_cmd") {
4655: # an old lond will not know currentdump
4656: # Do a dump and make it look like a currentdump
4657: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
4658: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4659: my %hash = @tmp;
4660: @tmp=();
4661: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
4662: } else {
4663: my @pairs=split(/\&/,$rep);
4664: foreach my $pair (@pairs) {
4665: my ($key,$value)=split(/=/,$pair,2);
4666: my ($symb,$param) = split(/:/,$key);
4667: $returnhash{&unescape($symb)}->{&unescape($param)} =
4668: &thaw_unescape($value);
4669: }
4670: }
4671: return %returnhash;
4672: }
4673:
4674: sub convert_dump_to_currentdump{
4675: my %hash = %{shift()};
4676: my %returnhash;
4677: # Code ripped from lond, essentially. The only difference
4678: # here is the unescaping done by lonnet::dump(). Conceivably
4679: # we might run in to problems with parameter names =~ /^v\./
4680: while (my ($key,$value) = each(%hash)) {
4681: my ($v,$symb,$param) = split(/:/,$key);
4682: $symb = &unescape($symb);
4683: $param = &unescape($param);
4684: next if ($v eq 'version' || $symb eq 'keys');
4685: next if (exists($returnhash{$symb}) &&
4686: exists($returnhash{$symb}->{$param}) &&
4687: $returnhash{$symb}->{'v.'.$param} > $v);
4688: $returnhash{$symb}->{$param}=$value;
4689: $returnhash{$symb}->{'v.'.$param}=$v;
4690: }
4691: #
4692: # Remove all of the keys in the hashes which keep track of
4693: # the version of the parameter.
4694: while (my ($symb,$param_hash) = each(%returnhash)) {
4695: # use a foreach because we are going to delete from the hash.
4696: foreach my $key (keys(%$param_hash)) {
4697: delete($param_hash->{$key}) if ($key =~ /^v\./);
4698: }
4699: }
4700: return \%returnhash;
4701: }
4702:
4703: # ------------------------------------------------------ critical inc interface
4704:
4705: sub cinc {
4706: return &inc(@_,'critical');
4707: }
4708:
4709: # --------------------------------------------------------------- inc interface
4710:
4711: sub inc {
4712: my ($namespace,$store,$udomain,$uname,$critical) = @_;
4713: if (!$udomain) { $udomain=$env{'user.domain'}; }
4714: if (!$uname) { $uname=$env{'user.name'}; }
4715: my $uhome=&homeserver($uname,$udomain);
4716: my $items='';
4717: if (! ref($store)) {
4718: # got a single value, so use that instead
4719: $items = &escape($store).'=&';
4720: } elsif (ref($store) eq 'SCALAR') {
4721: $items = &escape($$store).'=&';
4722: } elsif (ref($store) eq 'ARRAY') {
4723: $items = join('=&',map {&escape($_);} @{$store});
4724: } elsif (ref($store) eq 'HASH') {
4725: while (my($key,$value) = each(%{$store})) {
4726: $items.= &escape($key).'='.&escape($value).'&';
4727: }
4728: }
4729: $items=~s/\&$//;
4730: if ($critical) {
4731: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4732: } else {
4733: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4734: }
4735: }
4736:
4737: # --------------------------------------------------------------- put interface
4738:
4739: sub put {
4740: my ($namespace,$storehash,$udomain,$uname)=@_;
4741: if (!$udomain) { $udomain=$env{'user.domain'}; }
4742: if (!$uname) { $uname=$env{'user.name'}; }
4743: my $uhome=&homeserver($uname,$udomain);
4744: my $items='';
4745: foreach my $item (keys(%$storehash)) {
4746: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
4747: }
4748: $items=~s/\&$//;
4749: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
4750: }
4751:
4752: # ------------------------------------------------------------ newput interface
4753:
4754: sub newput {
4755: my ($namespace,$storehash,$udomain,$uname)=@_;
4756: if (!$udomain) { $udomain=$env{'user.domain'}; }
4757: if (!$uname) { $uname=$env{'user.name'}; }
4758: my $uhome=&homeserver($uname,$udomain);
4759: my $items='';
4760: foreach my $key (keys(%$storehash)) {
4761: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4762: }
4763: $items=~s/\&$//;
4764: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4765: }
4766:
4767: # --------------------------------------------------------- putstore interface
4768:
4769: sub putstore {
4770: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4771: if (!$udomain) { $udomain=$env{'user.domain'}; }
4772: if (!$uname) { $uname=$env{'user.name'}; }
4773: my $uhome=&homeserver($uname,$udomain);
4774: my $items='';
4775: foreach my $key (keys(%$storehash)) {
4776: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
4777: }
4778: $items=~s/\&$//;
4779: my $esc_symb=&escape($symb);
4780: my $esc_v=&escape($version);
4781: my $reply =
4782: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
4783: $uhome);
4784: if ($reply eq 'unknown_cmd') {
4785: # gfall back to way things use to be done
4786: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4787: $uname);
4788: }
4789: return $reply;
4790: }
4791:
4792: sub old_putstore {
4793: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4794: if (!$udomain) { $udomain=$env{'user.domain'}; }
4795: if (!$uname) { $uname=$env{'user.name'}; }
4796: my $uhome=&homeserver($uname,$udomain);
4797: my %newstorehash;
4798: foreach my $item (keys(%$storehash)) {
4799: my $key = $version.':'.&escape($symb).':'.$item;
4800: $newstorehash{$key} = $storehash->{$item};
4801: }
4802: my $items='';
4803: my %allitems = ();
4804: foreach my $item (keys(%newstorehash)) {
4805: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
4806: my $key = $1.':keys:'.$2;
4807: $allitems{$key} .= $3.':';
4808: }
4809: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
4810: }
4811: foreach my $item (keys(%allitems)) {
4812: $allitems{$item} =~ s/\:$//;
4813: $items.= $item.'='.$allitems{$item}.'&';
4814: }
4815: $items=~s/\&$//;
4816: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
4817: }
4818:
4819: # ------------------------------------------------------ critical put interface
4820:
4821: sub cput {
4822: my ($namespace,$storehash,$udomain,$uname)=@_;
4823: if (!$udomain) { $udomain=$env{'user.domain'}; }
4824: if (!$uname) { $uname=$env{'user.name'}; }
4825: my $uhome=&homeserver($uname,$udomain);
4826: my $items='';
4827: foreach my $item (keys(%$storehash)) {
4828: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
4829: }
4830: $items=~s/\&$//;
4831: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
4832: }
4833:
4834: # -------------------------------------------------------------- eget interface
4835:
4836: sub eget {
4837: my ($namespace,$storearr,$udomain,$uname)=@_;
4838: my $items='';
4839: foreach my $item (@$storearr) {
4840: $items.=&escape($item).'&';
4841: }
4842: $items=~s/\&$//;
4843: if (!$udomain) { $udomain=$env{'user.domain'}; }
4844: if (!$uname) { $uname=$env{'user.name'}; }
4845: my $uhome=&homeserver($uname,$udomain);
4846: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
4847: my @pairs=split(/\&/,$rep);
4848: my %returnhash=();
4849: my $i=0;
4850: foreach my $item (@$storearr) {
4851: $returnhash{$item}=&thaw_unescape($pairs[$i]);
4852: $i++;
4853: }
4854: return %returnhash;
4855: }
4856:
4857: # ------------------------------------------------------------ tmpput interface
4858: sub tmpput {
4859: my ($storehash,$server,$context)=@_;
4860: my $items='';
4861: foreach my $item (keys(%$storehash)) {
4862: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
4863: }
4864: $items=~s/\&$//;
4865: if (defined($context)) {
4866: $items .= ':'.&escape($context);
4867: }
4868: return &reply("tmpput:$items",$server);
4869: }
4870:
4871: # ------------------------------------------------------------ tmpget interface
4872: sub tmpget {
4873: my ($token,$server)=@_;
4874: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4875: my $rep=&reply("tmpget:$token",$server);
4876: my %returnhash;
4877: foreach my $item (split(/\&/,$rep)) {
4878: my ($key,$value)=split(/=/,$item);
4879: next if ($key =~ /^error: 2 /);
4880: $returnhash{&unescape($key)}=&thaw_unescape($value);
4881: }
4882: return %returnhash;
4883: }
4884:
4885: # ------------------------------------------------------------ tmpget interface
4886: sub tmpdel {
4887: my ($token,$server)=@_;
4888: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4889: return &reply("tmpdel:$token",$server);
4890: }
4891:
4892: # -------------------------------------------------- portfolio access checking
4893:
4894: sub portfolio_access {
4895: my ($requrl) = @_;
4896: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4897: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
4898: if ($result) {
4899: my %setters;
4900: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4901: my ($startblock,$endblock) =
4902: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4903: if ($startblock && $endblock) {
4904: return 'B';
4905: }
4906: } else {
4907: my ($startblock,$endblock) =
4908: &Apache::loncommon::blockcheck(\%setters,'port');
4909: if ($startblock && $endblock) {
4910: return 'B';
4911: }
4912: }
4913: }
4914: if ($result eq 'ok') {
4915: return 'F';
4916: } elsif ($result =~ /^[^:]+:guest_/) {
4917: return 'A';
4918: }
4919: return '';
4920: }
4921:
4922: sub get_portfolio_access {
4923: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4924:
4925: if (!ref($access_hash)) {
4926: my $current_perms = &get_portfile_permissions($udom,$unum);
4927: my %access_controls = &get_access_controls($current_perms,$group,
4928: $file_name);
4929: $access_hash = $access_controls{$file_name};
4930: }
4931:
4932: my ($public,$guest,@domains,@users,@courses,@groups);
4933: my $now = time;
4934: if (ref($access_hash) eq 'HASH') {
4935: foreach my $key (keys(%{$access_hash})) {
4936: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4937: if ($start > $now) {
4938: next;
4939: }
4940: if ($end && $end<$now) {
4941: next;
4942: }
4943: if ($scope eq 'public') {
4944: $public = $key;
4945: last;
4946: } elsif ($scope eq 'guest') {
4947: $guest = $key;
4948: } elsif ($scope eq 'domains') {
4949: push(@domains,$key);
4950: } elsif ($scope eq 'users') {
4951: push(@users,$key);
4952: } elsif ($scope eq 'course') {
4953: push(@courses,$key);
4954: } elsif ($scope eq 'group') {
4955: push(@groups,$key);
4956: }
4957: }
4958: if ($public) {
4959: return 'ok';
4960: }
4961: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4962: if ($guest) {
4963: return $guest;
4964: }
4965: } else {
4966: if (@domains > 0) {
4967: foreach my $domkey (@domains) {
4968: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4969: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4970: return 'ok';
4971: }
4972: }
4973: }
4974: }
4975: if (@users > 0) {
4976: foreach my $userkey (@users) {
4977: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4978: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4979: if (ref($item) eq 'HASH') {
4980: if (($item->{'uname'} eq $env{'user.name'}) &&
4981: ($item->{'udom'} eq $env{'user.domain'})) {
4982: return 'ok';
4983: }
4984: }
4985: }
4986: }
4987: }
4988: }
4989: my %roleshash;
4990: my @courses_and_groups = @courses;
4991: push(@courses_and_groups,@groups);
4992: if (@courses_and_groups > 0) {
4993: my (%allgroups,%allroles);
4994: my ($start,$end,$role,$sec,$group);
4995: foreach my $envkey (%env) {
4996: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
4997: my $cid = $2.'_'.$3;
4998: if ($1 eq 'gr') {
4999: $group = $4;
5000: $allgroups{$cid}{$group} = $env{$envkey};
5001: } else {
5002: if ($4 eq '') {
5003: $sec = 'none';
5004: } else {
5005: $sec = $4;
5006: }
5007: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5008: }
5009: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
5010: my $cid = $2.'_'.$3;
5011: if ($4 eq '') {
5012: $sec = 'none';
5013: } else {
5014: $sec = $4;
5015: }
5016: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5017: }
5018: }
5019: if (keys(%allroles) == 0) {
5020: return;
5021: }
5022: foreach my $key (@courses_and_groups) {
5023: my %content = %{$$access_hash{$key}};
5024: my $cnum = $content{'number'};
5025: my $cdom = $content{'domain'};
5026: my $cid = $cdom.'_'.$cnum;
5027: if (!exists($allroles{$cid})) {
5028: next;
5029: }
5030: foreach my $role_id (keys(%{$content{'roles'}})) {
5031: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5032: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5033: my @status = @{$content{'roles'}{$role_id}{'access'}};
5034: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5035: foreach my $role (keys(%{$allroles{$cid}})) {
5036: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5037: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5038: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5039: if (grep/^all$/,@sections) {
5040: return 'ok';
5041: } else {
5042: if (grep/^$sec$/,@sections) {
5043: return 'ok';
5044: }
5045: }
5046: }
5047: }
5048: if (keys(%{$allgroups{$cid}}) == 0) {
5049: if (grep/^none$/,@groups) {
5050: return 'ok';
5051: }
5052: } else {
5053: if (grep/^all$/,@groups) {
5054: return 'ok';
5055: }
5056: foreach my $group (keys(%{$allgroups{$cid}})) {
5057: if (grep/^$group$/,@groups) {
5058: return 'ok';
5059: }
5060: }
5061: }
5062: }
5063: }
5064: }
5065: }
5066: }
5067: if ($guest) {
5068: return $guest;
5069: }
5070: }
5071: }
5072: return;
5073: }
5074:
5075: sub course_group_datechecker {
5076: my ($dates,$now,$status) = @_;
5077: my ($start,$end) = split(/\./,$dates);
5078: if (!$start && !$end) {
5079: return 'ok';
5080: }
5081: if (grep/^active$/,@{$status}) {
5082: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5083: return 'ok';
5084: }
5085: }
5086: if (grep/^previous$/,@{$status}) {
5087: if ($end > $now ) {
5088: return 'ok';
5089: }
5090: }
5091: if (grep/^future$/,@{$status}) {
5092: if ($start > $now) {
5093: return 'ok';
5094: }
5095: }
5096: return;
5097: }
5098:
5099: sub parse_portfolio_url {
5100: my ($url) = @_;
5101:
5102: my ($type,$udom,$unum,$group,$file_name);
5103:
5104: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
5105: $type = 1;
5106: $udom = $1;
5107: $unum = $2;
5108: $file_name = $3;
5109: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
5110: $type = 2;
5111: $udom = $1;
5112: $unum = $2;
5113: $group = $3;
5114: $file_name = $3.'/'.$4;
5115: }
5116: if (wantarray) {
5117: return ($type,$udom,$unum,$file_name,$group);
5118: }
5119: return $type;
5120: }
5121:
5122: sub is_portfolio_url {
5123: my ($url) = @_;
5124: return scalar(&parse_portfolio_url($url));
5125: }
5126:
5127: sub is_portfolio_file {
5128: my ($file) = @_;
5129: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
5130: return 1;
5131: }
5132: return;
5133: }
5134:
5135: sub usertools_access {
5136: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref) = @_;
5137: my ($access,%tools);
5138: if ($context eq '') {
5139: $context = 'tools';
5140: }
5141: if ($context eq 'requestcourses') {
5142: %tools = (
5143: official => 1,
5144: unofficial => 1,
5145: community => 1,
5146: );
5147: } else {
5148: %tools = (
5149: aboutme => 1,
5150: blog => 1,
5151: portfolio => 1,
5152: );
5153: }
5154: return if (!defined($tools{$tool}));
5155:
5156: if ((!defined($udom)) || (!defined($uname))) {
5157: $udom = $env{'user.domain'};
5158: $uname = $env{'user.name'};
5159: }
5160:
5161: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5162: if ($action ne 'reload') {
5163: if ($context eq 'requestcourses') {
5164: return $env{'environment.canrequest.'.$tool};
5165: } else {
5166: return $env{'environment.availabletools.'.$tool};
5167: }
5168: }
5169: }
5170:
5171: my ($toolstatus,$inststatus);
5172:
5173: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5174: ($action ne 'reload')) {
5175: $toolstatus = $env{'environment.'.$context.'.'.$tool};
5176: $inststatus = $env{'environment.inststatus'};
5177: } else {
5178: if (ref($userenvref) eq 'HASH') {
5179: $toolstatus = $userenvref->{$context.'.'.$tool};
5180: $inststatus = $userenvref->{'inststatus'};
5181: } else {
5182: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5183: $toolstatus = $userenv{$context.'.'.$tool};
5184: $inststatus = $userenv{'inststatus'};
5185: }
5186: }
5187:
5188: if ($toolstatus ne '') {
5189: if ($toolstatus) {
5190: $access = 1;
5191: } else {
5192: $access = 0;
5193: }
5194: return $access;
5195: }
5196:
5197: my ($is_adv,%domdef);
5198: if (ref($is_advref) eq 'HASH') {
5199: $is_adv = $is_advref->{'is_adv'};
5200: } else {
5201: $is_adv = &is_advanced_user($udom,$uname);
5202: }
5203: if (ref($domdefref) eq 'HASH') {
5204: %domdef = %{$domdefref};
5205: } else {
5206: %domdef = &get_domain_defaults($udom);
5207: }
5208: if (ref($domdef{$tool}) eq 'HASH') {
5209: if ($is_adv) {
5210: if ($domdef{$tool}{'_LC_adv'} ne '') {
5211: if ($domdef{$tool}{'_LC_adv'}) {
5212: $access = 1;
5213: } else {
5214: $access = 0;
5215: }
5216: return $access;
5217: }
5218: }
5219: if ($inststatus ne '') {
5220: my ($hasaccess,$hasnoaccess);
5221: foreach my $affiliation (split(/:/,$inststatus)) {
5222: if ($domdef{$tool}{$affiliation} ne '') {
5223: if ($domdef{$tool}{$affiliation}) {
5224: $hasaccess = 1;
5225: } else {
5226: $hasnoaccess = 1;
5227: }
5228: }
5229: }
5230: if ($hasaccess || $hasnoaccess) {
5231: if ($hasaccess) {
5232: $access = 1;
5233: } elsif ($hasnoaccess) {
5234: $access = 0;
5235: }
5236: return $access;
5237: }
5238: } else {
5239: if ($domdef{$tool}{'default'} ne '') {
5240: if ($domdef{$tool}{'default'}) {
5241: $access = 1;
5242: } elsif ($domdef{$tool}{'default'} == 0) {
5243: $access = 0;
5244: }
5245: return $access;
5246: }
5247: }
5248: } else {
5249: if ($context eq 'tools') {
5250: $access = 1;
5251: } else {
5252: $access = 0;
5253: }
5254: return $access;
5255: }
5256: }
5257:
5258: sub is_course_owner {
5259: my ($cdom,$cnum,$udom,$uname) = @_;
5260: if (($udom eq '') || ($uname eq '')) {
5261: $udom = $env{'user.domain'};
5262: $uname = $env{'user.name'};
5263: }
5264: unless (($udom eq '') || ($uname eq '')) {
5265: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5266: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5267: return 1;
5268: } else {
5269: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5270: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5271: return 1;
5272: }
5273: }
5274: }
5275: }
5276: return;
5277: }
5278:
5279: sub is_advanced_user {
5280: my ($udom,$uname) = @_;
5281: if ($udom ne '' && $uname ne '') {
5282: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5283: return $env{'user.adv'};
5284: }
5285: }
5286: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5287: my %allroles;
5288: my $is_adv;
5289: foreach my $role (keys(%roleshash)) {
5290: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5291: my $area = '/'.$tdomain.'/'.$trest;
5292: if ($sec ne '') {
5293: $area .= '/'.$sec;
5294: }
5295: if (($area ne '') && ($trole ne '')) {
5296: my $spec=$trole.'.'.$area;
5297: if ($trole =~ /^cr\//) {
5298: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5299: } elsif ($trole ne 'gr') {
5300: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5301: }
5302: }
5303: }
5304: foreach my $role (keys(%allroles)) {
5305: last if ($is_adv);
5306: foreach my $item (split(/:/,$allroles{$role})) {
5307: if ($item ne '') {
5308: my ($privilege,$restrictions)=split(/&/,$item);
5309: if ($privilege eq 'adv') {
5310: $is_adv = 1;
5311: last;
5312: }
5313: }
5314: }
5315: }
5316: return $is_adv;
5317: }
5318:
5319: sub check_can_request {
5320: my ($dom,$can_request,$request_domains) = @_;
5321: my $canreq = 0;
5322: my ($types,$typename) = &Apache::loncommon::course_types();
5323: my @options = ('approval','validate','autolimit');
5324: my $optregex = join('|',@options);
5325: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5326: foreach my $type (@{$types}) {
5327: if (&usertools_access($env{'user.name'},
5328: $env{'user.domain'},
5329: $type,undef,'requestcourses')) {
5330: $canreq ++;
5331: if (ref($request_domains) eq 'HASH') {
5332: push(@{$request_domains->{$type}},$env{'user.domain'});
5333: }
5334: if ($dom eq $env{'user.domain'}) {
5335: $can_request->{$type} = 1;
5336: }
5337: }
5338: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5339: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5340: if (@curr > 0) {
5341: foreach my $item (@curr) {
5342: if (ref($request_domains) eq 'HASH') {
5343: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5344: if ($otherdom ne '') {
5345: if (ref($request_domains->{$type}) eq 'ARRAY') {
5346: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5347: push(@{$request_domains->{$type}},$otherdom);
5348: }
5349: } else {
5350: push(@{$request_domains->{$type}},$otherdom);
5351: }
5352: }
5353: }
5354: }
5355: unless($dom eq $env{'user.domain'}) {
5356: $canreq ++;
5357: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5358: $can_request->{$type} = 1;
5359: }
5360: }
5361: }
5362: }
5363: }
5364: }
5365: return $canreq;
5366: }
5367:
5368: # ---------------------------------------------- Custom access rule evaluation
5369:
5370: sub customaccess {
5371: my ($priv,$uri)=@_;
5372: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
5373: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
5374: $udom = &LONCAPA::clean_domain($udom);
5375: $ucrs = &LONCAPA::clean_username($ucrs);
5376: my $access=0;
5377: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
5378: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5379: if ($type eq 'user') {
5380: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5381: my ($tdom,$tuname)=split(m{/},$scope);
5382: if ($tdom) {
5383: if ($tdom ne $env{'user.domain'}) { next; }
5384: }
5385: if ($tuname) {
5386: if ($tuname ne $env{'user.name'}) { next; }
5387: }
5388: $access=($effect eq 'allow');
5389: last;
5390: }
5391: } else {
5392: if ($role) {
5393: if ($role ne $urole) { next; }
5394: }
5395: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5396: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5397: if ($tdom) {
5398: if ($tdom ne $udom) { next; }
5399: }
5400: if ($tcrs) {
5401: if ($tcrs ne $ucrs) { next; }
5402: }
5403: if ($tsec) {
5404: if ($tsec ne $usec) { next; }
5405: }
5406: $access=($effect eq 'allow');
5407: last;
5408: }
5409: if ($realm eq '' && $role eq '') {
5410: $access=($effect eq 'allow');
5411: }
5412: }
5413: }
5414: return $access;
5415: }
5416:
5417: # ------------------------------------------------- Check for a user privilege
5418:
5419: sub allowed {
5420: my ($priv,$uri,$symb,$role)=@_;
5421: my $ver_orguri=$uri;
5422: $uri=&deversion($uri);
5423: my $orguri=$uri;
5424: $uri=&declutter($uri);
5425:
5426: if ($priv eq 'evb') {
5427: # Evade communication block restrictions for specified role in a course
5428: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5429: return $1;
5430: } else {
5431: return;
5432: }
5433: }
5434:
5435: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
5436: # Free bre access to adm and meta resources
5437: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
5438: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5439: && ($priv eq 'bre')) {
5440: return 'F';
5441: }
5442:
5443: # Free bre access to user's own portfolio contents
5444: my ($space,$domain,$name,@dir)=split('/',$uri);
5445: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
5446: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
5447: my %setters;
5448: my ($startblock,$endblock) =
5449: &Apache::loncommon::blockcheck(\%setters,'port');
5450: if ($startblock && $endblock) {
5451: return 'B';
5452: } else {
5453: return 'F';
5454: }
5455: }
5456:
5457: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
5458: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5459: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5460: if (exists($env{'request.course.id'})) {
5461: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5462: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5463: if (($domain eq $cdom) && ($name eq $cnum)) {
5464: my $courseprivid=$env{'request.course.id'};
5465: $courseprivid=~s/\_/\//;
5466: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5467: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5468: return $1;
5469: } else {
5470: if ($env{'request.course.sec'}) {
5471: $courseprivid.='/'.$env{'request.course.sec'};
5472: }
5473: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5474: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5475: return $2;
5476: }
5477: }
5478: }
5479: }
5480: }
5481:
5482: # Free bre to public access
5483:
5484: if ($priv eq 'bre') {
5485: my $copyright=&metadata($uri,'copyright');
5486: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
5487: return 'F';
5488: }
5489: if ($copyright eq 'priv') {
5490: $uri=~/([^\/]+)\/([^\/]+)\//;
5491: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
5492: return '';
5493: }
5494: }
5495: if ($copyright eq 'domain') {
5496: $uri=~/([^\/]+)\/([^\/]+)\//;
5497: unless (($env{'user.domain'} eq $1) ||
5498: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
5499: return '';
5500: }
5501: }
5502: if ($env{'request.role'}=~ /li\.\//) {
5503: # Library role, so allow browsing of resources in this domain.
5504: return 'F';
5505: }
5506: if ($copyright eq 'custom') {
5507: unless (&customaccess($priv,$uri)) { return ''; }
5508: }
5509: }
5510: # Domain coordinator is trying to create a course
5511: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
5512: # uri is the requested domain in this case.
5513: # comparison to 'request.role.domain' shows if the user has selected
5514: # a role of dc for the domain in question.
5515: return 'F' if ($uri eq $env{'request.role.domain'});
5516: }
5517:
5518: my $thisallowed='';
5519: my $statecond=0;
5520: my $courseprivid='';
5521:
5522: my $ownaccess;
5523: # Community Coordinator or Assistant Co-author browsing resource space.
5524: if (($priv eq 'bro') && ($env{'user.author'})) {
5525: if ($uri eq '') {
5526: $ownaccess = 1;
5527: } else {
5528: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5529: my $udom = $env{'user.domain'};
5530: my $uname = $env{'user.name'};
5531: if ($uri =~ m{^\Q$udom\E/?$}) {
5532: $ownaccess = 1;
5533: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
5534: unless ($uri =~ m{\.\./}) {
5535: $ownaccess = 1;
5536: }
5537: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5538: my $now = time;
5539: if ($uri =~ m{^([^/]+)/?$}) {
5540: my $adom = $1;
5541: foreach my $key (keys(%env)) {
5542: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
5543: my ($start,$end) = split('.',$env{$key});
5544: if (($now >= $start) && (!$end || $end < $now)) {
5545: $ownaccess = 1;
5546: last;
5547: }
5548: }
5549: }
5550: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5551: my $adom = $1;
5552: my $aname = $2;
5553: foreach my $role ('ca','aa') {
5554: if ($env{"user.role.$role./$adom/$aname"}) {
5555: my ($start,$end) =
5556: split('.',$env{"user.role.$role./$adom/$aname"});
5557: if (($now >= $start) && (!$end || $end < $now)) {
5558: $ownaccess = 1;
5559: last;
5560: }
5561: }
5562: }
5563: }
5564: }
5565: }
5566: }
5567: }
5568:
5569: # Course
5570:
5571: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
5572: unless (($priv eq 'bro') && (!$ownaccess)) {
5573: $thisallowed.=$1;
5574: }
5575: }
5576:
5577: # Domain
5578:
5579: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
5580: =~/\Q$priv\E\&([^\:]*)/) {
5581: unless (($priv eq 'bro') && (!$ownaccess)) {
5582: $thisallowed.=$1;
5583: }
5584: }
5585:
5586: # Course: uri itself is a course
5587: my $courseuri=$uri;
5588: $courseuri=~s/\_(\d)/\/$1/;
5589: $courseuri=~s/^([^\/])/\/$1/;
5590:
5591: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
5592: =~/\Q$priv\E\&([^\:]*)/) {
5593: unless (($priv eq 'bro') && (!$ownaccess)) {
5594: $thisallowed.=$1;
5595: }
5596: }
5597:
5598: # URI is an uploaded document for this course, default permissions don't matter
5599: # not allowing 'edit' access (editupload) to uploaded course docs
5600: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
5601: $thisallowed='';
5602: my ($match)=&is_on_map($uri);
5603: if ($match) {
5604: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5605: =~/\Q$priv\E\&([^\:]*)/) {
5606: $thisallowed.=$1;
5607: }
5608: } else {
5609: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
5610: if ($refuri) {
5611: if ($refuri =~ m|^/adm/|) {
5612: $thisallowed='F';
5613: } else {
5614: $refuri=&declutter($refuri);
5615: my ($match) = &is_on_map($refuri);
5616: if ($match) {
5617: $thisallowed='F';
5618: }
5619: }
5620: }
5621: }
5622: }
5623:
5624: if ($priv eq 'bre'
5625: && $thisallowed ne 'F'
5626: && $thisallowed ne '2'
5627: && &is_portfolio_url($uri)) {
5628: $thisallowed = &portfolio_access($uri);
5629: }
5630:
5631: # Full access at system, domain or course-wide level? Exit.
5632: if ($thisallowed=~/F/) {
5633: return 'F';
5634: }
5635:
5636: # If this is generating or modifying users, exit with special codes
5637:
5638: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5639: if (($priv eq 'cca') || ($priv eq 'caa')) {
5640: my ($audom,$auname)=split('/',$uri);
5641: # no author name given, so this just checks on the general right to make a co-author in this domain
5642: unless ($auname) { return $thisallowed; }
5643: # an author name is given, so we are about to actually make a co-author for a certain account
5644: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5645: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5646: ($audom ne $env{'request.role.domain'}))) { return ''; }
5647: }
5648: return $thisallowed;
5649: }
5650: #
5651: # Gathered so far: system, domain and course wide privileges
5652: #
5653: # Course: See if uri or referer is an individual resource that is part of
5654: # the course
5655:
5656: if ($env{'request.course.id'}) {
5657:
5658: $courseprivid=$env{'request.course.id'};
5659: if ($env{'request.course.sec'}) {
5660: $courseprivid.='/'.$env{'request.course.sec'};
5661: }
5662: $courseprivid=~s/\_/\//;
5663: my $checkreferer=1;
5664: my ($match,$cond)=&is_on_map($uri);
5665: if ($match) {
5666: $statecond=$cond;
5667: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
5668: =~/\Q$priv\E\&([^\:]*)/) {
5669: $thisallowed.=$1;
5670: $checkreferer=0;
5671: }
5672: }
5673:
5674: if ($checkreferer) {
5675: my $refuri=$env{'httpref.'.$orguri};
5676: unless ($refuri) {
5677: foreach my $key (keys(%env)) {
5678: if ($key=~/^httpref\..*\*/) {
5679: my $pattern=$key;
5680: $pattern=~s/^httpref\.\/res\///;
5681: $pattern=~s/\*/\[\^\/\]\+/g;
5682: $pattern=~s/\//\\\//g;
5683: if ($orguri=~/$pattern/) {
5684: $refuri=$env{$key};
5685: }
5686: }
5687: }
5688: }
5689:
5690: if ($refuri) {
5691: $refuri=&declutter($refuri);
5692: my ($match,$cond)=&is_on_map($refuri);
5693: if ($match) {
5694: my $refstatecond=$cond;
5695: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
5696: =~/\Q$priv\E\&([^\:]*)/) {
5697: $thisallowed.=$1;
5698: $uri=$refuri;
5699: $statecond=$refstatecond;
5700: }
5701: }
5702: }
5703: }
5704: }
5705:
5706: #
5707: # Gathered now: all privileges that could apply, and condition number
5708: #
5709: #
5710: # Full or no access?
5711: #
5712:
5713: if ($thisallowed=~/F/) {
5714: return 'F';
5715: }
5716:
5717: unless ($thisallowed) {
5718: return '';
5719: }
5720:
5721: # Restrictions exist, deal with them
5722: #
5723: # C:according to course preferences
5724: # R:according to resource settings
5725: # L:unless locked
5726: # X:according to user session state
5727: #
5728:
5729: # Possibly locked functionality, check all courses
5730: # Locks might take effect only after 10 minutes cache expiration for other
5731: # courses, and 2 minutes for current course
5732:
5733: my $envkey;
5734: if ($thisallowed=~/L/) {
5735: foreach $envkey (keys(%env)) {
5736: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5737: my $courseid=$2;
5738: my $roleid=$1.'.'.$2;
5739: $courseid=~s/^\///;
5740: my $expiretime=600;
5741: if ($env{'request.role'} eq $roleid) {
5742: $expiretime=120;
5743: }
5744: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5745: my $prefix='course.'.$cdom.'_'.$cnum.'.';
5746: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
5747: &coursedescription($courseid,{'freshen_cache' => 1});
5748: }
5749: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5750: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5751: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5752: &log($env{'user.domain'},$env{'user.name'},
5753: $env{'user.home'},
5754: 'Locked by res: '.$priv.' for '.$uri.' due to '.
5755: $cdom.'/'.$cnum.'/'.$csec.' expire '.
5756: $env{$prefix.'priv.'.$priv.'.lock.expire'});
5757: return '';
5758: }
5759: }
5760: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5761: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5762: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5763: &log($env{'user.domain'},$env{'user.name'},
5764: $env{'user.home'},
5765: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
5766: $cdom.'/'.$cnum.'/'.$csec.' expire '.
5767: $env{$prefix.'priv.'.$priv.'.lock.expire'});
5768: return '';
5769: }
5770: }
5771: }
5772: }
5773: }
5774:
5775: #
5776: # Rest of the restrictions depend on selected course
5777: #
5778:
5779: unless ($env{'request.course.id'}) {
5780: if ($thisallowed eq 'A') {
5781: return 'A';
5782: } elsif ($thisallowed eq 'B') {
5783: return 'B';
5784: } else {
5785: return '1';
5786: }
5787: }
5788:
5789: #
5790: # Now user is definitely in a course
5791: #
5792:
5793:
5794: # Course preferences
5795:
5796: if ($thisallowed=~/C/) {
5797: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5798: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5799: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
5800: =~/\Q$rolecode\E/) {
5801: if (($priv ne 'pch') && ($priv ne 'plc')) {
5802: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5803: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5804: $env{'request.course.id'});
5805: }
5806: return '';
5807: }
5808:
5809: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
5810: =~/\Q$unamedom\E/) {
5811: if (($priv ne 'pch') && ($priv ne 'plc')) {
5812: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5813: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5814: $env{'request.course.id'});
5815: }
5816: return '';
5817: }
5818: }
5819:
5820: # Resource preferences
5821:
5822: if ($thisallowed=~/R/) {
5823: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5824: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
5825: if (($priv ne 'pch') && ($priv ne 'plc')) {
5826: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5827: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5828: }
5829: return '';
5830: }
5831: }
5832:
5833: # Restricted by state or randomout?
5834:
5835: if ($thisallowed=~/X/) {
5836: if ($env{'acc.randomout'}) {
5837: if (!$symb) { $symb=&symbread($uri,1); }
5838: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
5839: return '';
5840: }
5841: }
5842: if (&condval($statecond)) {
5843: return '2';
5844: } else {
5845: return '';
5846: }
5847: }
5848:
5849: if ($thisallowed eq 'A') {
5850: return 'A';
5851: } elsif ($thisallowed eq 'B') {
5852: return 'B';
5853: }
5854: return 'F';
5855: }
5856:
5857: sub split_uri_for_cond {
5858: my $uri=&deversion(&declutter(shift));
5859: my @uriparts=split(/\//,$uri);
5860: my $filename=pop(@uriparts);
5861: my $pathname=join('/',@uriparts);
5862: return ($pathname,$filename);
5863: }
5864: # --------------------------------------------------- Is a resource on the map?
5865:
5866: sub is_on_map {
5867: my ($pathname,$filename) = &split_uri_for_cond(shift);
5868: #Trying to find the conditional for the file
5869: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
5870: /\&\Q$filename\E\:([\d\|]+)\&/);
5871: if ($match) {
5872: return (1,$1);
5873: } else {
5874: return (0,0);
5875: }
5876: }
5877:
5878: # --------------------------------------------------------- Get symb from alias
5879:
5880: sub get_symb_from_alias {
5881: my $symb=shift;
5882: my ($map,$resid,$url)=&decode_symb($symb);
5883: # Already is a symb
5884: if ($url) { return $symb; }
5885: # Must be an alias
5886: my $aliassymb='';
5887: my %bighash;
5888: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
5889: &GDBM_READER(),0640)) {
5890: my $rid=$bighash{'mapalias_'.$symb};
5891: if ($rid) {
5892: my ($mapid,$resid)=split(/\./,$rid);
5893: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5894: $resid,$bighash{'src_'.$rid});
5895: }
5896: untie %bighash;
5897: }
5898: return $aliassymb;
5899: }
5900:
5901: # ----------------------------------------------------------------- Define Role
5902:
5903: sub definerole {
5904: if (allowed('mcr','/')) {
5905: my ($rolename,$sysrole,$domrole,$courole)=@_;
5906: foreach my $role (split(':',$sysrole)) {
5907: my ($crole,$cqual)=split(/\&/,$role);
5908: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5909: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5910: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
5911: return "refused:s:$crole&$cqual";
5912: }
5913: }
5914: }
5915: foreach my $role (split(':',$domrole)) {
5916: my ($crole,$cqual)=split(/\&/,$role);
5917: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5918: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5919: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
5920: return "refused:d:$crole&$cqual";
5921: }
5922: }
5923: }
5924: foreach my $role (split(':',$courole)) {
5925: my ($crole,$cqual)=split(/\&/,$role);
5926: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5927: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5928: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
5929: return "refused:c:$crole&$cqual";
5930: }
5931: }
5932: }
5933: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5934: "$env{'user.domain'}:$env{'user.name'}:".
5935: "rolesdef_$rolename=".
5936: escape($sysrole.'_'.$domrole.'_'.$courole);
5937: return reply($command,$env{'user.home'});
5938: } else {
5939: return 'refused';
5940: }
5941: }
5942:
5943: # ---------------- Make a metadata query against the network of library servers
5944:
5945: sub metadata_query {
5946: my ($query,$custom,$customshow,$server_array)=@_;
5947: my %rhash;
5948: my %libserv = &all_library();
5949: my @server_list = (defined($server_array) ? @$server_array
5950: : keys(%libserv) );
5951: for my $server (@server_list) {
5952: unless ($custom or $customshow) {
5953: my $reply=&reply("querysend:".&escape($query),$server);
5954: $rhash{$server}=$reply;
5955: }
5956: else {
5957: my $reply=&reply("querysend:".&escape($query).':'.
5958: &escape($custom).':'.&escape($customshow),
5959: $server);
5960: $rhash{$server}=$reply;
5961: }
5962: }
5963: return \%rhash;
5964: }
5965:
5966: # ----------------------------------------- Send log queries and wait for reply
5967:
5968: sub log_query {
5969: my ($uname,$udom,$query,%filters)=@_;
5970: my $uhome=&homeserver($uname,$udom);
5971: if ($uhome eq 'no_host') { return 'error: no_host'; }
5972: my $uhost=&hostname($uhome);
5973: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
5974: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5975: $uhome);
5976: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
5977: return get_query_reply($queryid);
5978: }
5979:
5980: # -------------------------- Update MySQL table for portfolio file
5981:
5982: sub update_portfolio_table {
5983: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
5984: if ($group ne '') {
5985: $file_name =~s /^\Q$group\E//;
5986: }
5987: my $homeserver = &homeserver($uname,$udom);
5988: my $queryid=
5989: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5990: ':'.&escape($file_name).':'.$action,$homeserver);
5991: my $reply = &get_query_reply($queryid);
5992: return $reply;
5993: }
5994:
5995: # -------------------------- Update MySQL allusers table
5996:
5997: sub update_allusers_table {
5998: my ($uname,$udom,$names) = @_;
5999: my $homeserver = &homeserver($uname,$udom);
6000: my $queryid=
6001: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
6002: 'lastname='.&escape($names->{'lastname'}).'%%'.
6003: 'firstname='.&escape($names->{'firstname'}).'%%'.
6004: 'middlename='.&escape($names->{'middlename'}).'%%'.
6005: 'generation='.&escape($names->{'generation'}).'%%'.
6006: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
6007: 'id='.&escape($names->{'id'}),$homeserver);
6008: return;
6009: }
6010:
6011: # ------- Request retrieval of institutional classlists for course(s)
6012:
6013: sub fetch_enrollment_query {
6014: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
6015: my $homeserver;
6016: my $maxtries = 1;
6017: if ($context eq 'automated') {
6018: $homeserver = $perlvar{'lonHostID'};
6019: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
6020: } else {
6021: $homeserver = &homeserver($cnum,$dom);
6022: }
6023: my $host=&hostname($homeserver);
6024: my $cmd = '';
6025: foreach my $affiliate (keys(%{$affiliatesref})) {
6026: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
6027: }
6028: $cmd =~ s/%%$//;
6029: $cmd = &escape($cmd);
6030: my $query = 'fetchenrollment';
6031: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
6032: unless ($queryid=~/^\Q$host\E\_/) {
6033: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
6034: return 'error: '.$queryid;
6035: }
6036: my $reply = &get_query_reply($queryid);
6037: my $tries = 1;
6038: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6039: $reply = &get_query_reply($queryid);
6040: $tries ++;
6041: }
6042: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6043: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6044: } else {
6045: my @responses = split(/:/,$reply);
6046: if ($homeserver eq $perlvar{'lonHostID'}) {
6047: foreach my $line (@responses) {
6048: my ($key,$value) = split(/=/,$line,2);
6049: $$replyref{$key} = $value;
6050: }
6051: } else {
6052: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
6053: foreach my $line (@responses) {
6054: my ($key,$value) = split(/=/,$line);
6055: $$replyref{$key} = $value;
6056: if ($value > 0) {
6057: foreach my $item (@{$$affiliatesref{$key}}) {
6058: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
6059: my $destname = $pathname.'/'.$filename;
6060: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
6061: if ($xml_classlist =~ /^error/) {
6062: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6063: } else {
6064: if ( open(FILE,">$destname") ) {
6065: print FILE &unescape($xml_classlist);
6066: close(FILE);
6067: } else {
6068: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
6069: }
6070: }
6071: }
6072: }
6073: }
6074: }
6075: return 'ok';
6076: }
6077: return 'error';
6078: }
6079:
6080: sub get_query_reply {
6081: my $queryid=shift;
6082: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
6083: my $reply='';
6084: for (1..100) {
6085: sleep 2;
6086: if (-e $replyfile.'.end') {
6087: if (open(my $fh,$replyfile)) {
6088: $reply = join('',<$fh>);
6089: close($fh);
6090: } else { return 'error: reply_file_error'; }
6091: return &unescape($reply);
6092: }
6093: }
6094: return 'timeout:'.$queryid;
6095: }
6096:
6097: sub courselog_query {
6098: #
6099: # possible filters:
6100: # url: url or symb
6101: # username
6102: # domain
6103: # action: view, submit, grade
6104: # start: timestamp
6105: # end: timestamp
6106: #
6107: my (%filters)=@_;
6108: unless ($env{'request.course.id'}) { return 'no_course'; }
6109: if ($filters{'url'}) {
6110: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6111: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6112: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6113: }
6114: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6115: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6116: return &log_query($cname,$cdom,'courselog',%filters);
6117: }
6118:
6119: sub userlog_query {
6120: #
6121: # possible filters:
6122: # action: log check role
6123: # start: timestamp
6124: # end: timestamp
6125: #
6126: my ($uname,$udom,%filters)=@_;
6127: return &log_query($uname,$udom,'userlog',%filters);
6128: }
6129:
6130: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6131:
6132: sub auto_run {
6133: my ($cnum,$cdom) = @_;
6134: my $response = 0;
6135: my $settings;
6136: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6137: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6138: $settings = $domconfig{'autoenroll'};
6139: if ($settings->{'run'} eq '1') {
6140: $response = 1;
6141: }
6142: } else {
6143: my $homeserver;
6144: if (&is_course($cdom,$cnum)) {
6145: $homeserver = &homeserver($cnum,$cdom);
6146: } else {
6147: $homeserver = &domain($cdom,'primary');
6148: }
6149: if ($homeserver ne 'no_host') {
6150: $response = &reply('autorun:'.$cdom,$homeserver);
6151: }
6152: }
6153: return $response;
6154: }
6155:
6156: sub auto_get_sections {
6157: my ($cnum,$cdom,$inst_coursecode) = @_;
6158: my $homeserver;
6159: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6160: $homeserver = &homeserver($cnum,$cdom);
6161: }
6162: if (!defined($homeserver)) {
6163: if ($cdom =~ /^$match_domain$/) {
6164: $homeserver = &domain($cdom,'primary');
6165: }
6166: }
6167: my @secs;
6168: if (defined($homeserver)) {
6169: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6170: unless ($response eq 'refused') {
6171: @secs = split(/:/,$response);
6172: }
6173: }
6174: return @secs;
6175: }
6176:
6177: sub auto_new_course {
6178: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
6179: my $homeserver = &homeserver($cnum,$cdom);
6180: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
6181: return $response;
6182: }
6183:
6184: sub auto_validate_courseID {
6185: my ($cnum,$cdom,$inst_course_id) = @_;
6186: my $homeserver = &homeserver($cnum,$cdom);
6187: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
6188: return $response;
6189: }
6190:
6191: sub auto_validate_instcode {
6192: my ($cnum,$cdom,$instcode,$owner) = @_;
6193: my ($homeserver,$response);
6194: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6195: $homeserver = &homeserver($cnum,$cdom);
6196: }
6197: if (!defined($homeserver)) {
6198: if ($cdom =~ /^$match_domain$/) {
6199: $homeserver = &domain($cdom,'primary');
6200: }
6201: }
6202: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6203: &escape($instcode).':'.&escape($owner),$homeserver));
6204: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6205: return ($outcome,$description);
6206: }
6207:
6208: sub auto_create_password {
6209: my ($cnum,$cdom,$authparam,$udom) = @_;
6210: my ($homeserver,$response);
6211: my $create_passwd = 0;
6212: my $authchk = '';
6213: if ($udom =~ /^$match_domain$/) {
6214: $homeserver = &domain($udom,'primary');
6215: }
6216: if ($homeserver eq '') {
6217: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6218: $homeserver = &homeserver($cnum,$cdom);
6219: }
6220: }
6221: if ($homeserver eq '') {
6222: $authchk = 'nodomain';
6223: } else {
6224: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6225: if ($response eq 'refused') {
6226: $authchk = 'refused';
6227: } else {
6228: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
6229: }
6230: }
6231: return ($authparam,$create_passwd,$authchk);
6232: }
6233:
6234: sub auto_photo_permission {
6235: my ($cnum,$cdom,$students) = @_;
6236: my $homeserver = &homeserver($cnum,$cdom);
6237: my ($outcome,$perm_reqd,$conditions) =
6238: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
6239: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6240: return (undef,undef);
6241: }
6242: return ($outcome,$perm_reqd,$conditions);
6243: }
6244:
6245: sub auto_checkphotos {
6246: my ($uname,$udom,$pid) = @_;
6247: my $homeserver = &homeserver($uname,$udom);
6248: my ($result,$resulttype);
6249: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
6250: &escape($uname).':'.&escape($pid),
6251: $homeserver));
6252: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6253: return (undef,undef);
6254: }
6255: if ($outcome) {
6256: ($result,$resulttype) = split(/:/,$outcome);
6257: }
6258: return ($result,$resulttype);
6259: }
6260:
6261: sub auto_photochoice {
6262: my ($cnum,$cdom) = @_;
6263: my $homeserver = &homeserver($cnum,$cdom);
6264: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
6265: &escape($cdom),
6266: $homeserver)));
6267: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6268: return (undef,undef);
6269: }
6270: return ($update,$comment);
6271: }
6272:
6273: sub auto_photoupdate {
6274: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6275: my $homeserver = &homeserver($cnum,$dom);
6276: my $host=&hostname($homeserver);
6277: my $cmd = '';
6278: my $maxtries = 1;
6279: foreach my $affiliate (keys(%{$affiliatesref})) {
6280: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
6281: }
6282: $cmd =~ s/%%$//;
6283: $cmd = &escape($cmd);
6284: my $query = 'institutionalphotos';
6285: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6286: unless ($queryid=~/^\Q$host\E\_/) {
6287: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6288: return 'error: '.$queryid;
6289: }
6290: my $reply = &get_query_reply($queryid);
6291: my $tries = 1;
6292: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6293: $reply = &get_query_reply($queryid);
6294: $tries ++;
6295: }
6296: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6297: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6298: } else {
6299: my @responses = split(/:/,$reply);
6300: my $outcome = shift(@responses);
6301: foreach my $item (@responses) {
6302: my ($key,$value) = split(/=/,$item);
6303: $$photo{$key} = $value;
6304: }
6305: return $outcome;
6306: }
6307: return 'error';
6308: }
6309:
6310: sub auto_instcode_format {
6311: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6312: $cat_order) = @_;
6313: my $courses = '';
6314: my @homeservers;
6315: if ($caller eq 'global') {
6316: my %servers = &get_servers($codedom,'library');
6317: foreach my $tryserver (keys(%servers)) {
6318: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6319: push(@homeservers,$tryserver);
6320: }
6321: }
6322: } elsif ($caller eq 'requests') {
6323: if ($codedom =~ /^$match_domain$/) {
6324: my $chome = &domain($codedom,'primary');
6325: unless ($chome eq 'no_host') {
6326: push(@homeservers,$chome);
6327: }
6328: }
6329: } else {
6330: push(@homeservers,&homeserver($caller,$codedom));
6331: }
6332: foreach my $code (keys(%{$instcodes})) {
6333: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
6334: }
6335: chop($courses);
6336: my $ok_response = 0;
6337: my $response;
6338: while (@homeservers > 0 && $ok_response == 0) {
6339: my $server = shift(@homeservers);
6340: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6341: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6342: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
6343: split(/:/,$response);
6344: %{$codes} = (%{$codes},&str2hash($codes_str));
6345: push(@{$codetitles},&str2array($codetitles_str));
6346: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6347: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6348: $ok_response = 1;
6349: }
6350: }
6351: if ($ok_response) {
6352: return 'ok';
6353: } else {
6354: return $response;
6355: }
6356: }
6357:
6358: sub auto_instcode_defaults {
6359: my ($domain,$returnhash,$code_order) = @_;
6360: my @homeservers;
6361:
6362: my %servers = &get_servers($domain,'library');
6363: foreach my $tryserver (keys(%servers)) {
6364: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6365: push(@homeservers,$tryserver);
6366: }
6367: }
6368:
6369: my $response;
6370: foreach my $server (@homeservers) {
6371: $response=&reply('autoinstcodedefaults:'.$domain,$server);
6372: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6373:
6374: foreach my $pair (split(/\&/,$response)) {
6375: my ($name,$value)=split(/\=/,$pair);
6376: if ($name eq 'code_order') {
6377: @{$code_order} = split(/\&/,&unescape($value));
6378: } else {
6379: $returnhash->{&unescape($name)}=&unescape($value);
6380: }
6381: }
6382: return 'ok';
6383: }
6384:
6385: return $response;
6386: }
6387:
6388: sub auto_possible_instcodes {
6389: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6390: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6391: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6392: return;
6393: }
6394: my (@homeservers,$uhome);
6395: if (defined(&domain($domain,'primary'))) {
6396: $uhome=&domain($domain,'primary');
6397: push(@homeservers,&domain($domain,'primary'));
6398: } else {
6399: my %servers = &get_servers($domain,'library');
6400: foreach my $tryserver (keys(%servers)) {
6401: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6402: push(@homeservers,$tryserver);
6403: }
6404: }
6405: }
6406: my $response;
6407: foreach my $server (@homeservers) {
6408: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6409: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6410: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6411: split(':',$response);
6412: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6413: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
6414: foreach my $item (split('&',$cat_title)) {
6415: my ($name,$value)=split('=',$item);
6416: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
6417: }
6418: foreach my $item (split('&',$cat_order)) {
6419: my ($name,$value)=split('=',$item);
6420: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
6421: }
6422: return 'ok';
6423: }
6424: return $response;
6425: }
6426:
6427: sub auto_courserequest_checks {
6428: my ($dom) = @_;
6429: my ($homeserver,%validations);
6430: if ($dom =~ /^$match_domain$/) {
6431: $homeserver = &domain($dom,'primary');
6432: }
6433: unless ($homeserver eq 'no_host') {
6434: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6435: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6436: my @items = split(/&/,$response);
6437: foreach my $item (@items) {
6438: my ($key,$value) = split('=',$item);
6439: $validations{&unescape($key)} = &thaw_unescape($value);
6440: }
6441: }
6442: }
6443: return %validations;
6444: }
6445:
6446: sub auto_courserequest_validation {
6447: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6448: my ($homeserver,$response);
6449: if ($dom =~ /^$match_domain$/) {
6450: $homeserver = &domain($dom,'primary');
6451: }
6452: unless ($homeserver eq 'no_host') {
6453:
6454: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
6455: ':'.&escape($crstype).':'.&escape($inststatuslist).
6456: ':'.&escape($instcode).':'.&escape($instseclist),
6457: $homeserver));
6458: }
6459: return $response;
6460: }
6461:
6462: sub auto_validate_class_sec {
6463: my ($cdom,$cnum,$owners,$inst_class) = @_;
6464: my $homeserver = &homeserver($cnum,$cdom);
6465: my $ownerlist;
6466: if (ref($owners) eq 'ARRAY') {
6467: $ownerlist = join(',',@{$owners});
6468: } else {
6469: $ownerlist = $owners;
6470: }
6471: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
6472: &escape($ownerlist).':'.$cdom,$homeserver);
6473: return $response;
6474: }
6475:
6476: # ------------------------------------------------------- Course Group routines
6477:
6478: sub get_coursegroups {
6479: my ($cdom,$cnum,$group,$namespace) = @_;
6480: return(&dump($namespace,$cdom,$cnum,$group));
6481: }
6482:
6483: sub modify_coursegroup {
6484: my ($cdom,$cnum,$groupsettings) = @_;
6485: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6486: }
6487:
6488: sub toggle_coursegroup_status {
6489: my ($cdom,$cnum,$group,$action) = @_;
6490: my ($from_namespace,$to_namespace);
6491: if ($action eq 'delete') {
6492: $from_namespace = 'coursegroups';
6493: $to_namespace = 'deleted_groups';
6494: } else {
6495: $from_namespace = 'deleted_groups';
6496: $to_namespace = 'coursegroups';
6497: }
6498: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
6499: if (my $tmp = &error(%curr_group)) {
6500: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6501: return ('read error',$tmp);
6502: } else {
6503: my %savedsettings = %curr_group;
6504: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
6505: my $deloutcome;
6506: if ($result eq 'ok') {
6507: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
6508: } else {
6509: return ('write error',$result);
6510: }
6511: if ($deloutcome eq 'ok') {
6512: return 'ok';
6513: } else {
6514: return ('delete error',$deloutcome);
6515: }
6516: }
6517: }
6518:
6519: sub modify_group_roles {
6520: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
6521: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6522: my $role = 'gr/'.&escape($userprivs);
6523: my ($uname,$udom) = split(/:/,$user);
6524: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
6525: if ($result eq 'ok') {
6526: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6527: }
6528: return $result;
6529: }
6530:
6531: sub modify_coursegroup_membership {
6532: my ($cdom,$cnum,$membership) = @_;
6533: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6534: return $result;
6535: }
6536:
6537: sub get_active_groups {
6538: my ($udom,$uname,$cdom,$cnum) = @_;
6539: my $now = time;
6540: my %groups = ();
6541: foreach my $key (keys(%env)) {
6542: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
6543: my ($start,$end) = split(/\./,$env{$key});
6544: if (($end!=0) && ($end<$now)) { next; }
6545: if (($start!=0) && ($start>$now)) { next; }
6546: if ($1 eq $cdom && $2 eq $cnum) {
6547: $groups{$3} = $env{$key} ;
6548: }
6549: }
6550: }
6551: return %groups;
6552: }
6553:
6554: sub get_group_membership {
6555: my ($cdom,$cnum,$group) = @_;
6556: return(&dump('groupmembership',$cdom,$cnum,$group));
6557: }
6558:
6559: sub get_users_groups {
6560: my ($udom,$uname,$courseid) = @_;
6561: my @usersgroups;
6562: my $cachetime=1800;
6563:
6564: my $hashid="$udom:$uname:$courseid";
6565: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6566: if (defined($cached)) {
6567: @usersgroups = split(/:/,$grouplist);
6568: } else {
6569: $grouplist = '';
6570: my $courseurl = &courseid_to_courseurl($courseid);
6571: my $extra = &freeze_escape({'skipcheck' => 1});
6572: my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
6573: my $access_end = $env{'course.'.$courseid.
6574: '.default_enrollment_end_date'};
6575: my $now = time;
6576: foreach my $key (keys(%roleshash)) {
6577: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6578: my $group = $1;
6579: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6580: my $start = $2;
6581: my $end = $1;
6582: if ($start == -1) { next; } # deleted from group
6583: if (($start!=0) && ($start>$now)) { next; }
6584: if (($end!=0) && ($end<$now)) {
6585: if ($access_end && $access_end < $now) {
6586: if ($access_end - $end < 86400) {
6587: push(@usersgroups,$group);
6588: }
6589: }
6590: next;
6591: }
6592: push(@usersgroups,$group);
6593: }
6594: }
6595: }
6596: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6597: $grouplist = join(':',@usersgroups);
6598: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
6599: }
6600: return @usersgroups;
6601: }
6602:
6603: sub devalidate_getgroups_cache {
6604: my ($udom,$uname,$cdom,$cnum)=@_;
6605: my $courseid = $cdom.'_'.$cnum;
6606:
6607: my $hashid="$udom:$uname:$courseid";
6608: &devalidate_cache_new('getgroups',$hashid);
6609: }
6610:
6611: # ------------------------------------------------------------------ Plain Text
6612:
6613: sub plaintext {
6614: my ($short,$type,$cid,$forcedefault) = @_;
6615: if ($short =~ m{^cr/}) {
6616: return (split('/',$short))[-1];
6617: }
6618: if (!defined($cid)) {
6619: $cid = $env{'request.course.id'};
6620: }
6621: my %rolenames = (
6622: Course => 'std',
6623: Community => 'alt1',
6624: );
6625: if ($cid ne '') {
6626: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6627: unless ($forcedefault) {
6628: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6629: &Apache::lonlocal::mt_escape(\$roletext);
6630: return &Apache::lonlocal::mt($roletext);
6631: }
6632: }
6633: }
6634: if ((defined($type)) && (defined($rolenames{$type})) &&
6635: (defined($rolenames{$type})) &&
6636: (defined($prp{$short}{$rolenames{$type}}))) {
6637: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
6638: } elsif ($cid ne '') {
6639: my $crstype = $env{'course.'.$cid.'.type'};
6640: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6641: (defined($prp{$short}{$rolenames{$crstype}}))) {
6642: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6643: }
6644: }
6645: return &Apache::lonlocal::mt($prp{$short}{'std'});
6646: }
6647:
6648: # ----------------------------------------------------------------- Assign Role
6649:
6650: sub assignrole {
6651: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6652: $context)=@_;
6653: my $mrole;
6654: if ($role =~ /^cr\//) {
6655: my $cwosec=$url;
6656: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
6657: unless (&allowed('ccr',$cwosec)) {
6658: my $refused = 1;
6659: if ($context eq 'requestcourses') {
6660: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6661: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6662: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6663: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6664: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6665: if ($crsenv{'internal.courseowner'} eq
6666: $env{'user.name'}.':'.$env{'user.domain'}) {
6667: $refused = '';
6668: }
6669: }
6670: }
6671: }
6672: }
6673: if ($refused) {
6674: &logthis('Refused custom assignrole: '.
6675: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6676: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6677: return 'refused';
6678: }
6679: }
6680: $mrole='cr';
6681: } elsif ($role =~ /^gr\//) {
6682: my $cwogrp=$url;
6683: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
6684: unless (&allowed('mdg',$cwogrp)) {
6685: &logthis('Refused group assignrole: '.
6686: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6687: $env{'user.name'}.' at '.$env{'user.domain'});
6688: return 'refused';
6689: }
6690: $mrole='gr';
6691: } else {
6692: my $cwosec=$url;
6693: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
6694: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6695: my $refused;
6696: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6697: if (!(&allowed('c'.$role,$url))) {
6698: $refused = 1;
6699: }
6700: } else {
6701: $refused = 1;
6702: }
6703: if ($refused) {
6704: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6705: if (!$selfenroll && $context eq 'course') {
6706: my %crsenv;
6707: if ($role eq 'cc' || $role eq 'co') {
6708: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6709: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
6710: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
6711: if ($crsenv{'internal.courseowner'} eq
6712: $env{'user.name'}.':'.$env{'user.domain'}) {
6713: $refused = '';
6714: }
6715: }
6716: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
6717: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
6718: if ($crsenv{'internal.courseowner'} eq
6719: $env{'user.name'}.':'.$env{'user.domain'}) {
6720: $refused = '';
6721: }
6722: }
6723: }
6724: }
6725: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6726: $refused = '';
6727: } elsif ($context eq 'requestcourses') {
6728: my @possroles = ('st','ta','ep','in','cc','co');
6729: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
6730: my $wrongcc;
6731: if ($cnum =~ /^$match_community$/) {
6732: $wrongcc = 1 if ($role eq 'cc');
6733: } else {
6734: $wrongcc = 1 if ($role eq 'co');
6735: }
6736: unless ($wrongcc) {
6737: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6738: if ($crsenv{'internal.courseowner'} eq
6739: $env{'user.name'}.':'.$env{'user.domain'}) {
6740: $refused = '';
6741: }
6742: }
6743: }
6744: }
6745: if ($refused) {
6746: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6747: ' '.$role.' '.$end.' '.$start.' by '.
6748: $env{'user.name'}.' at '.$env{'user.domain'});
6749: return 'refused';
6750: }
6751: }
6752: } elsif ($role eq 'au') {
6753: if ($url ne '/'.$udom.'/') {
6754: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
6755: ' to assign author role for '.$uname.':'.$udom.
6756: ' in domain: '.$url.' refused (wrong domain).');
6757: return 'refused';
6758: }
6759: }
6760: $mrole=$role;
6761: }
6762: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
6763: "$udom:$uname:$url".'_'."$mrole=$role";
6764: if ($end) { $command.='_'.$end; }
6765: if ($start) {
6766: if ($end) {
6767: $command.='_'.$start;
6768: } else {
6769: $command.='_0_'.$start;
6770: }
6771: }
6772: my $origstart = $start;
6773: my $origend = $end;
6774: my $delflag;
6775: # actually delete
6776: if ($deleteflag) {
6777: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
6778: # modify command to delete the role
6779: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
6780: "$udom:$uname:$url".'_'."$mrole";
6781: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
6782: # set start and finish to negative values for userrolelog
6783: $start=-1;
6784: $end=-1;
6785: $delflag = 1;
6786: }
6787: }
6788: # send command
6789: my $answer=&reply($command,&homeserver($uname,$udom));
6790: # log new user role if status is ok
6791: if ($answer eq 'ok') {
6792: &userrolelog($role,$uname,$udom,$url,$start,$end);
6793: # for course roles, perform group memberships changes triggered by role change.
6794: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
6795: unless ($role =~ /^gr/) {
6796: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
6797: $origstart,$selfenroll,$context);
6798: }
6799: if ($role eq 'cc') {
6800: &autoupdate_coowners($url,$end,$start,$uname,$udom);
6801: }
6802: }
6803: return $answer;
6804: }
6805:
6806: sub autoupdate_coowners {
6807: my ($url,$end,$start,$uname,$udom) = @_;
6808: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
6809: if (($cdom ne '') && ($cnum ne '')) {
6810: my $now = time;
6811: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
6812: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
6813: my %coursehash = &coursedescription($cdom.'_'.$cnum);
6814: my $instcode = $coursehash{'internal.coursecode'};
6815: if ($instcode ne '') {
6816: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
6817: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
6818: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
6819: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
6820: if ($result eq 'valid') {
6821: if ($coursehash{'internal.co-owners'}) {
6822: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6823: push(@newcoowners,$coowner);
6824: }
6825: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
6826: push(@newcoowners,$uname.':'.$udom);
6827: }
6828: @newcoowners = sort(@newcoowners);
6829: } else {
6830: push(@newcoowners,$uname.':'.$udom);
6831: }
6832: } else {
6833: if ($coursehash{'internal.co-owners'}) {
6834: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6835: unless ($coowner eq $uname.':'.$udom) {
6836: push(@newcoowners,$coowner);
6837: }
6838: }
6839: unless (@newcoowners > 0) {
6840: $delcoowners = 1;
6841: $coowners = '';
6842: }
6843: }
6844: }
6845: if (@newcoowners || $delcoowners) {
6846: &store_coowners($cdom,$cnum,$coursehash{'home'},
6847: $delcoowners,@newcoowners);
6848: }
6849: }
6850: }
6851: }
6852: }
6853: }
6854: }
6855:
6856: sub store_coowners {
6857: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
6858: my $cid = $cdom.'_'.$cnum;
6859: my ($coowners,$delresult,$putresult);
6860: if (@newcoowners) {
6861: $coowners = join(',',@newcoowners);
6862: my %coownershash = (
6863: 'internal.co-owners' => $coowners,
6864: );
6865: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
6866: if ($putresult eq 'ok') {
6867: if ($env{'course.'.$cid.'.num'} eq $cnum) {
6868: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
6869: }
6870: }
6871: }
6872: if ($delcoowners) {
6873: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
6874: if ($delresult eq 'ok') {
6875: if ($env{'course.'.$cid.'.internal.co-owners'}) {
6876: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
6877: }
6878: }
6879: }
6880: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
6881: my %crsinfo =
6882: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6883: if (ref($crsinfo{$cid}) eq 'HASH') {
6884: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
6885: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
6886: }
6887: }
6888: }
6889:
6890: # -------------------------------------------------- Modify user authentication
6891: # Overrides without validation
6892:
6893: sub modifyuserauth {
6894: my ($udom,$uname,$umode,$upass)=@_;
6895: my $uhome=&homeserver($uname,$udom);
6896: unless (&allowed('mau',$udom)) { return 'refused'; }
6897: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
6898: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6899: ' in domain '.$env{'request.role.domain'});
6900: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6901: &escape($upass),$uhome);
6902: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
6903: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6904: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6905: &log($udom,,$uname,$uhome,
6906: 'Authentication changed by '.$env{'user.domain'}.', '.
6907: $env{'user.name'}.', '.$umode.
6908: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6909: unless ($reply eq 'ok') {
6910: &logthis('Authentication mode error: '.$reply);
6911: return 'error: '.$reply;
6912: }
6913: return 'ok';
6914: }
6915:
6916: # --------------------------------------------------------------- Modify a user
6917:
6918: sub modifyuser {
6919: my ($udom, $uname, $uid,
6920: $umode, $upass, $first,
6921: $middle, $last, $gene,
6922: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
6923: $udom= &LONCAPA::clean_domain($udom);
6924: $uname=&LONCAPA::clean_username($uname);
6925: my $showcandelete = 'none';
6926: if (ref($candelete) eq 'ARRAY') {
6927: if (@{$candelete} > 0) {
6928: $showcandelete = join(', ',@{$candelete});
6929: }
6930: }
6931: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
6932: $umode.', '.$first.', '.$middle.', '.
6933: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
6934: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6935: ' desiredhome not specified').
6936: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6937: ' in domain '.$env{'request.role.domain'});
6938: my $uhome=&homeserver($uname,$udom,'true');
6939: my $newuser;
6940: if ($uhome eq 'no_host') {
6941: $newuser = 1;
6942: }
6943: # ----------------------------------------------------------------- Create User
6944: if (($uhome eq 'no_host') &&
6945: (($umode && $upass) || ($umode eq 'localauth'))) {
6946: my $unhome='';
6947: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
6948: $unhome = $desiredhome;
6949: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6950: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
6951: } else { # load balancing routine for determining $unhome
6952: my $loadm=10000000;
6953: my %servers = &get_servers($udom,'library');
6954: foreach my $tryserver (keys(%servers)) {
6955: my $answer=reply('load',$tryserver);
6956: if (($answer=~/\d+/) && ($answer<$loadm)) {
6957: $loadm=$answer;
6958: $unhome=$tryserver;
6959: }
6960: }
6961: }
6962: if (($unhome eq '') || ($unhome eq 'no_host')) {
6963: return 'error: unable to find a home server for '.$uname.
6964: ' in domain '.$udom;
6965: }
6966: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6967: &escape($upass),$unhome);
6968: unless ($reply eq 'ok') {
6969: return 'error: '.$reply;
6970: }
6971: $uhome=&homeserver($uname,$udom,'true');
6972: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
6973: return 'error: unable verify users home machine.';
6974: }
6975: } # End of creation of new user
6976: # ---------------------------------------------------------------------- Add ID
6977: if ($uid) {
6978: $uid=~tr/A-Z/a-z/;
6979: my %uidhash=&idrget($udom,$uname);
6980: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6981: && (!$forceid)) {
6982: unless ($uid eq $uidhash{$uname}) {
6983: return 'error: user id "'.$uid.'" does not match '.
6984: 'current user id "'.$uidhash{$uname}.'".';
6985: }
6986: } else {
6987: &idput($udom,($uname => $uid));
6988: }
6989: }
6990: # -------------------------------------------------------------- Add names, etc
6991: my @tmp=&get('environment',
6992: ['firstname','middlename','lastname','generation','id',
6993: 'permanentemail','inststatus'],
6994: $udom,$uname);
6995: my (%names,%oldnames);
6996: if ($tmp[0] =~ m/^error:.*/) {
6997: %names=();
6998: } else {
6999: %names = @tmp;
7000: %oldnames = %names;
7001: }
7002: #
7003: # If name, email and/or uid are blank (e.g., because an uploaded file
7004: # of users did not contain them), do not overwrite existing values
7005: # unless field is in $candelete array ref.
7006: #
7007:
7008: my @fields = ('firstname','middlename','lastname','generation',
7009: 'permanentemail','id');
7010: my %newvalues;
7011: if (ref($candelete) eq 'ARRAY') {
7012: foreach my $field (@fields) {
7013: if (grep(/^\Q$field\E$/,@{$candelete})) {
7014: if ($field eq 'firstname') {
7015: $names{$field} = $first;
7016: } elsif ($field eq 'middlename') {
7017: $names{$field} = $middle;
7018: } elsif ($field eq 'lastname') {
7019: $names{$field} = $last;
7020: } elsif ($field eq 'generation') {
7021: $names{$field} = $gene;
7022: } elsif ($field eq 'permanentemail') {
7023: $names{$field} = $email;
7024: } elsif ($field eq 'id') {
7025: $names{$field} = $uid;
7026: }
7027: }
7028: }
7029: }
7030: if ($first) { $names{'firstname'} = $first; }
7031: if (defined($middle)) { $names{'middlename'} = $middle; }
7032: if ($last) { $names{'lastname'} = $last; }
7033: if (defined($gene)) { $names{'generation'} = $gene; }
7034: if ($email) {
7035: $email=~s/[^\w\@\.\-\,]//gs;
7036: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
7037: }
7038: if ($uid) { $names{'id'} = $uid; }
7039: if (defined($inststatus)) {
7040: $names{'inststatus'} = '';
7041: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
7042: if (ref($usertypes) eq 'HASH') {
7043: my @okstatuses;
7044: foreach my $item (split(/:/,$inststatus)) {
7045: if (defined($usertypes->{$item})) {
7046: push(@okstatuses,$item);
7047: }
7048: }
7049: if (@okstatuses) {
7050: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
7051: }
7052: }
7053: }
7054: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
7055: $umode.', '.$first.', '.$middle.', '.
7056: $last.', '.$gene.', '.$email.', '.$inststatus;
7057: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
7058: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
7059: } else {
7060: $logmsg .= ' during self creation';
7061: }
7062: my $changed;
7063: if ($newuser) {
7064: $changed = 1;
7065: } else {
7066: foreach my $field (@fields) {
7067: if ($names{$field} ne $oldnames{$field}) {
7068: $changed = 1;
7069: last;
7070: }
7071: }
7072: }
7073: unless ($changed) {
7074: $logmsg = 'No changes in user information needed for: '.$logmsg;
7075: &logthis($logmsg);
7076: return 'ok';
7077: }
7078: my $reply = &put('environment', \%names, $udom,$uname);
7079: if ($reply ne 'ok') {
7080: return 'error: '.$reply;
7081: }
7082: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7083: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7084: }
7085: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7086: &devalidate_cache_new('namescache',$uname.':'.$udom);
7087: $logmsg = 'Success modifying user '.$logmsg;
7088: &logthis($logmsg);
7089: return 'ok';
7090: }
7091:
7092: # -------------------------------------------------------------- Modify student
7093:
7094: sub modifystudent {
7095: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
7096: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
7097: $selfenroll,$context,$inststatus)=@_;
7098: if (!$cid) {
7099: unless ($cid=$env{'request.course.id'}) {
7100: return 'not_in_class';
7101: }
7102: }
7103: # --------------------------------------------------------------- Make the user
7104: my $reply=&modifyuser
7105: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
7106: $desiredhome,$email,$inststatus);
7107: unless ($reply eq 'ok') { return $reply; }
7108: # This will cause &modify_student_enrollment to get the uid from the
7109: # students environment
7110: $uid = undef if (!$forceid);
7111: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
7112: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
7113: return $reply;
7114: }
7115:
7116: sub modify_student_enrollment {
7117: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
7118: my ($cdom,$cnum,$chome);
7119: if (!$cid) {
7120: unless ($cid=$env{'request.course.id'}) {
7121: return 'not_in_class';
7122: }
7123: $cdom=$env{'course.'.$cid.'.domain'};
7124: $cnum=$env{'course.'.$cid.'.num'};
7125: } else {
7126: ($cdom,$cnum)=split(/_/,$cid);
7127: }
7128: $chome=$env{'course.'.$cid.'.home'};
7129: if (!$chome) {
7130: $chome=&homeserver($cnum,$cdom);
7131: }
7132: if (!$chome) { return 'unknown_course'; }
7133: # Make sure the user exists
7134: my $uhome=&homeserver($uname,$udom);
7135: if (($uhome eq '') || ($uhome eq 'no_host')) {
7136: return 'error: no such user';
7137: }
7138: # Get student data if we were not given enough information
7139: if (!defined($first) || $first eq '' ||
7140: !defined($last) || $last eq '' ||
7141: !defined($uid) || $uid eq '' ||
7142: !defined($middle) || $middle eq '' ||
7143: !defined($gene) || $gene eq '') {
7144: # They did not supply us with enough data to enroll the student, so
7145: # we need to pick up more information.
7146: my %tmp = &get('environment',
7147: ['firstname','middlename','lastname', 'generation','id']
7148: ,$udom,$uname);
7149:
7150: #foreach my $key (keys(%tmp)) {
7151: # &logthis("key $key = ".$tmp{$key});
7152: #}
7153: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7154: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7155: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
7156: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
7157: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7158: }
7159: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
7160: my $reply=cput('classlist',
7161: {"$uname:$udom" =>
7162: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
7163: $cdom,$cnum);
7164: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
7165: return 'error: '.$reply;
7166: } else {
7167: &devalidate_getsection_cache($udom,$uname,$cid);
7168: }
7169: # Add student role to user
7170: my $uurl='/'.$cid;
7171: $uurl=~s/\_/\//g;
7172: if ($usec) {
7173: $uurl.='/'.$usec;
7174: }
7175: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
7176: }
7177:
7178: sub format_name {
7179: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7180: my $name;
7181: if ($first ne 'lastname') {
7182: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7183: } else {
7184: if ($lastname=~/\S/) {
7185: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7186: $name=~s/\s+,/,/;
7187: } else {
7188: $name.= $firstname.' '.$middlename.' '.$generation;
7189: }
7190: }
7191: $name=~s/^\s+//;
7192: $name=~s/\s+$//;
7193: $name=~s/\s+/ /g;
7194: return $name;
7195: }
7196:
7197: # ------------------------------------------------- Write to course preferences
7198:
7199: sub writecoursepref {
7200: my ($courseid,%prefs)=@_;
7201: $courseid=~s/^\///;
7202: $courseid=~s/\_/\//g;
7203: my ($cdomain,$cnum)=split(/\//,$courseid);
7204: my $chome=homeserver($cnum,$cdomain);
7205: if (($chome eq '') || ($chome eq 'no_host')) {
7206: return 'error: no such course';
7207: }
7208: my $cstring='';
7209: foreach my $pref (keys(%prefs)) {
7210: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
7211: }
7212: $cstring=~s/\&$//;
7213: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7214: }
7215:
7216: # ---------------------------------------------------------- Make/modify course
7217:
7218: sub createcourse {
7219: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
7220: $course_owner,$crstype,$cnum,$context,$category)=@_;
7221: $url=&declutter($url);
7222: my $cid='';
7223: if ($context eq 'requestcourses') {
7224: my $can_create = 0;
7225: my ($ownername,$ownerdom) = split(':',$course_owner);
7226: if ($udom eq $ownerdom) {
7227: if (&usertools_access($ownername,$ownerdom,$category,undef,
7228: $context)) {
7229: $can_create = 1;
7230: }
7231: } else {
7232: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7233: $category);
7234: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7235: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7236: if (@curr > 0) {
7237: my @options = qw(approval validate autolimit);
7238: my $optregex = join('|',@options);
7239: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7240: $can_create = 1;
7241: }
7242: }
7243: }
7244: }
7245: if ($can_create) {
7246: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7247: unless (&allowed('ccc',$udom)) {
7248: return 'refused';
7249: }
7250: }
7251: } else {
7252: return 'refused';
7253: }
7254: } elsif (!&allowed('ccc',$udom)) {
7255: return 'refused';
7256: }
7257: # --------------------------------------------------------------- Get Unique ID
7258: my $uname;
7259: if ($cnum =~ /^$match_courseid$/) {
7260: my $chome=&homeserver($cnum,$udom,'true');
7261: if (($chome eq '') || ($chome eq 'no_host')) {
7262: $uname = $cnum;
7263: } else {
7264: $uname = &generate_coursenum($udom,$crstype);
7265: }
7266: } else {
7267: $uname = &generate_coursenum($udom,$crstype);
7268: }
7269: return $uname if ($uname =~ /^error/);
7270: # -------------------------------------------------- Check supplied server name
7271: if (!defined($course_server)) {
7272: if (defined(&domain($udom,'primary'))) {
7273: $course_server = &domain($udom,'primary');
7274: } else {
7275: $course_server = $env{'user.home'};
7276: }
7277: }
7278: my %host_servers =
7279: &Apache::lonnet::get_servers($udom,'library');
7280: unless ($host_servers{$course_server}) {
7281: return 'error: invalid home server for course: '.$course_server;
7282: }
7283: # ------------------------------------------------------------- Make the course
7284: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
7285: $course_server);
7286: unless ($reply eq 'ok') { return 'error: '.$reply; }
7287: my $uhome=&homeserver($uname,$udom,'true');
7288: if (($uhome eq '') || ($uhome eq 'no_host')) {
7289: return 'error: no such course';
7290: }
7291: # ----------------------------------------------------------------- Course made
7292: # log existence
7293: my $now = time;
7294: my $newcourse = {
7295: $udom.'_'.$uname => {
7296: description => $description,
7297: inst_code => $inst_code,
7298: owner => $course_owner,
7299: type => $crstype,
7300: creator => $env{'user.name'}.':'.
7301: $env{'user.domain'},
7302: created => $now,
7303: context => $context,
7304: },
7305: };
7306: &courseidput($udom,$newcourse,$uhome,'notime');
7307: # set toplevel url
7308: my $topurl=$url;
7309: unless ($nonstandard) {
7310: # ------------------------------------------ For standard courses, make top url
7311: my $mapurl=&clutter($url);
7312: if ($mapurl eq '/res/') { $mapurl=''; }
7313: $env{'form.initmap'}=(<<ENDINITMAP);
7314: <map>
7315: <resource id="1" type="start"></resource>
7316: <resource id="2" src="$mapurl"></resource>
7317: <resource id="3" type="finish"></resource>
7318: <link index="1" from="1" to="2"></link>
7319: <link index="2" from="2" to="3"></link>
7320: </map>
7321: ENDINITMAP
7322: $topurl=&declutter(
7323: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
7324: );
7325: }
7326: # ----------------------------------------------------------- Write preferences
7327: &writecoursepref($udom.'_'.$uname,
7328: ('description' => $description,
7329: 'url' => $topurl,
7330: 'internal.creator' => $env{'user.name'}.':'.
7331: $env{'user.domain'},
7332: 'internal.created' => $now,
7333: 'internal.creationcontext' => $context)
7334: );
7335: return '/'.$udom.'/'.$uname;
7336: }
7337:
7338: # ------------------------------------------------------------------- Create ID
7339: sub generate_coursenum {
7340: my ($udom,$crstype) = @_;
7341: my $domdesc = &domain($udom);
7342: return 'error: invalid domain' if ($domdesc eq '');
7343: my $first;
7344: if ($crstype eq 'Community') {
7345: $first = '0';
7346: } else {
7347: $first = int(1+rand(9));
7348: }
7349: my $uname=$first.
7350: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7351: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7352: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7353: # ----------------------------------------------- Make sure that does not exist
7354: my $uhome=&homeserver($uname,$udom,'true');
7355: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7356: if ($crstype eq 'Community') {
7357: $first = '0';
7358: } else {
7359: $first = int(1+rand(9));
7360: }
7361: $uname=$first.
7362: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7363: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7364: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7365: $uhome=&homeserver($uname,$udom,'true');
7366: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7367: return 'error: unable to generate unique course-ID';
7368: }
7369: }
7370: return $uname;
7371: }
7372:
7373: sub is_course {
7374: my ($cdom,$cnum) = @_;
7375: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
7376: undef,'.');
7377: if (exists($courses{$cdom.'_'.$cnum})) {
7378: return 1;
7379: }
7380: return 0;
7381: }
7382:
7383: sub store_userdata {
7384: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
7385: my $result;
7386: if ($datakey ne '') {
7387: if (ref($storehash) eq 'HASH') {
7388: if ($udom eq '' || $uname eq '') {
7389: $udom = $env{'user.domain'};
7390: $uname = $env{'user.name'};
7391: }
7392: my $uhome=&homeserver($uname,$udom);
7393: if (($uhome eq '') || ($uhome eq 'no_host')) {
7394: $result = 'error: no_host';
7395: } else {
7396: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7397: $storehash->{'host'} = $perlvar{'lonHostID'};
7398:
7399: my $namevalue='';
7400: foreach my $key (keys(%{$storehash})) {
7401: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7402: }
7403: $namevalue=~s/\&$//;
7404: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
7405: $namevalue,$uhome);
7406: }
7407: } else {
7408: $result = 'error: data to store was not a hash reference';
7409: }
7410: } else {
7411: $result= 'error: invalid requestkey';
7412: }
7413: return $result;
7414: }
7415:
7416: # ---------------------------------------------------------- Assign Custom Role
7417:
7418: sub assigncustomrole {
7419: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
7420: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
7421: $end,$start,$deleteflag,$selfenroll,$context);
7422: }
7423:
7424: # ----------------------------------------------------------------- Revoke Role
7425:
7426: sub revokerole {
7427: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
7428: my $now=time;
7429: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
7430: }
7431:
7432: # ---------------------------------------------------------- Revoke Custom Role
7433:
7434: sub revokecustomrole {
7435: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
7436: my $now=time;
7437: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
7438: $deleteflag,$selfenroll,$context);
7439: }
7440:
7441: # ------------------------------------------------------------ Disk usage
7442: sub diskusage {
7443: my ($udom,$uname,$directorypath,$getpropath)=@_;
7444: $directorypath =~ s/\/$//;
7445: my $listing=&reply('du2:'.&escape($directorypath).':'
7446: .&escape($getpropath).':'.&escape($uname).':'
7447: .&escape($udom),homeserver($uname,$udom));
7448: if ($listing eq 'unknown_cmd') {
7449: if ($getpropath) {
7450: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7451: }
7452: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7453: }
7454: return $listing;
7455: }
7456:
7457: sub is_locked {
7458: my ($file_name, $domain, $user, $which) = @_;
7459: my @check;
7460: my $is_locked;
7461: push(@check,$file_name);
7462: my %locked = &get('file_permissions',\@check,
7463: $env{'user.domain'},$env{'user.name'});
7464: my ($tmp)=keys(%locked);
7465: if ($tmp=~/^error:/) { undef(%locked); }
7466:
7467: if (ref($locked{$file_name}) eq 'ARRAY') {
7468: $is_locked = 'false';
7469: foreach my $entry (@{$locked{$file_name}}) {
7470: if (ref($entry) eq 'ARRAY') {
7471: $is_locked = 'true';
7472: if (ref($which) eq 'ARRAY') {
7473: push(@{$which},$entry);
7474: } else {
7475: last;
7476: }
7477: }
7478: }
7479: } else {
7480: $is_locked = 'false';
7481: }
7482: return $is_locked;
7483: }
7484:
7485: sub declutter_portfile {
7486: my ($file) = @_;
7487: $file =~ s{^(/portfolio/|portfolio/)}{/};
7488: return $file;
7489: }
7490:
7491: # ------------------------------------------------------------- Mark as Read Only
7492:
7493: sub mark_as_readonly {
7494: my ($domain,$user,$files,$what) = @_;
7495: my %current_permissions = &dump('file_permissions',$domain,$user);
7496: my ($tmp)=keys(%current_permissions);
7497: if ($tmp=~/^error:/) { undef(%current_permissions); }
7498: foreach my $file (@{$files}) {
7499: $file = &declutter_portfile($file);
7500: push(@{$current_permissions{$file}},$what);
7501: }
7502: &put('file_permissions',\%current_permissions,$domain,$user);
7503: return;
7504: }
7505:
7506: # ------------------------------------------------------------Save Selected Files
7507:
7508: sub save_selected_files {
7509: my ($user, $path, @files) = @_;
7510: my $filename = $user."savedfiles";
7511: my @other_files = &files_not_in_path($user, $path);
7512: open (OUT, '>'.$tmpdir.$filename);
7513: foreach my $file (@files) {
7514: print (OUT $env{'form.currentpath'}.$file."\n");
7515: }
7516: foreach my $file (@other_files) {
7517: print (OUT $file."\n");
7518: }
7519: close (OUT);
7520: return 'ok';
7521: }
7522:
7523: sub clear_selected_files {
7524: my ($user) = @_;
7525: my $filename = $user."savedfiles";
7526: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7527: print (OUT undef);
7528: close (OUT);
7529: return ("ok");
7530: }
7531:
7532: sub files_in_path {
7533: my ($user, $path) = @_;
7534: my $filename = $user."savedfiles";
7535: my %return_files;
7536: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7537: while (my $line_in = <IN>) {
7538: chomp ($line_in);
7539: my @paths_and_file = split (m!/!, $line_in);
7540: my $file_part = pop (@paths_and_file);
7541: my $path_part = join ('/', @paths_and_file);
7542: $path_part.='/';
7543: my $path_and_file = $path_part.$file_part;
7544: if ($path_part eq $path) {
7545: $return_files{$file_part}= 'selected';
7546: }
7547: }
7548: close (IN);
7549: return (\%return_files);
7550: }
7551:
7552: # called in portfolio select mode, to show files selected NOT in current directory
7553: sub files_not_in_path {
7554: my ($user, $path) = @_;
7555: my $filename = $user."savedfiles";
7556: my @return_files;
7557: my $path_part;
7558: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7559: while (my $line = <IN>) {
7560: #ok, I know it's clunky, but I want it to work
7561: my @paths_and_file = split(m|/|, $line);
7562: my $file_part = pop(@paths_and_file);
7563: chomp($file_part);
7564: my $path_part = join('/', @paths_and_file);
7565: $path_part .= '/';
7566: my $path_and_file = $path_part.$file_part;
7567: if ($path_part ne $path) {
7568: push(@return_files, ($path_and_file));
7569: }
7570: }
7571: close(OUT);
7572: return (@return_files);
7573: }
7574:
7575: #----------------------------------------------Get portfolio file permissions
7576:
7577: sub get_portfile_permissions {
7578: my ($domain,$user) = @_;
7579: my %current_permissions = &dump('file_permissions',$domain,$user);
7580: my ($tmp)=keys(%current_permissions);
7581: if ($tmp=~/^error:/) { undef(%current_permissions); }
7582: return \%current_permissions;
7583: }
7584:
7585: #---------------------------------------------Get portfolio file access controls
7586:
7587: sub get_access_controls {
7588: my ($current_permissions,$group,$file) = @_;
7589: my %access;
7590: my $real_file = $file;
7591: $file =~ s/\.meta$//;
7592: if (defined($file)) {
7593: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7594: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
7595: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
7596: }
7597: }
7598: } else {
7599: foreach my $key (keys(%{$current_permissions})) {
7600: if ($key =~ /\0accesscontrol$/) {
7601: if (defined($group)) {
7602: if ($key !~ m-^\Q$group\E/-) {
7603: next;
7604: }
7605: }
7606: my ($fullpath) = split(/\0/,$key);
7607: if (ref($$current_permissions{$key}) eq 'HASH') {
7608: foreach my $control (keys(%{$$current_permissions{$key}})) {
7609: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7610: }
7611: }
7612: }
7613: }
7614: }
7615: return %access;
7616: }
7617:
7618: sub modify_access_controls {
7619: my ($file_name,$changes,$domain,$user)=@_;
7620: my ($outcome,$deloutcome);
7621: my %store_permissions;
7622: my %new_values;
7623: my %new_control;
7624: my %translation;
7625: my @deletions = ();
7626: my $now = time;
7627: if (exists($$changes{'activate'})) {
7628: if (ref($$changes{'activate'}) eq 'HASH') {
7629: my @newitems = sort(keys(%{$$changes{'activate'}}));
7630: my $numnew = scalar(@newitems);
7631: for (my $i=0; $i<$numnew; $i++) {
7632: my $newkey = $newitems[$i];
7633: my $newid = &Apache::loncommon::get_cgi_id();
7634: if ($newkey =~ /^\d+:/) {
7635: $newkey =~ s/^(\d+)/$newid/;
7636: $translation{$1} = $newid;
7637: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7638: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7639: $translation{$1} = $newid;
7640: }
7641: $new_values{$file_name."\0".$newkey} =
7642: $$changes{'activate'}{$newitems[$i]};
7643: $new_control{$newkey} = $now;
7644: }
7645: }
7646: }
7647: my %todelete;
7648: my %changed_items;
7649: foreach my $action ('delete','update') {
7650: if (exists($$changes{$action})) {
7651: if (ref($$changes{$action}) eq 'HASH') {
7652: foreach my $key (keys(%{$$changes{$action}})) {
7653: my ($itemnum) = ($key =~ /^([^:]+):/);
7654: if ($action eq 'delete') {
7655: $todelete{$itemnum} = 1;
7656: } else {
7657: $changed_items{$itemnum} = $key;
7658: }
7659: }
7660: }
7661: }
7662: }
7663: # get lock on access controls for file.
7664: my $lockhash = {
7665: $file_name."\0".'locked_access_records' => $env{'user.name'}.
7666: ':'.$env{'user.domain'},
7667: };
7668: my $tries = 0;
7669: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7670:
7671: while (($gotlock ne 'ok') && $tries <3) {
7672: $tries ++;
7673: sleep 1;
7674: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7675: }
7676: if ($gotlock eq 'ok') {
7677: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
7678: my ($tmp)=keys(%curr_permissions);
7679: if ($tmp=~/^error:/) { undef(%curr_permissions); }
7680: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
7681: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
7682: if (ref($curr_controls) eq 'HASH') {
7683: foreach my $control_item (keys(%{$curr_controls})) {
7684: my ($itemnum) = ($control_item =~ /^([^:]+):/);
7685: if (defined($todelete{$itemnum})) {
7686: push(@deletions,$file_name."\0".$control_item);
7687: } else {
7688: if (defined($changed_items{$itemnum})) {
7689: $new_control{$changed_items{$itemnum}} = $now;
7690: push(@deletions,$file_name."\0".$control_item);
7691: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
7692: } else {
7693: $new_control{$control_item} = $$curr_controls{$control_item};
7694: }
7695: }
7696: }
7697: }
7698: }
7699: my ($group);
7700: if (&is_course($domain,$user)) {
7701: ($group,my $file) = split(/\//,$file_name,2);
7702: }
7703: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
7704: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
7705: $outcome = &put('file_permissions',\%new_values,$domain,$user);
7706: # remove lock
7707: my @del_lock = ($file_name."\0".'locked_access_records');
7708: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
7709: my $sqlresult =
7710: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
7711: $group);
7712: } else {
7713: $outcome = "error: could not obtain lockfile\n";
7714: }
7715: return ($outcome,$deloutcome,\%new_values,\%translation);
7716: }
7717:
7718: sub make_public_indefinitely {
7719: my ($requrl) = @_;
7720: my $now = time;
7721: my $action = 'activate';
7722: my $aclnum = 0;
7723: if (&is_portfolio_url($requrl)) {
7724: my (undef,$udom,$unum,$file_name,$group) =
7725: &parse_portfolio_url($requrl);
7726: my $current_perms = &get_portfile_permissions($udom,$unum);
7727: my %access_controls = &get_access_controls($current_perms,
7728: $group,$file_name);
7729: foreach my $key (keys(%{$access_controls{$file_name}})) {
7730: my ($num,$scope,$end,$start) =
7731: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7732: if ($scope eq 'public') {
7733: if ($start <= $now && $end == 0) {
7734: $action = 'none';
7735: } else {
7736: $action = 'update';
7737: $aclnum = $num;
7738: }
7739: last;
7740: }
7741: }
7742: if ($action eq 'none') {
7743: return 'ok';
7744: } else {
7745: my %changes;
7746: my $newend = 0;
7747: my $newstart = $now;
7748: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
7749: $changes{$action}{$newkey} = {
7750: type => 'public',
7751: time => {
7752: start => $newstart,
7753: end => $newend,
7754: },
7755: };
7756: my ($outcome,$deloutcome,$new_values,$translation) =
7757: &modify_access_controls($file_name,\%changes,$udom,$unum);
7758: return $outcome;
7759: }
7760: } else {
7761: return 'invalid';
7762: }
7763: }
7764:
7765: #------------------------------------------------------Get Marked as Read Only
7766:
7767: sub get_marked_as_readonly {
7768: my ($domain,$user,$what,$group) = @_;
7769: my $current_permissions = &get_portfile_permissions($domain,$user);
7770: my @readonly_files;
7771: my $cmp1=$what;
7772: if (ref($what)) { $cmp1=join('',@{$what}) };
7773: while (my ($file_name,$value) = each(%{$current_permissions})) {
7774: if (defined($group)) {
7775: if ($file_name !~ m-^\Q$group\E/-) {
7776: next;
7777: }
7778: }
7779: if (ref($value) eq "ARRAY"){
7780: foreach my $stored_what (@{$value}) {
7781: my $cmp2=$stored_what;
7782: if (ref($stored_what) eq 'ARRAY') {
7783: $cmp2=join('',@{$stored_what});
7784: }
7785: if ($cmp1 eq $cmp2) {
7786: push(@readonly_files, $file_name);
7787: last;
7788: } elsif (!defined($what)) {
7789: push(@readonly_files, $file_name);
7790: last;
7791: }
7792: }
7793: }
7794: }
7795: return @readonly_files;
7796: }
7797: #-----------------------------------------------------------Get Marked as Read Only Hash
7798:
7799: sub get_marked_as_readonly_hash {
7800: my ($current_permissions,$group,$what) = @_;
7801: my %readonly_files;
7802: while (my ($file_name,$value) = each(%{$current_permissions})) {
7803: if (defined($group)) {
7804: if ($file_name !~ m-^\Q$group\E/-) {
7805: next;
7806: }
7807: }
7808: if (ref($value) eq "ARRAY"){
7809: foreach my $stored_what (@{$value}) {
7810: if (ref($stored_what) eq 'ARRAY') {
7811: foreach my $lock_descriptor(@{$stored_what}) {
7812: if ($lock_descriptor eq 'graded') {
7813: $readonly_files{$file_name} = 'graded';
7814: } elsif ($lock_descriptor eq 'handback') {
7815: $readonly_files{$file_name} = 'handback';
7816: } else {
7817: if (!exists($readonly_files{$file_name})) {
7818: $readonly_files{$file_name} = 'locked';
7819: }
7820: }
7821: }
7822: }
7823: }
7824: }
7825: }
7826: return %readonly_files;
7827: }
7828: # ------------------------------------------------------------ Unmark as Read Only
7829:
7830: sub unmark_as_readonly {
7831: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7832: # for portfolio submissions, $what contains [$symb,$crsid]
7833: my ($domain,$user,$what,$file_name,$group) = @_;
7834: $file_name = &declutter_portfile($file_name);
7835: my $symb_crs = $what;
7836: if (ref($what)) { $symb_crs=join('',@$what); }
7837: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
7838: my ($tmp)=keys(%current_permissions);
7839: if ($tmp=~/^error:/) { undef(%current_permissions); }
7840: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
7841: foreach my $file (@readonly_files) {
7842: my $clean_file = &declutter_portfile($file);
7843: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
7844: my $current_locks = $current_permissions{$file};
7845: my @new_locks;
7846: my @del_keys;
7847: if (ref($current_locks) eq "ARRAY"){
7848: foreach my $locker (@{$current_locks}) {
7849: my $compare=$locker;
7850: if (ref($locker) eq 'ARRAY') {
7851: $compare=join('',@{$locker});
7852: if ($compare ne $symb_crs) {
7853: push(@new_locks, $locker);
7854: }
7855: }
7856: }
7857: if (scalar(@new_locks) > 0) {
7858: $current_permissions{$file} = \@new_locks;
7859: } else {
7860: push(@del_keys, $file);
7861: &del('file_permissions',\@del_keys, $domain, $user);
7862: delete($current_permissions{$file});
7863: }
7864: }
7865: }
7866: &put('file_permissions',\%current_permissions,$domain,$user);
7867: return;
7868: }
7869:
7870: # ------------------------------------------------------------ Directory lister
7871:
7872: sub dirlist {
7873: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
7874: $uri=~s/^\///;
7875: $uri=~s/\/$//;
7876: my ($udom, $uname);
7877: if ($getuserdir) {
7878: $udom = $userdomain;
7879: $uname = $username;
7880: } else {
7881: (undef,$udom,$uname)=split(/\//,$uri);
7882: if(defined($userdomain)) {
7883: $udom = $userdomain;
7884: }
7885: if(defined($username)) {
7886: $uname = $username;
7887: }
7888: }
7889: my ($dirRoot,$listing,@listing_results);
7890:
7891: $dirRoot = $perlvar{'lonDocRoot'};
7892: if (defined($getpropath)) {
7893: $dirRoot = &propath($udom,$uname);
7894: $dirRoot =~ s/\/$//;
7895: } elsif (defined($getuserdir)) {
7896: my $subdir=$uname.'__';
7897: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7898: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7899: ."/$udom/$subdir/$uname";
7900: } elsif (defined($alternateRoot)) {
7901: $dirRoot = $alternateRoot;
7902: }
7903:
7904: if($udom) {
7905: if($uname) {
7906: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
7907: .$getuserdir.':'.&escape($dirRoot)
7908: .':'.&escape($uname).':'.&escape($udom),
7909: &homeserver($uname,$udom));
7910: if ($listing eq 'unknown_cmd') {
7911: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7912: &homeserver($uname,$udom));
7913: } else {
7914: @listing_results = map { &unescape($_); } split(/:/,$listing);
7915: }
7916: if ($listing eq 'unknown_cmd') {
7917: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7918: &homeserver($uname,$udom));
7919: @listing_results = split(/:/,$listing);
7920: } else {
7921: @listing_results = map { &unescape($_); } split(/:/,$listing);
7922: }
7923: return @listing_results;
7924: } elsif(!$alternateRoot) {
7925: my %allusers;
7926: my %servers = &get_servers($udom,'library');
7927: foreach my $tryserver (keys(%servers)) {
7928: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7929: &escape($udom),$tryserver);
7930: if ($listing eq 'unknown_cmd') {
7931: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7932: $udom, $tryserver);
7933: } else {
7934: @listing_results = map { &unescape($_); } split(/:/,$listing);
7935: }
7936: if ($listing eq 'unknown_cmd') {
7937: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7938: $udom, $tryserver);
7939: @listing_results = split(/:/,$listing);
7940: } else {
7941: @listing_results =
7942: map { &unescape($_); } split(/:/,$listing);
7943: }
7944: if ($listing_results[0] ne 'no_such_dir' &&
7945: $listing_results[0] ne 'empty' &&
7946: $listing_results[0] ne 'con_lost') {
7947: foreach my $line (@listing_results) {
7948: my ($entry) = split(/&/,$line,2);
7949: $allusers{$entry} = 1;
7950: }
7951: }
7952: }
7953: my $alluserstr='';
7954: foreach my $user (sort(keys(%allusers))) {
7955: $alluserstr.=$user.'&user:';
7956: }
7957: $alluserstr=~s/:$//;
7958: return split(/:/,$alluserstr);
7959: } else {
7960: return ('missing user name');
7961: }
7962: } elsif(!defined($getpropath)) {
7963: my @all_domains = sort(&all_domains());
7964: foreach my $domain (@all_domains) {
7965: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7966: }
7967: return @all_domains;
7968: } else {
7969: return ('missing domain');
7970: }
7971: }
7972:
7973: # --------------------------------------------- GetFileTimestamp
7974: # This function utilizes dirlist and returns the date stamp for
7975: # when it was last modified. It will also return an error of -1
7976: # if an error occurs
7977:
7978: sub GetFileTimestamp {
7979: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
7980: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7981: $studentName = &LONCAPA::clean_username($studentName);
7982: my ($fileStat) =
7983: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7984: undef,$getuserdir);
7985: my @stats = split('&', $fileStat);
7986: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7987: # @stats contains first the filename, then the stat output
7988: return $stats[10]; # so this is 10 instead of 9.
7989: } else {
7990: return -1;
7991: }
7992: }
7993:
7994: sub stat_file {
7995: my ($uri) = @_;
7996: $uri = &clutter_with_no_wrapper($uri);
7997:
7998: my ($udom,$uname,$file);
7999: if ($uri =~ m-^/(uploaded|editupload)/-) {
8000: ($udom,$uname,$file) =
8001: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
8002: $file = 'userfiles/'.$file;
8003: }
8004: if ($uri =~ m-^/res/-) {
8005: ($udom,$uname) =
8006: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
8007: $file = $uri;
8008: }
8009:
8010: if (!$udom || !$uname || !$file) {
8011: # unable to handle the uri
8012: return ();
8013: }
8014: my $getpropath;
8015: if ($file =~ /^userfiles\//) {
8016: $getpropath = 1;
8017: }
8018: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
8019: my @stats = split('&', $result);
8020:
8021: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
8022: shift(@stats); #filename is first
8023: return @stats;
8024: }
8025: return ();
8026: }
8027:
8028: # -------------------------------------------------------- Value of a Condition
8029:
8030: # gets the value of a specific preevaluated condition
8031: # stored in the string $env{user.state.<cid>}
8032: # or looks up a condition reference in the bighash and if if hasn't
8033: # already been evaluated recurses into docondval to get the value of
8034: # the condition, then memoizing it to
8035: # $env{user.state.<cid>.<condition>}
8036: sub directcondval {
8037: my $number=shift;
8038: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
8039: &Apache::lonuserstate::evalstate();
8040: }
8041: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
8042: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
8043: } elsif ($number =~ /^_/) {
8044: my $sub_condition;
8045: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8046: &GDBM_READER(),0640)) {
8047: $sub_condition=$bighash{'conditions'.$number};
8048: untie(%bighash);
8049: }
8050: my $value = &docondval($sub_condition);
8051: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
8052: return $value;
8053: }
8054: if ($env{'user.state.'.$env{'request.course.id'}}) {
8055: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
8056: } else {
8057: return 2;
8058: }
8059: }
8060:
8061: # get the collection of conditions for this resource
8062: sub condval {
8063: my $condidx=shift;
8064: my $allpathcond='';
8065: foreach my $cond (split(/\|/,$condidx)) {
8066: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8067: $allpathcond.=
8068: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8069: }
8070: }
8071: $allpathcond=~s/\|$//;
8072: return &docondval($allpathcond);
8073: }
8074:
8075: #evaluates an expression of conditions
8076: sub docondval {
8077: my ($allpathcond) = @_;
8078: my $result=0;
8079: if ($env{'request.course.id'}
8080: && defined($allpathcond)) {
8081: my $operand='|';
8082: my @stack;
8083: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8084: if ($chunk eq '(') {
8085: push @stack,($operand,$result);
8086: } elsif ($chunk eq ')') {
8087: my $before=pop @stack;
8088: if (pop @stack eq '&') {
8089: $result=$result>$before?$before:$result;
8090: } else {
8091: $result=$result>$before?$result:$before;
8092: }
8093: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8094: $operand=$chunk;
8095: } else {
8096: my $new=directcondval($chunk);
8097: if ($operand eq '&') {
8098: $result=$result>$new?$new:$result;
8099: } else {
8100: $result=$result>$new?$result:$new;
8101: }
8102: }
8103: }
8104: }
8105: return $result;
8106: }
8107:
8108: # ---------------------------------------------------- Devalidate courseresdata
8109:
8110: sub devalidatecourseresdata {
8111: my ($coursenum,$coursedomain)=@_;
8112: my $hashid=$coursenum.':'.$coursedomain;
8113: &devalidate_cache_new('courseres',$hashid);
8114: }
8115:
8116:
8117: # --------------------------------------------------- Course Resourcedata Query
8118: #
8119: # Parameters:
8120: # $coursenum - Number of the course.
8121: # $coursedomain - Domain at which the course was created.
8122: # Returns:
8123: # A hash of the course parameters along (I think) with timestamps
8124: # and version info.
8125:
8126: sub get_courseresdata {
8127: my ($coursenum,$coursedomain)=@_;
8128: my $coursehom=&homeserver($coursenum,$coursedomain);
8129: my $hashid=$coursenum.':'.$coursedomain;
8130: my ($result,$cached)=&is_cached_new('courseres',$hashid);
8131: my %dumpreply;
8132: unless (defined($cached)) {
8133: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
8134: $result=\%dumpreply;
8135: my ($tmp) = keys(%dumpreply);
8136: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
8137: &do_cache_new('courseres',$hashid,$result,600);
8138: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8139: return $tmp;
8140: } elsif ($tmp =~ /^(error)/) {
8141: $result=undef;
8142: &do_cache_new('courseres',$hashid,$result,600);
8143: }
8144: }
8145: return $result;
8146: }
8147:
8148: sub devalidateuserresdata {
8149: my ($uname,$udom)=@_;
8150: my $hashid="$udom:$uname";
8151: &devalidate_cache_new('userres',$hashid);
8152: }
8153:
8154: sub get_userresdata {
8155: my ($uname,$udom)=@_;
8156: #most student don\'t have any data set, check if there is some data
8157: if (&EXT_cache_status($udom,$uname)) { return undef; }
8158:
8159: my $hashid="$udom:$uname";
8160: my ($result,$cached)=&is_cached_new('userres',$hashid);
8161: if (!defined($cached)) {
8162: my %resourcedata=&dump('resourcedata',$udom,$uname);
8163: $result=\%resourcedata;
8164: &do_cache_new('userres',$hashid,$result,600);
8165: }
8166: my ($tmp)=keys(%$result);
8167: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8168: return $result;
8169: }
8170: #error 2 occurs when the .db doesn't exist
8171: if ($tmp!~/error: 2 /) {
8172: &logthis("<font color=\"blue\">WARNING:".
8173: " Trying to get resource data for ".
8174: $uname." at ".$udom.": ".
8175: $tmp."</font>");
8176: } elsif ($tmp=~/error: 2 /) {
8177: #&EXT_cache_set($udom,$uname);
8178: &do_cache_new('userres',$hashid,undef,600);
8179: undef($tmp); # not really an error so don't send it back
8180: }
8181: return $tmp;
8182: }
8183: #----------------------------------------------- resdata - return resource data
8184: # Purpose:
8185: # Return resource data for either users or for a course.
8186: # Parameters:
8187: # $name - Course/user name.
8188: # $domain - Name of the domain the user/course is registered on.
8189: # $type - Type of thing $name is (must be 'course' or 'user'
8190: # @which - Array of names of resources desired.
8191: # Returns:
8192: # The value of the first reasource in @which that is found in the
8193: # resource hash.
8194: # Exceptional Conditions:
8195: # If the $type passed in is not valid (not the string 'course' or
8196: # 'user', an undefined reference is returned.
8197: # If none of the resources are found, an undef is returned
8198: sub resdata {
8199: my ($name,$domain,$type,@which)=@_;
8200: my $result;
8201: if ($type eq 'course') {
8202: $result=&get_courseresdata($name,$domain);
8203: } elsif ($type eq 'user') {
8204: $result=&get_userresdata($name,$domain);
8205: }
8206: if (!ref($result)) { return $result; }
8207: foreach my $item (@which) {
8208: if (defined($result->{$item->[0]})) {
8209: return [$result->{$item->[0]},$item->[1]];
8210: }
8211: }
8212: return undef;
8213: }
8214:
8215: #
8216: # EXT resource caching routines
8217: #
8218:
8219: sub clear_EXT_cache_status {
8220: &delenv('cache.EXT.');
8221: }
8222:
8223: sub EXT_cache_status {
8224: my ($target_domain,$target_user) = @_;
8225: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
8226: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
8227: # We know already the user has no data
8228: return 1;
8229: } else {
8230: return 0;
8231: }
8232: }
8233:
8234: sub EXT_cache_set {
8235: my ($target_domain,$target_user) = @_;
8236: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
8237: #&appenv({$cachename => time});
8238: }
8239:
8240: # --------------------------------------------------------- Value of a Variable
8241: sub EXT {
8242:
8243: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
8244: unless ($varname) { return ''; }
8245: #get real user name/domain, courseid and symb
8246: my $courseid;
8247: my $publicuser;
8248: if ($symbparm) {
8249: $symbparm=&get_symb_from_alias($symbparm);
8250: }
8251: if (!($uname && $udom)) {
8252: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
8253: if (!$symbparm) { $symbparm=$cursymb; }
8254: } else {
8255: $courseid=$env{'request.course.id'};
8256: }
8257: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8258: my $rest;
8259: if (defined($therest[0])) {
8260: $rest=join('.',@therest);
8261: } else {
8262: $rest='';
8263: }
8264:
8265: my $qualifierrest=$qualifier;
8266: if ($rest) { $qualifierrest.='.'.$rest; }
8267: my $spacequalifierrest=$space;
8268: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
8269: if ($realm eq 'user') {
8270: # --------------------------------------------------------------- user.resource
8271: if ($space eq 'resource') {
8272: if ( (defined($Apache::lonhomework::parsing_a_problem)
8273: || defined($Apache::lonhomework::parsing_a_task))
8274: &&
8275: ($symbparm eq &symbread()) ) {
8276: # if we are in the middle of processing the resource the
8277: # get the value we are planning on committing
8278: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8279: return $Apache::lonhomework::results{$qualifierrest};
8280: } else {
8281: return $Apache::lonhomework::history{$qualifierrest};
8282: }
8283: } else {
8284: my %restored;
8285: if ($publicuser || $env{'request.state'} eq 'construct') {
8286: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8287: } else {
8288: %restored=&restore($symbparm,$courseid,$udom,$uname);
8289: }
8290: return $restored{$qualifierrest};
8291: }
8292: # ----------------------------------------------------------------- user.access
8293: } elsif ($space eq 'access') {
8294: # FIXME - not supporting calls for a specific user
8295: return &allowed($qualifier,$rest);
8296: # ------------------------------------------ user.preferences, user.environment
8297: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
8298: if (($uname eq $env{'user.name'}) &&
8299: ($udom eq $env{'user.domain'})) {
8300: return $env{join('.',('environment',$qualifierrest))};
8301: } else {
8302: my %returnhash;
8303: if (!$publicuser) {
8304: %returnhash=&userenvironment($udom,$uname,
8305: $qualifierrest);
8306: }
8307: return $returnhash{$qualifierrest};
8308: }
8309: # ----------------------------------------------------------------- user.course
8310: } elsif ($space eq 'course') {
8311: # FIXME - not supporting calls for a specific user
8312: return $env{join('.',('request.course',$qualifier))};
8313: # ------------------------------------------------------------------- user.role
8314: } elsif ($space eq 'role') {
8315: # FIXME - not supporting calls for a specific user
8316: my ($role,$where)=split(/\./,$env{'request.role'});
8317: if ($qualifier eq 'value') {
8318: return $role;
8319: } elsif ($qualifier eq 'extent') {
8320: return $where;
8321: }
8322: # ----------------------------------------------------------------- user.domain
8323: } elsif ($space eq 'domain') {
8324: return $udom;
8325: # ------------------------------------------------------------------- user.name
8326: } elsif ($space eq 'name') {
8327: return $uname;
8328: # ---------------------------------------------------- Any other user namespace
8329: } else {
8330: my %reply;
8331: if (!$publicuser) {
8332: %reply=&get($space,[$qualifierrest],$udom,$uname);
8333: }
8334: return $reply{$qualifierrest};
8335: }
8336: } elsif ($realm eq 'query') {
8337: # ---------------------------------------------- pull stuff out of query string
8338: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8339: [$spacequalifierrest]);
8340: return $env{'form.'.$spacequalifierrest};
8341: } elsif ($realm eq 'request') {
8342: # ------------------------------------------------------------- request.browser
8343: if ($space eq 'browser') {
8344: if ($qualifier eq 'textremote') {
8345: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
8346: return 1;
8347: } else {
8348: return 0;
8349: }
8350: } else {
8351: return $env{'browser.'.$qualifier};
8352: }
8353: # ------------------------------------------------------------ request.filename
8354: } else {
8355: return $env{'request.'.$spacequalifierrest};
8356: }
8357: } elsif ($realm eq 'course') {
8358: # ---------------------------------------------------------- course.description
8359: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
8360: } elsif ($realm eq 'resource') {
8361:
8362: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
8363: if (!$symbparm) { $symbparm=&symbread(); }
8364: }
8365:
8366: if ($space eq 'title') {
8367: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8368: return &gettitle($symbparm);
8369: }
8370:
8371: if ($space eq 'map') {
8372: my ($map) = &decode_symb($symbparm);
8373: return &symbread($map);
8374: }
8375: if ($space eq 'filename') {
8376: if ($symbparm) {
8377: return &clutter((&decode_symb($symbparm))[2]);
8378: }
8379: return &hreflocation('',$env{'request.filename'});
8380: }
8381:
8382: my ($section, $group, @groups);
8383: my ($courselevelm,$courselevel);
8384: if ($symbparm && defined($courseid) &&
8385: $courseid eq $env{'request.course.id'}) {
8386:
8387: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
8388:
8389: # ----------------------------------------------------- Cascading lookup scheme
8390: my $symbp=$symbparm;
8391: my $mapp=&deversion((&decode_symb($symbp))[0]);
8392:
8393: my $symbparm=$symbp.'.'.$spacequalifierrest;
8394: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8395:
8396: if (($env{'user.name'} eq $uname) &&
8397: ($env{'user.domain'} eq $udom)) {
8398: $section=$env{'request.course.sec'};
8399: @groups = split(/:/,$env{'request.course.groups'});
8400: @groups=&sort_course_groups($courseid,@groups);
8401: } else {
8402: if (! defined($usection)) {
8403: $section=&getsection($udom,$uname,$courseid);
8404: } else {
8405: $section = $usection;
8406: }
8407: @groups = &get_users_groups($udom,$uname,$courseid);
8408: }
8409:
8410: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8411: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8412: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8413:
8414: $courselevel=$courseid.'.'.$spacequalifierrest;
8415: my $courselevelr=$courseid.'.'.$symbparm;
8416: $courselevelm=$courseid.'.'.$mapparm;
8417:
8418: # ----------------------------------------------------------- first, check user
8419:
8420: my $userreply=&resdata($uname,$udom,'user',
8421: ([$courselevelr,'resource'],
8422: [$courselevelm,'map' ],
8423: [$courselevel, 'course' ]));
8424: if (defined($userreply)) { return &get_reply($userreply); }
8425:
8426: # ------------------------------------------------ second, check some of course
8427: my $coursereply;
8428: if (@groups > 0) {
8429: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8430: $mapparm,$spacequalifierrest);
8431: if (defined($coursereply)) { return &get_reply($coursereply); }
8432: }
8433:
8434: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8435: $env{'course.'.$courseid.'.domain'},
8436: 'course',
8437: ([$seclevelr, 'resource'],
8438: [$seclevelm, 'map' ],
8439: [$seclevel, 'course' ],
8440: [$courselevelr,'resource']));
8441: if (defined($coursereply)) { return &get_reply($coursereply); }
8442:
8443: # ------------------------------------------------------ third, check map parms
8444: my %parmhash=();
8445: my $thisparm='';
8446: if (tie(%parmhash,'GDBM_File',
8447: $env{'request.course.fn'}.'_parms.db',
8448: &GDBM_READER(),0640)) {
8449: $thisparm=$parmhash{$symbparm};
8450: untie(%parmhash);
8451: }
8452: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
8453: }
8454: # ------------------------------------------ fourth, look in resource metadata
8455:
8456: $spacequalifierrest=~s/\./\_/;
8457: my $filename;
8458: if (!$symbparm) { $symbparm=&symbread(); }
8459: if ($symbparm) {
8460: $filename=(&decode_symb($symbparm))[2];
8461: } else {
8462: $filename=$env{'request.filename'};
8463: }
8464: my $metadata=&metadata($filename,$spacequalifierrest);
8465: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
8466: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
8467: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
8468:
8469: # ---------------------------------------------- fourth, look in rest of course
8470: if ($symbparm && defined($courseid) &&
8471: $courseid eq $env{'request.course.id'}) {
8472: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8473: $env{'course.'.$courseid.'.domain'},
8474: 'course',
8475: ([$courselevelm,'map' ],
8476: [$courselevel, 'course']));
8477: if (defined($coursereply)) { return &get_reply($coursereply); }
8478: }
8479: # ------------------------------------------------------------------ Cascade up
8480: unless ($space eq '0') {
8481: my @parts=split(/_/,$space);
8482: my $id=pop(@parts);
8483: my $part=join('_',@parts);
8484: if ($part eq '') { $part='0'; }
8485: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
8486: $symbparm,$udom,$uname,$section,1);
8487: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
8488: }
8489: if ($recurse) { return undef; }
8490: my $pack_def=&packages_tab_default($filename,$varname);
8491: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
8492: # ---------------------------------------------------- Any other user namespace
8493: } elsif ($realm eq 'environment') {
8494: # ----------------------------------------------------------------- environment
8495: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8496: return $env{'environment.'.$spacequalifierrest};
8497: } else {
8498: if ($uname eq 'anonymous' && $udom eq '') {
8499: return '';
8500: }
8501: my %returnhash=&userenvironment($udom,$uname,
8502: $spacequalifierrest);
8503: return $returnhash{$spacequalifierrest};
8504: }
8505: } elsif ($realm eq 'system') {
8506: # ----------------------------------------------------------------- system.time
8507: if ($space eq 'time') {
8508: return time;
8509: }
8510: } elsif ($realm eq 'server') {
8511: # ----------------------------------------------------------------- system.time
8512: if ($space eq 'name') {
8513: return $ENV{'SERVER_NAME'};
8514: }
8515: }
8516: return '';
8517: }
8518:
8519: sub get_reply {
8520: my ($reply_value) = @_;
8521: if (ref($reply_value) eq 'ARRAY') {
8522: if (wantarray) {
8523: return @$reply_value;
8524: }
8525: return $reply_value->[0];
8526: } else {
8527: return $reply_value;
8528: }
8529: }
8530:
8531: sub check_group_parms {
8532: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8533: my @groupitems = ();
8534: my $resultitem;
8535: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
8536: foreach my $group (@{$groups}) {
8537: foreach my $level (@levels) {
8538: my $item = $courseid.'.['.$group.'].'.$level->[0];
8539: push(@groupitems,[$item,$level->[1]]);
8540: }
8541: }
8542: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8543: $env{'course.'.$courseid.'.domain'},
8544: 'course',@groupitems);
8545: return $coursereply;
8546: }
8547:
8548: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
8549: my ($courseid,@groups) = @_;
8550: @groups = sort(@groups);
8551: return @groups;
8552: }
8553:
8554: sub packages_tab_default {
8555: my ($uri,$varname)=@_;
8556: my (undef,$part,$name)=split(/\./,$varname);
8557:
8558: my (@extension,@specifics,$do_default);
8559: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
8560: my ($pack_type,$pack_part)=split(/_/,$package,2);
8561: if ($pack_type eq 'default') {
8562: $do_default=1;
8563: } elsif ($pack_type eq 'extension') {
8564: push(@extension,[$package,$pack_type,$pack_part]);
8565: } elsif ($pack_part eq $part || $pack_type eq 'part') {
8566: # only look at packages defaults for packages that this id is
8567: push(@specifics,[$package,$pack_type,$pack_part]);
8568: }
8569: }
8570: # first look for a package that matches the requested part id
8571: foreach my $package (@specifics) {
8572: my (undef,$pack_type,$pack_part)=@{$package};
8573: next if ($pack_part ne $part);
8574: if (defined($packagetab{"$pack_type&$name&default"})) {
8575: return $packagetab{"$pack_type&$name&default"};
8576: }
8577: }
8578: # look for any possible matching non extension_ package
8579: foreach my $package (@specifics) {
8580: my (undef,$pack_type,$pack_part)=@{$package};
8581: if (defined($packagetab{"$pack_type&$name&default"})) {
8582: return $packagetab{"$pack_type&$name&default"};
8583: }
8584: if ($pack_type eq 'part') { $pack_part='0'; }
8585: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8586: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
8587: }
8588: }
8589: # look for any posible extension_ match
8590: foreach my $package (@extension) {
8591: my ($package,$pack_type)=@{$package};
8592: if (defined($packagetab{"$pack_type&$name&default"})) {
8593: return $packagetab{"$pack_type&$name&default"};
8594: }
8595: if (defined($packagetab{$package."&$name&default"})) {
8596: return $packagetab{$package."&$name&default"};
8597: }
8598: }
8599: # look for a global default setting
8600: if ($do_default && defined($packagetab{"default&$name&default"})) {
8601: return $packagetab{"default&$name&default"};
8602: }
8603: return undef;
8604: }
8605:
8606: sub add_prefix_and_part {
8607: my ($prefix,$part)=@_;
8608: my $keyroot;
8609: if (defined($prefix) && $prefix !~ /^__/) {
8610: # prefix that has a part already
8611: $keyroot=$prefix;
8612: } elsif (defined($prefix)) {
8613: # prefix that is missing a part
8614: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8615: } else {
8616: # no prefix at all
8617: if (defined($part)) { $keyroot='_'.$part; }
8618: }
8619: return $keyroot;
8620: }
8621:
8622: # ---------------------------------------------------------------- Get metadata
8623:
8624: my %metaentry;
8625: sub metadata {
8626: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
8627: $uri=&declutter($uri);
8628: # if it is a non metadata possible uri return quickly
8629: if (($uri eq '') ||
8630: (($uri =~ m|^/*adm/|) &&
8631: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
8632: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
8633: return undef;
8634: }
8635: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8636: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
8637: return undef;
8638: }
8639: my $filename=$uri;
8640: $uri=~s/\.meta$//;
8641: #
8642: # Is the metadata already cached?
8643: # Look at timestamp of caching
8644: # Everything is cached by the main uri, libraries are never directly cached
8645: #
8646: if (!defined($liburi)) {
8647: my ($result,$cached)=&is_cached_new('meta',$uri);
8648: if (defined($cached)) { return $result->{':'.$what}; }
8649: }
8650: {
8651: #
8652: # Is this a recursive call for a library?
8653: #
8654: # if (! exists($metacache{$uri})) {
8655: # $metacache{$uri}={};
8656: # }
8657: my $cachetime = 60*60;
8658: if ($liburi) {
8659: $liburi=&declutter($liburi);
8660: $filename=$liburi;
8661: } else {
8662: &devalidate_cache_new('meta',$uri);
8663: undef(%metaentry);
8664: }
8665: my %metathesekeys=();
8666: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
8667: my $metastring;
8668: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
8669: my $which = &hreflocation('','/'.($liburi || $uri));
8670: $metastring =
8671: &Apache::lonnet::ssi_body($which,
8672: ('grade_target' => 'meta'));
8673: $cachetime = 1; # only want this cached in the child not long term
8674: } elsif (($uri !~ m -^(editupload)/-) &&
8675: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
8676: my $file=&filelocation('',&clutter($filename));
8677: #push(@{$metaentry{$uri.'.file'}},$file);
8678: $metastring=&getfile($file);
8679: }
8680: my $parser=HTML::LCParser->new(\$metastring);
8681: my $token;
8682: undef %metathesekeys;
8683: while ($token=$parser->get_token) {
8684: if ($token->[0] eq 'S') {
8685: if (defined($token->[2]->{'package'})) {
8686: #
8687: # This is a package - get package info
8688: #
8689: my $package=$token->[2]->{'package'};
8690: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8691: if (defined($token->[2]->{'id'})) {
8692: $keyroot.='_'.$token->[2]->{'id'};
8693: }
8694: if ($metaentry{':packages'}) {
8695: $metaentry{':packages'}.=','.$package.$keyroot;
8696: } else {
8697: $metaentry{':packages'}=$package.$keyroot;
8698: }
8699: foreach my $pack_entry (keys(%packagetab)) {
8700: my $part=$keyroot;
8701: $part=~s/^\_//;
8702: if ($pack_entry=~/^\Q$package\E\&/ ||
8703: $pack_entry=~/^\Q$package\E_0\&/) {
8704: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
8705: # ignore package.tab specified default values
8706: # here &package_tab_default() will fetch those
8707: if ($subp eq 'default') { next; }
8708: my $value=$packagetab{$pack_entry};
8709: my $unikey;
8710: if ($pack =~ /_0$/) {
8711: $unikey='parameter_0_'.$name;
8712: $part=0;
8713: } else {
8714: $unikey='parameter'.$keyroot.'_'.$name;
8715: }
8716: if ($subp eq 'display') {
8717: $value.=' [Part: '.$part.']';
8718: }
8719: $metaentry{':'.$unikey.'.part'}=$part;
8720: $metathesekeys{$unikey}=1;
8721: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8722: $metaentry{':'.$unikey.'.'.$subp}=$value;
8723: }
8724: if (defined($metaentry{':'.$unikey.'.default'})) {
8725: $metaentry{':'.$unikey}=
8726: $metaentry{':'.$unikey.'.default'};
8727: }
8728: }
8729: }
8730: } else {
8731: #
8732: # This is not a package - some other kind of start tag
8733: #
8734: my $entry=$token->[1];
8735: my $unikey;
8736: if ($entry eq 'import') {
8737: $unikey='';
8738: } else {
8739: $unikey=$entry;
8740: }
8741: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8742:
8743: if (defined($token->[2]->{'id'})) {
8744: $unikey.='_'.$token->[2]->{'id'};
8745: }
8746:
8747: if ($entry eq 'import') {
8748: #
8749: # Importing a library here
8750: #
8751: if ($depthcount<20) {
8752: my $location=$parser->get_text('/import');
8753: my $dir=$filename;
8754: $dir=~s|[^/]*$||;
8755: $location=&filelocation($dir,$location);
8756: my $metadata =
8757: &metadata($uri,'keys', $location,$unikey,
8758: $depthcount+1);
8759: foreach my $meta (split(',',$metadata)) {
8760: $metaentry{':'.$meta}=$metaentry{':'.$meta};
8761: $metathesekeys{$meta}=1;
8762: }
8763: }
8764: } else {
8765: if (defined($token->[2]->{'name'})) {
8766: $unikey.='_'.$token->[2]->{'name'};
8767: }
8768: $metathesekeys{$unikey}=1;
8769: foreach my $param (@{$token->[3]}) {
8770: $metaentry{':'.$unikey.'.'.$param} =
8771: $token->[2]->{$param};
8772: }
8773: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
8774: my $default=$metaentry{':'.$unikey.'.default'};
8775: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
8776: # only ws inside the tag, and not in default, so use default
8777: # as value
8778: $metaentry{':'.$unikey}=$default;
8779: } elsif ( $internaltext =~ /\S/ ) {
8780: # something interesting inside the tag
8781: $metaentry{':'.$unikey}=$internaltext;
8782: } else {
8783: # no interesting values, don't set a default
8784: }
8785: # end of not-a-package not-a-library import
8786: }
8787: # end of not-a-package start tag
8788: }
8789: # the next is the end of "start tag"
8790: }
8791: }
8792: my ($extension) = ($uri =~ /\.(\w+)$/);
8793: $extension = lc($extension);
8794: if ($extension eq 'htm') { $extension='html'; }
8795:
8796: foreach my $key (keys(%packagetab)) {
8797: #no specific packages #how's our extension
8798: if ($key!~/^extension_\Q$extension\E&/) { next; }
8799: &metadata_create_package_def($uri,$key,'extension_'.$extension,
8800: \%metathesekeys);
8801: }
8802:
8803: if (!exists($metaentry{':packages'})
8804: || $packagetab{"import_defaults&extension_$extension"}) {
8805: foreach my $key (keys(%packagetab)) {
8806: #no specific packages well let's get default then
8807: if ($key!~/^default&/) { next; }
8808: &metadata_create_package_def($uri,$key,'default',
8809: \%metathesekeys);
8810: }
8811: }
8812: # are there custom rights to evaluate
8813: if ($metaentry{':copyright'} eq 'custom') {
8814:
8815: #
8816: # Importing a rights file here
8817: #
8818: unless ($depthcount) {
8819: my $location=$metaentry{':customdistributionfile'};
8820: my $dir=$filename;
8821: $dir=~s|[^/]*$||;
8822: $location=&filelocation($dir,$location);
8823: my $rights_metadata =
8824: &metadata($uri,'keys',$location,'_rights',
8825: $depthcount+1);
8826: foreach my $rights (split(',',$rights_metadata)) {
8827: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8828: $metathesekeys{$rights}=1;
8829: }
8830: }
8831: }
8832: # uniqifiy package listing
8833: my %seen;
8834: my @uniq_packages =
8835: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8836: $metaentry{':packages'} = join(',',@uniq_packages);
8837:
8838: $metaentry{':keys'} = join(',',keys(%metathesekeys));
8839: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8840: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
8841: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
8842: # this is the end of "was not already recently cached
8843: }
8844: return $metaentry{':'.$what};
8845: }
8846:
8847: sub metadata_create_package_def {
8848: my ($uri,$key,$package,$metathesekeys)=@_;
8849: my ($pack,$name,$subp)=split(/\&/,$key);
8850: if ($subp eq 'default') { next; }
8851:
8852: if (defined($metaentry{':packages'})) {
8853: $metaentry{':packages'}.=','.$package;
8854: } else {
8855: $metaentry{':packages'}=$package;
8856: }
8857: my $value=$packagetab{$key};
8858: my $unikey;
8859: $unikey='parameter_0_'.$name;
8860: $metaentry{':'.$unikey.'.part'}=0;
8861: $$metathesekeys{$unikey}=1;
8862: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8863: $metaentry{':'.$unikey.'.'.$subp}=$value;
8864: }
8865: if (defined($metaentry{':'.$unikey.'.default'})) {
8866: $metaentry{':'.$unikey}=
8867: $metaentry{':'.$unikey.'.default'};
8868: }
8869: }
8870:
8871: sub metadata_generate_part0 {
8872: my ($metadata,$metacache,$uri) = @_;
8873: my %allnames;
8874: foreach my $metakey (keys(%$metadata)) {
8875: if ($metakey=~/^parameter\_(.*)/) {
8876: my $part=$$metacache{':'.$metakey.'.part'};
8877: my $name=$$metacache{':'.$metakey.'.name'};
8878: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
8879: $allnames{$name}=$part;
8880: }
8881: }
8882: }
8883: foreach my $name (keys(%allnames)) {
8884: $$metadata{"parameter_0_$name"}=1;
8885: my $key=":parameter_0_$name";
8886: $$metacache{"$key.part"}='0';
8887: $$metacache{"$key.name"}=$name;
8888: $$metacache{"$key.type"}=$$metacache{':parameter_'.
8889: $allnames{$name}.'_'.$name.
8890: '.type'};
8891: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
8892: '.display'};
8893: my $expr='[Part: '.$allnames{$name}.']';
8894: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
8895: $$metacache{"$key.display"}=$olddis;
8896: }
8897: }
8898:
8899: # ------------------------------------------------------ Devalidate title cache
8900:
8901: sub devalidate_title_cache {
8902: my ($url)=@_;
8903: if (!$env{'request.course.id'}) { return; }
8904: my $symb=&symbread($url);
8905: if (!$symb) { return; }
8906: my $key=$env{'request.course.id'}."\0".$symb;
8907: &devalidate_cache_new('title',$key);
8908: }
8909:
8910: # ------------------------------------------------- Get the title of a course
8911:
8912: sub current_course_title {
8913: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8914: }
8915: # ------------------------------------------------- Get the title of a resource
8916:
8917: sub gettitle {
8918: my $urlsymb=shift;
8919: my $symb=&symbread($urlsymb);
8920: if ($symb) {
8921: my $key=$env{'request.course.id'}."\0".$symb;
8922: my ($result,$cached)=&is_cached_new('title',$key);
8923: if (defined($cached)) {
8924: return $result;
8925: }
8926: my ($map,$resid,$url)=&decode_symb($symb);
8927: my $title='';
8928: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8929: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8930: } else {
8931: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8932: &GDBM_READER(),0640)) {
8933: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8934: $title=$bighash{'title_'.$mapid.'.'.$resid};
8935: untie(%bighash);
8936: }
8937: }
8938: $title=~s/\&colon\;/\:/gs;
8939: if ($title) {
8940: return &do_cache_new('title',$key,$title,600);
8941: }
8942: $urlsymb=$url;
8943: }
8944: my $title=&metadata($urlsymb,'title');
8945: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8946: return $title;
8947: }
8948:
8949: sub get_slot {
8950: my ($which,$cnum,$cdom)=@_;
8951: if (!$cnum || !$cdom) {
8952: (undef,my $courseid)=&whichuser();
8953: $cdom=$env{'course.'.$courseid.'.domain'};
8954: $cnum=$env{'course.'.$courseid.'.num'};
8955: }
8956: my $key=join("\0",'slots',$cdom,$cnum,$which);
8957: my %slotinfo;
8958: if (exists($remembered{$key})) {
8959: $slotinfo{$which} = $remembered{$key};
8960: } else {
8961: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8962: &Apache::lonhomework::showhash(%slotinfo);
8963: my ($tmp)=keys(%slotinfo);
8964: if ($tmp=~/^error:/) { return (); }
8965: $remembered{$key} = $slotinfo{$which};
8966: }
8967: if (ref($slotinfo{$which}) eq 'HASH') {
8968: return %{$slotinfo{$which}};
8969: }
8970: return $slotinfo{$which};
8971: }
8972: # ------------------------------------------------- Update symbolic store links
8973:
8974: sub symblist {
8975: my ($mapname,%newhash)=@_;
8976: $mapname=&deversion(&declutter($mapname));
8977: my %hash;
8978: if (($env{'request.course.fn'}) && (%newhash)) {
8979: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
8980: &GDBM_WRCREAT(),0640)) {
8981: foreach my $url (keys(%newhash)) {
8982: next if ($url eq 'last_known'
8983: && $env{'form.no_update_last_known'});
8984: $hash{declutter($url)}=&encode_symb($mapname,
8985: $newhash{$url}->[1],
8986: $newhash{$url}->[0]);
8987: }
8988: if (untie(%hash)) {
8989: return 'ok';
8990: }
8991: }
8992: }
8993: return 'error';
8994: }
8995:
8996: # --------------------------------------------------------------- Verify a symb
8997:
8998: sub symbverify {
8999: my ($symb,$thisurl)=@_;
9000: my $thisfn=$thisurl;
9001: $thisfn=&declutter($thisfn);
9002: # direct jump to resource in page or to a sequence - will construct own symbs
9003: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
9004: # check URL part
9005: my ($map,$resid,$url)=&decode_symb($symb);
9006:
9007: unless ($url eq $thisfn) { return 0; }
9008:
9009: $symb=&symbclean($symb);
9010: $thisurl=&deversion($thisurl);
9011: $thisfn=&deversion($thisfn);
9012:
9013: my %bighash;
9014: my $okay=0;
9015:
9016: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9017: &GDBM_READER(),0640)) {
9018: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
9019: $thisurl =~ s/\?.+$//;
9020: }
9021: my $ids=$bighash{'ids_'.&clutter($thisurl)};
9022: unless ($ids) {
9023: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
9024: $ids=$bighash{$idkey};
9025: }
9026: if ($ids) {
9027: # ------------------------------------------------------------------- Has ID(s)
9028: foreach my $id (split(/\,/,$ids)) {
9029: my ($mapid,$resid)=split(/\./,$id);
9030: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
9031: $symb =~ s/\?.+$//;
9032: }
9033: if (
9034: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
9035: eq $symb) {
9036: if (($env{'request.role.adv'}) ||
9037: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
9038: ($thisurl eq '/adm/navmaps')) {
9039: $okay=1;
9040: }
9041: }
9042: }
9043: }
9044: untie(%bighash);
9045: }
9046: return $okay;
9047: }
9048:
9049: # --------------------------------------------------------------- Clean-up symb
9050:
9051: sub symbclean {
9052: my $symb=shift;
9053: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9054: # remove version from map
9055: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
9056:
9057: # remove version from URL
9058: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
9059:
9060: # remove wrapper
9061:
9062: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
9063: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
9064: return $symb;
9065: }
9066:
9067: # ---------------------------------------------- Split symb to find map and url
9068:
9069: sub encode_symb {
9070: my ($map,$resid,$url)=@_;
9071: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
9072: }
9073:
9074: sub decode_symb {
9075: my $symb=shift;
9076: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9077: my ($map,$resid,$url)=split(/___/,$symb);
9078: return (&fixversion($map),$resid,&fixversion($url));
9079: }
9080:
9081: sub fixversion {
9082: my $fn=shift;
9083: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
9084: my %bighash;
9085: my $uri=&clutter($fn);
9086: my $key=$env{'request.course.id'}.'_'.$uri;
9087: # is this cached?
9088: my ($result,$cached)=&is_cached_new('courseresversion',$key);
9089: if (defined($cached)) { return $result; }
9090: # unfortunately not cached, or expired
9091: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9092: &GDBM_READER(),0640)) {
9093: if ($bighash{'version_'.$uri}) {
9094: my $version=$bighash{'version_'.$uri};
9095: unless (($version eq 'mostrecent') ||
9096: ($version==&getversion($uri))) {
9097: $uri=~s/\.(\w+)$/\.$version\.$1/;
9098: }
9099: }
9100: untie %bighash;
9101: }
9102: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
9103: }
9104:
9105: sub deversion {
9106: my $url=shift;
9107: $url=~s/\.\d+\.(\w+)$/\.$1/;
9108: return $url;
9109: }
9110:
9111: # ------------------------------------------------------ Return symb list entry
9112:
9113: sub symbread {
9114: my ($thisfn,$donotrecurse)=@_;
9115: my $cache_str='request.symbread.cached.'.$thisfn;
9116: if (defined($env{$cache_str})) { return $env{$cache_str}; }
9117: # no filename provided? try from environment
9118: unless ($thisfn) {
9119: if ($env{'request.symb'}) {
9120: return $env{$cache_str}=&symbclean($env{'request.symb'});
9121: }
9122: $thisfn=$env{'request.filename'};
9123: }
9124: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
9125: # is that filename actually a symb? Verify, clean, and return
9126: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
9127: if (&symbverify($thisfn,$1)) {
9128: return $env{$cache_str}=&symbclean($thisfn);
9129: }
9130: }
9131: $thisfn=declutter($thisfn);
9132: my %hash;
9133: my %bighash;
9134: my $syval='';
9135: if (($env{'request.course.fn'}) && ($thisfn)) {
9136: my $targetfn = $thisfn;
9137: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
9138: $targetfn = 'adm/wrapper/'.$thisfn;
9139: }
9140: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9141: $targetfn=$1;
9142: }
9143: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
9144: &GDBM_READER(),0640)) {
9145: $syval=$hash{$targetfn};
9146: untie(%hash);
9147: }
9148: # ---------------------------------------------------------- There was an entry
9149: if ($syval) {
9150: #unless ($syval=~/\_\d+$/) {
9151: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
9152: #&appenv({'request.ambiguous' => $thisfn});
9153: #return $env{$cache_str}='';
9154: #}
9155: #$syval.=$1;
9156: #}
9157: } else {
9158: # ------------------------------------------------------- Was not in symb table
9159: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9160: &GDBM_READER(),0640)) {
9161: # ---------------------------------------------- Get ID(s) for current resource
9162: my $ids=$bighash{'ids_'.&clutter($thisfn)};
9163: unless ($ids) {
9164: $ids=$bighash{'ids_/'.$thisfn};
9165: }
9166: unless ($ids) {
9167: # alias?
9168: $ids=$bighash{'mapalias_'.$thisfn};
9169: }
9170: if ($ids) {
9171: # ------------------------------------------------------------------- Has ID(s)
9172: my @possibilities=split(/\,/,$ids);
9173: if ($#possibilities==0) {
9174: # ----------------------------------------------- There is only one possibility
9175: my ($mapid,$resid)=split(/\./,$ids);
9176: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9177: $resid,$thisfn);
9178: } elsif (!$donotrecurse) {
9179: # ------------------------------------------ There is more than one possibility
9180: my $realpossible=0;
9181: foreach my $id (@possibilities) {
9182: my $file=$bighash{'src_'.$id};
9183: if (&allowed('bre',$file)) {
9184: my ($mapid,$resid)=split(/\./,$id);
9185: if ($bighash{'map_type_'.$mapid} ne 'page') {
9186: $realpossible++;
9187: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9188: $resid,$thisfn);
9189: }
9190: }
9191: }
9192: if ($realpossible!=1) { $syval=''; }
9193: } else {
9194: $syval='';
9195: }
9196: }
9197: untie(%bighash)
9198: }
9199: }
9200: if ($syval) {
9201: return $env{$cache_str}=$syval;
9202: }
9203: }
9204: &appenv({'request.ambiguous' => $thisfn});
9205: return $env{$cache_str}='';
9206: }
9207:
9208: # ---------------------------------------------------------- Return random seed
9209:
9210: sub numval {
9211: my $txt=shift;
9212: $txt=~tr/A-J/0-9/;
9213: $txt=~tr/a-j/0-9/;
9214: $txt=~tr/K-T/0-9/;
9215: $txt=~tr/k-t/0-9/;
9216: $txt=~tr/U-Z/0-5/;
9217: $txt=~tr/u-z/0-5/;
9218: $txt=~s/\D//g;
9219: if ($_64bit) { if ($txt > 2**32) { return -1; } }
9220: return int($txt);
9221: }
9222:
9223: sub numval2 {
9224: my $txt=shift;
9225: $txt=~tr/A-J/0-9/;
9226: $txt=~tr/a-j/0-9/;
9227: $txt=~tr/K-T/0-9/;
9228: $txt=~tr/k-t/0-9/;
9229: $txt=~tr/U-Z/0-5/;
9230: $txt=~tr/u-z/0-5/;
9231: $txt=~s/\D//g;
9232: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9233: my $total;
9234: foreach my $val (@txts) { $total+=$val; }
9235: if ($_64bit) { if ($total > 2**32) { return -1; } }
9236: return int($total);
9237: }
9238:
9239: sub numval3 {
9240: use integer;
9241: my $txt=shift;
9242: $txt=~tr/A-J/0-9/;
9243: $txt=~tr/a-j/0-9/;
9244: $txt=~tr/K-T/0-9/;
9245: $txt=~tr/k-t/0-9/;
9246: $txt=~tr/U-Z/0-5/;
9247: $txt=~tr/u-z/0-5/;
9248: $txt=~s/\D//g;
9249: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9250: my $total;
9251: foreach my $val (@txts) { $total+=$val; }
9252: if ($_64bit) { $total=(($total<<32)>>32); }
9253: return $total;
9254: }
9255:
9256: sub digest {
9257: my ($data)=@_;
9258: my $digest=&Digest::MD5::md5($data);
9259: my ($a,$b,$c,$d)=unpack("iiii",$digest);
9260: my ($e,$f);
9261: {
9262: use integer;
9263: $e=($a+$b);
9264: $f=($c+$d);
9265: if ($_64bit) {
9266: $e=(($e<<32)>>32);
9267: $f=(($f<<32)>>32);
9268: }
9269: }
9270: if (wantarray) {
9271: return ($e,$f);
9272: } else {
9273: my $g;
9274: {
9275: use integer;
9276: $g=($e+$f);
9277: if ($_64bit) {
9278: $g=(($g<<32)>>32);
9279: }
9280: }
9281: return $g;
9282: }
9283: }
9284:
9285: sub latest_rnd_algorithm_id {
9286: return '64bit5';
9287: }
9288:
9289: sub get_rand_alg {
9290: my ($courseid)=@_;
9291: if (!$courseid) { $courseid=(&whichuser())[1]; }
9292: if ($courseid) {
9293: return $env{"course.$courseid.rndseed"};
9294: }
9295: return &latest_rnd_algorithm_id();
9296: }
9297:
9298: sub validCODE {
9299: my ($CODE)=@_;
9300: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9301: return 0;
9302: }
9303:
9304: sub getCODE {
9305: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
9306: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9307: defined($Apache::lonhomework::parsing_a_task) ) &&
9308: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
9309: return $Apache::lonhomework::history{'resource.CODE'};
9310: }
9311: return undef;
9312: }
9313:
9314: sub rndseed {
9315: my ($symb,$courseid,$domain,$username)=@_;
9316: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
9317: if (!defined($symb)) {
9318: unless ($symb=$wsymb) { return time; }
9319: }
9320: if (!$courseid) { $courseid=$wcourseid; }
9321: if (!$domain) { $domain=$wdomain; }
9322: if (!$username) { $username=$wusername }
9323: my $which=&get_rand_alg();
9324:
9325: if (defined(&getCODE())) {
9326: if ($which eq '64bit5') {
9327: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9328: } elsif ($which eq '64bit4') {
9329: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9330: } else {
9331: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9332: }
9333: } elsif ($which eq '64bit5') {
9334: return &rndseed_64bit5($symb,$courseid,$domain,$username);
9335: } elsif ($which eq '64bit4') {
9336: return &rndseed_64bit4($symb,$courseid,$domain,$username);
9337: } elsif ($which eq '64bit3') {
9338: return &rndseed_64bit3($symb,$courseid,$domain,$username);
9339: } elsif ($which eq '64bit2') {
9340: return &rndseed_64bit2($symb,$courseid,$domain,$username);
9341: } elsif ($which eq '64bit') {
9342: return &rndseed_64bit($symb,$courseid,$domain,$username);
9343: }
9344: return &rndseed_32bit($symb,$courseid,$domain,$username);
9345: }
9346:
9347: sub rndseed_32bit {
9348: my ($symb,$courseid,$domain,$username)=@_;
9349: {
9350: use integer;
9351: my $symbchck=unpack("%32C*",$symb) << 27;
9352: my $symbseed=numval($symb) << 22;
9353: my $namechck=unpack("%32C*",$username) << 17;
9354: my $nameseed=numval($username) << 12;
9355: my $domainseed=unpack("%32C*",$domain) << 7;
9356: my $courseseed=unpack("%32C*",$courseid);
9357: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
9358: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9359: #&logthis("rndseed :$num:$symb");
9360: if ($_64bit) { $num=(($num<<32)>>32); }
9361: return $num;
9362: }
9363: }
9364:
9365: sub rndseed_64bit {
9366: my ($symb,$courseid,$domain,$username)=@_;
9367: {
9368: use integer;
9369: my $symbchck=unpack("%32S*",$symb) << 21;
9370: my $symbseed=numval($symb) << 10;
9371: my $namechck=unpack("%32S*",$username);
9372:
9373: my $nameseed=numval($username) << 21;
9374: my $domainseed=unpack("%32S*",$domain) << 10;
9375: my $courseseed=unpack("%32S*",$courseid);
9376:
9377: my $num1=$symbchck+$symbseed+$namechck;
9378: my $num2=$nameseed+$domainseed+$courseseed;
9379: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9380: #&logthis("rndseed :$num:$symb");
9381: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9382: return "$num1,$num2";
9383: }
9384: }
9385:
9386: sub rndseed_64bit2 {
9387: my ($symb,$courseid,$domain,$username)=@_;
9388: {
9389: use integer;
9390: # strings need to be an even # of cahracters long, it it is odd the
9391: # last characters gets thrown away
9392: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9393: my $symbseed=numval($symb) << 10;
9394: my $namechck=unpack("%32S*",$username.' ');
9395:
9396: my $nameseed=numval($username) << 21;
9397: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9398: my $courseseed=unpack("%32S*",$courseid.' ');
9399:
9400: my $num1=$symbchck+$symbseed+$namechck;
9401: my $num2=$nameseed+$domainseed+$courseseed;
9402: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9403: #&logthis("rndseed :$num:$symb");
9404: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9405: return "$num1,$num2";
9406: }
9407: }
9408:
9409: sub rndseed_64bit3 {
9410: my ($symb,$courseid,$domain,$username)=@_;
9411: {
9412: use integer;
9413: # strings need to be an even # of cahracters long, it it is odd the
9414: # last characters gets thrown away
9415: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9416: my $symbseed=numval2($symb) << 10;
9417: my $namechck=unpack("%32S*",$username.' ');
9418:
9419: my $nameseed=numval2($username) << 21;
9420: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9421: my $courseseed=unpack("%32S*",$courseid.' ');
9422:
9423: my $num1=$symbchck+$symbseed+$namechck;
9424: my $num2=$nameseed+$domainseed+$courseseed;
9425: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9426: #&logthis("rndseed :$num1:$num2:$_64bit");
9427: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9428:
9429: return "$num1:$num2";
9430: }
9431: }
9432:
9433: sub rndseed_64bit4 {
9434: my ($symb,$courseid,$domain,$username)=@_;
9435: {
9436: use integer;
9437: # strings need to be an even # of cahracters long, it it is odd the
9438: # last characters gets thrown away
9439: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9440: my $symbseed=numval3($symb) << 10;
9441: my $namechck=unpack("%32S*",$username.' ');
9442:
9443: my $nameseed=numval3($username) << 21;
9444: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9445: my $courseseed=unpack("%32S*",$courseid.' ');
9446:
9447: my $num1=$symbchck+$symbseed+$namechck;
9448: my $num2=$nameseed+$domainseed+$courseseed;
9449: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9450: #&logthis("rndseed :$num1:$num2:$_64bit");
9451: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9452:
9453: return "$num1:$num2";
9454: }
9455: }
9456:
9457: sub rndseed_64bit5 {
9458: my ($symb,$courseid,$domain,$username)=@_;
9459: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9460: return "$num1:$num2";
9461: }
9462:
9463: sub rndseed_CODE_64bit {
9464: my ($symb,$courseid,$domain,$username)=@_;
9465: {
9466: use integer;
9467: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9468: my $symbseed=numval2($symb);
9469: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9470: my $CODEseed=numval(&getCODE());
9471: my $courseseed=unpack("%32S*",$courseid.' ');
9472: my $num1=$symbseed+$CODEchck;
9473: my $num2=$CODEseed+$courseseed+$symbchck;
9474: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9475: #&logthis("rndseed :$num1:$num2:$symb");
9476: if ($_64bit) { $num1=(($num1<<32)>>32); }
9477: if ($_64bit) { $num2=(($num2<<32)>>32); }
9478: return "$num1:$num2";
9479: }
9480: }
9481:
9482: sub rndseed_CODE_64bit4 {
9483: my ($symb,$courseid,$domain,$username)=@_;
9484: {
9485: use integer;
9486: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9487: my $symbseed=numval3($symb);
9488: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9489: my $CODEseed=numval3(&getCODE());
9490: my $courseseed=unpack("%32S*",$courseid.' ');
9491: my $num1=$symbseed+$CODEchck;
9492: my $num2=$CODEseed+$courseseed+$symbchck;
9493: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9494: #&logthis("rndseed :$num1:$num2:$symb");
9495: if ($_64bit) { $num1=(($num1<<32)>>32); }
9496: if ($_64bit) { $num2=(($num2<<32)>>32); }
9497: return "$num1:$num2";
9498: }
9499: }
9500:
9501: sub rndseed_CODE_64bit5 {
9502: my ($symb,$courseid,$domain,$username)=@_;
9503: my $code = &getCODE();
9504: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9505: return "$num1:$num2";
9506: }
9507:
9508: sub setup_random_from_rndseed {
9509: my ($rndseed)=@_;
9510: if ($rndseed =~/([,:])/) {
9511: my ($num1,$num2)=split(/[,:]/,$rndseed);
9512: &Math::Random::random_set_seed(abs($num1),abs($num2));
9513: } else {
9514: &Math::Random::random_set_seed_from_phrase($rndseed);
9515: }
9516: }
9517:
9518: sub latest_receipt_algorithm_id {
9519: return 'receipt3';
9520: }
9521:
9522: sub recunique {
9523: my $fucourseid=shift;
9524: my $unique;
9525: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9526: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
9527: $unique=$env{"course.$fucourseid.internal.encseed"};
9528: } else {
9529: $unique=$perlvar{'lonReceipt'};
9530: }
9531: return unpack("%32C*",$unique);
9532: }
9533:
9534: sub recprefix {
9535: my $fucourseid=shift;
9536: my $prefix;
9537: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9538: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
9539: $prefix=$env{"course.$fucourseid.internal.encpref"};
9540: } else {
9541: $prefix=$perlvar{'lonHostID'};
9542: }
9543: return unpack("%32C*",$prefix);
9544: }
9545:
9546: sub ireceipt {
9547: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
9548:
9549: my $return =&recprefix($fucourseid).'-';
9550:
9551: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9552: $env{'request.state'} eq 'construct') {
9553: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9554: return $return;
9555: }
9556:
9557: my $cuname=unpack("%32C*",$funame);
9558: my $cudom=unpack("%32C*",$fudom);
9559: my $cucourseid=unpack("%32C*",$fucourseid);
9560: my $cusymb=unpack("%32C*",$fusymb);
9561: my $cunique=&recunique($fucourseid);
9562: my $cpart=unpack("%32S*",$part);
9563: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
9564:
9565: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
9566:
9567: $return.= ($cunique%$cuname+
9568: $cunique%$cudom+
9569: $cusymb%$cuname+
9570: $cusymb%$cudom+
9571: $cucourseid%$cuname+
9572: $cucourseid%$cudom+
9573: $cpart%$cuname+
9574: $cpart%$cudom);
9575: } else {
9576: $return.= ($cunique%$cuname+
9577: $cunique%$cudom+
9578: $cusymb%$cuname+
9579: $cusymb%$cudom+
9580: $cucourseid%$cuname+
9581: $cucourseid%$cudom);
9582: }
9583: return $return;
9584: }
9585:
9586: sub receipt {
9587: my ($part)=@_;
9588: my ($symb,$courseid,$domain,$name) = &whichuser();
9589: return &ireceipt($name,$domain,$courseid,$symb,$part);
9590: }
9591:
9592: sub whichuser {
9593: my ($passedsymb)=@_;
9594: my ($symb,$courseid,$domain,$name,$publicuser);
9595: if (defined($env{'form.grade_symb'})) {
9596: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
9597: my $allowed=&allowed('vgr',$tmp_courseid);
9598: if (!$allowed &&
9599: exists($env{'request.course.sec'}) &&
9600: $env{'request.course.sec'} !~ /^\s*$/) {
9601: $allowed=&allowed('vgr',$tmp_courseid.
9602: '/'.$env{'request.course.sec'});
9603: }
9604: if ($allowed) {
9605: ($symb)=&get_env_multiple('form.grade_symb');
9606: $courseid=$tmp_courseid;
9607: ($domain)=&get_env_multiple('form.grade_domain');
9608: ($name)=&get_env_multiple('form.grade_username');
9609: return ($symb,$courseid,$domain,$name,$publicuser);
9610: }
9611: }
9612: if (!$passedsymb) {
9613: $symb=&symbread();
9614: } else {
9615: $symb=$passedsymb;
9616: }
9617: $courseid=$env{'request.course.id'};
9618: $domain=$env{'user.domain'};
9619: $name=$env{'user.name'};
9620: if ($name eq 'public' && $domain eq 'public') {
9621: if (!defined($env{'form.username'})) {
9622: $env{'form.username'}.=time.rand(10000000);
9623: }
9624: $name.=$env{'form.username'};
9625: }
9626: return ($symb,$courseid,$domain,$name,$publicuser);
9627:
9628: }
9629:
9630: # ------------------------------------------------------------ Serves up a file
9631: # returns either the contents of the file or
9632: # -1 if the file doesn't exist
9633: #
9634: # if the target is a file that was uploaded via DOCS,
9635: # a check will be made to see if a current copy exists on the local server,
9636: # if it does this will be served, otherwise a copy will be retrieved from
9637: # the home server for the course and stored in /home/httpd/html/userfiles on
9638: # the local server.
9639:
9640: sub getfile {
9641: my ($file) = @_;
9642: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
9643: &repcopy($file);
9644: return &readfile($file);
9645: }
9646:
9647: sub repcopy_userfile {
9648: my ($file)=@_;
9649: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
9650: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
9651: my ($cdom,$cnum,$filename) =
9652: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
9653: my $uri="/uploaded/$cdom/$cnum/$filename";
9654: if (-e "$file") {
9655: # we already have a local copy, check it out
9656: my @fileinfo = stat($file);
9657: my $rtncode;
9658: my $info;
9659: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
9660: if ($lwpresp ne 'ok') {
9661: # there is no such file anymore, even though we had a local copy
9662: if ($rtncode eq '404') {
9663: unlink($file);
9664: }
9665: return -1;
9666: }
9667: if ($info < $fileinfo[9]) {
9668: # nice, the file we have is up-to-date, just say okay
9669: return 'ok';
9670: } else {
9671: # the file is outdated, get rid of it
9672: unlink($file);
9673: }
9674: }
9675: # one way or the other, at this point, we don't have the file
9676: # construct the correct path for the file
9677: my @parts = ($cdom,$cnum);
9678: if ($filename =~ m|^(.+)/[^/]+$|) {
9679: push @parts, split(/\//,$1);
9680: }
9681: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
9682: foreach my $part (@parts) {
9683: $path .= '/'.$part;
9684: if (!-e $path) {
9685: mkdir($path,0770);
9686: }
9687: }
9688: # now the path exists for sure
9689: # get a user agent
9690: my $ua=new LWP::UserAgent;
9691: my $transferfile=$file.'.in.transfer';
9692: # FIXME: this should flock
9693: if (-e $transferfile) { return 'ok'; }
9694: my $request;
9695: $uri=~s/^\///;
9696: my $homeserver = &homeserver($cnum,$cdom);
9697: my $protocol = $protocol{$homeserver};
9698: $protocol = 'http' if ($protocol ne 'https');
9699: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
9700: my $response=$ua->request($request,$transferfile);
9701: # did it work?
9702: if ($response->is_error()) {
9703: unlink($transferfile);
9704: &logthis("Userfile repcopy failed for $uri");
9705: return -1;
9706: }
9707: # worked, rename the transfer file
9708: rename($transferfile,$file);
9709: return 'ok';
9710: }
9711:
9712: sub tokenwrapper {
9713: my $uri=shift;
9714: $uri=~s|^https?\://([^/]+)||;
9715: $uri=~s|^/||;
9716: $env{'user.environment'}=~/\/([^\/]+)\.id/;
9717: my $token=$1;
9718: my (undef,$udom,$uname,$file)=split('/',$uri,4);
9719: if ($udom && $uname && $file) {
9720: $file=~s|(\?\.*)*$||;
9721: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
9722: my $homeserver = &homeserver($uname,$udom);
9723: my $protocol = $protocol{$homeserver};
9724: $protocol = 'http' if ($protocol ne 'https');
9725: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
9726: (($uri=~/\?/)?'&':'?').'token='.$token.
9727: '&tokenissued='.$perlvar{'lonHostID'};
9728: } else {
9729: return '/adm/notfound.html';
9730: }
9731: }
9732:
9733: # call with reqtype HEAD: get last modification time
9734: # call with reqtype GET: get the file contents
9735: # Do not call this with reqtype GET for large files! It loads everything into memory
9736: #
9737: sub getuploaded {
9738: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
9739: $uri=~s/^\///;
9740: my $homeserver = &homeserver($cnum,$cdom);
9741: my $protocol = $protocol{$homeserver};
9742: $protocol = 'http' if ($protocol ne 'https');
9743: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
9744: my $ua=new LWP::UserAgent;
9745: my $request=new HTTP::Request($reqtype,$uri);
9746: my $response=$ua->request($request);
9747: $$rtncode = $response->code;
9748: if (! $response->is_success()) {
9749: return 'failed';
9750: }
9751: if ($reqtype eq 'HEAD') {
9752: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
9753: } elsif ($reqtype eq 'GET') {
9754: $$info = $response->content;
9755: }
9756: return 'ok';
9757: }
9758:
9759: sub readfile {
9760: my $file = shift;
9761: if ( (! -e $file ) || ($file eq '') ) { return -1; };
9762: my $fh;
9763: open($fh,"<$file");
9764: my $a='';
9765: while (my $line = <$fh>) { $a .= $line; }
9766: return $a;
9767: }
9768:
9769: sub filelocation {
9770: my ($dir,$file) = @_;
9771: my $location;
9772: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
9773:
9774: if ($file =~ m-^/adm/-) {
9775: $file=~s-^/adm/wrapper/-/-;
9776: $file=~s-^/adm/coursedocs/showdoc/-/-;
9777: }
9778:
9779: if ($file=~m:^/~:) { # is a contruction space reference
9780: $location = $file;
9781: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
9782: } elsif ($file=~m{^/home/$match_username/public_html/}) {
9783: # is a correct contruction space reference
9784: $location = $file;
9785: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
9786: $location = $file;
9787: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
9788: my ($udom,$uname,$filename)=
9789: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
9790: my $home=&homeserver($uname,$udom);
9791: my $is_me=0;
9792: my @ids=¤t_machine_ids();
9793: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
9794: if ($is_me) {
9795: $location=&propath($udom,$uname).'/userfiles/'.$filename;
9796: } else {
9797: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
9798: $udom.'/'.$uname.'/'.$filename;
9799: }
9800: } elsif ($file =~ m-^/adm/-) {
9801: $location = $perlvar{'lonDocRoot'}.'/'.$file;
9802: } else {
9803: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9804: $file=~s:^/res/:/:;
9805: if ( !( $file =~ m:^/:) ) {
9806: $location = $dir. '/'.$file;
9807: } else {
9808: $location = '/home/httpd/html/res'.$file;
9809: }
9810: }
9811: $location=~s://+:/:g; # remove duplicate /
9812: while ($location=~m{/\.\./}) {
9813: if ($location =~ m{/[^/]+/\.\./}) {
9814: $location=~ s{/[^/]+/\.\./}{/}g;
9815: } else {
9816: $location=~ s{/\.\./}{/}g;
9817: }
9818: } #remove dir/..
9819: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9820: return $location;
9821: }
9822:
9823: sub hreflocation {
9824: my ($dir,$file)=@_;
9825: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
9826: $file=filelocation($dir,$file);
9827: } elsif ($file=~m-^/adm/-) {
9828: $file=~s-^/adm/wrapper/-/-;
9829: $file=~s-^/adm/coursedocs/showdoc/-/-;
9830: }
9831: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9832: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
9833: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9834: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
9835: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
9836: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
9837: -/uploaded/$1/$2/-x;
9838: }
9839: if ($file=~ m{^/userfiles/}) {
9840: $file =~ s{^/userfiles/}{/uploaded/};
9841: }
9842: return $file;
9843: }
9844:
9845: sub current_machine_domains {
9846: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9847: }
9848:
9849: sub machine_domains {
9850: my ($hostname) = @_;
9851: my @domains;
9852: my %hostname = &all_hostnames();
9853: while( my($id, $name) = each(%hostname)) {
9854: # &logthis("-$id-$name-$hostname-");
9855: if ($hostname eq $name) {
9856: push(@domains,&host_domain($id));
9857: }
9858: }
9859: return @domains;
9860: }
9861:
9862: sub current_machine_ids {
9863: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9864: }
9865:
9866: sub machine_ids {
9867: my ($hostname) = @_;
9868: $hostname ||= &hostname($perlvar{'lonHostID'});
9869: my @ids;
9870: my %name_to_host = &all_names();
9871: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9872: return @{ $name_to_host{$hostname} };
9873: }
9874: return;
9875: }
9876:
9877: sub additional_machine_domains {
9878: my @domains;
9879: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9880: while( my $line = <$fh>) {
9881: $line =~ s/\s//g;
9882: push(@domains,$line);
9883: }
9884: return @domains;
9885: }
9886:
9887: sub default_login_domain {
9888: my $domain = $perlvar{'lonDefDomain'};
9889: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9890: foreach my $posdom (¤t_machine_domains(),
9891: &additional_machine_domains()) {
9892: if (lc($posdom) eq lc($testdomain)) {
9893: $domain=$posdom;
9894: last;
9895: }
9896: }
9897: return $domain;
9898: }
9899:
9900: # ------------------------------------------------------------- Declutters URLs
9901:
9902: sub declutter {
9903: my $thisfn=shift;
9904: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
9905: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9906: $thisfn=~s/^\///;
9907: $thisfn=~s|^adm/wrapper/||;
9908: $thisfn=~s|^adm/coursedocs/showdoc/||;
9909: $thisfn=~s/^res\///;
9910: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
9911: $thisfn=~s/\?.+$//;
9912: }
9913: return $thisfn;
9914: }
9915:
9916: # ------------------------------------------------------------- Clutter up URLs
9917:
9918: sub clutter {
9919: my $thisfn='/'.&declutter(shift);
9920: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
9921: || $thisfn =~ m{^/adm/(includes|pages)} ) {
9922: $thisfn='/res'.$thisfn;
9923: }
9924: if ($thisfn !~m|^/adm|) {
9925: if ($thisfn =~ m|^/ext/|) {
9926: $thisfn='/adm/wrapper'.$thisfn;
9927: } else {
9928: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9929: my $embstyle=&Apache::loncommon::fileembstyle($ext);
9930: if ($embstyle eq 'ssi'
9931: || ($embstyle eq 'hdn')
9932: || ($embstyle eq 'rat')
9933: || ($embstyle eq 'prv')
9934: || ($embstyle eq 'ign')) {
9935: #do nothing with these
9936: } elsif (($embstyle eq 'img')
9937: || ($embstyle eq 'emb')
9938: || ($embstyle eq 'wrp')) {
9939: $thisfn='/adm/wrapper'.$thisfn;
9940: } elsif ($embstyle eq 'unk'
9941: && $thisfn!~/\.(sequence|page)$/) {
9942: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
9943: } else {
9944: # &logthis("Got a blank emb style");
9945: }
9946: }
9947: }
9948: return $thisfn;
9949: }
9950:
9951: sub clutter_with_no_wrapper {
9952: my $uri = &clutter(shift);
9953: if ($uri =~ m-^/adm/-) {
9954: $uri =~ s-^/adm/wrapper/-/-;
9955: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9956: }
9957: return $uri;
9958: }
9959:
9960: sub freeze_escape {
9961: my ($value)=@_;
9962: if (ref($value)) {
9963: $value=&nfreeze($value);
9964: return '__FROZEN__'.&escape($value);
9965: }
9966: return &escape($value);
9967: }
9968:
9969:
9970: sub thaw_unescape {
9971: my ($value)=@_;
9972: if ($value =~ /^__FROZEN__/) {
9973: substr($value,0,10,undef);
9974: $value=&unescape($value);
9975: return &thaw($value);
9976: }
9977: return &unescape($value);
9978: }
9979:
9980: sub correct_line_ends {
9981: my ($result)=@_;
9982: $$result =~s/\r\n/\n/mg;
9983: $$result =~s/\r/\n/mg;
9984: }
9985: # ================================================================ Main Program
9986:
9987: sub goodbye {
9988: &logthis("Starting Shut down");
9989: #not converted to using infrastruture and probably shouldn't be
9990: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
9991: #converted
9992: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
9993: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9994: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9995: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
9996: #1.1 only
9997: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9998: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
9999: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10000: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10001: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
10002: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10003: &logthis(sprintf("%-20s is %s",'hits',$hits));
10004: &flushcourselogs();
10005: &logthis("Shutting down");
10006: }
10007:
10008: sub get_dns {
10009: my ($url,$func,$ignore_cache) = @_;
10010: if (!$ignore_cache) {
10011: my ($content,$cached)=
10012: &Apache::lonnet::is_cached_new('dns',$url);
10013: if ($cached) {
10014: &$func($content);
10015: return;
10016: }
10017: }
10018:
10019: my %alldns;
10020: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10021: foreach my $dns (<$config>) {
10022: next if ($dns !~ /^\^(\S*)/x);
10023: my $line = $1;
10024: my ($host,$protocol) = split(/:/,$line);
10025: if ($protocol ne 'https') {
10026: $protocol = 'http';
10027: }
10028: $alldns{$host} = $protocol;
10029: }
10030: while (%alldns) {
10031: my ($dns) = keys(%alldns);
10032: my $ua=new LWP::UserAgent;
10033: $ua->timeout(30);
10034: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
10035: my $response=$ua->request($request);
10036: delete($alldns{$dns});
10037: next if ($response->is_error());
10038: my @content = split("\n",$response->content);
10039: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
10040: &$func(\@content);
10041: return;
10042: }
10043: close($config);
10044: my $which = (split('/',$url))[3];
10045: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10046: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
10047: my @content = <$config>;
10048: &$func(\@content);
10049: return;
10050: }
10051: # ------------------------------------------------------------ Read domain file
10052: {
10053: my $loaded;
10054: my %domain;
10055:
10056: sub parse_domain_tab {
10057: my ($lines) = @_;
10058: foreach my $line (@$lines) {
10059: next if ($line =~ /^(\#|\s*$ )/x);
10060:
10061: chomp($line);
10062: my ($name,@elements) = split(/:/,$line,9);
10063: my %this_domain;
10064: foreach my $field ('description', 'auth_def', 'auth_arg_def',
10065: 'lang_def', 'city', 'longi', 'lati',
10066: 'primary') {
10067: $this_domain{$field} = shift(@elements);
10068: }
10069: $domain{$name} = \%this_domain;
10070: }
10071: }
10072:
10073: sub reset_domain_info {
10074: undef($loaded);
10075: undef(%domain);
10076: }
10077:
10078: sub load_domain_tab {
10079: my ($ignore_cache) = @_;
10080: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
10081: my $fh;
10082: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10083: my @lines = <$fh>;
10084: &parse_domain_tab(\@lines);
10085: }
10086: close($fh);
10087: $loaded = 1;
10088: }
10089:
10090: sub domain {
10091: &load_domain_tab() if (!$loaded);
10092:
10093: my ($name,$what) = @_;
10094: return if ( !exists($domain{$name}) );
10095:
10096: if (!$what) {
10097: return $domain{$name}{'description'};
10098: }
10099: return $domain{$name}{$what};
10100: }
10101:
10102: sub domain_info {
10103: &load_domain_tab() if (!$loaded);
10104: return %domain;
10105: }
10106:
10107: }
10108:
10109:
10110: # ------------------------------------------------------------- Read hosts file
10111: {
10112: my %hostname;
10113: my %hostdom;
10114: my %libserv;
10115: my $loaded;
10116: my %name_to_host;
10117: my %internetdom;
10118: my %LC_dns_serv;
10119:
10120: sub parse_hosts_tab {
10121: my ($file) = @_;
10122: foreach my $configline (@$file) {
10123: next if ($configline =~ /^(\#|\s*$ )/x);
10124: chomp($configline);
10125: if ($configline =~ /^\^/) {
10126: if ($configline =~ /^\^([\w.\-]+)/) {
10127: $LC_dns_serv{$1} = 1;
10128: }
10129: next;
10130: }
10131: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
10132: $name=~s/\s//g;
10133: if ($id && $domain && $role && $name) {
10134: $hostname{$id}=$name;
10135: push(@{$name_to_host{$name}}, $id);
10136: $hostdom{$id}=$domain;
10137: if ($role eq 'library') { $libserv{$id}=$name; }
10138: if (defined($protocol)) {
10139: if ($protocol eq 'https') {
10140: $protocol{$id} = $protocol;
10141: } else {
10142: $protocol{$id} = 'http';
10143: }
10144: } else {
10145: $protocol{$id} = 'http';
10146: }
10147: if (defined($intdom)) {
10148: $internetdom{$id} = $intdom;
10149: }
10150: }
10151: }
10152: }
10153:
10154: sub reset_hosts_info {
10155: &purge_remembered();
10156: &reset_domain_info();
10157: &reset_hosts_ip_info();
10158: undef(%name_to_host);
10159: undef(%hostname);
10160: undef(%hostdom);
10161: undef(%libserv);
10162: undef($loaded);
10163: }
10164:
10165: sub load_hosts_tab {
10166: my ($ignore_cache) = @_;
10167: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
10168: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10169: my @config = <$config>;
10170: &parse_hosts_tab(\@config);
10171: close($config);
10172: $loaded=1;
10173: }
10174:
10175: sub hostname {
10176: &load_hosts_tab() if (!$loaded);
10177:
10178: my ($lonid) = @_;
10179: return $hostname{$lonid};
10180: }
10181:
10182: sub all_hostnames {
10183: &load_hosts_tab() if (!$loaded);
10184:
10185: return %hostname;
10186: }
10187:
10188: sub all_names {
10189: &load_hosts_tab() if (!$loaded);
10190:
10191: return %name_to_host;
10192: }
10193:
10194: sub all_host_domain {
10195: &load_hosts_tab() if (!$loaded);
10196: return %hostdom;
10197: }
10198:
10199: sub is_library {
10200: &load_hosts_tab() if (!$loaded);
10201:
10202: return exists($libserv{$_[0]});
10203: }
10204:
10205: sub all_library {
10206: &load_hosts_tab() if (!$loaded);
10207:
10208: return %libserv;
10209: }
10210:
10211: sub unique_library {
10212: #2x reverse removes all hostnames that appear more than once
10213: my %unique = reverse &all_library();
10214: return reverse %unique;
10215: }
10216:
10217: sub get_servers {
10218: &load_hosts_tab() if (!$loaded);
10219:
10220: my ($domain,$type) = @_;
10221: my %possible_hosts = ($type eq 'library') ? %libserv
10222: : %hostname;
10223: my %result;
10224: if (ref($domain) eq 'ARRAY') {
10225: while ( my ($host,$hostname) = each(%possible_hosts)) {
10226: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
10227: $result{$host} = $hostname;
10228: }
10229: }
10230: } else {
10231: while ( my ($host,$hostname) = each(%possible_hosts)) {
10232: if ($hostdom{$host} eq $domain) {
10233: $result{$host} = $hostname;
10234: }
10235: }
10236: }
10237: return %result;
10238: }
10239:
10240: sub get_unique_servers {
10241: my %unique = reverse &get_servers(@_);
10242: return reverse %unique;
10243: }
10244:
10245: sub host_domain {
10246: &load_hosts_tab() if (!$loaded);
10247:
10248: my ($lonid) = @_;
10249: return $hostdom{$lonid};
10250: }
10251:
10252: sub all_domains {
10253: &load_hosts_tab() if (!$loaded);
10254:
10255: my %seen;
10256: my @uniq = grep(!$seen{$_}++, values(%hostdom));
10257: return @uniq;
10258: }
10259:
10260: sub internet_dom {
10261: &load_hosts_tab() if (!$loaded);
10262:
10263: my ($lonid) = @_;
10264: return $internetdom{$lonid};
10265: }
10266:
10267: sub is_LC_dns {
10268: &load_hosts_tab() if (!$loaded);
10269:
10270: my ($hostname) = @_;
10271: return exists($LC_dns_serv{$hostname});
10272: }
10273:
10274: }
10275:
10276: {
10277: my %iphost;
10278: my %name_to_ip;
10279: my %lonid_to_ip;
10280:
10281: sub get_hosts_from_ip {
10282: my ($ip) = @_;
10283: my %iphosts = &get_iphost();
10284: if (ref($iphosts{$ip})) {
10285: return @{$iphosts{$ip}};
10286: }
10287: return;
10288: }
10289:
10290: sub reset_hosts_ip_info {
10291: undef(%iphost);
10292: undef(%name_to_ip);
10293: undef(%lonid_to_ip);
10294: }
10295:
10296: sub get_host_ip {
10297: my ($lonid) = @_;
10298: if (exists($lonid_to_ip{$lonid})) {
10299: return $lonid_to_ip{$lonid};
10300: }
10301: my $name=&hostname($lonid);
10302: my $ip = gethostbyname($name);
10303: return if (!$ip || length($ip) ne 4);
10304: $ip=inet_ntoa($ip);
10305: $name_to_ip{$name} = $ip;
10306: $lonid_to_ip{$lonid} = $ip;
10307: return $ip;
10308: }
10309:
10310: sub get_iphost {
10311: my ($ignore_cache) = @_;
10312:
10313: if (!$ignore_cache) {
10314: if (%iphost) {
10315: return %iphost;
10316: }
10317: my ($ip_info,$cached)=
10318: &Apache::lonnet::is_cached_new('iphost','iphost');
10319: if ($cached) {
10320: %iphost = %{$ip_info->[0]};
10321: %name_to_ip = %{$ip_info->[1]};
10322: %lonid_to_ip = %{$ip_info->[2]};
10323: return %iphost;
10324: }
10325: }
10326:
10327: # get yesterday's info for fallback
10328: my %old_name_to_ip;
10329: my ($ip_info,$cached)=
10330: &Apache::lonnet::is_cached_new('iphost','iphost');
10331: if ($cached) {
10332: %old_name_to_ip = %{$ip_info->[1]};
10333: }
10334:
10335: my %name_to_host = &all_names();
10336: foreach my $name (keys(%name_to_host)) {
10337: my $ip;
10338: if (!exists($name_to_ip{$name})) {
10339: $ip = gethostbyname($name);
10340: if (!$ip || length($ip) ne 4) {
10341: if (defined($old_name_to_ip{$name})) {
10342: $ip = $old_name_to_ip{$name};
10343: &logthis("Can't find $name defaulting to old $ip");
10344: } else {
10345: &logthis("Name $name no IP found");
10346: next;
10347: }
10348: } else {
10349: $ip=inet_ntoa($ip);
10350: }
10351: $name_to_ip{$name} = $ip;
10352: } else {
10353: $ip = $name_to_ip{$name};
10354: }
10355: foreach my $id (@{ $name_to_host{$name} }) {
10356: $lonid_to_ip{$id} = $ip;
10357: }
10358: push(@{$iphost{$ip}},@{$name_to_host{$name}});
10359: }
10360: &Apache::lonnet::do_cache_new('iphost','iphost',
10361: [\%iphost,\%name_to_ip,\%lonid_to_ip],
10362: 48*60*60);
10363:
10364: return %iphost;
10365: }
10366:
10367: #
10368: # Given a DNS returns the loncapa host name for that DNS
10369: #
10370: sub host_from_dns {
10371: my ($dns) = @_;
10372: my @hosts;
10373: my $ip;
10374:
10375: if (exists($name_to_ip{$dns})) {
10376: $ip = $name_to_ip{$dns};
10377: }
10378: if (!$ip) {
10379: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10380: if (length($ip) == 4) {
10381: $ip = &IO::Socket::inet_ntoa($ip);
10382: }
10383: }
10384: if ($ip) {
10385: @hosts = get_hosts_from_ip($ip);
10386: return $hosts[0];
10387: }
10388: return undef;
10389: }
10390:
10391: sub get_internet_names {
10392: my ($lonid) = @_;
10393: return if ($lonid eq '');
10394: my ($idnref,$cached)=
10395: &Apache::lonnet::is_cached_new('internetnames',$lonid);
10396: if ($cached) {
10397: return $idnref;
10398: }
10399: my $ip = &get_host_ip($lonid);
10400: my @hosts = &get_hosts_from_ip($ip);
10401: my %iphost = &get_iphost();
10402: my (@idns,%seen);
10403: foreach my $id (@hosts) {
10404: my $dom = &host_domain($id);
10405: my $prim_id = &domain($dom,'primary');
10406: my $prim_ip = &get_host_ip($prim_id);
10407: next if ($seen{$prim_ip});
10408: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10409: foreach my $id (@{$iphost{$prim_ip}}) {
10410: my $intdom = &internet_dom($id);
10411: unless (grep(/^\Q$intdom\E$/,@idns)) {
10412: push(@idns,$intdom);
10413: }
10414: }
10415: }
10416: $seen{$prim_ip} = 1;
10417: }
10418: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10419: }
10420:
10421: }
10422:
10423: sub all_loncaparevs {
10424: 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);
10425: }
10426:
10427: BEGIN {
10428:
10429: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10430: unless ($readit) {
10431: {
10432: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10433: %perlvar = (%perlvar,%{$configvars});
10434: }
10435:
10436:
10437: # ------------------------------------------------------ Read spare server file
10438: {
10439: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
10440:
10441: while (my $configline=<$config>) {
10442: chomp($configline);
10443: if ($configline) {
10444: my ($host,$type) = split(':',$configline,2);
10445: if (!defined($type) || $type eq '') { $type = 'default' };
10446: push(@{ $spareid{$type} }, $host);
10447: }
10448: }
10449: close($config);
10450: }
10451: # ------------------------------------------------------------ Read permissions
10452: {
10453: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
10454:
10455: while (my $configline=<$config>) {
10456: chomp($configline);
10457: if ($configline) {
10458: my ($role,$perm)=split(/ /,$configline);
10459: if ($perm ne '') { $pr{$role}=$perm; }
10460: }
10461: }
10462: close($config);
10463: }
10464:
10465: # -------------------------------------------- Read plain texts for permissions
10466: {
10467: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
10468:
10469: while (my $configline=<$config>) {
10470: chomp($configline);
10471: if ($configline) {
10472: my ($short,@plain)=split(/:/,$configline);
10473: %{$prp{$short}} = ();
10474: if (@plain > 0) {
10475: $prp{$short}{'std'} = $plain[0];
10476: for (my $i=1; $i<@plain; $i++) {
10477: $prp{$short}{'alt'.$i} = $plain[$i];
10478: }
10479: }
10480: }
10481: }
10482: close($config);
10483: }
10484:
10485: # ---------------------------------------------------------- Read package table
10486: {
10487: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
10488:
10489: while (my $configline=<$config>) {
10490: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
10491: chomp($configline);
10492: my ($short,$plain)=split(/:/,$configline);
10493: my ($pack,$name)=split(/\&/,$short);
10494: if ($plain ne '') {
10495: $packagetab{$pack.'&'.$name.'&name'}=$name;
10496: $packagetab{$short}=$plain;
10497: }
10498: }
10499: close($config);
10500: }
10501:
10502: # ---------------------------------------------------------- Read loncaparev table
10503: {
10504: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10505: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10506: while (my $configline=<$config>) {
10507: chomp($configline);
10508: my ($hostid,$loncaparev)=split(/:/,$configline);
10509: $loncaparevs{$hostid}=$loncaparev;
10510: }
10511: close($config);
10512: }
10513: }
10514: }
10515:
10516: # ---------------------------------------------------------- Read serverhostID table
10517: {
10518: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10519: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10520: while (my $configline=<$config>) {
10521: chomp($configline);
10522: my ($name,$id)=split(/:/,$configline);
10523: $serverhomeIDs{$name}=$id;
10524: }
10525: close($config);
10526: }
10527: }
10528: }
10529:
10530: {
10531: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
10532: if (-e $file) {
10533: my $parser = HTML::LCParser->new($file);
10534: while (my $token = $parser->get_token()) {
10535: if ($token->[0] eq 'S') {
10536: my $item = $token->[1];
10537: my $name = $token->[2]{'name'};
10538: my $value = $token->[2]{'value'};
10539: if ($item ne '' && $name ne '' && $value ne '') {
10540: my $release = $parser->get_text();
10541: $release =~ s/(^\s*|\s*$ )//gx;
10542: $needsrelease{$item.':'.$name.':'.$value} = $release;
10543: }
10544: }
10545: }
10546: }
10547: }
10548:
10549: # ---------------------------------------------------------- Read managers table
10550: {
10551: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
10552: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
10553: while (my $configline=<$config>) {
10554: chomp($configline);
10555: next if ($configline =~ /^\#/);
10556: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
10557: $managerstab{$configline} = 1;
10558: }
10559: }
10560: close($config);
10561: }
10562: }
10563: }
10564:
10565: # ------------- set up temporary directory
10566: {
10567: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
10568:
10569: }
10570:
10571: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
10572: 'compress_threshold'=> 20_000,
10573: });
10574:
10575: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
10576: $dumpcount=0;
10577: $locknum=0;
10578:
10579: &logtouch();
10580: &logthis('<font color="yellow">INFO: Read configuration</font>');
10581: $readit=1;
10582: {
10583: use integer;
10584: my $test=(2**32)+1;
10585: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
10586: &logthis(" Detected 64bit platform ($_64bit)");
10587: }
10588: }
10589: }
10590:
10591: 1;
10592: __END__
10593:
10594: =pod
10595:
10596: =head1 NAME
10597:
10598: Apache::lonnet - Subroutines to ask questions about things in the network.
10599:
10600: =head1 SYNOPSIS
10601:
10602: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
10603:
10604: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
10605:
10606: Common parameters:
10607:
10608: =over 4
10609:
10610: =item *
10611:
10612: $uname : an internal username (if $cname expecting a course Id specifically)
10613:
10614: =item *
10615:
10616: $udom : a domain (if $cdom expecting a course's domain specifically)
10617:
10618: =item *
10619:
10620: $symb : a resource instance identifier
10621:
10622: =item *
10623:
10624: $namespace : the name of a .db file that contains the data needed or
10625: being set.
10626:
10627: =back
10628:
10629: =head1 OVERVIEW
10630:
10631: lonnet provides subroutines which interact with the
10632: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
10633: about classes, users, and resources.
10634:
10635: For many of these objects you can also use this to store data about
10636: them or modify them in various ways.
10637:
10638: =head2 Symbs
10639:
10640: To identify a specific instance of a resource, LON-CAPA uses symbols
10641: or "symbs"X<symb>. These identifiers are built from the URL of the
10642: map, the resource number of the resource in the map, and the URL of
10643: the resource itself. The latter is somewhat redundant, but might help
10644: if maps change.
10645:
10646: An example is
10647:
10648: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
10649:
10650: The respective map entry is
10651:
10652: <resource id="19" src="/res/msu/korte/tests/part12.problem"
10653: title="Problem 2">
10654: </resource>
10655:
10656: Symbs are used by the random number generator, as well as to store and
10657: restore data specific to a certain instance of for example a problem.
10658:
10659: =head2 Storing And Retrieving Data
10660:
10661: X<store()>X<cstore()>X<restore()>Three of the most important functions
10662: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10663: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10664: is is the non-critical message twin of cstore. These functions are for
10665: handlers to store a perl hash to a user's permanent data space in an
10666: easy manner, and to retrieve it again on another call. It is expected
10667: that a handler would use this once at the beginning to retrieve data,
10668: and then again once at the end to send only the new data back.
10669:
10670: The data is stored in the user's data directory on the user's
10671: homeserver under the ID of the course.
10672:
10673: The hash that is returned by restore will have all of the previous
10674: value for all of the elements of the hash.
10675:
10676: Example:
10677:
10678: #creating a hash
10679: my %hash;
10680: $hash{'foo'}='bar';
10681:
10682: #storing it
10683: &Apache::lonnet::cstore(\%hash);
10684:
10685: #changing a value
10686: $hash{'foo'}='notbar';
10687:
10688: #adding a new value
10689: $hash{'bar'}='foo';
10690: &Apache::lonnet::cstore(\%hash);
10691:
10692: #retrieving the hash
10693: my %history=&Apache::lonnet::restore();
10694:
10695: #print the hash
10696: foreach my $key (sort(keys(%history))) {
10697: print("\%history{$key} = $history{$key}");
10698: }
10699:
10700: Will print out:
10701:
10702: %history{1:foo} = bar
10703: %history{1:keys} = foo:timestamp
10704: %history{1:timestamp} = 990455579
10705: %history{2:bar} = foo
10706: %history{2:foo} = notbar
10707: %history{2:keys} = foo:bar:timestamp
10708: %history{2:timestamp} = 990455580
10709: %history{bar} = foo
10710: %history{foo} = notbar
10711: %history{timestamp} = 990455580
10712: %history{version} = 2
10713:
10714: Note that the special hash entries C<keys>, C<version> and
10715: C<timestamp> were added to the hash. C<version> will be equal to the
10716: total number of versions of the data that have been stored. The
10717: C<timestamp> attribute will be the UNIX time the hash was
10718: stored. C<keys> is available in every historical section to list which
10719: keys were added or changed at a specific historical revision of a
10720: hash.
10721:
10722: B<Warning>: do not store the hash that restore returns directly. This
10723: will cause a mess since it will restore the historical keys as if the
10724: were new keys. I.E. 1:foo will become 1:1:foo etc.
10725:
10726: Calling convention:
10727:
10728: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10729: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
10730:
10731: For more detailed information, see lonnet specific documentation.
10732:
10733: =head1 RETURN MESSAGES
10734:
10735: =over 4
10736:
10737: =item * B<con_lost>: unable to contact remote host
10738:
10739: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10740: when the connection is brought back up
10741:
10742: =item * B<con_failed>: unable to contact remote host and unable to save message
10743: for later delivery
10744:
10745: =item * B<error:>: an error a occurred, a description of the error follows the :
10746:
10747: =item * B<no_such_host>: unable to fund a host associated with the user/domain
10748: that was requested
10749:
10750: =back
10751:
10752: =head1 PUBLIC SUBROUTINES
10753:
10754: =head2 Session Environment Functions
10755:
10756: =over 4
10757:
10758: =item *
10759: X<appenv()>
10760: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
10761: the user envirnoment file, and will be restored for each access this
10762: user makes during this session, also modifies the %env for the current
10763: process. Optional rolesarrayref - if defined contains a reference to an array
10764: of roles which are exempt from the restriction on modifying user.role entries
10765: in the user's environment.db and in %env.
10766:
10767: =item *
10768: X<delenv()>
10769: B<delenv($delthis,$regexp)>: removes all items from the session
10770: environment file that begin with $delthis. If the
10771: optional second arg - $regexp - is true, $delthis is treated as a
10772: regular expression, otherwise \Q$delthis\E is used.
10773: The values are also deleted from the current processes %env.
10774:
10775: =item * get_env_multiple($name)
10776:
10777: gets $name from the %env hash, it seemlessly handles the cases where multiple
10778: values may be defined and end up as an array ref.
10779:
10780: returns an array of values
10781:
10782: =back
10783:
10784: =head2 User Information
10785:
10786: =over 4
10787:
10788: =item *
10789: X<queryauthenticate()>
10790: B<queryauthenticate($uname,$udom)>: try to determine user's current
10791: authentication scheme
10792:
10793: =item *
10794: X<authenticate()>
10795: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
10796: authenticate user from domain's lib servers (first use the current
10797: one). C<$upass> should be the users password.
10798: $checkdefauth is optional (value is 1 if a check should be made to
10799: authenticate user using default authentication method, and allow
10800: account creation if username does not have account in the domain).
10801: $clientcancheckhost is optional (value is 1 if checking whether the
10802: server can host will occur on the client side in lonauth.pm).
10803:
10804: =item *
10805: X<homeserver()>
10806: B<homeserver($uname,$udom)>: find the server which has
10807: the user's directory and files (there must be only one), this caches
10808: the answer, and also caches if there is a borken connection.
10809:
10810: =item *
10811: X<idget()>
10812: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10813: (IDs are a unique resource in a domain, there must be only 1 ID per
10814: username, and only 1 username per ID in a specific domain) (returns
10815: hash: id=>name,id=>name)
10816:
10817: =item *
10818: X<idrget()>
10819: B<idrget($udom,@unames)>: find the IDs behind a list of
10820: usernames (returns hash: name=>id,name=>id)
10821:
10822: =item *
10823: X<idput()>
10824: B<idput($udom,%ids)>: store away a list of names and associated IDs
10825:
10826: =item *
10827: X<rolesinit()>
10828: B<rolesinit($udom,$username,$authhost)>: get user privileges
10829:
10830: =item *
10831: X<getsection()>
10832: B<getsection($udom,$uname,$cname)>: finds the section of student in the
10833: course $cname, return section name/number or '' for "not in course"
10834: and '-1' for "no section"
10835:
10836: =item *
10837: X<userenvironment()>
10838: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
10839: passed in @what from the requested user's environment, returns a hash
10840:
10841: =item *
10842: X<userlog_query()>
10843: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10844: activity.log file. %filters defines filters applied when parsing the
10845: log file. These can be start or end timestamps, or the type of action
10846: - log to look for Login or Logout events, check for Checkin or
10847: Checkout, role for role selection. The response is in the form
10848: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
10849: escaped strings of the action recorded in the activity.log file.
10850:
10851: =back
10852:
10853: =head2 User Roles
10854:
10855: =over 4
10856:
10857: =item *
10858:
10859: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
10860: F: full access
10861: U,I,K: authentication modes (cxx only)
10862: '': forbidden
10863: 1: user needs to choose course
10864: 2: browse allowed
10865: A: passphrase authentication needed
10866:
10867: =item *
10868:
10869: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10870: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10871: and course level
10872:
10873: =item *
10874:
10875: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
10876: (rolesplain.tab); plain text explanation of a user role term.
10877: $type is Course (default) or Community.
10878: If $forcedefault evaluates to true, text returned will be default
10879: text for $type. Otherwise, if this is a course, the text returned
10880: will be a custom name for the role (if defined in the course's
10881: environment). If no custom name is defined the default is returned.
10882:
10883: =item *
10884:
10885: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
10886: All arguments are optional. Returns a hash of a roles, either for
10887: co-author/assistant author roles for a user's Construction Space
10888: (default), or if $context is 'userroles', roles for the user himself,
10889: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10890: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10891: For each key, value is set to colon-separated start and end times for
10892: the role. If no username and domain are specified, will default to
10893: current user/domain. Types, roles, and roledoms are references to arrays
10894: of role statuses (active, future or previous), roles
10895: (e.g., cc,in, st etc.) and domains of the roles which can be used
10896: to restrict the list of roles reported. If no array ref is
10897: provided for types, will default to return only active roles.
10898:
10899: =back
10900:
10901: =head2 User Modification
10902:
10903: =over 4
10904:
10905: =item *
10906:
10907: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
10908: user for the level given by URL. Optional start and end dates (leave empty
10909: string or zero for "no date")
10910:
10911: =item *
10912:
10913: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10914: change a users, password, possible return values are: ok,
10915: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10916: refused
10917:
10918: =item *
10919:
10920: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
10921:
10922: =item *
10923:
10924: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
10925: $forceid,$desiredhome,$email,$inststatus,$candelete) :
10926:
10927: will update user information (firstname,middlename,lastname,generation,
10928: permanentemail), and if forceid is true, student/employee ID also.
10929: A user's institutional affiliation(s) can also be updated.
10930: User information fields will not be overwritten with empty entries
10931: unless the field is included in the $candelete array reference.
10932: This array is included when a single user is modified via "Manage Users",
10933: or when Autoupdate.pl is run by cron in a domain.
10934:
10935: =item *
10936:
10937: modifystudent
10938:
10939: modify a student's enrollment and identification information.
10940: The course id is resolved based on the current users environment.
10941: This means the envoking user must be a course coordinator or otherwise
10942: associated with a course.
10943:
10944: This call is essentially a wrapper for lonnet::modifyuser and
10945: lonnet::modify_student_enrollment
10946:
10947: Inputs:
10948:
10949: =over 4
10950:
10951: =item B<$udom> Student's loncapa domain
10952:
10953: =item B<$uname> Student's loncapa login name
10954:
10955: =item B<$uid> Student/Employee ID
10956:
10957: =item B<$umode> Student's authentication mode
10958:
10959: =item B<$upass> Student's password
10960:
10961: =item B<$first> Student's first name
10962:
10963: =item B<$middle> Student's middle name
10964:
10965: =item B<$last> Student's last name
10966:
10967: =item B<$gene> Student's generation
10968:
10969: =item B<$usec> Student's section in course
10970:
10971: =item B<$end> Unix time of the roles expiration
10972:
10973: =item B<$start> Unix time of the roles start date
10974:
10975: =item B<$forceid> If defined, allow $uid to be changed
10976:
10977: =item B<$desiredhome> server to use as home server for student
10978:
10979: =item B<$email> Student's permanent e-mail address
10980:
10981: =item B<$type> Type of enrollment (auto or manual)
10982:
10983: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10984:
10985: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
10986:
10987: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
10988:
10989: =item B<$context> role change context (shown in User Management Logs display in a course)
10990:
10991: =item B<$inststatus> institutional status of user - : separated string of escaped status types
10992:
10993: =back
10994:
10995: =item *
10996:
10997: modify_student_enrollment
10998:
10999: Change a students enrollment status in a class. The environment variable
11000: 'role.request.course' must be defined for this function to proceed.
11001:
11002: Inputs:
11003:
11004: =over 4
11005:
11006: =item $udom, students domain
11007:
11008: =item $uname, students name
11009:
11010: =item $uid, students user id
11011:
11012: =item $first, students first name
11013:
11014: =item $middle
11015:
11016: =item $last
11017:
11018: =item $gene
11019:
11020: =item $usec
11021:
11022: =item $end
11023:
11024: =item $start
11025:
11026: =item $type
11027:
11028: =item $locktype
11029:
11030: =item $cid
11031:
11032: =item $selfenroll
11033:
11034: =item $context
11035:
11036: =back
11037:
11038:
11039: =item *
11040:
11041: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11042: custom role; give a custom role to a user for the level given by URL. Specify
11043: name and domain of role author, and role name
11044:
11045: =item *
11046:
11047: revokerole($udom,$uname,$url,$role) : revoke a role for url
11048:
11049: =item *
11050:
11051: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11052:
11053: =back
11054:
11055: =head2 Course Infomation
11056:
11057: =over 4
11058:
11059: =item *
11060:
11061: coursedescription($courseid) : returns a hash of information about the
11062: specified course id, including all environment settings for the
11063: course, the description of the course will be in the hash under the
11064: key 'description'
11065:
11066: =item *
11067:
11068: resdata($name,$domain,$type,@which) : request for current parameter
11069: setting for a specific $type, where $type is either 'course' or 'user',
11070: @what should be a list of parameters to ask about. This routine caches
11071: answers for 5 minutes.
11072:
11073: =item *
11074:
11075: get_courseresdata($courseid, $domain) : dump the entire course resource
11076: data base, returning a hash that is keyed by the resource name and has
11077: values that are the resource value. I believe that the timestamps and
11078: versions are also returned.
11079:
11080:
11081: =back
11082:
11083: =head2 Course Modification
11084:
11085: =over 4
11086:
11087: =item *
11088:
11089: writecoursepref($courseid,%prefs) : write preferences (environment
11090: database) for a course
11091:
11092: =item *
11093:
11094: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11095:
11096: =item *
11097:
11098: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
11099:
11100: =back
11101:
11102: =head2 Resource Subroutines
11103:
11104: =over 4
11105:
11106: =item *
11107:
11108: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
11109:
11110: =item *
11111:
11112: repcopy($filename) : subscribes to the requested file, and attempts to
11113: replicate from the owning library server, Might return
11114: 'unavailable', 'not_found', 'forbidden', 'ok', or
11115: 'bad_request', also attempts to grab the metadata for the
11116: resource. Expects the local filesystem pathname
11117: (/home/httpd/html/res/....)
11118:
11119: =back
11120:
11121: =head2 Resource Information
11122:
11123: =over 4
11124:
11125: =item *
11126:
11127: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
11128: a vairety of different possible values, $varname should be a request
11129: string, and the other parameters can be used to specify who and what
11130: one is asking about.
11131:
11132: Possible values for $varname are environment.lastname (or other item
11133: from the envirnment hash), user.name (or someother aspect about the
11134: user), resource.0.maxtries (or some other part and parameter of a
11135: resource)
11136:
11137: =item *
11138:
11139: directcondval($number) : get current value of a condition; reads from a state
11140: string
11141:
11142: =item *
11143:
11144: condval($condidx) : value of condition index based on state
11145:
11146: =item *
11147:
11148: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11149: resource's metadata, $what should be either a specific key, or either
11150: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11151: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11152:
11153: this function automatically caches all requests
11154:
11155: =item *
11156:
11157: metadata_query($query,$custom,$customshow) : make a metadata query against the
11158: network of library servers; returns file handle of where SQL and regex results
11159: will be stored for query
11160:
11161: =item *
11162:
11163: symbread($filename) : return symbolic list entry (filename argument optional);
11164: returns the data handle
11165:
11166: =item *
11167:
11168: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
11169: a possible symb for the URL in $thisfn, and if is an encryypted
11170: resource that the user accessed using /enc/ returns a 1 on success, 0
11171: on failure, user must be in a course, as it assumes the existance of
11172: the course initial hash, and uses $env('request.course.id'}
11173:
11174:
11175: =item *
11176:
11177: symbclean($symb) : removes versions numbers from a symb, returns the
11178: cleaned symb
11179:
11180: =item *
11181:
11182: is_on_map($uri) : checks if the $uri is somewhere on the current
11183: course map, user must be in a course for it to work.
11184:
11185: =item *
11186:
11187: numval($salt) : return random seed value (addend for rndseed)
11188:
11189: =item *
11190:
11191: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11192: a random seed, all arguments are optional, if they aren't sent it uses the
11193: environment to derive them. Note: if symb isn't sent and it can't get one
11194: from &symbread it will use the current time as its return value
11195:
11196: =item *
11197:
11198: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11199: unfakeable, receipt
11200:
11201: =item *
11202:
11203: receipt() : API to ireceipt working off of env values; given out to users
11204:
11205: =item *
11206:
11207: countacc($url) : count the number of accesses to a given URL
11208:
11209: =item *
11210:
11211: 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
11212:
11213: =item *
11214:
11215: 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)
11216:
11217: =item *
11218:
11219: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
11220:
11221: =item *
11222:
11223: devalidate($symb) : devalidate temporary spreadsheet calculations,
11224: forcing spreadsheet to reevaluate the resource scores next time.
11225:
11226: =back
11227:
11228: =head2 Storing/Retreiving Data
11229:
11230: =over 4
11231:
11232: =item *
11233:
11234: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11235: for this url; hashref needs to be given and should be a \%hashname; the
11236: remaining args aren't required and if they aren't passed or are '' they will
11237: be derived from the env
11238:
11239: =item *
11240:
11241: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11242: uses critical subroutine
11243:
11244: =item *
11245:
11246: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11247: all args are optional
11248:
11249: =item *
11250:
11251: dumpstore($namespace,$udom,$uname,$regexp,$range) :
11252: dumps the complete (or key matching regexp) namespace into a hash
11253: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11254: normally &store()ed into
11255:
11256: $range should be either an integer '100' (give me the first 100
11257: matching records)
11258: or be two integers sperated by a - with no spaces
11259: '30-50' (give me the 30th through the 50th matching
11260: records)
11261:
11262:
11263: =item *
11264:
11265: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11266: replaces a &store() version of data with a replacement set of data
11267: for a particular resource in a namespace passed in the $storehash hash
11268: reference
11269:
11270: =item *
11271:
11272: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11273: works very similar to store/cstore, but all data is stored in a
11274: temporary location and can be reset using tmpreset, $storehash should
11275: be a hash reference, returns nothing on success
11276:
11277: =item *
11278:
11279: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11280: similar to restore, but all data is stored in a temporary location and
11281: can be reset using tmpreset. Returns a hash of values on success,
11282: error string otherwise.
11283:
11284: =item *
11285:
11286: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11287: deltes all keys for $symb form the temporary storage hash.
11288:
11289: =item *
11290:
11291: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11292: reference filled in from namesp ($udom and $uname are optional)
11293:
11294: =item *
11295:
11296: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11297: namesp ($udom and $uname are optional)
11298:
11299: =item *
11300:
11301: dump($namespace,$udom,$uname,$regexp,$range) :
11302: dumps the complete (or key matching regexp) namespace into a hash
11303: ($udom, $uname, $regexp, $range are optional)
11304:
11305: $range should be either an integer '100' (give me the first 100
11306: matching records)
11307: or be two integers sperated by a - with no spaces
11308: '30-50' (give me the 30th through the 50th matching
11309: records)
11310: =item *
11311:
11312: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11313: $store can be a scalar, an array reference, or if the amount to be
11314: incremented is > 1, a hash reference.
11315:
11316: ($udom and $uname are optional)
11317:
11318: =item *
11319:
11320: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11321: ($udom and $uname are optional)
11322:
11323: =item *
11324:
11325: cput($namespace,$storehash,$udom,$uname) : critical put
11326: ($udom and $uname are optional)
11327:
11328: =item *
11329:
11330: newput($namespace,$storehash,$udom,$uname) :
11331:
11332: Attempts to store the items in the $storehash, but only if they don't
11333: currently exist, if this succeeds you can be certain that you have
11334: successfully created a new key value pair in the $namespace db.
11335:
11336:
11337: Args:
11338: $namespace: name of database to store values to
11339: $storehash: hashref to store to the db
11340: $udom: (optional) domain of user containing the db
11341: $uname: (optional) name of user caontaining the db
11342:
11343: Returns:
11344: 'ok' -> succeeded in storing all keys of $storehash
11345: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11346: least <key> already existed in the db (other
11347: requested keys may also already exist)
11348: 'error: <msg>' -> unable to tie the DB or other error occurred
11349: 'con_lost' -> unable to contact request server
11350: 'refused' -> action was not allowed by remote machine
11351:
11352:
11353: =item *
11354:
11355: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11356: reference filled in from namesp (encrypts the return communication)
11357: ($udom and $uname are optional)
11358:
11359: =item *
11360:
11361: log($udom,$name,$home,$message) : write to permanent log for user; use
11362: critical subroutine
11363:
11364: =item *
11365:
11366: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11367: array reference filled in from namespace found in domain level on either
11368: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
11369:
11370: =item *
11371:
11372: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11373: domain level either on specified domain server ($uhome) or primary domain
11374: server ($udom and $uhome are optional)
11375:
11376: =item *
11377:
11378: get_domain_defaults($target_domain) : returns hash with defaults for
11379: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11380: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11381: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11382: Values are retrieved from cache (if current), or from domain's configuration.db
11383: (if available), or lastly from values in lonTabs/dns_domain,tab,
11384: or lonTabs/domain.tab.
11385:
11386: %domdefaults = &get_auth_defaults($target_domain);
11387:
11388: =back
11389:
11390: =head2 Network Status Functions
11391:
11392: =over 4
11393:
11394: =item *
11395:
11396: dirlist($uri) : return directory list based on URI
11397:
11398: =item *
11399:
11400: spareserver() : find server with least workload from spare.tab
11401:
11402:
11403: =item *
11404:
11405: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11406: if there is no corresponding loncapa host.
11407:
11408: =back
11409:
11410:
11411: =head2 Apache Request
11412:
11413: =over 4
11414:
11415: =item *
11416:
11417: ssi($url,%hash) : server side include, does a complete request cycle on url to
11418: localhost, posts hash
11419:
11420: =back
11421:
11422: =head2 Data to String to Data
11423:
11424: =over 4
11425:
11426: =item *
11427:
11428: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11429: and '&' separators, supports elements that are arrayrefs and hashrefs
11430:
11431: =item *
11432:
11433: hashref2str($hashref) : convert a hashref into a string complete with
11434: escaping and '=' and '&' separators, supports elements that are
11435: arrayrefs and hashrefs
11436:
11437: =item *
11438:
11439: arrayref2str($arrayref) : convert an arrayref into a string complete
11440: with escaping and '&' separators, supports elements that are arrayrefs
11441: and hashrefs
11442:
11443: =item *
11444:
11445: str2hash($string) : convert string to hash using unescaping and
11446: splitting on '=' and '&', supports elements that are arrayrefs and
11447: hashrefs
11448:
11449: =item *
11450:
11451: str2array($string) : convert string to hash using unescaping and
11452: splitting on '&', supports elements that are arrayrefs and hashrefs
11453:
11454: =back
11455:
11456: =head2 Logging Routines
11457:
11458: These routines allow one to make log messages in the lonnet.log and
11459: lonnet.perm logfiles.
11460:
11461: =over 4
11462:
11463: =item *
11464:
11465: logtouch() : make sure the logfile, lonnet.log, exists
11466:
11467: =item *
11468:
11469: logthis() : append message to the normal lonnet.log file, it gets
11470: preiodically rolled over and deleted.
11471:
11472: =item *
11473:
11474: logperm() : append a permanent message to lonnet.perm.log, this log
11475: file never gets deleted by any automated portion of the system, only
11476: messages of critical importance should go in here.
11477:
11478: =back
11479:
11480: =head2 General File Helper Routines
11481:
11482: =over 4
11483:
11484: =item *
11485:
11486: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
11487: (a) files in /uploaded
11488: (i) If a local copy of the file exists -
11489: compares modification date of local copy with last-modified date for
11490: definitive version stored on home server for course. If local copy is
11491: stale, requests a new version from the home server and stores it.
11492: If the original has been removed from the home server, then local copy
11493: is unlinked.
11494: (ii) If local copy does not exist -
11495: requests the file from the home server and stores it.
11496:
11497: If $caller is 'uploadrep':
11498: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
11499: for request for files originally uploaded via DOCS.
11500: - returns 'ok' if fresh local copy now available, -1 otherwise.
11501:
11502: Otherwise:
11503: This indicates a call from the content generation phase of the request.
11504: - returns the entire contents of the file or -1.
11505:
11506: (b) files in /res
11507: - returns the entire contents of a file or -1;
11508: it properly subscribes to and replicates the file if neccessary.
11509:
11510:
11511: =item *
11512:
11513: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
11514: reference
11515:
11516: returns either a stat() list of data about the file or an empty list
11517: if the file doesn't exist or couldn't find out about it (connection
11518: problems or user unknown)
11519:
11520: =item *
11521:
11522: filelocation($dir,$file) : returns file system location of a file
11523: based on URI; meant to be "fairly clean" absolute reference, $dir is a
11524: directory that relative $file lookups are to looked in ($dir of /a/dir
11525: and a file of ../bob will become /a/bob)
11526:
11527: =item *
11528:
11529: hreflocation($dir,$file) : returns file system location or a URL; same as
11530: filelocation except for hrefs
11531:
11532: =item *
11533:
11534: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
11535:
11536: =back
11537:
11538: =head2 Usererfile file routines (/uploaded*)
11539:
11540: =over 4
11541:
11542: =item *
11543:
11544: userfileupload(): main rotine for putting a file in a user or course's
11545: filespace, arguments are,
11546:
11547: formname - required - this is the name of the element in $env where the
11548: filename, and the contents of the file to create/modifed exist
11549: the filename is in $env{'form.'.$formname.'.filename'} and the
11550: contents of the file is located in $env{'form.'.$formname}
11551: context - if coursedoc, store the file in the course of the active role
11552: of the current user;
11553: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
11554: if 'canceloverwrite': delete file in tmp/overwrites directory
11555: subdir - required - subdirectory to put the file in under ../userfiles/
11556: if undefined, it will be placed in "unknown"
11557:
11558: (This routine calls clean_filename() to remove any dangerous
11559: characters from the filename, and then calls finuserfileupload() to
11560: complete the transaction)
11561:
11562: returns either the url of the uploaded file (/uploaded/....) if successful
11563: and /adm/notfound.html if unsuccessful
11564:
11565: =item *
11566:
11567: clean_filename(): routine for cleaing a filename up for storage in
11568: userfile space, argument is:
11569:
11570: filename - proposed filename
11571:
11572: returns: the new clean filename
11573:
11574: =item *
11575:
11576: finishuserfileupload(): routine that creates and sends the file to
11577: userspace, probably shouldn't be called directly
11578:
11579: docuname: username or courseid of destination for the file
11580: docudom: domain of user/course of destination for the file
11581: formname: same as for userfileupload()
11582: fname: filename (including subdirectories) for the file
11583: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
11584: allfiles: reference to hash used to store objects found by parser
11585: codebase: reference to hash used for codebases of java objects found by parser
11586: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
11587: thumbheight: height (pixels) of thumbnail to be created for uploaded image
11588: resizewidth: width to be used to resize image using resizeImage from ImageMagick
11589: resizeheight: height to be used to resize image using resizeImage from ImageMagick
11590: context: if 'overwrite', will move the uploaded file from its temporary location to
11591: userfiles to facilitate overwriting a previously uploaded file with same name.
11592: mimetype: reference to scalar to accommodate mime type determined
11593: from File::MMagic if $parser = parse.
11594:
11595: returns either the url of the uploaded file (/uploaded/....) if successful
11596: and /adm/notfound.html if unsuccessful (or an error message if context
11597: was 'overwrite').
11598:
11599:
11600: =item *
11601:
11602: renameuserfile(): renames an existing userfile to a new name
11603:
11604: Args:
11605: docuname: username or courseid of destination for the file
11606: docudom: domain of user/course of destination for the file
11607: old: current file name (including any subdirs under userfiles)
11608: new: desired file name (including any subdirs under userfiles)
11609:
11610: =item *
11611:
11612: mkdiruserfile(): creates a directory is a userfiles dir
11613:
11614: Args:
11615: docuname: username or courseid of destination for the file
11616: docudom: domain of user/course of destination for the file
11617: dir: dir to create (including any subdirs under userfiles)
11618:
11619: =item *
11620:
11621: removeuserfile(): removes a file that exists in userfiles
11622:
11623: Args:
11624: docuname: username or courseid of destination for the file
11625: docudom: domain of user/course of destination for the file
11626: fname: filname to delete (including any subdirs under userfiles)
11627:
11628: =item *
11629:
11630: removeuploadedurl(): convience function for removeuserfile()
11631:
11632: Args:
11633: url: a full /uploaded/... url to delete
11634:
11635: =item *
11636:
11637: get_portfile_permissions():
11638: Args:
11639: domain: domain of user or course contain the portfolio files
11640: user: name of user or num of course contain the portfolio files
11641: Returns:
11642: hashref of a dump of the proper file_permissions.db
11643:
11644:
11645: =item *
11646:
11647: get_access_controls():
11648:
11649: Args:
11650: current_permissions: the hash ref returned from get_portfile_permissions()
11651: group: (optional) the group you want the files associated with
11652: file: (optional) the file you want access info on
11653:
11654: Returns:
11655: a hash (keys are file names) of hashes containing
11656: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
11657: values are XML containing access control settings (see below)
11658:
11659: Internal notes:
11660:
11661: access controls are stored in file_permissions.db as key=value pairs.
11662: key -> path to file/file_name\0uniqueID:scope_end_start
11663: where scope -> public,guest,course,group,domains or users.
11664: end -> UNIX time for end of access (0 -> no end date)
11665: start -> UNIX time for start of access
11666:
11667: value -> XML description of access control
11668: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
11669: <start></start>
11670: <end></end>
11671:
11672: <password></password> for scope type = guest
11673:
11674: <domain></domain> for scope type = course or group
11675: <number></number>
11676: <roles id="">
11677: <role></role>
11678: <access></access>
11679: <section></section>
11680: <group></group>
11681: </roles>
11682:
11683: <dom></dom> for scope type = domains
11684:
11685: <users> for scope type = users
11686: <user>
11687: <uname></uname>
11688: <udom></udom>
11689: </user>
11690: </users>
11691: </scope>
11692:
11693: Access data is also aggregated for each file in an additional key=value pair:
11694: key -> path to file/file_name\0accesscontrol
11695: value -> reference to hash
11696: hash contains key = value pairs
11697: where key = uniqueID:scope_end_start
11698: value = UNIX time record was last updated
11699:
11700: Used to improve speed of look-ups of access controls for each file.
11701:
11702: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11703:
11704: modify_access_controls():
11705:
11706: Modifies access controls for a portfolio file
11707: Args
11708: 1. file name
11709: 2. reference to hash of required changes,
11710: 3. domain
11711: 4. username
11712: where domain,username are the domain of the portfolio owner
11713: (either a user or a course)
11714:
11715: Returns:
11716: 1. result of additions or updates ('ok' or 'error', with error message).
11717: 2. result of deletions ('ok' or 'error', with error message).
11718: 3. reference to hash of any new or updated access controls.
11719: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11720: key = integer (inbound ID)
11721: value = uniqueID
11722:
11723: =back
11724:
11725: =head2 HTTP Helper Routines
11726:
11727: =over 4
11728:
11729: =item *
11730:
11731: escape() : unpack non-word characters into CGI-compatible hex codes
11732:
11733: =item *
11734:
11735: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11736:
11737: =back
11738:
11739: =head1 PRIVATE SUBROUTINES
11740:
11741: =head2 Underlying communication routines (Shouldn't call)
11742:
11743: =over 4
11744:
11745: =item *
11746:
11747: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11748:
11749: =item *
11750:
11751: reply() : uses subreply to send a message to remote machine, logs all failures
11752:
11753: =item *
11754:
11755: critical() : passes a critical message to another server; if cannot
11756: get through then place message in connection buffer directory and
11757: returns con_delayed, if incapable of saving message, returns
11758: con_failed
11759:
11760: =item *
11761:
11762: reconlonc() : tries to reconnect lonc client processes.
11763:
11764: =back
11765:
11766: =head2 Resource Access Logging
11767:
11768: =over 4
11769:
11770: =item *
11771:
11772: flushcourselogs() : flush (save) buffer logs and access logs
11773:
11774: =item *
11775:
11776: courselog($what) : save message for course in hash
11777:
11778: =item *
11779:
11780: courseacclog($what) : save message for course using &courselog(). Perform
11781: special processing for specific resource types (problems, exams, quizzes, etc).
11782:
11783: =item *
11784:
11785: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11786: as a PerlChildExitHandler
11787:
11788: =back
11789:
11790: =head2 Other
11791:
11792: =over 4
11793:
11794: =item *
11795:
11796: symblist($mapname,%newhash) : update symbolic storage links
11797:
11798: =back
11799:
11800: =cut
11801:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>