1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.1035 2009/10/24 03:24:25 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);
80:
81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
82: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
83: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
84: %courseownerbuf, %coursetypebuf,$locknum);
85:
86: use IO::Socket;
87: use GDBM_File;
88: use HTML::LCParser;
89: use Fcntl qw(:flock);
90: use Storable qw(thaw nfreeze);
91: use Time::HiRes qw( gettimeofday tv_interval );
92: use Cache::Memcached;
93: use Digest::MD5;
94: use Math::Random;
95: use File::MMagic;
96: use LONCAPA qw(:DEFAULT :match);
97: use LONCAPA::Configuration;
98:
99: my $readit;
100: my $max_connection_retries = 10; # Or some such value.
101:
102: my $upload_photo_form = 0; #Variable to check when user upload a photo 0=not 1=true
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_loncaparev {
201: my ($dom,$lonhost) = @_;
202: if (defined($lonhost)) {
203: if (!defined(&hostname($lonhost))) {
204: undef($lonhost);
205: }
206: }
207: if (!defined($lonhost)) {
208: if (defined(&domain($dom,'primary'))) {
209: $lonhost=&domain($dom,'primary');
210: if ($lonhost eq 'no_host') {
211: undef($lonhost);
212: }
213: }
214: }
215: if (defined($lonhost)) {
216: my $cachetime = 24*3600;
217: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
218: if (defined($cached)) {
219: return $loncaparev;
220: } else {
221: my $loncaparev = &reply('serverloncaparev',$lonhost);
222: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
223: }
224: }
225: }
226:
227: # -------------------------------------------------- Non-critical communication
228: sub subreply {
229: my ($cmd,$server)=@_;
230: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
231: #
232: # With loncnew process trimming, there's a timing hole between lonc server
233: # process exit and the master server picking up the listen on the AF_UNIX
234: # socket. In that time interval, a lock file will exist:
235:
236: my $lockfile=$peerfile.".lock";
237: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
238: sleep(1);
239: }
240: # At this point, either a loncnew parent is listening or an old lonc
241: # or loncnew child is listening so we can connect or everything's dead.
242: #
243: # We'll give the connection a few tries before abandoning it. If
244: # connection is not possible, we'll con_lost back to the client.
245: #
246: my $client;
247: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
248: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
249: Type => SOCK_STREAM,
250: Timeout => 10);
251: if ($client) {
252: last; # Connected!
253: } else {
254: &create_connection(&hostname($server),$server);
255: }
256: sleep(1); # Try again later if failed connection.
257: }
258: my $answer;
259: if ($client) {
260: print $client "sethost:$server:$cmd\n";
261: $answer=<$client>;
262: if (!$answer) { $answer="con_lost"; }
263: chomp($answer);
264: } else {
265: $answer = 'con_lost'; # Failed connection.
266: }
267: return $answer;
268: }
269:
270: sub reply {
271: my ($cmd,$server)=@_;
272: unless (defined(&hostname($server))) { return 'no_such_host'; }
273: my $answer=subreply($cmd,$server);
274: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
275: &logthis("<font color=\"blue\">WARNING:".
276: " $cmd to $server returned $answer</font>");
277: }
278: return $answer;
279: }
280:
281: # ----------------------------------------------------------- Send USR1 to lonc
282:
283: sub reconlonc {
284: my ($lonid) = @_;
285: my $hostname = &hostname($lonid);
286: if ($lonid) {
287: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
288: if ($hostname && -e $peerfile) {
289: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
290: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
291: Type => SOCK_STREAM,
292: Timeout => 10);
293: if ($client) {
294: print $client ("reset_retries\n");
295: my $answer=<$client>;
296: #reset just this one.
297: }
298: }
299: return;
300: }
301:
302: &logthis("Trying to reconnect lonc");
303: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
304: if (open(my $fh,"<$loncfile")) {
305: my $loncpid=<$fh>;
306: chomp($loncpid);
307: if (kill 0 => $loncpid) {
308: &logthis("lonc at pid $loncpid responding, sending USR1");
309: kill USR1 => $loncpid;
310: sleep 1;
311: } else {
312: &logthis(
313: "<font color=\"blue\">WARNING:".
314: " lonc at pid $loncpid not responding, giving up</font>");
315: }
316: } else {
317: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
318: }
319: }
320:
321: # ------------------------------------------------------ Critical communication
322:
323: sub critical {
324: my ($cmd,$server)=@_;
325: unless (&hostname($server)) {
326: &logthis("<font color=\"blue\">WARNING:".
327: " Critical message to unknown server ($server)</font>");
328: return 'no_such_host';
329: }
330: my $answer=reply($cmd,$server);
331: if ($answer eq 'con_lost') {
332: &reconlonc("$perlvar{'lonSockDir'}/$server");
333: my $answer=reply($cmd,$server);
334: if ($answer eq 'con_lost') {
335: my $now=time;
336: my $middlename=$cmd;
337: $middlename=substr($middlename,0,16);
338: $middlename=~s/\W//g;
339: my $dfilename=
340: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
341: $dumpcount++;
342: {
343: my $dfh;
344: if (open($dfh,">$dfilename")) {
345: print $dfh "$cmd\n";
346: close($dfh);
347: }
348: }
349: sleep 2;
350: my $wcmd='';
351: {
352: my $dfh;
353: if (open($dfh,"<$dfilename")) {
354: $wcmd=<$dfh>;
355: close($dfh);
356: }
357: }
358: chomp($wcmd);
359: if ($wcmd eq $cmd) {
360: &logthis("<font color=\"blue\">WARNING: ".
361: "Connection buffer $dfilename: $cmd</font>");
362: &logperm("D:$server:$cmd");
363: return 'con_delayed';
364: } else {
365: &logthis("<font color=\"red\">CRITICAL:"
366: ." Critical connection failed: $server $cmd</font>");
367: &logperm("F:$server:$cmd");
368: return 'con_failed';
369: }
370: }
371: }
372: return $answer;
373: }
374:
375: # ------------------------------------------- check if return value is an error
376:
377: sub error {
378: my ($result) = @_;
379: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
380: if ($2 == 2) { return undef; }
381: return $1;
382: }
383: return undef;
384: }
385:
386: sub convert_and_load_session_env {
387: my ($lonidsdir,$handle)=@_;
388: my @profile;
389: {
390: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
391: if (!$opened) {
392: return 0;
393: }
394: flock($idf,LOCK_SH);
395: @profile=<$idf>;
396: close($idf);
397: }
398: my %temp_env;
399: foreach my $line (@profile) {
400: if ($line !~ m/=/) {
401: return 0;
402: }
403: chomp($line);
404: my ($envname,$envvalue)=split(/=/,$line,2);
405: $temp_env{&unescape($envname)} = &unescape($envvalue);
406: }
407: unlink("$lonidsdir/$handle.id");
408: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
409: 0640)) {
410: %disk_env = %temp_env;
411: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
412: untie(%disk_env);
413: }
414: return 1;
415: }
416:
417: # ------------------------------------------- Transfer profile into environment
418: my $env_loaded;
419: sub transfer_profile_to_env {
420: my ($lonidsdir,$handle,$force_transfer) = @_;
421: if (!$force_transfer && $env_loaded) { return; }
422:
423: if (!defined($lonidsdir)) {
424: $lonidsdir = $perlvar{'lonIDsDir'};
425: }
426: if (!defined($handle)) {
427: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
428: }
429:
430: my $convert;
431: {
432: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
433: if (!$opened) {
434: return;
435: }
436: flock($idf,LOCK_SH);
437: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
438: &GDBM_READER(),0640)) {
439: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
440: untie(%disk_env);
441: } else {
442: $convert = 1;
443: }
444: }
445: if ($convert) {
446: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
447: &logthis("Failed to load session, or convert session.");
448: }
449: }
450:
451: my %remove;
452: while ( my $envname = each(%env) ) {
453: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
454: if ($time < time-300) {
455: $remove{$key}++;
456: }
457: }
458: }
459:
460: $env{'user.environment'} = "$lonidsdir/$handle.id";
461: $env_loaded=1;
462: foreach my $expired_key (keys(%remove)) {
463: &delenv($expired_key);
464: }
465: }
466:
467: # ---------------------------------------------------- Check for valid session
468: sub check_for_valid_session {
469: my ($r) = @_;
470: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
471: my $lonid=$cookies{'lonID'};
472: return undef if (!$lonid);
473:
474: my $handle=&LONCAPA::clean_handle($lonid->value);
475: my $lonidsdir=$r->dir_config('lonIDsDir');
476: return undef if (!-e "$lonidsdir/$handle.id");
477:
478: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
479: return undef if (!$opened);
480:
481: flock($idf,LOCK_SH);
482: my %disk_env;
483: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
484: &GDBM_READER(),0640)) {
485: return undef;
486: }
487:
488: if (!defined($disk_env{'user.name'})
489: || !defined($disk_env{'user.domain'})) {
490: return undef;
491: }
492: return $handle;
493: }
494:
495: sub timed_flock {
496: my ($file,$lock_type) = @_;
497: my $failed=0;
498: eval {
499: local $SIG{__DIE__}='DEFAULT';
500: local $SIG{ALRM}=sub {
501: $failed=1;
502: die("failed lock");
503: };
504: alarm(13);
505: flock($file,$lock_type);
506: alarm(0);
507: };
508: if ($failed) {
509: return undef;
510: } else {
511: return 1;
512: }
513: }
514:
515: # ---------------------------------------------------------- Append Environment
516:
517: sub appenv {
518: my ($newenv,$roles) = @_;
519: if (ref($newenv) eq 'HASH') {
520: foreach my $key (keys(%{$newenv})) {
521: my $refused = 0;
522: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
523: $refused = 1;
524: if (ref($roles) eq 'ARRAY') {
525: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
526: if (grep(/^\Q$role\E$/,@{$roles})) {
527: $refused = 0;
528: }
529: }
530: }
531: if ($refused) {
532: &logthis("<font color=\"blue\">WARNING: ".
533: "Attempt to modify environment ".$key." to ".$newenv->{$key}
534: .'</font>');
535: delete($newenv->{$key});
536: } else {
537: $env{$key}=$newenv->{$key};
538: }
539: }
540: my $opened = open(my $env_file,'+<',$env{'user.environment'});
541: if ($opened
542: && &timed_flock($env_file,LOCK_EX)
543: &&
544: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
545: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
546: while (my ($key,$value) = each(%{$newenv})) {
547: $disk_env{$key} = $value;
548: }
549: untie(%disk_env);
550: }
551: }
552: return 'ok';
553: }
554: # ----------------------------------------------------- Delete from Environment
555:
556: sub delenv {
557: my ($delthis,$regexp) = @_;
558: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
559: &logthis("<font color=\"blue\">WARNING: ".
560: "Attempt to delete from environment ".$delthis);
561: return 'error';
562: }
563: my $opened = open(my $env_file,'+<',$env{'user.environment'});
564: if ($opened
565: && &timed_flock($env_file,LOCK_EX)
566: &&
567: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
568: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
569: foreach my $key (keys(%disk_env)) {
570: if ($regexp) {
571: if ($key=~/^$delthis/) {
572: delete($env{$key});
573: delete($disk_env{$key});
574: }
575: } else {
576: if ($key=~/^\Q$delthis\E/) {
577: delete($env{$key});
578: delete($disk_env{$key});
579: }
580: }
581: }
582: untie(%disk_env);
583: }
584: return 'ok';
585: }
586:
587: sub get_env_multiple {
588: my ($name) = @_;
589: my @values;
590: if (defined($env{$name})) {
591: # exists is it an array
592: if (ref($env{$name})) {
593: @values=@{ $env{$name} };
594: } else {
595: $values[0]=$env{$name};
596: }
597: }
598: return(@values);
599: }
600:
601: # ------------------------------------------------------------------- Locking
602:
603: sub set_lock {
604: my ($text)=@_;
605: $locknum++;
606: my $id=$$.'-'.$locknum;
607: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
608: 'session.lock.'.$id => $text});
609: return $id;
610: }
611:
612: sub get_locks {
613: my $num=0;
614: my %texts=();
615: foreach my $lock (split(/\,/,$env{'session.locks'})) {
616: if ($lock=~/\w/) {
617: $num++;
618: $texts{$lock}=$env{'session.lock.'.$lock};
619: }
620: }
621: return ($num,%texts);
622: }
623:
624: sub remove_lock {
625: my ($id)=@_;
626: my $newlocks='';
627: foreach my $lock (split(/\,/,$env{'session.locks'})) {
628: if (($lock=~/\w/) && ($lock ne $id)) {
629: $newlocks.=','.$lock;
630: }
631: }
632: &appenv({'session.locks' => $newlocks});
633: &delenv('session.lock.'.$id);
634: }
635:
636: sub remove_all_locks {
637: my $activelocks=$env{'session.locks'};
638: foreach my $lock (split(/\,/,$env{'session.locks'})) {
639: if ($lock=~/\w/) {
640: &remove_lock($lock);
641: }
642: }
643: }
644:
645:
646: # ------------------------------------------ Find out current server userload
647: sub userload {
648: my $numusers=0;
649: {
650: opendir(LONIDS,$perlvar{'lonIDsDir'});
651: my $filename;
652: my $curtime=time;
653: while ($filename=readdir(LONIDS)) {
654: next if ($filename eq '.' || $filename eq '..');
655: next if ($filename =~ /publicuser_\d+\.id/);
656: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
657: if ($curtime-$mtime < 1800) { $numusers++; }
658: }
659: closedir(LONIDS);
660: }
661: my $userloadpercent=0;
662: my $maxuserload=$perlvar{'lonUserLoadLim'};
663: if ($maxuserload) {
664: $userloadpercent=100*$numusers/$maxuserload;
665: }
666: $userloadpercent=sprintf("%.2f",$userloadpercent);
667: return $userloadpercent;
668: }
669:
670: # ------------------------------------------ Fight off request when overloaded
671:
672: sub overloaderror {
673: my ($r,$checkserver)=@_;
674: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
675: my $loadavg;
676: if ($checkserver eq $perlvar{'lonHostID'}) {
677: open(my $loadfile,'/proc/loadavg');
678: $loadavg=<$loadfile>;
679: $loadavg =~ s/\s.*//g;
680: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
681: close($loadfile);
682: } else {
683: $loadavg=&reply('load',$checkserver);
684: }
685: my $overload=$loadavg-100;
686: if ($overload>0) {
687: $r->err_headers_out->{'Retry-After'}=$overload;
688: $r->log_error('Overload of '.$overload.' on '.$checkserver);
689: return 413;
690: }
691: return '';
692: }
693:
694: # ------------------------------ Find server with least workload from spare.tab
695:
696: sub spareserver {
697: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
698: my $spare_server;
699: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
700: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
701: : $userloadpercent;
702:
703: foreach my $try_server (@{ $spareid{'primary'} }) {
704: ($spare_server, $lowest_load) =
705: &compare_server_load($try_server, $spare_server, $lowest_load);
706: }
707:
708: my $found_server = ($spare_server ne '' && $lowest_load < 100);
709:
710: if (!$found_server) {
711: foreach my $try_server (@{ $spareid{'default'} }) {
712: ($spare_server, $lowest_load) =
713: &compare_server_load($try_server, $spare_server, $lowest_load);
714: }
715: }
716:
717: if (!$want_server_name) {
718: my $protocol = 'http';
719: if ($protocol{$spare_server} eq 'https') {
720: $protocol = $protocol{$spare_server};
721: }
722: if (defined($spare_server)) {
723: my $hostname = &hostname($spare_server);
724: if (defined($hostname)) {
725: $spare_server = $protocol.'://'.$hostname;
726: }
727: }
728: }
729: return $spare_server;
730: }
731:
732: sub compare_server_load {
733: my ($try_server, $spare_server, $lowest_load) = @_;
734:
735: my $loadans = &reply('load', $try_server);
736: my $userloadans = &reply('userload',$try_server);
737:
738: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
739: next; #didn't get a number from the server
740: }
741:
742: my $load;
743: if ($loadans =~ /\d/) {
744: if ($userloadans =~ /\d/) {
745: #both are numbers, pick the bigger one
746: $load = ($loadans > $userloadans) ? $loadans
747: : $userloadans;
748: } else {
749: $load = $loadans;
750: }
751: } else {
752: $load = $userloadans;
753: }
754:
755: if (($load =~ /\d/) && ($load < $lowest_load)) {
756: $spare_server = $try_server;
757: $lowest_load = $load;
758: }
759: return ($spare_server,$lowest_load);
760: }
761:
762: # --------------------------- ask offload servers if user already has a session
763: sub find_existing_session {
764: my ($udom,$uname) = @_;
765: foreach my $try_server (@{ $spareid{'primary'} },
766: @{ $spareid{'default'} }) {
767: return $try_server if (&has_user_session($try_server, $udom, $uname));
768: }
769: return;
770: }
771:
772: # -------------------------------- ask if server already has a session for user
773: sub has_user_session {
774: my ($lonid,$udom,$uname) = @_;
775: my $result = &reply(join(':','userhassession',
776: map {&escape($_)} ($udom,$uname)),$lonid);
777: return 1 if ($result eq 'ok');
778:
779: return 0;
780: }
781:
782: # --------------------------------------------- Try to change a user's password
783:
784: sub changepass {
785: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
786: $currentpass = &escape($currentpass);
787: $newpass = &escape($newpass);
788: my $lonhost = $perlvar{'lonHostID'};
789: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
790: $server);
791: if (! $answer) {
792: &logthis("No reply on password change request to $server ".
793: "by $uname in domain $udom.");
794: } elsif ($answer =~ "^ok") {
795: &logthis("$uname in $udom successfully changed their password ".
796: "on $server.");
797: } elsif ($answer =~ "^pwchange_failure") {
798: &logthis("$uname in $udom was unable to change their password ".
799: "on $server. The action was blocked by either lcpasswd ".
800: "or pwchange");
801: } elsif ($answer =~ "^non_authorized") {
802: &logthis("$uname in $udom did not get their password correct when ".
803: "attempting to change it on $server.");
804: } elsif ($answer =~ "^auth_mode_error") {
805: &logthis("$uname in $udom attempted to change their password despite ".
806: "not being locally or internally authenticated on $server.");
807: } elsif ($answer =~ "^unknown_user") {
808: &logthis("$uname in $udom attempted to change their password ".
809: "on $server but were unable to because $server is not ".
810: "their home server.");
811: } elsif ($answer =~ "^refused") {
812: &logthis("$server refused to change $uname in $udom password because ".
813: "it was sent an unencrypted request to change the password.");
814: } elsif ($answer =~ "invalid_client") {
815: &logthis("$server refused to change $uname in $udom password because ".
816: "it was a reset by e-mail originating from an invalid server.");
817: }
818: return $answer;
819: }
820:
821: # ----------------------- Try to determine user's current authentication scheme
822:
823: sub queryauthenticate {
824: my ($uname,$udom)=@_;
825: my $uhome=&homeserver($uname,$udom);
826: if (!$uhome) {
827: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
828: return 'no_host';
829: }
830: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
831: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
832: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
833: }
834: return $answer;
835: }
836:
837: # --------- Try to authenticate user from domain's lib servers (first this one)
838:
839: sub authenticate {
840: my ($uname,$upass,$udom,$checkdefauth)=@_;
841: $upass=&escape($upass);
842: $uname= &LONCAPA::clean_username($uname);
843: my $uhome=&homeserver($uname,$udom,1);
844: my $newhome;
845: if ((!$uhome) || ($uhome eq 'no_host')) {
846: # Maybe the machine was offline and only re-appeared again recently?
847: &reconlonc();
848: # One more
849: $uhome=&homeserver($uname,$udom,1);
850: if (($uhome eq 'no_host') && $checkdefauth) {
851: if (defined(&domain($udom,'primary'))) {
852: $newhome=&domain($udom,'primary');
853: }
854: if ($newhome ne '') {
855: $uhome = $newhome;
856: }
857: }
858: if ((!$uhome) || ($uhome eq 'no_host')) {
859: &logthis("User $uname at $udom is unknown in authenticate");
860: return 'no_host';
861: }
862: }
863: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
864: if ($answer eq 'authorized') {
865: if ($newhome) {
866: &logthis("User $uname at $udom authorized by $uhome, but needs account");
867: return 'no_account_on_host';
868: } else {
869: &logthis("User $uname at $udom authorized by $uhome");
870: return $uhome;
871: }
872: }
873: if ($answer eq 'non_authorized') {
874: &logthis("User $uname at $udom rejected by $uhome");
875: return 'no_host';
876: }
877: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
878: return 'no_host';
879: }
880:
881: # ---------------------- Find the homebase for a user from domain's lib servers
882:
883: my %homecache;
884: sub homeserver {
885: my ($uname,$udom,$ignoreBadCache)=@_;
886: my $index="$uname:$udom";
887:
888: if (exists($homecache{$index})) { return $homecache{$index}; }
889:
890: my %servers = &get_servers($udom,'library');
891: foreach my $tryserver (keys(%servers)) {
892: next if ($ignoreBadCache ne 'true' &&
893: exists($badServerCache{$tryserver}));
894:
895: my $answer=reply("home:$udom:$uname",$tryserver);
896: if ($answer eq 'found') {
897: delete($badServerCache{$tryserver});
898: return $homecache{$index}=$tryserver;
899: } elsif ($answer eq 'no_host') {
900: $badServerCache{$tryserver}=1;
901: }
902: }
903: return 'no_host';
904: }
905:
906: # ------------------------------------- Find the usernames behind a list of IDs
907:
908: sub idget {
909: my ($udom,@ids)=@_;
910: my %returnhash=();
911:
912: my %servers = &get_servers($udom,'library');
913: foreach my $tryserver (keys(%servers)) {
914: my $idlist=join('&',@ids);
915: $idlist=~tr/A-Z/a-z/;
916: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
917: my @answer=();
918: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
919: @answer=split(/\&/,$reply);
920: } ;
921: my $i;
922: for ($i=0;$i<=$#ids;$i++) {
923: if ($answer[$i]) {
924: $returnhash{$ids[$i]}=$answer[$i];
925: }
926: }
927: }
928: return %returnhash;
929: }
930:
931: # ------------------------------------- Find the IDs behind a list of usernames
932:
933: sub idrget {
934: my ($udom,@unames)=@_;
935: my %returnhash=();
936: foreach my $uname (@unames) {
937: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
938: }
939: return %returnhash;
940: }
941:
942: # ------------------------------- Store away a list of names and associated IDs
943:
944: sub idput {
945: my ($udom,%ids)=@_;
946: my %servers=();
947: foreach my $uname (keys(%ids)) {
948: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
949: my $uhom=&homeserver($uname,$udom);
950: if ($uhom ne 'no_host') {
951: my $id=&escape($ids{$uname});
952: $id=~tr/A-Z/a-z/;
953: my $esc_unam=&escape($uname);
954: if ($servers{$uhom}) {
955: $servers{$uhom}.='&'.$id.'='.$esc_unam;
956: } else {
957: $servers{$uhom}=$id.'='.$esc_unam;
958: }
959: }
960: }
961: foreach my $server (keys(%servers)) {
962: &critical('idput:'.$udom.':'.$servers{$server},$server);
963: }
964: }
965:
966: # ------------------------------dump from db file owned by domainconfig user
967: sub dump_dom {
968: my ($namespace,$udom,$regexp,$range)=@_;
969: if (!$udom) {
970: $udom=$env{'user.domain'};
971: }
972: my %returnhash;
973: if ($udom) {
974: my $uname = &get_domainconfiguser($udom);
975: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
976: }
977: return %returnhash;
978: }
979:
980: # ------------------------------------------ get items from domain db files
981:
982: sub get_dom {
983: my ($namespace,$storearr,$udom,$uhome)=@_;
984: my $items='';
985: foreach my $item (@$storearr) {
986: $items.=&escape($item).'&';
987: }
988: $items=~s/\&$//;
989: if (!$udom) {
990: $udom=$env{'user.domain'};
991: if (defined(&domain($udom,'primary'))) {
992: $uhome=&domain($udom,'primary');
993: } else {
994: undef($uhome);
995: }
996: } else {
997: if (!$uhome) {
998: if (defined(&domain($udom,'primary'))) {
999: $uhome=&domain($udom,'primary');
1000: }
1001: }
1002: }
1003: if ($udom && $uhome && ($uhome ne 'no_host')) {
1004: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1005: my %returnhash;
1006: if ($rep eq '' || $rep =~ /^error: 2 /) {
1007: return %returnhash;
1008: }
1009: my @pairs=split(/\&/,$rep);
1010: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1011: return @pairs;
1012: }
1013: my $i=0;
1014: foreach my $item (@$storearr) {
1015: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1016: $i++;
1017: }
1018: return %returnhash;
1019: } else {
1020: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1021: }
1022: }
1023:
1024: # -------------------------------------------- put items in domain db files
1025:
1026: sub put_dom {
1027: my ($namespace,$storehash,$udom,$uhome)=@_;
1028: if (!$udom) {
1029: $udom=$env{'user.domain'};
1030: if (defined(&domain($udom,'primary'))) {
1031: $uhome=&domain($udom,'primary');
1032: } else {
1033: undef($uhome);
1034: }
1035: } else {
1036: if (!$uhome) {
1037: if (defined(&domain($udom,'primary'))) {
1038: $uhome=&domain($udom,'primary');
1039: }
1040: }
1041: }
1042: if ($udom && $uhome && ($uhome ne 'no_host')) {
1043: my $items='';
1044: foreach my $item (keys(%$storehash)) {
1045: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1046: }
1047: $items=~s/\&$//;
1048: return &reply("putdom:$udom:$namespace:$items",$uhome);
1049: } else {
1050: &logthis("put_dom failed - no homeserver and/or domain");
1051: }
1052: }
1053:
1054: # --------------------- newput for items in db file owned by domainconfig user
1055: sub newput_dom {
1056: my ($namespace,$storehash,$udom) = @_;
1057: my $result;
1058: if (!$udom) {
1059: $udom=$env{'user.domain'};
1060: }
1061: if ($udom) {
1062: my $uname = &get_domainconfiguser($udom);
1063: $result = &newput($namespace,$storehash,$udom,$uname);
1064: }
1065: return $result;
1066: }
1067:
1068: # --------------------- delete for items in db file owned by domainconfig user
1069: sub del_dom {
1070: my ($namespace,$storearr,$udom)=@_;
1071: if (ref($storearr) eq 'ARRAY') {
1072: if (!$udom) {
1073: $udom=$env{'user.domain'};
1074: }
1075: if ($udom) {
1076: my $uname = &get_domainconfiguser($udom);
1077: return &del($namespace,$storearr,$udom,$uname);
1078: }
1079: }
1080: }
1081:
1082: # ----------------------------------construct domainconfig user for a domain
1083: sub get_domainconfiguser {
1084: my ($udom) = @_;
1085: return $udom.'-domainconfig';
1086: }
1087:
1088: sub retrieve_inst_usertypes {
1089: my ($udom) = @_;
1090: my (%returnhash,@order);
1091: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1092: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1093: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1094: %returnhash = %{$domdefs{'inststatustypes'}};
1095: @order = @{$domdefs{'inststatusorder'}};
1096: } else {
1097: if (defined(&domain($udom,'primary'))) {
1098: my $uhome=&domain($udom,'primary');
1099: my $rep=&reply("inst_usertypes:$udom",$uhome);
1100: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1101: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1102: return (\%returnhash,\@order);
1103: }
1104: my ($hashitems,$orderitems) = split(/:/,$rep);
1105: my @pairs=split(/\&/,$hashitems);
1106: foreach my $item (@pairs) {
1107: my ($key,$value)=split(/=/,$item,2);
1108: $key = &unescape($key);
1109: next if ($key =~ /^error: 2 /);
1110: $returnhash{$key}=&thaw_unescape($value);
1111: }
1112: my @esc_order = split(/\&/,$orderitems);
1113: foreach my $item (@esc_order) {
1114: push(@order,&unescape($item));
1115: }
1116: } else {
1117: &logthis("get_dom failed - no primary domain server for $udom");
1118: }
1119: }
1120: return (\%returnhash,\@order);
1121: }
1122:
1123: sub is_domainimage {
1124: my ($url) = @_;
1125: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1126: if (&domain($1) ne '') {
1127: return '1';
1128: }
1129: }
1130: return;
1131: }
1132:
1133: sub inst_directory_query {
1134: my ($srch) = @_;
1135: my $udom = $srch->{'srchdomain'};
1136: my %results;
1137: my $homeserver = &domain($udom,'primary');
1138: my $outcome;
1139: if ($homeserver ne '') {
1140: my $queryid=&reply("querysend:instdirsearch:".
1141: &escape($srch->{'srchby'}).':'.
1142: &escape($srch->{'srchterm'}).':'.
1143: &escape($srch->{'srchtype'}),$homeserver);
1144: my $host=&hostname($homeserver);
1145: if ($queryid !~/^\Q$host\E\_/) {
1146: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1147: return;
1148: }
1149: my $response = &get_query_reply($queryid);
1150: my $maxtries = 5;
1151: my $tries = 1;
1152: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1153: $response = &get_query_reply($queryid);
1154: $tries ++;
1155: }
1156:
1157: if (!&error($response) && $response ne 'refused') {
1158: if ($response eq 'unavailable') {
1159: $outcome = $response;
1160: } else {
1161: $outcome = 'ok';
1162: my @matches = split(/\n/,$response);
1163: foreach my $match (@matches) {
1164: my ($key,$value) = split(/=/,$match);
1165: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1166: }
1167: }
1168: }
1169: }
1170: return ($outcome,%results);
1171: }
1172:
1173: sub usersearch {
1174: my ($srch) = @_;
1175: my $dom = $srch->{'srchdomain'};
1176: my %results;
1177: my %libserv = &all_library();
1178: my $query = 'usersearch';
1179: foreach my $tryserver (keys(%libserv)) {
1180: if (&host_domain($tryserver) eq $dom) {
1181: my $host=&hostname($tryserver);
1182: my $queryid=
1183: &reply("querysend:".&escape($query).':'.
1184: &escape($srch->{'srchby'}).':'.
1185: &escape($srch->{'srchtype'}).':'.
1186: &escape($srch->{'srchterm'}),$tryserver);
1187: if ($queryid !~/^\Q$host\E\_/) {
1188: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1189: next;
1190: }
1191: my $reply = &get_query_reply($queryid);
1192: my $maxtries = 1;
1193: my $tries = 1;
1194: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1195: $reply = &get_query_reply($queryid);
1196: $tries ++;
1197: }
1198: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1199: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1200: } else {
1201: my @matches;
1202: if ($reply =~ /\n/) {
1203: @matches = split(/\n/,$reply);
1204: } else {
1205: @matches = split(/\&/,$reply);
1206: }
1207: foreach my $match (@matches) {
1208: my ($uname,$udom,%userhash);
1209: foreach my $entry (split(/:/,$match)) {
1210: my ($key,$value) =
1211: map {&unescape($_);} split(/=/,$entry);
1212: $userhash{$key} = $value;
1213: if ($key eq 'username') {
1214: $uname = $value;
1215: } elsif ($key eq 'domain') {
1216: $udom = $value;
1217: }
1218: }
1219: $results{$uname.':'.$udom} = \%userhash;
1220: }
1221: }
1222: }
1223: }
1224: return %results;
1225: }
1226:
1227: sub get_instuser {
1228: my ($udom,$uname,$id) = @_;
1229: my $homeserver = &domain($udom,'primary');
1230: my ($outcome,%results);
1231: if ($homeserver ne '') {
1232: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1233: &escape($id).':'.&escape($udom),$homeserver);
1234: my $host=&hostname($homeserver);
1235: if ($queryid !~/^\Q$host\E\_/) {
1236: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1237: return;
1238: }
1239: my $response = &get_query_reply($queryid);
1240: my $maxtries = 5;
1241: my $tries = 1;
1242: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1243: $response = &get_query_reply($queryid);
1244: $tries ++;
1245: }
1246: if (!&error($response) && $response ne 'refused') {
1247: if ($response eq 'unavailable') {
1248: $outcome = $response;
1249: } else {
1250: $outcome = 'ok';
1251: my @matches = split(/\n/,$response);
1252: foreach my $match (@matches) {
1253: my ($key,$value) = split(/=/,$match);
1254: $results{&unescape($key)} = &thaw_unescape($value);
1255: }
1256: }
1257: }
1258: }
1259: my %userinfo;
1260: if (ref($results{$uname}) eq 'HASH') {
1261: %userinfo = %{$results{$uname}};
1262: }
1263: return ($outcome,%userinfo);
1264: }
1265:
1266: sub inst_rulecheck {
1267: my ($udom,$uname,$id,$item,$rules) = @_;
1268: my %returnhash;
1269: if ($udom ne '') {
1270: if (ref($rules) eq 'ARRAY') {
1271: @{$rules} = map {&escape($_);} (@{$rules});
1272: my $rulestr = join(':',@{$rules});
1273: my $homeserver=&domain($udom,'primary');
1274: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1275: my $response;
1276: if ($item eq 'username') {
1277: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1278: ':'.&escape($uname).':'.$rulestr,
1279: $homeserver));
1280: } elsif ($item eq 'id') {
1281: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1282: ':'.&escape($id).':'.$rulestr,
1283: $homeserver));
1284: } elsif ($item eq 'selfcreate') {
1285: $response=&unescape(&reply('instselfcreatecheck:'.
1286: &escape($udom).':'.&escape($uname).
1287: ':'.$rulestr,$homeserver));
1288: }
1289: if ($response ne 'refused') {
1290: my @pairs=split(/\&/,$response);
1291: foreach my $item (@pairs) {
1292: my ($key,$value)=split(/=/,$item,2);
1293: $key = &unescape($key);
1294: next if ($key =~ /^error: 2 /);
1295: $returnhash{$key}=&thaw_unescape($value);
1296: }
1297: }
1298: }
1299: }
1300: }
1301: return %returnhash;
1302: }
1303:
1304: sub inst_userrules {
1305: my ($udom,$check) = @_;
1306: my (%ruleshash,@ruleorder);
1307: if ($udom ne '') {
1308: my $homeserver=&domain($udom,'primary');
1309: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1310: my $response;
1311: if ($check eq 'id') {
1312: $response=&reply('instidrules:'.&escape($udom),
1313: $homeserver);
1314: } elsif ($check eq 'email') {
1315: $response=&reply('instemailrules:'.&escape($udom),
1316: $homeserver);
1317: } else {
1318: $response=&reply('instuserrules:'.&escape($udom),
1319: $homeserver);
1320: }
1321: if (($response ne 'refused') && ($response ne 'error') &&
1322: ($response ne 'unknown_cmd') &&
1323: ($response ne 'no_such_host')) {
1324: my ($hashitems,$orderitems) = split(/:/,$response);
1325: my @pairs=split(/\&/,$hashitems);
1326: foreach my $item (@pairs) {
1327: my ($key,$value)=split(/=/,$item,2);
1328: $key = &unescape($key);
1329: next if ($key =~ /^error: 2 /);
1330: $ruleshash{$key}=&thaw_unescape($value);
1331: }
1332: my @esc_order = split(/\&/,$orderitems);
1333: foreach my $item (@esc_order) {
1334: push(@ruleorder,&unescape($item));
1335: }
1336: }
1337: }
1338: }
1339: return (\%ruleshash,\@ruleorder);
1340: }
1341:
1342: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1343:
1344: sub get_domain_defaults {
1345: my ($domain) = @_;
1346: my $cachetime = 60*60*24;
1347: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1348: if (defined($cached)) {
1349: if (ref($result) eq 'HASH') {
1350: return %{$result};
1351: }
1352: }
1353: my %domdefaults;
1354: my %domconfig =
1355: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1356: 'requestcourses','inststatus'],$domain);
1357: if (ref($domconfig{'defaults'}) eq 'HASH') {
1358: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1359: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1360: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1361: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1362: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1363: } else {
1364: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1365: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1366: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1367: }
1368: if (ref($domconfig{'quotas'}) eq 'HASH') {
1369: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1370: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1371: } else {
1372: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1373: }
1374: my @usertools = ('aboutme','blog','portfolio');
1375: foreach my $item (@usertools) {
1376: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1377: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1378: }
1379: }
1380: }
1381: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1382: foreach my $item ('official','unofficial','community') {
1383: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1384: }
1385: }
1386: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1387: foreach my $item ('inststatustypes','inststatusorder') {
1388: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1389: }
1390: }
1391: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1392: $cachetime);
1393: return %domdefaults;
1394: }
1395:
1396: # --------------------------------------------------- Assign a key to a student
1397:
1398: sub assign_access_key {
1399: #
1400: # a valid key looks like uname:udom#comments
1401: # comments are being appended
1402: #
1403: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1404: $kdom=
1405: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1406: $knum=
1407: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1408: $cdom=
1409: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1410: $cnum=
1411: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1412: $udom=$env{'user.name'} unless (defined($udom));
1413: $uname=$env{'user.domain'} unless (defined($uname));
1414: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1415: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1416: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1417: # assigned to this person
1418: # - this should not happen,
1419: # unless something went wrong
1420: # the first time around
1421: # ready to assign
1422: $logentry=$1.'; '.$logentry;
1423: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1424: $kdom,$knum) eq 'ok') {
1425: # key now belongs to user
1426: my $envkey='key.'.$cdom.'_'.$cnum;
1427: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1428: &appenv({'environment.'.$envkey => $ckey});
1429: return 'ok';
1430: } else {
1431: return
1432: 'error: Count not permanently assign key, will need to be re-entered later.';
1433: }
1434: } else {
1435: return 'error: Could not assign key, try again later.';
1436: }
1437: } elsif (!$existing{$ckey}) {
1438: # the key does not exist
1439: return 'error: The key does not exist';
1440: } else {
1441: # the key is somebody else's
1442: return 'error: The key is already in use';
1443: }
1444: }
1445:
1446: # ------------------------------------------ put an additional comment on a key
1447:
1448: sub comment_access_key {
1449: #
1450: # a valid key looks like uname:udom#comments
1451: # comments are being appended
1452: #
1453: my ($ckey,$cdom,$cnum,$logentry)=@_;
1454: $cdom=
1455: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1456: $cnum=
1457: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1458: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1459: if ($existing{$ckey}) {
1460: $existing{$ckey}.='; '.$logentry;
1461: # ready to assign
1462: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1463: $cdom,$cnum) eq 'ok') {
1464: return 'ok';
1465: } else {
1466: return 'error: Count not store comment.';
1467: }
1468: } else {
1469: # the key does not exist
1470: return 'error: The key does not exist';
1471: }
1472: }
1473:
1474: # ------------------------------------------------------ Generate a set of keys
1475:
1476: sub generate_access_keys {
1477: my ($number,$cdom,$cnum,$logentry)=@_;
1478: $cdom=
1479: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1480: $cnum=
1481: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1482: unless (&allowed('mky',$cdom)) { return 0; }
1483: unless (($cdom) && ($cnum)) { return 0; }
1484: if ($number>10000) { return 0; }
1485: sleep(2); # make sure don't get same seed twice
1486: srand(time()^($$+($$<<15))); # from "Programming Perl"
1487: my $total=0;
1488: for (my $i=1;$i<=$number;$i++) {
1489: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1490: sprintf("%lx",int(100000*rand)).'-'.
1491: sprintf("%lx",int(100000*rand));
1492: $newkey=~s/1/g/g; # folks mix up 1 and l
1493: $newkey=~s/0/h/g; # and also 0 and O
1494: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1495: if ($existing{$newkey}) {
1496: $i--;
1497: } else {
1498: if (&put('accesskeys',
1499: { $newkey => '# generated '.localtime().
1500: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1501: '; '.$logentry },
1502: $cdom,$cnum) eq 'ok') {
1503: $total++;
1504: }
1505: }
1506: }
1507: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1508: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1509: return $total;
1510: }
1511:
1512: # ------------------------------------------------------- Validate an accesskey
1513:
1514: sub validate_access_key {
1515: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1516: $cdom=
1517: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1518: $cnum=
1519: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1520: $udom=$env{'user.domain'} unless (defined($udom));
1521: $uname=$env{'user.name'} unless (defined($uname));
1522: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1523: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1524: }
1525:
1526: # ------------------------------------- Find the section of student in a course
1527: sub devalidate_getsection_cache {
1528: my ($udom,$unam,$courseid)=@_;
1529: my $hashid="$udom:$unam:$courseid";
1530: &devalidate_cache_new('getsection',$hashid);
1531: }
1532:
1533: sub courseid_to_courseurl {
1534: my ($courseid) = @_;
1535: #already url style courseid
1536: return $courseid if ($courseid =~ m{^/});
1537:
1538: if (exists($env{'course.'.$courseid.'.num'})) {
1539: my $cnum = $env{'course.'.$courseid.'.num'};
1540: my $cdom = $env{'course.'.$courseid.'.domain'};
1541: return "/$cdom/$cnum";
1542: }
1543:
1544: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1545: if (exists($courseinfo{'num'})) {
1546: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1547: }
1548:
1549: return undef;
1550: }
1551:
1552: sub getsection {
1553: my ($udom,$unam,$courseid)=@_;
1554: my $cachetime=1800;
1555:
1556: my $hashid="$udom:$unam:$courseid";
1557: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1558: if (defined($cached)) { return $result; }
1559:
1560: my %Pending;
1561: my %Expired;
1562: #
1563: # Each role can either have not started yet (pending), be active,
1564: # or have expired.
1565: #
1566: # If there is an active role, we are done.
1567: #
1568: # If there is more than one role which has not started yet,
1569: # choose the one which will start sooner
1570: # If there is one role which has not started yet, return it.
1571: #
1572: # If there is more than one expired role, choose the one which ended last.
1573: # If there is a role which has expired, return it.
1574: #
1575: $courseid = &courseid_to_courseurl($courseid);
1576: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1577: foreach my $key (keys(%roleshash)) {
1578: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1579: my $section=$1;
1580: if ($key eq $courseid.'_st') { $section=''; }
1581: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1582: my $now=time;
1583: if (defined($end) && $end && ($now > $end)) {
1584: $Expired{$end}=$section;
1585: next;
1586: }
1587: if (defined($start) && $start && ($now < $start)) {
1588: $Pending{$start}=$section;
1589: next;
1590: }
1591: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1592: }
1593: #
1594: # Presumedly there will be few matching roles from the above
1595: # loop and the sorting time will be negligible.
1596: if (scalar(keys(%Pending))) {
1597: my ($time) = sort {$a <=> $b} keys(%Pending);
1598: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1599: }
1600: if (scalar(keys(%Expired))) {
1601: my @sorted = sort {$a <=> $b} keys(%Expired);
1602: my $time = pop(@sorted);
1603: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1604: }
1605: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1606: }
1607:
1608: sub save_cache {
1609: &purge_remembered();
1610: #&Apache::loncommon::validate_page();
1611: undef(%env);
1612: undef($env_loaded);
1613: }
1614:
1615: my $to_remember=-1;
1616: my %remembered;
1617: my %accessed;
1618: my $kicks=0;
1619: my $hits=0;
1620: sub make_key {
1621: my ($name,$id) = @_;
1622: if (length($id) > 65
1623: && length(&escape($id)) > 200) {
1624: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1625: }
1626: return &escape($name.':'.$id);
1627: }
1628:
1629: sub devalidate_cache_new {
1630: my ($name,$id,$debug) = @_;
1631: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1632: $id=&make_key($name,$id);
1633: $memcache->delete($id);
1634: delete($remembered{$id});
1635: delete($accessed{$id});
1636: }
1637:
1638: sub is_cached_new {
1639: my ($name,$id,$debug) = @_;
1640: $id=&make_key($name,$id);
1641: if (exists($remembered{$id})) {
1642: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1643: $accessed{$id}=[&gettimeofday()];
1644: $hits++;
1645: return ($remembered{$id},1);
1646: }
1647: my $value = $memcache->get($id);
1648: if (!(defined($value))) {
1649: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1650: return (undef,undef);
1651: }
1652: if ($value eq '__undef__') {
1653: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1654: $value=undef;
1655: }
1656: &make_room($id,$value,$debug);
1657: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1658: return ($value,1);
1659: }
1660:
1661: sub do_cache_new {
1662: my ($name,$id,$value,$time,$debug) = @_;
1663: $id=&make_key($name,$id);
1664: my $setvalue=$value;
1665: if (!defined($setvalue)) {
1666: $setvalue='__undef__';
1667: }
1668: if (!defined($time) ) {
1669: $time=600;
1670: }
1671: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1672: my $result = $memcache->set($id,$setvalue,$time);
1673: if (! $result) {
1674: &logthis("caching of id -> $id failed");
1675: $memcache->disconnect_all();
1676: }
1677: # need to make a copy of $value
1678: &make_room($id,$value,$debug);
1679: return $value;
1680: }
1681:
1682: sub make_room {
1683: my ($id,$value,$debug)=@_;
1684:
1685: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1686: : $value;
1687: if ($to_remember<0) { return; }
1688: $accessed{$id}=[&gettimeofday()];
1689: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1690: my $to_kick;
1691: my $max_time=0;
1692: foreach my $other (keys(%accessed)) {
1693: if (&tv_interval($accessed{$other}) > $max_time) {
1694: $to_kick=$other;
1695: $max_time=&tv_interval($accessed{$other});
1696: }
1697: }
1698: delete($remembered{$to_kick});
1699: delete($accessed{$to_kick});
1700: $kicks++;
1701: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1702: return;
1703: }
1704:
1705: sub purge_remembered {
1706: #&logthis("Tossing ".scalar(keys(%remembered)));
1707: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1708: undef(%remembered);
1709: undef(%accessed);
1710: }
1711: # ------------------------------------- Read an entry from a user's environment
1712:
1713: sub userenvironment {
1714: my ($udom,$unam,@what)=@_;
1715: my $items;
1716: foreach my $item (@what) {
1717: $items.=&escape($item).'&';
1718: }
1719: $items=~s/\&$//;
1720: my %returnhash=();
1721: my $uhome = &homeserver($unam,$udom);
1722: unless ($uhome eq 'no_host') {
1723: my @answer=split(/\&/,
1724: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1725: my $i;
1726: for ($i=0;$i<=$#what;$i++) {
1727: $returnhash{$what[$i]}=&unescape($answer[$i]);
1728: }
1729: }
1730: return %returnhash;
1731: }
1732:
1733: # ---------------------------------------------------------- Get a studentphoto
1734: sub studentphoto {
1735: my ($udom,$unam,$ext) = @_;
1736: my $home=&Apache::lonnet::homeserver($unam,$udom);
1737: if (defined($env{'request.course.id'})) {
1738: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1739: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1740: return(&retrievestudentphoto($udom,$unam,$ext));
1741: } else {
1742: my ($result,$perm_reqd)=
1743: &Apache::lonnet::auto_photo_permission($unam,$udom);
1744: if ($result eq 'ok') {
1745: if (!($perm_reqd eq 'yes')) {
1746: return(&retrievestudentphoto($udom,$unam,$ext));
1747: }
1748: }
1749: }
1750: }
1751: } else {
1752: my ($result,$perm_reqd) =
1753: &Apache::lonnet::auto_photo_permission($unam,$udom);
1754: if ($result eq 'ok') {
1755: if (!($perm_reqd eq 'yes')) {
1756: return(&retrievestudentphoto($udom,$unam,$ext));
1757: }
1758: }
1759: }
1760: return '/adm/lonKaputt/lonlogo_broken.gif';
1761: }
1762:
1763: sub retrievestudentphoto {
1764: my ($udom,$unam,$ext,$type) = @_;
1765: my $home=&Apache::lonnet::homeserver($unam,$udom);
1766: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1767: if ($ret eq 'ok') {
1768: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1769: if ($type eq 'thumbnail') {
1770: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1771: }
1772: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1773: return $tokenurl;
1774: } else {
1775: if ($type eq 'thumbnail') {
1776: return '/adm/lonKaputt/genericstudent_tn.gif';
1777: } else {
1778: return '/adm/lonKaputt/lonlogo_broken.gif';
1779: }
1780: }
1781: }
1782:
1783: # -------------------------------------------------------------------- New chat
1784:
1785: sub chatsend {
1786: my ($newentry,$anon,$group)=@_;
1787: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1788: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1789: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1790: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1791: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1792: &escape($newentry)).':'.$group,$chome);
1793: }
1794:
1795: # ------------------------------------------ Find current version of a resource
1796:
1797: sub getversion {
1798: my $fname=&clutter(shift);
1799: unless ($fname=~/^\/res\//) { return -1; }
1800: return ¤tversion(&filelocation('',$fname));
1801: }
1802:
1803: sub currentversion {
1804: my $fname=shift;
1805: my ($result,$cached)=&is_cached_new('resversion',$fname);
1806: if (defined($cached)) { return $result; }
1807: my $author=$fname;
1808: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1809: my ($udom,$uname)=split(/\//,$author);
1810: my $home=homeserver($uname,$udom);
1811: if ($home eq 'no_host') {
1812: return -1;
1813: }
1814: my $answer=reply("currentversion:$fname",$home);
1815: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1816: return -1;
1817: }
1818: return &do_cache_new('resversion',$fname,$answer,600);
1819: }
1820:
1821: # ----------------------------- Subscribe to a resource, return URL if possible
1822:
1823: sub subscribe {
1824: my $fname=shift;
1825: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1826: $fname=~s/[\n\r]//g;
1827: my $author=$fname;
1828: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1829: my ($udom,$uname)=split(/\//,$author);
1830: my $home=homeserver($uname,$udom);
1831: if ($home eq 'no_host') {
1832: return 'not_found';
1833: }
1834: my $answer=reply("sub:$fname",$home);
1835: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1836: $answer.=' by '.$home;
1837: }
1838: return $answer;
1839: }
1840:
1841: # -------------------------------------------------------------- Replicate file
1842:
1843: sub repcopy {
1844: my $filename=shift;
1845: $filename=~s/\/+/\//g;
1846: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1847: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1848: if ($filename=~m|^/home/httpd/html/userfiles/| or
1849: $filename=~m -^/*(uploaded|editupload)/-) {
1850: return &repcopy_userfile($filename);
1851: }
1852: $filename=~s/[\n\r]//g;
1853: my $transname="$filename.in.transfer";
1854: # FIXME: this should flock
1855: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1856: my $remoteurl=subscribe($filename);
1857: if ($remoteurl =~ /^con_lost by/) {
1858: &logthis("Subscribe returned $remoteurl: $filename");
1859: return 'unavailable';
1860: } elsif ($remoteurl eq 'not_found') {
1861: #&logthis("Subscribe returned not_found: $filename");
1862: return 'not_found';
1863: } elsif ($remoteurl =~ /^rejected by/) {
1864: &logthis("Subscribe returned $remoteurl: $filename");
1865: return 'forbidden';
1866: } elsif ($remoteurl eq 'directory') {
1867: return 'ok';
1868: } else {
1869: my $author=$filename;
1870: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1871: my ($udom,$uname)=split(/\//,$author);
1872: my $home=homeserver($uname,$udom);
1873: unless ($home eq $perlvar{'lonHostID'}) {
1874: my @parts=split(/\//,$filename);
1875: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1876: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1877: &logthis("Malconfiguration for replication: $filename");
1878: return 'bad_request';
1879: }
1880: my $count;
1881: for ($count=5;$count<$#parts;$count++) {
1882: $path.="/$parts[$count]";
1883: if ((-e $path)!=1) {
1884: mkdir($path,0777);
1885: }
1886: }
1887: my $ua=new LWP::UserAgent;
1888: my $request=new HTTP::Request('GET',"$remoteurl");
1889: my $response=$ua->request($request,$transname);
1890: if ($response->is_error()) {
1891: unlink($transname);
1892: my $message=$response->status_line;
1893: &logthis("<font color=\"blue\">WARNING:"
1894: ." LWP get: $message: $filename</font>");
1895: return 'unavailable';
1896: } else {
1897: if ($remoteurl!~/\.meta$/) {
1898: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1899: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1900: if ($mresponse->is_error()) {
1901: unlink($filename.'.meta');
1902: &logthis(
1903: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1904: }
1905: }
1906: rename($transname,$filename);
1907: return 'ok';
1908: }
1909: }
1910: }
1911: }
1912:
1913: # ------------------------------------------------ Get server side include body
1914: sub ssi_body {
1915: my ($filelink,%form)=@_;
1916: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1917: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1918: }
1919: my $output='';
1920: my $response;
1921: if ($filelink=~/^https?\:/) {
1922: ($output,$response)=&externalssi($filelink);
1923: } else {
1924: $filelink .= $filelink=~/\?/ ? '&' : '?';
1925: $filelink .= 'inhibitmenu=yes';
1926: ($output,$response)=&ssi($filelink,%form);
1927: }
1928: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1929: $output=~s/^.*?\<body[^\>]*\>//si;
1930: $output=~s/\<\/body\s*\>.*?$//si;
1931: if (wantarray) {
1932: return ($output, $response);
1933: } else {
1934: return $output;
1935: }
1936: }
1937:
1938: # --------------------------------------------------------- Server Side Include
1939:
1940: sub absolute_url {
1941: my ($host_name) = @_;
1942: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1943: if ($host_name eq '') {
1944: $host_name = $ENV{'SERVER_NAME'};
1945: }
1946: return $protocol.$host_name;
1947: }
1948:
1949: #
1950: # Server side include.
1951: # Parameters:
1952: # fn Possibly encrypted resource name/id.
1953: # form Hash that describes how the rendering should be done
1954: # and other things.
1955: # Returns:
1956: # Scalar context: The content of the response.
1957: # Array context: 2 element list of the content and the full response object.
1958: #
1959: sub ssi {
1960:
1961: my ($fn,%form)=@_;
1962: my $ua=new LWP::UserAgent;
1963: my $request;
1964:
1965: $form{'no_update_last_known'}=1;
1966: &Apache::lonenc::check_encrypt(\$fn);
1967: if (%form) {
1968: $request=new HTTP::Request('POST',&absolute_url().$fn);
1969: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1970: } else {
1971: $request=new HTTP::Request('GET',&absolute_url().$fn);
1972: }
1973:
1974: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1975: my $response=$ua->request($request);
1976:
1977: if (wantarray) {
1978: return ($response->content, $response);
1979: } else {
1980: return $response->content;
1981: }
1982: }
1983:
1984: sub externalssi {
1985: my ($url)=@_;
1986: my $ua=new LWP::UserAgent;
1987: my $request=new HTTP::Request('GET',$url);
1988: my $response=$ua->request($request);
1989: if (wantarray) {
1990: return ($response->content, $response);
1991: } else {
1992: return $response->content;
1993: }
1994: }
1995:
1996: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1997:
1998: sub allowuploaded {
1999: my ($srcurl,$url)=@_;
2000: $url=&clutter(&declutter($url));
2001: my $dir=$url;
2002: $dir=~s/\/[^\/]+$//;
2003: my %httpref=();
2004: my $httpurl=&hreflocation('',$url);
2005: $httpref{'httpref.'.$httpurl}=$srcurl;
2006: &Apache::lonnet::appenv(\%httpref);
2007: }
2008:
2009: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
2010: # input: action, courseID, current domain, intended
2011: # path to file, source of file, instruction to parse file for objects,
2012: # ref to hash for embedded objects,
2013: # ref to hash for codebase of java objects.
2014: #
2015: # output: url to file (if action was uploaddoc),
2016: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
2017: #
2018: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2019: # course.
2020: #
2021: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2022: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2023: # course's home server.
2024: #
2025: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2026: # be copied from $source (current location) to
2027: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2028: # and will then be copied to
2029: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2030: # course's home server.
2031: #
2032: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2033: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
2034: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2035: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2036: # in course's home server.
2037: #
2038:
2039: sub process_coursefile {
2040: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
2041: my $fetchresult;
2042: my $home=&homeserver($docuname,$docudom);
2043: if ($action eq 'propagate') {
2044: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2045: $home);
2046: } else {
2047: my $fpath = '';
2048: my $fname = $file;
2049: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2050: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2051: my $filepath = &build_filepath($fpath);
2052: if ($action eq 'copy') {
2053: if ($source eq '') {
2054: $fetchresult = 'no source file';
2055: return $fetchresult;
2056: } else {
2057: my $destination = $filepath.'/'.$fname;
2058: rename($source,$destination);
2059: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2060: $home);
2061: }
2062: } elsif ($action eq 'uploaddoc') {
2063: open(my $fh,'>'.$filepath.'/'.$fname);
2064: print $fh $env{'form.'.$source};
2065: close($fh);
2066: if ($parser eq 'parse') {
2067: my $mm = new File::MMagic;
2068: my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
2069: if ($mime_type eq 'text/html') {
2070: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2071: unless ($parse_result eq 'ok') {
2072: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2073: }
2074: }
2075: }
2076: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2077: $home);
2078: if ($fetchresult eq 'ok') {
2079: return '/uploaded/'.$fpath.'/'.$fname;
2080: } else {
2081: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2082: ' to host '.$home.': '.$fetchresult);
2083: return '/adm/notfound.html';
2084: }
2085: }
2086: }
2087: unless ( $fetchresult eq 'ok') {
2088: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2089: ' to host '.$home.': '.$fetchresult);
2090: }
2091: return $fetchresult;
2092: }
2093:
2094: sub build_filepath {
2095: my ($fpath) = @_;
2096: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2097: unless ($fpath eq '') {
2098: my @parts=split('/',$fpath);
2099: foreach my $part (@parts) {
2100: $filepath.= '/'.$part;
2101: if ((-e $filepath)!=1) {
2102: mkdir($filepath,0777);
2103: }
2104: }
2105: }
2106: return $filepath;
2107: }
2108:
2109: sub store_edited_file {
2110: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
2111: my $file = $primary_url;
2112: $file =~ s#^/uploaded/$docudom/$docuname/##;
2113: my $fpath = '';
2114: my $fname = $file;
2115: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2116: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2117: my $filepath = &build_filepath($fpath);
2118: open(my $fh,'>'.$filepath.'/'.$fname);
2119: print $fh $content;
2120: close($fh);
2121: my $home=&homeserver($docuname,$docudom);
2122: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2123: $home);
2124: if ($$fetchresult eq 'ok') {
2125: return '/uploaded/'.$fpath.'/'.$fname;
2126: } else {
2127: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2128: ' to host '.$home.': '.$$fetchresult);
2129: return '/adm/notfound.html';
2130: }
2131: }
2132:
2133: sub clean_filename {
2134: my ($fname,$args)=@_;
2135: # Replace Windows backslashes by forward slashes
2136: $fname=~s/\\/\//g;
2137: if (!$args->{'keep_path'}) {
2138: # Get rid of everything but the actual filename
2139: $fname=~s/^.*\/([^\/]+)$/$1/;
2140: }
2141: # Replace spaces by underscores
2142: $fname=~s/\s+/\_/g;
2143: # Replace all other weird characters by nothing
2144: $fname=~s{[^/\w\.\-]}{}g;
2145: # Replace all .\d. sequences with _\d. so they no longer look like version
2146: # numbers
2147: $fname=~s/\.(\d+)(?=\.)/_$1/g;
2148: return $fname;
2149: }
2150: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
2151: sub resizeImage {
2152: my($img_url) = @_;
2153: my $ima = Image::Magick->new;
2154: $ima->Read($img_url);
2155: if($ima->Get('width') > 400)
2156: {
2157: my $factor = $ima->Get('width')/400;
2158: $ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
2159: }
2160: if($ima->Get('height') > 500)
2161: {
2162: my $factor = $ima->Get('height')/500;
2163: $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
2164: }
2165:
2166: $ima->Write($img_url);
2167: }
2168:
2169: #Wrapper function for userphotoupload
2170: sub userphotoupload
2171: {
2172: my($formname,$subdir) = @_;
2173: $upload_photo_form = 1;
2174: return &userfileupload($formname,undef,$subdir);
2175: }
2176:
2177: # --------------- Take an uploaded file and put it into the userfiles directory
2178: # input: $formname - the contents of the file are in $env{"form.$formname"}
2179: # the desired filenam is in $env{"form.$formname.filename"}
2180: # $coursedoc - if true up to the current course
2181: # if false
2182: # $subdir - directory in userfile to store the file into
2183: # $parser - instruction to parse file for objects ($parser = parse)
2184: # $allfiles - reference to hash for embedded objects
2185: # $codebase - reference to hash for codebase of java objects
2186: # $desuname - username for permanent storage of uploaded file
2187: # $dsetudom - domain for permanaent storage of uploaded file
2188: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2189: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
2190: #
2191: # output: url of file in userspace, or error: <message>
2192: # or /adm/notfound.html if failure to upload occurse
2193:
2194:
2195: sub userfileupload {
2196: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
2197: $destudom,$thumbwidth,$thumbheight)=@_;
2198: if (!defined($subdir)) { $subdir='unknown'; }
2199: my $fname=$env{'form.'.$formname.'.filename'};
2200: $fname=&clean_filename($fname);
2201: # See if there is anything left
2202: unless ($fname) { return 'error: no uploaded file'; }
2203: chop($env{'form.'.$formname});
2204: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
2205: my $now = time;
2206: my $filepath = 'tmp/helprequests/'.$now;
2207: my @parts=split(/\//,$filepath);
2208: my $fullpath = $perlvar{'lonDaemons'};
2209: for (my $i=0;$i<@parts;$i++) {
2210: $fullpath .= '/'.$parts[$i];
2211: if ((-e $fullpath)!=1) {
2212: mkdir($fullpath,0777);
2213: }
2214: }
2215: open(my $fh,'>'.$fullpath.'/'.$fname);
2216: print $fh $env{'form.'.$formname};
2217: close($fh);
2218: return $fullpath.'/'.$fname;
2219: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
2220: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2221: '_'.$env{'user.domain'}.'/pending';
2222: my @parts=split(/\//,$filepath);
2223: my $fullpath = $perlvar{'lonDaemons'};
2224: for (my $i=0;$i<@parts;$i++) {
2225: $fullpath .= '/'.$parts[$i];
2226: if ((-e $fullpath)!=1) {
2227: mkdir($fullpath,0777);
2228: }
2229: }
2230: open(my $fh,'>'.$fullpath.'/'.$fname);
2231: print $fh $env{'form.'.$formname};
2232: close($fh);
2233: return $fullpath.'/'.$fname;
2234: }
2235: if ($subdir eq 'scantron') {
2236: $fname = 'scantron_orig_'.$fname;
2237: } else {
2238: # Create the directory if not present
2239: $fname="$subdir/$fname";
2240: }
2241: if ($coursedoc) {
2242: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2243: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2244: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
2245: return &finishuserfileupload($docuname,$docudom,
2246: $formname,$fname,$parser,$allfiles,
2247: $codebase,$thumbwidth,$thumbheight);
2248: } else {
2249: $fname=$env{'form.folder'}.'/'.$fname;
2250: return &process_coursefile('uploaddoc',$docuname,$docudom,
2251: $fname,$formname,$parser,
2252: $allfiles,$codebase);
2253: }
2254: } elsif (defined($destuname)) {
2255: my $docuname=$destuname;
2256: my $docudom=$destudom;
2257: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2258: $parser,$allfiles,$codebase,
2259: $thumbwidth,$thumbheight);
2260:
2261: } else {
2262: my $docuname=$env{'user.name'};
2263: my $docudom=$env{'user.domain'};
2264: if (exists($env{'form.group'})) {
2265: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2266: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2267: }
2268: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2269: $parser,$allfiles,$codebase,
2270: $thumbwidth,$thumbheight);
2271: }
2272: }
2273:
2274: sub finishuserfileupload {
2275: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
2276: $thumbwidth,$thumbheight) = @_;
2277: my $path=$docudom.'/'.$docuname.'/';
2278: my $filepath=$perlvar{'lonDocRoot'};
2279:
2280: my ($fnamepath,$file,$fetchthumb);
2281: $file=$fname;
2282: if ($fname=~m|/|) {
2283: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2284: $path.=$fnamepath.'/';
2285: }
2286: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
2287: my $count;
2288: for ($count=4;$count<=$#parts;$count++) {
2289: $filepath.="/$parts[$count]";
2290: if ((-e $filepath)!=1) {
2291: mkdir($filepath,0777);
2292: }
2293: }
2294:
2295: # Save the file
2296: {
2297: if (!open(FH,'>'.$filepath.'/'.$file)) {
2298: &logthis('Failed to create '.$filepath.'/'.$file);
2299: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2300: return '/adm/notfound.html';
2301: }
2302: if (!print FH ($env{'form.'.$formname})) {
2303: &logthis('Failed to write to '.$filepath.'/'.$file);
2304: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2305: return '/adm/notfound.html';
2306: }
2307: close(FH);
2308: if($upload_photo_form==1)
2309: {
2310: resizeImage($filepath.'/'.$file);
2311: $upload_photo_form = 0;
2312: }
2313: }
2314: if ($parser eq 'parse') {
2315: my $mm = new File::MMagic;
2316: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2317: if ($mime_type eq 'text/html') {
2318: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2319: $allfiles,$codebase);
2320: unless ($parse_result eq 'ok') {
2321: &logthis('Failed to parse '.$filepath.$file.
2322: ' for embedded media: '.$parse_result);
2323: }
2324: }
2325: }
2326: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2327: my $input = $filepath.'/'.$file;
2328: my $output = $filepath.'/'.'tn-'.$file;
2329: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2330: system("convert -sample $thumbsize $input $output");
2331: if (-e $filepath.'/'.'tn-'.$file) {
2332: $fetchthumb = 1;
2333: }
2334: }
2335:
2336: # Notify homeserver to grep it
2337: #
2338: my $docuhome=&homeserver($docuname,$docudom);
2339: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
2340: if ($fetchresult eq 'ok') {
2341: if ($fetchthumb) {
2342: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2343: if ($thumbresult ne 'ok') {
2344: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2345: $docuhome.': '.$thumbresult);
2346: }
2347: }
2348: #
2349: # Return the URL to it
2350: return '/uploaded/'.$path.$file;
2351: } else {
2352: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2353: ': '.$fetchresult);
2354: return '/adm/notfound.html';
2355: }
2356: }
2357:
2358: sub extract_embedded_items {
2359: my ($fullpath,$allfiles,$codebase,$content) = @_;
2360: my @state = ();
2361: my %javafiles = (
2362: codebase => '',
2363: code => '',
2364: archive => ''
2365: );
2366: my %mediafiles = (
2367: src => '',
2368: movie => '',
2369: );
2370: my $p;
2371: if ($content) {
2372: $p = HTML::LCParser->new($content);
2373: } else {
2374: $p = HTML::LCParser->new($fullpath);
2375: }
2376: while (my $t=$p->get_token()) {
2377: if ($t->[0] eq 'S') {
2378: my ($tagname, $attr) = ($t->[1],$t->[2]);
2379: push(@state, $tagname);
2380: if (lc($tagname) eq 'allow') {
2381: &add_filetype($allfiles,$attr->{'src'},'src');
2382: }
2383: if (lc($tagname) eq 'img') {
2384: &add_filetype($allfiles,$attr->{'src'},'src');
2385: }
2386: if (lc($tagname) eq 'a') {
2387: &add_filetype($allfiles,$attr->{'href'},'href');
2388: }
2389: if (lc($tagname) eq 'script') {
2390: if ($attr->{'archive'} =~ /\.jar$/i) {
2391: &add_filetype($allfiles,$attr->{'archive'},'archive');
2392: } else {
2393: &add_filetype($allfiles,$attr->{'src'},'src');
2394: }
2395: }
2396: if (lc($tagname) eq 'link') {
2397: if (lc($attr->{'rel'}) eq 'stylesheet') {
2398: &add_filetype($allfiles,$attr->{'href'},'href');
2399: }
2400: }
2401: if (lc($tagname) eq 'object' ||
2402: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2403: foreach my $item (keys(%javafiles)) {
2404: $javafiles{$item} = '';
2405: }
2406: }
2407: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2408: my $name = lc($attr->{'name'});
2409: foreach my $item (keys(%javafiles)) {
2410: if ($name eq $item) {
2411: $javafiles{$item} = $attr->{'value'};
2412: last;
2413: }
2414: }
2415: foreach my $item (keys(%mediafiles)) {
2416: if ($name eq $item) {
2417: &add_filetype($allfiles, $attr->{'value'}, 'value');
2418: last;
2419: }
2420: }
2421: }
2422: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2423: foreach my $item (keys(%javafiles)) {
2424: if ($attr->{$item}) {
2425: $javafiles{$item} = $attr->{$item};
2426: last;
2427: }
2428: }
2429: foreach my $item (keys(%mediafiles)) {
2430: if ($attr->{$item}) {
2431: &add_filetype($allfiles,$attr->{$item},$item);
2432: last;
2433: }
2434: }
2435: }
2436: } elsif ($t->[0] eq 'E') {
2437: my ($tagname) = ($t->[1]);
2438: if ($javafiles{'codebase'} ne '') {
2439: $javafiles{'codebase'} .= '/';
2440: }
2441: if (lc($tagname) eq 'applet' ||
2442: lc($tagname) eq 'object' ||
2443: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2444: ) {
2445: foreach my $item (keys(%javafiles)) {
2446: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2447: my $file=$javafiles{'codebase'}.$javafiles{$item};
2448: &add_filetype($allfiles,$file,$item);
2449: }
2450: }
2451: }
2452: pop @state;
2453: }
2454: }
2455: return 'ok';
2456: }
2457:
2458: sub add_filetype {
2459: my ($allfiles,$file,$type)=@_;
2460: if (exists($allfiles->{$file})) {
2461: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2462: push(@{$allfiles->{$file}}, &escape($type));
2463: }
2464: } else {
2465: @{$allfiles->{$file}} = (&escape($type));
2466: }
2467: }
2468:
2469: sub removeuploadedurl {
2470: my ($url)=@_;
2471: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
2472: return &removeuserfile($uname,$udom,$fname);
2473: }
2474:
2475: sub removeuserfile {
2476: my ($docuname,$docudom,$fname)=@_;
2477: my $home=&homeserver($docuname,$docudom);
2478: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
2479: if ($result eq 'ok') {
2480: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2481: my $metafile = $fname.'.meta';
2482: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
2483: my $url = "/uploaded/$docudom/$docuname/$fname";
2484: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
2485: my $sqlresult =
2486: &update_portfolio_table($docuname,$docudom,$file,
2487: 'portfolio_metadata',$group,
2488: 'delete');
2489: }
2490: }
2491: return $result;
2492: }
2493:
2494: sub mkdiruserfile {
2495: my ($docuname,$docudom,$dir)=@_;
2496: my $home=&homeserver($docuname,$docudom);
2497: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2498: }
2499:
2500: sub renameuserfile {
2501: my ($docuname,$docudom,$old,$new)=@_;
2502: my $home=&homeserver($docuname,$docudom);
2503: my $result = &reply("renameuserfile:$docudom:$docuname:".
2504: &escape("$old").':'.&escape("$new"),$home);
2505: if ($result eq 'ok') {
2506: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2507: my $oldmeta = $old.'.meta';
2508: my $newmeta = $new.'.meta';
2509: my $metaresult =
2510: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
2511: my $url = "/uploaded/$docudom/$docuname/$old";
2512: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
2513: my $sqlresult =
2514: &update_portfolio_table($docuname,$docudom,$file,
2515: 'portfolio_metadata',$group,
2516: 'delete');
2517: }
2518: }
2519: return $result;
2520: }
2521:
2522: # ------------------------------------------------------------------------- Log
2523:
2524: sub log {
2525: my ($dom,$nam,$hom,$what)=@_;
2526: return critical("log:$dom:$nam:$what",$hom);
2527: }
2528:
2529: # ------------------------------------------------------------------ Course Log
2530: #
2531: # This routine flushes several buffers of non-mission-critical nature
2532: #
2533:
2534: sub flushcourselogs {
2535: &logthis('Flushing log buffers');
2536: #
2537: # course logs
2538: # This is a log of all transactions in a course, which can be used
2539: # for data mining purposes
2540: #
2541: # It also collects the courseid database, which lists last transaction
2542: # times and course titles for all courseids
2543: #
2544: my %courseidbuffer=();
2545: foreach my $crsid (keys(%courselogs)) {
2546: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
2547: &escape($courselogs{$crsid}),
2548: $coursehombuf{$crsid}) eq 'ok') {
2549: delete $courselogs{$crsid};
2550: } else {
2551: &logthis('Failed to flush log buffer for '.$crsid);
2552: if (length($courselogs{$crsid})>40000) {
2553: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
2554: " exceeded maximum size, deleting.</font>");
2555: delete $courselogs{$crsid};
2556: }
2557: }
2558: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
2559: 'description' => $coursedescrbuf{$crsid},
2560: 'inst_code' => $courseinstcodebuf{$crsid},
2561: 'type' => $coursetypebuf{$crsid},
2562: 'owner' => $courseownerbuf{$crsid},
2563: };
2564: }
2565: #
2566: # Write course id database (reverse lookup) to homeserver of courses
2567: # Is used in pickcourse
2568: #
2569: foreach my $crs_home (keys(%courseidbuffer)) {
2570: my $response = &courseidput(&host_domain($crs_home),
2571: $courseidbuffer{$crs_home},
2572: $crs_home,'timeonly');
2573: }
2574: #
2575: # File accesses
2576: # Writes to the dynamic metadata of resources to get hit counts, etc.
2577: #
2578: foreach my $entry (keys(%accesshash)) {
2579: if ($entry =~ /___count$/) {
2580: my ($dom,$name);
2581: ($dom,$name,undef)=
2582: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
2583: if (! defined($dom) || $dom eq '' ||
2584: ! defined($name) || $name eq '') {
2585: my $cid = $env{'request.course.id'};
2586: $dom = $env{'request.'.$cid.'.domain'};
2587: $name = $env{'request.'.$cid.'.num'};
2588: }
2589: my $value = $accesshash{$entry};
2590: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2591: my %temphash=($url => $value);
2592: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2593: if ($result eq 'ok') {
2594: delete $accesshash{$entry};
2595: } elsif ($result eq 'unknown_cmd') {
2596: # Target server has old code running on it.
2597: my %temphash=($entry => $value);
2598: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2599: delete $accesshash{$entry};
2600: }
2601: }
2602: } else {
2603: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
2604: my %temphash=($entry => $accesshash{$entry});
2605: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2606: delete $accesshash{$entry};
2607: }
2608: }
2609: }
2610: #
2611: # Roles
2612: # Reverse lookup of user roles for course faculty/staff and co-authorship
2613: #
2614: foreach my $entry (keys(%userrolehash)) {
2615: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
2616: split(/\:/,$entry);
2617: if (&Apache::lonnet::put('nohist_userroles',
2618: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
2619: $rudom,$runame) eq 'ok') {
2620: delete $userrolehash{$entry};
2621: }
2622: }
2623: #
2624: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2625: #
2626: my %domrolebuffer = ();
2627: foreach my $entry (keys(%domainrolehash)) {
2628: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
2629: if ($domrolebuffer{$rudom}) {
2630: $domrolebuffer{$rudom}.='&'.&escape($entry).
2631: '='.&escape($domainrolehash{$entry});
2632: } else {
2633: $domrolebuffer{$rudom}.=&escape($entry).
2634: '='.&escape($domainrolehash{$entry});
2635: }
2636: delete $domainrolehash{$entry};
2637: }
2638: foreach my $dom (keys(%domrolebuffer)) {
2639: my %servers = &get_servers($dom,'library');
2640: foreach my $tryserver (keys(%servers)) {
2641: unless (&reply('domroleput:'.$dom.':'.
2642: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2643: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2644: }
2645: }
2646: }
2647: $dumpcount++;
2648: }
2649:
2650: sub courselog {
2651: my $what=shift;
2652: $what=time.':'.$what;
2653: unless ($env{'request.course.id'}) { return ''; }
2654: $coursedombuf{$env{'request.course.id'}}=
2655: $env{'course.'.$env{'request.course.id'}.'.domain'};
2656: $coursenumbuf{$env{'request.course.id'}}=
2657: $env{'course.'.$env{'request.course.id'}.'.num'};
2658: $coursehombuf{$env{'request.course.id'}}=
2659: $env{'course.'.$env{'request.course.id'}.'.home'};
2660: $coursedescrbuf{$env{'request.course.id'}}=
2661: $env{'course.'.$env{'request.course.id'}.'.description'};
2662: $courseinstcodebuf{$env{'request.course.id'}}=
2663: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2664: $courseownerbuf{$env{'request.course.id'}}=
2665: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
2666: $coursetypebuf{$env{'request.course.id'}}=
2667: $env{'course.'.$env{'request.course.id'}.'.type'};
2668: if (defined $courselogs{$env{'request.course.id'}}) {
2669: $courselogs{$env{'request.course.id'}}.='&'.$what;
2670: } else {
2671: $courselogs{$env{'request.course.id'}}.=$what;
2672: }
2673: if (length($courselogs{$env{'request.course.id'}})>4048) {
2674: &flushcourselogs();
2675: }
2676: }
2677:
2678: sub courseacclog {
2679: my $fnsymb=shift;
2680: unless ($env{'request.course.id'}) { return ''; }
2681: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
2682: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
2683: $what.=':POST';
2684: # FIXME: Probably ought to escape things....
2685: foreach my $key (keys(%env)) {
2686: if ($key=~/^form\.(.*)/) {
2687: my $formitem = $1;
2688: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2689: $what.=':'.$formitem.'='.$env{$key};
2690: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2691: $what.=':'.$formitem.'='.$env{$key};
2692: }
2693: }
2694: }
2695: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2696: # FIXME: We should not be depending on a form parameter that someone
2697: # editing lonsearchcat.pm might change in the future.
2698: if ($env{'form.phase'} eq 'course_search') {
2699: $what.= ':POST';
2700: # FIXME: Probably ought to escape things....
2701: foreach my $element ('courseexp','crsfulltext','crsrelated',
2702: 'crsdiscuss') {
2703: $what.=':'.$element.'='.$env{'form.'.$element};
2704: }
2705: }
2706: }
2707: &courselog($what);
2708: }
2709:
2710: sub countacc {
2711: my $url=&declutter(shift);
2712: return if (! defined($url) || $url eq '');
2713: unless ($env{'request.course.id'}) { return ''; }
2714: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
2715: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
2716: $accesshash{$key}++;
2717: }
2718:
2719: sub linklog {
2720: my ($from,$to)=@_;
2721: $from=&declutter($from);
2722: $to=&declutter($to);
2723: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2724: $accesshash{$to.'___'.$from.'___goto'}=1;
2725: }
2726:
2727: sub userrolelog {
2728: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
2729: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
2730: ($trole=~/^in/) || ($trole=~/^cc/) ||
2731: ($trole=~/^ep/) || ($trole=~/^cr/) ||
2732: ($trole=~/^ta/)) {
2733: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2734: $userrolehash
2735: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2736: =$tend.':'.$tstart;
2737: }
2738: if (($env{'request.role'} =~ /dc\./) &&
2739: (($trole=~/^au/) || ($trole=~/^in/) ||
2740: ($trole=~/^cc/) || ($trole=~/^ep/) ||
2741: ($trole=~/^cr/) || ($trole=~/^ta/))) {
2742: $userrolehash
2743: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2744: =$tend.':'.$tstart;
2745: }
2746: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2747: ($trole=~/^li/) || ($trole=~/^li/) ||
2748: ($trole=~/^au/) || ($trole=~/^dg/) ||
2749: ($trole=~/^sc/)) {
2750: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2751: $domainrolehash
2752: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2753: = $tend.':'.$tstart;
2754: }
2755: }
2756:
2757: sub courserolelog {
2758: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
2759: if (($trole eq 'cc') || ($trole eq 'in') ||
2760: ($trole eq 'ep') || ($trole eq 'ad') ||
2761: ($trole eq 'ta') || ($trole eq 'st') ||
2762: ($trole=~/^cr/) || ($trole eq 'gr')) {
2763: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
2764: my $cdom = $1;
2765: my $cnum = $2;
2766: my $sec = $3;
2767: my $namespace = 'rolelog';
2768: my %storehash = (
2769: role => $trole,
2770: start => $tstart,
2771: end => $tend,
2772: selfenroll => $selfenroll,
2773: context => $context,
2774: );
2775: if ($trole eq 'gr') {
2776: $namespace = 'groupslog';
2777: $storehash{'group'} = $sec;
2778: } else {
2779: $storehash{'section'} = $sec;
2780: }
2781: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
2782: if (($trole ne 'st') || ($sec ne '')) {
2783: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
2784: }
2785: }
2786: }
2787: return;
2788: }
2789:
2790: sub get_course_adv_roles {
2791: my ($cid,$codes) = @_;
2792: $cid=$env{'request.course.id'} unless (defined($cid));
2793: my %coursehash=&coursedescription($cid);
2794: my $crstype = &Apache::loncommon::course_type($cid);
2795: my %nothide=();
2796: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2797: if ($user !~ /:/) {
2798: $nothide{join(':',split(/[\@]/,$user))}=1;
2799: } else {
2800: $nothide{$user}=1;
2801: }
2802: }
2803: my %returnhash=();
2804: my %dumphash=
2805: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2806: my $now=time;
2807: my %privileged;
2808: foreach my $entry (keys(%dumphash)) {
2809: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2810: if (($tstart) && ($tstart<0)) { next; }
2811: if (($tend) && ($tend<$now)) { next; }
2812: if (($tstart) && ($now<$tstart)) { next; }
2813: my ($role,$username,$domain,$section)=split(/\:/,$entry);
2814: if ($username eq '' || $domain eq '') { next; }
2815: unless (ref($privileged{$domain}) eq 'HASH') {
2816: my %dompersonnel =
2817: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
2818: $privileged{$domain} = {};
2819: foreach my $server (keys(%dompersonnel)) {
2820: if (ref($dompersonnel{$server}) eq 'HASH') {
2821: foreach my $user (keys(%{$dompersonnel{$server}})) {
2822: my ($trole,$uname,$udom) = split(/:/,$user);
2823: $privileged{$udom}{$uname} = 1;
2824: }
2825: }
2826: }
2827: }
2828: if ((exists($privileged{$domain}{$username})) &&
2829: (!$nothide{$username.':'.$domain})) { next; }
2830: if ($role eq 'cr') { next; }
2831: if ($codes) {
2832: if ($section) { $role .= ':'.$section; }
2833: if ($returnhash{$role}) {
2834: $returnhash{$role}.=','.$username.':'.$domain;
2835: } else {
2836: $returnhash{$role}=$username.':'.$domain;
2837: }
2838: } else {
2839: my $key=&plaintext($role,$crstype);
2840: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
2841: if ($returnhash{$key}) {
2842: $returnhash{$key}.=','.$username.':'.$domain;
2843: } else {
2844: $returnhash{$key}=$username.':'.$domain;
2845: }
2846: }
2847: }
2848: return %returnhash;
2849: }
2850:
2851: sub get_my_roles {
2852: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
2853: unless (defined($uname)) { $uname=$env{'user.name'}; }
2854: unless (defined($udom)) { $udom=$env{'user.domain'}; }
2855: my (%dumphash,%nothide);
2856: if ($context eq 'userroles') {
2857: %dumphash = &dump('roles',$udom,$uname);
2858: } else {
2859: %dumphash=
2860: &dump('nohist_userroles',$udom,$uname);
2861: if ($hidepriv) {
2862: my %coursehash=&coursedescription($udom.'_'.$uname);
2863: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2864: if ($user !~ /:/) {
2865: $nothide{join(':',split(/[\@]/,$user))} = 1;
2866: } else {
2867: $nothide{$user} = 1;
2868: }
2869: }
2870: }
2871: }
2872: my %returnhash=();
2873: my $now=time;
2874: my %privileged;
2875: foreach my $entry (keys(%dumphash)) {
2876: my ($role,$tend,$tstart);
2877: if ($context eq 'userroles') {
2878: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
2879: } else {
2880: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2881: }
2882: if (($tstart) && ($tstart<0)) { next; }
2883: my $status = 'active';
2884: if (($tend) && ($tend<=$now)) {
2885: $status = 'previous';
2886: }
2887: if (($tstart) && ($now<$tstart)) {
2888: $status = 'future';
2889: }
2890: if (ref($types) eq 'ARRAY') {
2891: if (!grep(/^\Q$status\E$/,@{$types})) {
2892: next;
2893: }
2894: } else {
2895: if ($status ne 'active') {
2896: next;
2897: }
2898: }
2899: my ($rolecode,$username,$domain,$section,$area);
2900: if ($context eq 'userroles') {
2901: ($area,$rolecode) = split(/_/,$entry);
2902: (undef,$domain,$username,$section) = split(/\//,$area);
2903: } else {
2904: ($role,$username,$domain,$section) = split(/\:/,$entry);
2905: }
2906: if (ref($roledoms) eq 'ARRAY') {
2907: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
2908: next;
2909: }
2910: }
2911: if (ref($roles) eq 'ARRAY') {
2912: if (!grep(/^\Q$role\E$/,@{$roles})) {
2913: if ($role =~ /^cr\//) {
2914: if (!grep(/^cr$/,@{$roles})) {
2915: next;
2916: }
2917: } else {
2918: next;
2919: }
2920: }
2921: }
2922: if ($hidepriv) {
2923: if ($context eq 'userroles') {
2924: if ((&privileged($username,$domain)) &&
2925: (!$nothide{$username.':'.$domain})) {
2926: next;
2927: }
2928: } else {
2929: unless (ref($privileged{$domain}) eq 'HASH') {
2930: my %dompersonnel =
2931: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
2932: $privileged{$domain} = {};
2933: if (keys(%dompersonnel)) {
2934: foreach my $server (keys(%dompersonnel)) {
2935: if (ref($dompersonnel{$server}) eq 'HASH') {
2936: foreach my $user (keys(%{$dompersonnel{$server}})) {
2937: my ($trole,$uname,$udom) = split(/:/,$user);
2938: $privileged{$udom}{$uname} = $trole;
2939: }
2940: }
2941: }
2942: }
2943: }
2944: if (exists($privileged{$domain}{$username})) {
2945: if (!$nothide{$username.':'.$domain}) {
2946: next;
2947: }
2948: }
2949: }
2950: }
2951: if ($withsec) {
2952: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
2953: $tstart.':'.$tend;
2954: } else {
2955: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
2956: }
2957: }
2958: return %returnhash;
2959: }
2960:
2961: # ----------------------------------------------------- Frontpage Announcements
2962: #
2963: #
2964:
2965: sub postannounce {
2966: my ($server,$text)=@_;
2967: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
2968: unless ($text=~/\w/) { $text=''; }
2969: return &reply('setannounce:'.&escape($text),$server);
2970: }
2971:
2972: sub getannounce {
2973:
2974: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
2975: my $announcement='';
2976: while (my $line = <$fh>) { $announcement .= $line; }
2977: close($fh);
2978: if ($announcement=~/\w/) {
2979: return
2980: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
2981: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
2982: } else {
2983: return '';
2984: }
2985: } else {
2986: return '';
2987: }
2988: }
2989:
2990: # ---------------------------------------------------------- Course ID routines
2991: # Deal with domain's nohist_courseid.db files
2992: #
2993:
2994: sub courseidput {
2995: my ($domain,$storehash,$coursehome,$caller) = @_;
2996: my $outcome;
2997: if ($caller eq 'timeonly') {
2998: my $cids = '';
2999: foreach my $item (keys(%$storehash)) {
3000: $cids.=&escape($item).'&';
3001: }
3002: $cids=~s/\&$//;
3003: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3004: $coursehome);
3005: } else {
3006: my $items = '';
3007: foreach my $item (keys(%$storehash)) {
3008: $items.= &escape($item).'='.
3009: &freeze_escape($$storehash{$item}).'&';
3010: }
3011: $items=~s/\&$//;
3012: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3013: $coursehome);
3014: }
3015: if ($outcome eq 'unknown_cmd') {
3016: my $what;
3017: foreach my $cid (keys(%$storehash)) {
3018: $what .= &escape($cid).'=';
3019: foreach my $item ('description','inst_code','owner','type') {
3020: $what .= &escape($storehash->{$cid}{$item}).':';
3021: }
3022: $what =~ s/\:$/&/;
3023: }
3024: $what =~ s/\&$//;
3025: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3026: } else {
3027: return $outcome;
3028: }
3029: }
3030:
3031: sub courseiddump {
3032: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
3033: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
3034: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
3035: $cloneonly,$createdbefore,$createdafter,$creationcontext)=@_;
3036: my $as_hash = 1;
3037: my %returnhash;
3038: if (!$domfilter) { $domfilter=''; }
3039: my %libserv = &all_library();
3040: foreach my $tryserver (keys(%libserv)) {
3041: if ( ( $hostidflag == 1
3042: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3043: || (!defined($hostidflag)) ) {
3044:
3045: if (($domfilter eq '') ||
3046: (&host_domain($tryserver) eq $domfilter)) {
3047: my $rep =
3048: &reply('courseiddump:'.&host_domain($tryserver).':'.
3049: $sincefilter.':'.&escape($descfilter).':'.
3050: &escape($instcodefilter).':'.&escape($ownerfilter).
3051: ':'.&escape($coursefilter).':'.&escape($typefilter).
3052: ':'.&escape($regexp_ok).':'.$as_hash.':'.
3053: &escape($selfenrollonly).':'.&escape($catfilter).':'.
3054: $showhidden.':'.$caller.':'.&escape($cloner).':'.
3055: &escape($cc_clone).':'.$cloneonly.':'.
3056: &escape($createdbefore).':'.&escape($createdafter).':'.
3057: &escape($creationcontext),$tryserver);
3058: my @pairs=split(/\&/,$rep);
3059: foreach my $item (@pairs) {
3060: my ($key,$value)=split(/\=/,$item,2);
3061: $key = &unescape($key);
3062: next if ($key =~ /^error: 2 /);
3063: my $result = &thaw_unescape($value);
3064: if (ref($result) eq 'HASH') {
3065: $returnhash{$key}=$result;
3066: } else {
3067: my @responses = split(/:/,$value);
3068: my @items = ('description','inst_code','owner','type');
3069: for (my $i=0; $i<@responses; $i++) {
3070: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
3071: }
3072: }
3073: }
3074: }
3075: }
3076: }
3077: return %returnhash;
3078: }
3079:
3080: # ---------------------------------------------------------- DC e-mail
3081:
3082: sub dcmailput {
3083: my ($domain,$msgid,$message,$server)=@_;
3084: my $status = &Apache::lonnet::critical(
3085: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3086: &escape($message),$server);
3087: return $status;
3088: }
3089:
3090: sub dcmaildump {
3091: my ($dom,$startdate,$enddate,$senders) = @_;
3092: my %returnhash=();
3093:
3094: if (defined(&domain($dom,'primary'))) {
3095: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3096: &escape($enddate).':';
3097: my @esc_senders=map { &escape($_)} @$senders;
3098: $cmd.=&escape(join('&',@esc_senders));
3099: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
3100: my ($key,$value) = split(/\=/,$line,2);
3101: if (($key) && ($value)) {
3102: $returnhash{&unescape($key)} = &unescape($value);
3103: }
3104: }
3105: }
3106: return %returnhash;
3107: }
3108: # ---------------------------------------------------------- Domain roles
3109:
3110: sub get_domain_roles {
3111: my ($dom,$roles,$startdate,$enddate)=@_;
3112: if ((!defined($startdate)) || ($startdate eq '')) {
3113: $startdate = '.';
3114: }
3115: if ((!defined($enddate)) || ($enddate eq '')) {
3116: $enddate = '.';
3117: }
3118: my $rolelist;
3119: if (ref($roles) eq 'ARRAY') {
3120: $rolelist = join(':',@{$roles});
3121: }
3122: my %personnel = ();
3123:
3124: my %servers = &get_servers($dom,'library');
3125: foreach my $tryserver (keys(%servers)) {
3126: %{$personnel{$tryserver}}=();
3127: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3128: &escape($startdate).':'.
3129: &escape($enddate).':'.
3130: &escape($rolelist), $tryserver))) {
3131: my ($key,$value) = split(/\=/,$line,2);
3132: if (($key) && ($value)) {
3133: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3134: }
3135: }
3136: }
3137: return %personnel;
3138: }
3139:
3140: # ----------------------------------------------------------- Check out an item
3141:
3142: sub get_first_access {
3143: my ($type,$argsymb)=@_;
3144: my ($symb,$courseid,$udom,$uname)=&whichuser();
3145: if ($argsymb) { $symb=$argsymb; }
3146: my ($map,$id,$res)=&decode_symb($symb);
3147: if ($type eq 'course') {
3148: $res='course';
3149: } elsif ($type eq 'map') {
3150: $res=&symbread($map);
3151: } else {
3152: $res=$symb;
3153: }
3154: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3155: return $times{"$courseid\0$res"};
3156: }
3157:
3158: sub set_first_access {
3159: my ($type)=@_;
3160: my ($symb,$courseid,$udom,$uname)=&whichuser();
3161: my ($map,$id,$res)=&decode_symb($symb);
3162: if ($type eq 'course') {
3163: $res='course';
3164: } elsif ($type eq 'map') {
3165: $res=&symbread($map);
3166: } else {
3167: $res=$symb;
3168: }
3169: my $firstaccess=&get_first_access($type,$symb);
3170: if (!$firstaccess) {
3171: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
3172: }
3173: return 'already_set';
3174: }
3175:
3176: sub checkout {
3177: my ($symb,$tuname,$tudom,$tcrsid)=@_;
3178: my $now=time;
3179: my $lonhost=$perlvar{'lonHostID'};
3180: my $infostr=&escape(
3181: 'CHECKOUTTOKEN&'.
3182: $tuname.'&'.
3183: $tudom.'&'.
3184: $tcrsid.'&'.
3185: $symb.'&'.
3186: $now.'&'.$ENV{'REMOTE_ADDR'});
3187: my $token=&reply('tmpput:'.$infostr,$lonhost);
3188: if ($token=~/^error\:/) {
3189: &logthis("<font color=\"blue\">WARNING: ".
3190: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
3191: "</font>");
3192: return '';
3193: }
3194:
3195: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
3196: $token=~tr/a-z/A-Z/;
3197:
3198: my %infohash=('resource.0.outtoken' => $token,
3199: 'resource.0.checkouttime' => $now,
3200: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
3201:
3202: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3203: return '';
3204: } else {
3205: &logthis("<font color=\"blue\">WARNING: ".
3206: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
3207: "</font>");
3208: }
3209:
3210: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3211: &escape('Checkout '.$infostr.' - '.
3212: $token)) ne 'ok') {
3213: return '';
3214: } else {
3215: &logthis("<font color=\"blue\">WARNING: ".
3216: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
3217: "</font>");
3218: }
3219: return $token;
3220: }
3221:
3222: # ------------------------------------------------------------ Check in an item
3223:
3224: sub checkin {
3225: my $token=shift;
3226: my $now=time;
3227: my ($ta,$tb,$lonhost)=split(/\*/,$token);
3228: $lonhost=~tr/A-Z/a-z/;
3229: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
3230: $dtoken=~s/\W/\_/g;
3231: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
3232: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
3233:
3234: unless (($tuname) && ($tudom)) {
3235: &logthis('Check in '.$token.' ('.$dtoken.') failed');
3236: return '';
3237: }
3238:
3239: unless (&allowed('mgr',$tcrsid)) {
3240: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
3241: $env{'user.name'}.' - '.$env{'user.domain'});
3242: return '';
3243: }
3244:
3245: my %infohash=('resource.0.intoken' => $token,
3246: 'resource.0.checkintime' => $now,
3247: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
3248:
3249: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3250: return '';
3251: }
3252:
3253: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3254: &escape('Checkin - '.$token)) ne 'ok') {
3255: return '';
3256: }
3257:
3258: return ($symb,$tuname,$tudom,$tcrsid);
3259: }
3260:
3261: # --------------------------------------------- Set Expire Date for Spreadsheet
3262:
3263: sub expirespread {
3264: my ($uname,$udom,$stype,$usymb)=@_;
3265: my $cid=$env{'request.course.id'};
3266: if ($cid) {
3267: my $now=time;
3268: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
3269: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3270: $env{'course.'.$cid.'.num'}.
3271: ':nohist_expirationdates:'.
3272: &escape($key).'='.$now,
3273: $env{'course.'.$cid.'.home'})
3274: }
3275: return 'ok';
3276: }
3277:
3278: # ----------------------------------------------------- Devalidate Spreadsheets
3279:
3280: sub devalidate {
3281: my ($symb,$uname,$udom)=@_;
3282: my $cid=$env{'request.course.id'};
3283: if ($cid) {
3284: # delete the stored spreadsheets for
3285: # - the student level sheet of this user in course's homespace
3286: # - the assessment level sheet for this resource
3287: # for this user in user's homespace
3288: # - current conditional state info
3289: my $key=$uname.':'.$udom.':';
3290: my $status=
3291: &del('nohist_calculatedsheets',
3292: [$key.'studentcalc:'],
3293: $env{'course.'.$cid.'.domain'},
3294: $env{'course.'.$cid.'.num'})
3295: .' '.
3296: &del('nohist_calculatedsheets_'.$cid,
3297: [$key.'assesscalc:'.$symb],$udom,$uname);
3298: unless ($status eq 'ok ok') {
3299: &logthis('Could not devalidate spreadsheet '.
3300: $uname.' at '.$udom.' for '.
3301: $symb.': '.$status);
3302: }
3303: &delenv('user.state.'.$cid);
3304: }
3305: }
3306:
3307: sub get_scalar {
3308: my ($string,$end) = @_;
3309: my $value;
3310: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3311: $value = $1;
3312: } elsif ($$string =~ s/^([^&]*?)&//) {
3313: $value = $1;
3314: }
3315: return &unescape($value);
3316: }
3317:
3318: sub array2str {
3319: my (@array) = @_;
3320: my $result=&arrayref2str(\@array);
3321: $result=~s/^__ARRAY_REF__//;
3322: $result=~s/__END_ARRAY_REF__$//;
3323: return $result;
3324: }
3325:
3326: sub arrayref2str {
3327: my ($arrayref) = @_;
3328: my $result='__ARRAY_REF__';
3329: foreach my $elem (@$arrayref) {
3330: if(ref($elem) eq 'ARRAY') {
3331: $result.=&arrayref2str($elem).'&';
3332: } elsif(ref($elem) eq 'HASH') {
3333: $result.=&hashref2str($elem).'&';
3334: } elsif(ref($elem)) {
3335: #print("Got a ref of ".(ref($elem))." skipping.");
3336: } else {
3337: $result.=&escape($elem).'&';
3338: }
3339: }
3340: $result=~s/\&$//;
3341: $result .= '__END_ARRAY_REF__';
3342: return $result;
3343: }
3344:
3345: sub hash2str {
3346: my (%hash) = @_;
3347: my $result=&hashref2str(\%hash);
3348: $result=~s/^__HASH_REF__//;
3349: $result=~s/__END_HASH_REF__$//;
3350: return $result;
3351: }
3352:
3353: sub hashref2str {
3354: my ($hashref)=@_;
3355: my $result='__HASH_REF__';
3356: foreach my $key (sort(keys(%$hashref))) {
3357: if (ref($key) eq 'ARRAY') {
3358: $result.=&arrayref2str($key).'=';
3359: } elsif (ref($key) eq 'HASH') {
3360: $result.=&hashref2str($key).'=';
3361: } elsif (ref($key)) {
3362: $result.='=';
3363: #print("Got a ref of ".(ref($key))." skipping.");
3364: } else {
3365: if ($key) {$result.=&escape($key).'=';} else { last; }
3366: }
3367:
3368: if(ref($hashref->{$key}) eq 'ARRAY') {
3369: $result.=&arrayref2str($hashref->{$key}).'&';
3370: } elsif(ref($hashref->{$key}) eq 'HASH') {
3371: $result.=&hashref2str($hashref->{$key}).'&';
3372: } elsif(ref($hashref->{$key})) {
3373: $result.='&';
3374: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
3375: } else {
3376: $result.=&escape($hashref->{$key}).'&';
3377: }
3378: }
3379: $result=~s/\&$//;
3380: $result .= '__END_HASH_REF__';
3381: return $result;
3382: }
3383:
3384: sub str2hash {
3385: my ($string)=@_;
3386: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3387: return %$hash;
3388: }
3389:
3390: sub str2hashref {
3391: my ($string) = @_;
3392:
3393: my %hash;
3394:
3395: if($string !~ /^__HASH_REF__/) {
3396: if (! ($string eq '' || !defined($string))) {
3397: $hash{'error'}='Not hash reference';
3398: }
3399: return (\%hash, $string);
3400: }
3401:
3402: $string =~ s/^__HASH_REF__//;
3403:
3404: while($string !~ /^__END_HASH_REF__/) {
3405: #key
3406: my $key='';
3407: if($string =~ /^__HASH_REF__/) {
3408: ($key, $string)=&str2hashref($string);
3409: if(defined($key->{'error'})) {
3410: $hash{'error'}='Bad data';
3411: return (\%hash, $string);
3412: }
3413: } elsif($string =~ /^__ARRAY_REF__/) {
3414: ($key, $string)=&str2arrayref($string);
3415: if($key->[0] eq 'Array reference error') {
3416: $hash{'error'}='Bad data';
3417: return (\%hash, $string);
3418: }
3419: } else {
3420: $string =~ s/^(.*?)=//;
3421: $key=&unescape($1);
3422: }
3423: $string =~ s/^=//;
3424:
3425: #value
3426: my $value='';
3427: if($string =~ /^__HASH_REF__/) {
3428: ($value, $string)=&str2hashref($string);
3429: if(defined($value->{'error'})) {
3430: $hash{'error'}='Bad data';
3431: return (\%hash, $string);
3432: }
3433: } elsif($string =~ /^__ARRAY_REF__/) {
3434: ($value, $string)=&str2arrayref($string);
3435: if($value->[0] eq 'Array reference error') {
3436: $hash{'error'}='Bad data';
3437: return (\%hash, $string);
3438: }
3439: } else {
3440: $value=&get_scalar(\$string,'__END_HASH_REF__');
3441: }
3442: $string =~ s/^&//;
3443:
3444: $hash{$key}=$value;
3445: }
3446:
3447: $string =~ s/^__END_HASH_REF__//;
3448:
3449: return (\%hash, $string);
3450: }
3451:
3452: sub str2array {
3453: my ($string)=@_;
3454: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3455: return @$array;
3456: }
3457:
3458: sub str2arrayref {
3459: my ($string) = @_;
3460: my @array;
3461:
3462: if($string !~ /^__ARRAY_REF__/) {
3463: if (! ($string eq '' || !defined($string))) {
3464: $array[0]='Array reference error';
3465: }
3466: return (\@array, $string);
3467: }
3468:
3469: $string =~ s/^__ARRAY_REF__//;
3470:
3471: while($string !~ /^__END_ARRAY_REF__/) {
3472: my $value='';
3473: if($string =~ /^__HASH_REF__/) {
3474: ($value, $string)=&str2hashref($string);
3475: if(defined($value->{'error'})) {
3476: $array[0] ='Array reference error';
3477: return (\@array, $string);
3478: }
3479: } elsif($string =~ /^__ARRAY_REF__/) {
3480: ($value, $string)=&str2arrayref($string);
3481: if($value->[0] eq 'Array reference error') {
3482: $array[0] ='Array reference error';
3483: return (\@array, $string);
3484: }
3485: } else {
3486: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3487: }
3488: $string =~ s/^&//;
3489:
3490: push(@array, $value);
3491: }
3492:
3493: $string =~ s/^__END_ARRAY_REF__//;
3494:
3495: return (\@array, $string);
3496: }
3497:
3498: # -------------------------------------------------------------------Temp Store
3499:
3500: sub tmpreset {
3501: my ($symb,$namespace,$domain,$stuname) = @_;
3502: if (!$symb) {
3503: $symb=&symbread();
3504: if (!$symb) { $symb= $env{'request.url'}; }
3505: }
3506: $symb=escape($symb);
3507:
3508: if (!$namespace) { $namespace=$env{'request.state'}; }
3509: $namespace=~s/\//\_/g;
3510: $namespace=~s/\W//g;
3511:
3512: if (!$domain) { $domain=$env{'user.domain'}; }
3513: if (!$stuname) { $stuname=$env{'user.name'}; }
3514: if ($domain eq 'public' && $stuname eq 'public') {
3515: $stuname=$ENV{'REMOTE_ADDR'};
3516: }
3517: my $path=$perlvar{'lonDaemons'}.'/tmp';
3518: my %hash;
3519: if (tie(%hash,'GDBM_File',
3520: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
3521: &GDBM_WRCREAT(),0640)) {
3522: foreach my $key (keys(%hash)) {
3523: if ($key=~ /:$symb/) {
3524: delete($hash{$key});
3525: }
3526: }
3527: }
3528: }
3529:
3530: sub tmpstore {
3531: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3532:
3533: if (!$symb) {
3534: $symb=&symbread();
3535: if (!$symb) { $symb= $env{'request.url'}; }
3536: }
3537: $symb=escape($symb);
3538:
3539: if (!$namespace) {
3540: # I don't think we would ever want to store this for a course.
3541: # it seems this will only be used if we don't have a course.
3542: #$namespace=$env{'request.course.id'};
3543: #if (!$namespace) {
3544: $namespace=$env{'request.state'};
3545: #}
3546: }
3547: $namespace=~s/\//\_/g;
3548: $namespace=~s/\W//g;
3549: if (!$domain) { $domain=$env{'user.domain'}; }
3550: if (!$stuname) { $stuname=$env{'user.name'}; }
3551: if ($domain eq 'public' && $stuname eq 'public') {
3552: $stuname=$ENV{'REMOTE_ADDR'};
3553: }
3554: my $now=time;
3555: my %hash;
3556: my $path=$perlvar{'lonDaemons'}.'/tmp';
3557: if (tie(%hash,'GDBM_File',
3558: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
3559: &GDBM_WRCREAT(),0640)) {
3560: $hash{"version:$symb"}++;
3561: my $version=$hash{"version:$symb"};
3562: my $allkeys='';
3563: foreach my $key (keys(%$storehash)) {
3564: $allkeys.=$key.':';
3565: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
3566: }
3567: $hash{"$version:$symb:timestamp"}=$now;
3568: $allkeys.='timestamp';
3569: $hash{"$version:keys:$symb"}=$allkeys;
3570: if (untie(%hash)) {
3571: return 'ok';
3572: } else {
3573: return "error:$!";
3574: }
3575: } else {
3576: return "error:$!";
3577: }
3578: }
3579:
3580: # -----------------------------------------------------------------Temp Restore
3581:
3582: sub tmprestore {
3583: my ($symb,$namespace,$domain,$stuname) = @_;
3584:
3585: if (!$symb) {
3586: $symb=&symbread();
3587: if (!$symb) { $symb= $env{'request.url'}; }
3588: }
3589: $symb=escape($symb);
3590:
3591: if (!$namespace) { $namespace=$env{'request.state'}; }
3592:
3593: if (!$domain) { $domain=$env{'user.domain'}; }
3594: if (!$stuname) { $stuname=$env{'user.name'}; }
3595: if ($domain eq 'public' && $stuname eq 'public') {
3596: $stuname=$ENV{'REMOTE_ADDR'};
3597: }
3598: my %returnhash;
3599: $namespace=~s/\//\_/g;
3600: $namespace=~s/\W//g;
3601: my %hash;
3602: my $path=$perlvar{'lonDaemons'}.'/tmp';
3603: if (tie(%hash,'GDBM_File',
3604: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
3605: &GDBM_READER(),0640)) {
3606: my $version=$hash{"version:$symb"};
3607: $returnhash{'version'}=$version;
3608: my $scope;
3609: for ($scope=1;$scope<=$version;$scope++) {
3610: my $vkeys=$hash{"$scope:keys:$symb"};
3611: my @keys=split(/:/,$vkeys);
3612: my $key;
3613: $returnhash{"$scope:keys"}=$vkeys;
3614: foreach $key (@keys) {
3615: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3616: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3617: }
3618: }
3619: if (!(untie(%hash))) {
3620: return "error:$!";
3621: }
3622: } else {
3623: return "error:$!";
3624: }
3625: return %returnhash;
3626: }
3627:
3628: # ----------------------------------------------------------------------- Store
3629:
3630: sub store {
3631: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3632: my $home='';
3633:
3634: if ($stuname) { $home=&homeserver($stuname,$domain); }
3635:
3636: $symb=&symbclean($symb);
3637: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
3638:
3639: if (!$domain) { $domain=$env{'user.domain'}; }
3640: if (!$stuname) { $stuname=$env{'user.name'}; }
3641:
3642: &devalidate($symb,$stuname,$domain);
3643:
3644: $symb=escape($symb);
3645: if (!$namespace) {
3646: unless ($namespace=$env{'request.course.id'}) {
3647: return '';
3648: }
3649: }
3650: if (!$home) { $home=$env{'user.home'}; }
3651:
3652: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3653: $$storehash{'host'}=$perlvar{'lonHostID'};
3654:
3655: my $namevalue='';
3656: foreach my $key (keys(%$storehash)) {
3657: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
3658: }
3659: $namevalue=~s/\&$//;
3660: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
3661: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
3662: }
3663:
3664: # -------------------------------------------------------------- Critical Store
3665:
3666: sub cstore {
3667: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3668: my $home='';
3669:
3670: if ($stuname) { $home=&homeserver($stuname,$domain); }
3671:
3672: $symb=&symbclean($symb);
3673: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
3674:
3675: if (!$domain) { $domain=$env{'user.domain'}; }
3676: if (!$stuname) { $stuname=$env{'user.name'}; }
3677:
3678: &devalidate($symb,$stuname,$domain);
3679:
3680: $symb=escape($symb);
3681: if (!$namespace) {
3682: unless ($namespace=$env{'request.course.id'}) {
3683: return '';
3684: }
3685: }
3686: if (!$home) { $home=$env{'user.home'}; }
3687:
3688: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3689: $$storehash{'host'}=$perlvar{'lonHostID'};
3690:
3691: my $namevalue='';
3692: foreach my $key (keys(%$storehash)) {
3693: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
3694: }
3695: $namevalue=~s/\&$//;
3696: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
3697: return critical
3698: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
3699: }
3700:
3701: # --------------------------------------------------------------------- Restore
3702:
3703: sub restore {
3704: my ($symb,$namespace,$domain,$stuname) = @_;
3705: my $home='';
3706:
3707: if ($stuname) { $home=&homeserver($stuname,$domain); }
3708:
3709: if (!$symb) {
3710: unless ($symb=escape(&symbread())) { return ''; }
3711: } else {
3712: $symb=&escape(&symbclean($symb));
3713: }
3714: if (!$namespace) {
3715: unless ($namespace=$env{'request.course.id'}) {
3716: return '';
3717: }
3718: }
3719: if (!$domain) { $domain=$env{'user.domain'}; }
3720: if (!$stuname) { $stuname=$env{'user.name'}; }
3721: if (!$home) { $home=$env{'user.home'}; }
3722: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3723:
3724: my %returnhash=();
3725: foreach my $line (split(/\&/,$answer)) {
3726: my ($name,$value)=split(/\=/,$line);
3727: $returnhash{&unescape($name)}=&thaw_unescape($value);
3728: }
3729: my $version;
3730: for ($version=1;$version<=$returnhash{'version'};$version++) {
3731: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3732: $returnhash{$item}=$returnhash{$version.':'.$item};
3733: }
3734: }
3735: return %returnhash;
3736: }
3737:
3738: # ---------------------------------------------------------- Course Description
3739:
3740: sub coursedescription {
3741: my ($courseid,$args)=@_;
3742: $courseid=~s/^\///;
3743: $courseid=~s/\_/\//g;
3744: my ($cdomain,$cnum)=split(/\//,$courseid);
3745: my $chome=&homeserver($cnum,$cdomain);
3746: my $normalid=$cdomain.'_'.$cnum;
3747: # need to always cache even if we get errors otherwise we keep
3748: # trying and trying and trying to get the course description.
3749: my %envhash=();
3750: my %returnhash=();
3751:
3752: my $expiretime=600;
3753: if ($env{'request.course.id'} eq $normalid) {
3754: $expiretime=120;
3755: }
3756:
3757: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3758: if (!$args->{'freshen_cache'}
3759: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3760: foreach my $key (keys(%env)) {
3761: next if ($key !~ /^\Q$prefix\E(.*)/);
3762: my ($setting) = $1;
3763: $returnhash{$setting} = $env{$key};
3764: }
3765: return %returnhash;
3766: }
3767:
3768: # get the data agin
3769: if (!$args->{'one_time'}) {
3770: $envhash{'course.'.$normalid.'.last_cache'}=time;
3771: }
3772:
3773: if ($chome ne 'no_host') {
3774: %returnhash=&dump('environment',$cdomain,$cnum);
3775: if (!exists($returnhash{'con_lost'})) {
3776: $returnhash{'home'}= $chome;
3777: $returnhash{'domain'} = $cdomain;
3778: $returnhash{'num'} = $cnum;
3779: if (!defined($returnhash{'type'})) {
3780: $returnhash{'type'} = 'Course';
3781: }
3782: while (my ($name,$value) = each %returnhash) {
3783: $envhash{'course.'.$normalid.'.'.$name}=$value;
3784: }
3785: $returnhash{'url'}=&clutter($returnhash{'url'});
3786: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
3787: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
3788: $envhash{'course.'.$normalid.'.home'}=$chome;
3789: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
3790: $envhash{'course.'.$normalid.'.num'}=$cnum;
3791: }
3792: }
3793: if (!$args->{'one_time'}) {
3794: &appenv(\%envhash);
3795: }
3796: return %returnhash;
3797: }
3798:
3799: # -------------------------------------------------See if a user is privileged
3800:
3801: sub privileged {
3802: my ($username,$domain)=@_;
3803: my $rolesdump=&reply("dump:$domain:$username:roles",
3804: &homeserver($username,$domain));
3805: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
3806: ($rolesdump =~ /^error:/)) {
3807: return 0;
3808: }
3809: my $now=time;
3810: if ($rolesdump ne '') {
3811: foreach my $entry (split(/&/,$rolesdump)) {
3812: if ($entry!~/^rolesdef_/) {
3813: my ($area,$role)=split(/=/,$entry);
3814: $area=~s/\_\w\w$//;
3815: my ($trole,$tend,$tstart)=split(/_/,$role);
3816: if (($trole eq 'dc') || ($trole eq 'su')) {
3817: my $active=1;
3818: if ($tend) {
3819: if ($tend<$now) { $active=0; }
3820: }
3821: if ($tstart) {
3822: if ($tstart>$now) { $active=0; }
3823: }
3824: if ($active) { return 1; }
3825: }
3826: }
3827: }
3828: }
3829: return 0;
3830: }
3831:
3832: # -------------------------------------------------------- Get user privileges
3833:
3834: sub rolesinit {
3835: my ($domain,$username,$authhost)=@_;
3836: my $now=time;
3837: my %userroles = ('user.login.time' => $now);
3838: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
3839: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
3840: ($rolesdump =~ /^error:/)) {
3841: return \%userroles;
3842: }
3843: my %allroles=();
3844: my %allgroups=();
3845: my $group_privs;
3846:
3847: if ($rolesdump ne '') {
3848: foreach my $entry (split(/&/,$rolesdump)) {
3849: if ($entry!~/^rolesdef_/) {
3850: my ($area,$role)=split(/=/,$entry);
3851: $area=~s/\_\w\w$//;
3852: my ($trole,$tend,$tstart,$group_privs);
3853: if ($role=~/^cr/) {
3854: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
3855: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
3856: ($tend,$tstart)=split('_',$trest);
3857: } else {
3858: $trole=$role;
3859: }
3860: } elsif ($role =~ m|^gr/|) {
3861: ($trole,$tend,$tstart) = split(/_/,$role);
3862: ($trole,$group_privs) = split(/\//,$trole);
3863: $group_privs = &unescape($group_privs);
3864: } else {
3865: ($trole,$tend,$tstart)=split(/_/,$role);
3866: }
3867: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
3868: $username);
3869: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
3870: if (($tend!=0) && ($tend<$now)) { $trole=''; }
3871: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
3872: if (($area ne '') && ($trole ne '')) {
3873: my $spec=$trole.'.'.$area;
3874: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
3875: if ($trole =~ /^cr\//) {
3876: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
3877: } elsif ($trole eq 'gr') {
3878: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
3879: } else {
3880: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
3881: }
3882: }
3883: }
3884: }
3885: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
3886: $userroles{'user.adv'} = $adv;
3887: $userroles{'user.author'} = $author;
3888: $env{'user.adv'}=$adv;
3889: }
3890: return \%userroles;
3891: }
3892:
3893: sub set_arearole {
3894: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
3895: # log the associated role with the area
3896: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
3897: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
3898: }
3899:
3900: sub custom_roleprivs {
3901: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
3902: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
3903: my $homsvr=homeserver($rauthor,$rdomain);
3904: if (&hostname($homsvr) ne '') {
3905: my ($rdummy,$roledef)=
3906: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
3907: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
3908: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
3909: if (defined($syspriv)) {
3910: $$allroles{'cm./'}.=':'.$syspriv;
3911: $$allroles{$spec.'./'}.=':'.$syspriv;
3912: }
3913: if ($tdomain ne '') {
3914: if (defined($dompriv)) {
3915: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
3916: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
3917: }
3918: if (($trest ne '') && (defined($coursepriv))) {
3919: $$allroles{'cm.'.$area}.=':'.$coursepriv;
3920: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
3921: }
3922: }
3923: }
3924: }
3925: }
3926:
3927: sub group_roleprivs {
3928: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
3929: my $access = 1;
3930: my $now = time;
3931: if (($tend!=0) && ($tend<$now)) { $access = 0; }
3932: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
3933: if ($access) {
3934: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
3935: $$allgroups{$course}{$group} .=':'.$group_privs;
3936: }
3937: }
3938:
3939: sub standard_roleprivs {
3940: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
3941: if (defined($pr{$trole.':s'})) {
3942: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
3943: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
3944: }
3945: if ($tdomain ne '') {
3946: if (defined($pr{$trole.':d'})) {
3947: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3948: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3949: }
3950: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
3951: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
3952: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
3953: }
3954: }
3955: }
3956:
3957: sub set_userprivs {
3958: my ($userroles,$allroles,$allgroups) = @_;
3959: my $author=0;
3960: my $adv=0;
3961: my %grouproles = ();
3962: if (keys(%{$allgroups}) > 0) {
3963: foreach my $role (keys(%{$allroles})) {
3964: my ($trole,$area,$sec,$extendedarea);
3965: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
3966: $trole = $1;
3967: $area = $2;
3968: $sec = $3;
3969: $extendedarea = $area.$sec;
3970: if (exists($$allgroups{$area})) {
3971: foreach my $group (keys(%{$$allgroups{$area}})) {
3972: my $spec = $trole.'.'.$extendedarea;
3973: $grouproles{$spec.'.'.$area.'/'.$group} =
3974: $$allgroups{$area}{$group};
3975: }
3976: }
3977: }
3978: }
3979: }
3980: foreach my $group (keys(%grouproles)) {
3981: $$allroles{$group} = $grouproles{$group};
3982: }
3983: foreach my $role (keys(%{$allroles})) {
3984: my %thesepriv;
3985: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
3986: foreach my $item (split(/:/,$$allroles{$role})) {
3987: if ($item ne '') {
3988: my ($privilege,$restrictions)=split(/&/,$item);
3989: if ($restrictions eq '') {
3990: $thesepriv{$privilege}='F';
3991: } elsif ($thesepriv{$privilege} ne 'F') {
3992: $thesepriv{$privilege}.=$restrictions;
3993: }
3994: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
3995: }
3996: }
3997: my $thesestr='';
3998: foreach my $priv (keys(%thesepriv)) {
3999: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4000: }
4001: $userroles->{'user.priv.'.$role} = $thesestr;
4002: }
4003: return ($author,$adv);
4004: }
4005:
4006: sub role_status {
4007: my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
4008: my @pwhere = ();
4009: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4010: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4011: unless (!defined($$role) || $$role eq '') {
4012: $$where=join('.',@pwhere);
4013: $$trolecode=$$role.'.'.$$where;
4014: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4015: $$tstatus='is';
4016: if ($$tstart && $$tstart>$then) {
4017: $$tstatus='future';
4018: if ($$tstart<$now) {
4019: if ($$tstart && $$tstart>$refresh) {
4020: if (($$where ne '') && ($$role ne '')) {
4021: my (%allroles,%allgroups,$group_privs);
4022: my %userroles = (
4023: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4024: );
4025: my $spec=$$role.'.'.$$where;
4026: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4027: if ($$role eq 'gr') {
4028: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4029: $env{'user.name'})=@_;
4030: my ($trole) = split('_',$role,1);
4031: (undef,my $group_privs) = split(/\//,$trole);
4032: $group_privs = &unescape($group_privs);
4033: }
4034: if ($$role =~ /^cr\//) {
4035: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
4036: } elsif ($$role eq 'gr') {
4037: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4038: $env{'user.name'});
4039: my $trole = split('_',$rolehash{$$where.'_'.$$role},1);
4040: (undef,my $group_privs) = split(/\//,$trole);
4041: $group_privs = &unescape($group_privs);
4042: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
4043: } else {
4044: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4045: }
4046: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups);
4047: &appenv(\%userroles,[$$role,'cm']);
4048: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4049: }
4050: }
4051: $$tstatus = 'is';
4052: }
4053: }
4054: if ($$tend) {
4055: if ($$tend<$then) {
4056: $$tstatus='expired';
4057: } elsif ($$tend<$now) {
4058: $$tstatus='will_not';
4059: }
4060: }
4061: }
4062: }
4063: }
4064:
4065: sub check_adhoc_privs {
4066: my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
4067: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4068: if ($env{$cckey}) {
4069: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
4070: &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
4071: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
4072: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4073: }
4074: } else {
4075: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4076: }
4077: }
4078:
4079: sub set_adhoc_privileges {
4080: # role can be cc or ca
4081: my ($dcdom,$pickedcourse,$role) = @_;
4082: my $area = '/'.$dcdom.'/'.$pickedcourse;
4083: my $spec = $role.'.'.$area;
4084: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4085: $env{'user.name'});
4086: my %ccrole = ();
4087: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4088: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4089: &appenv(\%userroles,[$role,'cm']);
4090: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4091: &appenv( {'request.role' => $spec,
4092: 'request.role.domain' => $dcdom,
4093: 'request.course.sec' => ''
4094: }
4095: );
4096: my $tadv=0;
4097: if (&allowed('adv') eq 'F') { $tadv=1; }
4098: &appenv({'request.role.adv' => $tadv});
4099: }
4100:
4101: # --------------------------------------------------------------- get interface
4102:
4103: sub get {
4104: my ($namespace,$storearr,$udomain,$uname)=@_;
4105: my $items='';
4106: foreach my $item (@$storearr) {
4107: $items.=&escape($item).'&';
4108: }
4109: $items=~s/\&$//;
4110: if (!$udomain) { $udomain=$env{'user.domain'}; }
4111: if (!$uname) { $uname=$env{'user.name'}; }
4112: my $uhome=&homeserver($uname,$udomain);
4113:
4114: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
4115: my @pairs=split(/\&/,$rep);
4116: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4117: return @pairs;
4118: }
4119: my %returnhash=();
4120: my $i=0;
4121: foreach my $item (@$storearr) {
4122: $returnhash{$item}=&thaw_unescape($pairs[$i]);
4123: $i++;
4124: }
4125: return %returnhash;
4126: }
4127:
4128: # --------------------------------------------------------------- del interface
4129:
4130: sub del {
4131: my ($namespace,$storearr,$udomain,$uname)=@_;
4132: my $items='';
4133: foreach my $item (@$storearr) {
4134: $items.=&escape($item).'&';
4135: }
4136:
4137: $items=~s/\&$//;
4138: if (!$udomain) { $udomain=$env{'user.domain'}; }
4139: if (!$uname) { $uname=$env{'user.name'}; }
4140: my $uhome=&homeserver($uname,$udomain);
4141: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
4142: }
4143:
4144: # -------------------------------------------------------------- dump interface
4145:
4146: sub dump {
4147: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
4148: if (!$udomain) { $udomain=$env{'user.domain'}; }
4149: if (!$uname) { $uname=$env{'user.name'}; }
4150: my $uhome=&homeserver($uname,$udomain);
4151: if ($regexp) {
4152: $regexp=&escape($regexp);
4153: } else {
4154: $regexp='.';
4155: }
4156: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4157: my @pairs=split(/\&/,$rep);
4158: my %returnhash=();
4159: foreach my $item (@pairs) {
4160: my ($key,$value)=split(/=/,$item,2);
4161: $key = &unescape($key);
4162: next if ($key =~ /^error: 2 /);
4163: $returnhash{$key}=&thaw_unescape($value);
4164: }
4165: return %returnhash;
4166: }
4167:
4168: # --------------------------------------------------------- dumpstore interface
4169:
4170: sub dumpstore {
4171: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
4172: if (!$udomain) { $udomain=$env{'user.domain'}; }
4173: if (!$uname) { $uname=$env{'user.name'}; }
4174: my $uhome=&homeserver($uname,$udomain);
4175: if ($regexp) {
4176: $regexp=&escape($regexp);
4177: } else {
4178: $regexp='.';
4179: }
4180: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4181: my @pairs=split(/\&/,$rep);
4182: my %returnhash=();
4183: foreach my $item (@pairs) {
4184: my ($key,$value)=split(/=/,$item,2);
4185: next if ($key =~ /^error: 2 /);
4186: $returnhash{$key}=&thaw_unescape($value);
4187: }
4188: return %returnhash;
4189: }
4190:
4191: # -------------------------------------------------------------- keys interface
4192:
4193: sub getkeys {
4194: my ($namespace,$udomain,$uname)=@_;
4195: if (!$udomain) { $udomain=$env{'user.domain'}; }
4196: if (!$uname) { $uname=$env{'user.name'}; }
4197: my $uhome=&homeserver($uname,$udomain);
4198: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4199: my @keyarray=();
4200: foreach my $key (split(/\&/,$rep)) {
4201: next if ($key =~ /^error: 2 /);
4202: push(@keyarray,&unescape($key));
4203: }
4204: return @keyarray;
4205: }
4206:
4207: # --------------------------------------------------------------- currentdump
4208: sub currentdump {
4209: my ($courseid,$sdom,$sname)=@_;
4210: $courseid = $env{'request.course.id'} if (! defined($courseid));
4211: $sdom = $env{'user.domain'} if (! defined($sdom));
4212: $sname = $env{'user.name'} if (! defined($sname));
4213: my $uhome = &homeserver($sname,$sdom);
4214: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
4215: return if ($rep =~ /^(error:|no_such_host)/);
4216: #
4217: my %returnhash=();
4218: #
4219: if ($rep eq "unknown_cmd") {
4220: # an old lond will not know currentdump
4221: # Do a dump and make it look like a currentdump
4222: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
4223: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4224: my %hash = @tmp;
4225: @tmp=();
4226: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
4227: } else {
4228: my @pairs=split(/\&/,$rep);
4229: foreach my $pair (@pairs) {
4230: my ($key,$value)=split(/=/,$pair,2);
4231: my ($symb,$param) = split(/:/,$key);
4232: $returnhash{&unescape($symb)}->{&unescape($param)} =
4233: &thaw_unescape($value);
4234: }
4235: }
4236: return %returnhash;
4237: }
4238:
4239: sub convert_dump_to_currentdump{
4240: my %hash = %{shift()};
4241: my %returnhash;
4242: # Code ripped from lond, essentially. The only difference
4243: # here is the unescaping done by lonnet::dump(). Conceivably
4244: # we might run in to problems with parameter names =~ /^v\./
4245: while (my ($key,$value) = each(%hash)) {
4246: my ($v,$symb,$param) = split(/:/,$key);
4247: $symb = &unescape($symb);
4248: $param = &unescape($param);
4249: next if ($v eq 'version' || $symb eq 'keys');
4250: next if (exists($returnhash{$symb}) &&
4251: exists($returnhash{$symb}->{$param}) &&
4252: $returnhash{$symb}->{'v.'.$param} > $v);
4253: $returnhash{$symb}->{$param}=$value;
4254: $returnhash{$symb}->{'v.'.$param}=$v;
4255: }
4256: #
4257: # Remove all of the keys in the hashes which keep track of
4258: # the version of the parameter.
4259: while (my ($symb,$param_hash) = each(%returnhash)) {
4260: # use a foreach because we are going to delete from the hash.
4261: foreach my $key (keys(%$param_hash)) {
4262: delete($param_hash->{$key}) if ($key =~ /^v\./);
4263: }
4264: }
4265: return \%returnhash;
4266: }
4267:
4268: # ------------------------------------------------------ critical inc interface
4269:
4270: sub cinc {
4271: return &inc(@_,'critical');
4272: }
4273:
4274: # --------------------------------------------------------------- inc interface
4275:
4276: sub inc {
4277: my ($namespace,$store,$udomain,$uname,$critical) = @_;
4278: if (!$udomain) { $udomain=$env{'user.domain'}; }
4279: if (!$uname) { $uname=$env{'user.name'}; }
4280: my $uhome=&homeserver($uname,$udomain);
4281: my $items='';
4282: if (! ref($store)) {
4283: # got a single value, so use that instead
4284: $items = &escape($store).'=&';
4285: } elsif (ref($store) eq 'SCALAR') {
4286: $items = &escape($$store).'=&';
4287: } elsif (ref($store) eq 'ARRAY') {
4288: $items = join('=&',map {&escape($_);} @{$store});
4289: } elsif (ref($store) eq 'HASH') {
4290: while (my($key,$value) = each(%{$store})) {
4291: $items.= &escape($key).'='.&escape($value).'&';
4292: }
4293: }
4294: $items=~s/\&$//;
4295: if ($critical) {
4296: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4297: } else {
4298: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4299: }
4300: }
4301:
4302: # --------------------------------------------------------------- put interface
4303:
4304: sub put {
4305: my ($namespace,$storehash,$udomain,$uname)=@_;
4306: if (!$udomain) { $udomain=$env{'user.domain'}; }
4307: if (!$uname) { $uname=$env{'user.name'}; }
4308: my $uhome=&homeserver($uname,$udomain);
4309: my $items='';
4310: foreach my $item (keys(%$storehash)) {
4311: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
4312: }
4313: $items=~s/\&$//;
4314: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
4315: }
4316:
4317: # ------------------------------------------------------------ newput interface
4318:
4319: sub newput {
4320: my ($namespace,$storehash,$udomain,$uname)=@_;
4321: if (!$udomain) { $udomain=$env{'user.domain'}; }
4322: if (!$uname) { $uname=$env{'user.name'}; }
4323: my $uhome=&homeserver($uname,$udomain);
4324: my $items='';
4325: foreach my $key (keys(%$storehash)) {
4326: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4327: }
4328: $items=~s/\&$//;
4329: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4330: }
4331:
4332: # --------------------------------------------------------- putstore interface
4333:
4334: sub putstore {
4335: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4336: if (!$udomain) { $udomain=$env{'user.domain'}; }
4337: if (!$uname) { $uname=$env{'user.name'}; }
4338: my $uhome=&homeserver($uname,$udomain);
4339: my $items='';
4340: foreach my $key (keys(%$storehash)) {
4341: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
4342: }
4343: $items=~s/\&$//;
4344: my $esc_symb=&escape($symb);
4345: my $esc_v=&escape($version);
4346: my $reply =
4347: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
4348: $uhome);
4349: if ($reply eq 'unknown_cmd') {
4350: # gfall back to way things use to be done
4351: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4352: $uname);
4353: }
4354: return $reply;
4355: }
4356:
4357: sub old_putstore {
4358: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4359: if (!$udomain) { $udomain=$env{'user.domain'}; }
4360: if (!$uname) { $uname=$env{'user.name'}; }
4361: my $uhome=&homeserver($uname,$udomain);
4362: my %newstorehash;
4363: foreach my $item (keys(%$storehash)) {
4364: my $key = $version.':'.&escape($symb).':'.$item;
4365: $newstorehash{$key} = $storehash->{$item};
4366: }
4367: my $items='';
4368: my %allitems = ();
4369: foreach my $item (keys(%newstorehash)) {
4370: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
4371: my $key = $1.':keys:'.$2;
4372: $allitems{$key} .= $3.':';
4373: }
4374: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
4375: }
4376: foreach my $item (keys(%allitems)) {
4377: $allitems{$item} =~ s/\:$//;
4378: $items.= $item.'='.$allitems{$item}.'&';
4379: }
4380: $items=~s/\&$//;
4381: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
4382: }
4383:
4384: # ------------------------------------------------------ critical put interface
4385:
4386: sub cput {
4387: my ($namespace,$storehash,$udomain,$uname)=@_;
4388: if (!$udomain) { $udomain=$env{'user.domain'}; }
4389: if (!$uname) { $uname=$env{'user.name'}; }
4390: my $uhome=&homeserver($uname,$udomain);
4391: my $items='';
4392: foreach my $item (keys(%$storehash)) {
4393: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
4394: }
4395: $items=~s/\&$//;
4396: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
4397: }
4398:
4399: # -------------------------------------------------------------- eget interface
4400:
4401: sub eget {
4402: my ($namespace,$storearr,$udomain,$uname)=@_;
4403: my $items='';
4404: foreach my $item (@$storearr) {
4405: $items.=&escape($item).'&';
4406: }
4407: $items=~s/\&$//;
4408: if (!$udomain) { $udomain=$env{'user.domain'}; }
4409: if (!$uname) { $uname=$env{'user.name'}; }
4410: my $uhome=&homeserver($uname,$udomain);
4411: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
4412: my @pairs=split(/\&/,$rep);
4413: my %returnhash=();
4414: my $i=0;
4415: foreach my $item (@$storearr) {
4416: $returnhash{$item}=&thaw_unescape($pairs[$i]);
4417: $i++;
4418: }
4419: return %returnhash;
4420: }
4421:
4422: # ------------------------------------------------------------ tmpput interface
4423: sub tmpput {
4424: my ($storehash,$server,$context)=@_;
4425: my $items='';
4426: foreach my $item (keys(%$storehash)) {
4427: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
4428: }
4429: $items=~s/\&$//;
4430: if (defined($context)) {
4431: $items .= ':'.&escape($context);
4432: }
4433: return &reply("tmpput:$items",$server);
4434: }
4435:
4436: # ------------------------------------------------------------ tmpget interface
4437: sub tmpget {
4438: my ($token,$server)=@_;
4439: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4440: my $rep=&reply("tmpget:$token",$server);
4441: my %returnhash;
4442: foreach my $item (split(/\&/,$rep)) {
4443: my ($key,$value)=split(/=/,$item);
4444: next if ($key =~ /^error: 2 /);
4445: $returnhash{&unescape($key)}=&thaw_unescape($value);
4446: }
4447: return %returnhash;
4448: }
4449:
4450: # ------------------------------------------------------------ tmpget interface
4451: sub tmpdel {
4452: my ($token,$server)=@_;
4453: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4454: return &reply("tmpdel:$token",$server);
4455: }
4456:
4457: # -------------------------------------------------- portfolio access checking
4458:
4459: sub portfolio_access {
4460: my ($requrl) = @_;
4461: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4462: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
4463: if ($result) {
4464: my %setters;
4465: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4466: my ($startblock,$endblock) =
4467: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4468: if ($startblock && $endblock) {
4469: return 'B';
4470: }
4471: } else {
4472: my ($startblock,$endblock) =
4473: &Apache::loncommon::blockcheck(\%setters,'port');
4474: if ($startblock && $endblock) {
4475: return 'B';
4476: }
4477: }
4478: }
4479: if ($result eq 'ok') {
4480: return 'F';
4481: } elsif ($result =~ /^[^:]+:guest_/) {
4482: return 'A';
4483: }
4484: return '';
4485: }
4486:
4487: sub get_portfolio_access {
4488: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4489:
4490: if (!ref($access_hash)) {
4491: my $current_perms = &get_portfile_permissions($udom,$unum);
4492: my %access_controls = &get_access_controls($current_perms,$group,
4493: $file_name);
4494: $access_hash = $access_controls{$file_name};
4495: }
4496:
4497: my ($public,$guest,@domains,@users,@courses,@groups);
4498: my $now = time;
4499: if (ref($access_hash) eq 'HASH') {
4500: foreach my $key (keys(%{$access_hash})) {
4501: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4502: if ($start > $now) {
4503: next;
4504: }
4505: if ($end && $end<$now) {
4506: next;
4507: }
4508: if ($scope eq 'public') {
4509: $public = $key;
4510: last;
4511: } elsif ($scope eq 'guest') {
4512: $guest = $key;
4513: } elsif ($scope eq 'domains') {
4514: push(@domains,$key);
4515: } elsif ($scope eq 'users') {
4516: push(@users,$key);
4517: } elsif ($scope eq 'course') {
4518: push(@courses,$key);
4519: } elsif ($scope eq 'group') {
4520: push(@groups,$key);
4521: }
4522: }
4523: if ($public) {
4524: return 'ok';
4525: }
4526: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4527: if ($guest) {
4528: return $guest;
4529: }
4530: } else {
4531: if (@domains > 0) {
4532: foreach my $domkey (@domains) {
4533: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4534: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4535: return 'ok';
4536: }
4537: }
4538: }
4539: }
4540: if (@users > 0) {
4541: foreach my $userkey (@users) {
4542: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4543: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4544: if (ref($item) eq 'HASH') {
4545: if (($item->{'uname'} eq $env{'user.name'}) &&
4546: ($item->{'udom'} eq $env{'user.domain'})) {
4547: return 'ok';
4548: }
4549: }
4550: }
4551: }
4552: }
4553: }
4554: my %roleshash;
4555: my @courses_and_groups = @courses;
4556: push(@courses_and_groups,@groups);
4557: if (@courses_and_groups > 0) {
4558: my (%allgroups,%allroles);
4559: my ($start,$end,$role,$sec,$group);
4560: foreach my $envkey (%env) {
4561: if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
4562: my $cid = $2.'_'.$3;
4563: if ($1 eq 'gr') {
4564: $group = $4;
4565: $allgroups{$cid}{$group} = $env{$envkey};
4566: } else {
4567: if ($4 eq '') {
4568: $sec = 'none';
4569: } else {
4570: $sec = $4;
4571: }
4572: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4573: }
4574: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
4575: my $cid = $2.'_'.$3;
4576: if ($4 eq '') {
4577: $sec = 'none';
4578: } else {
4579: $sec = $4;
4580: }
4581: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4582: }
4583: }
4584: if (keys(%allroles) == 0) {
4585: return;
4586: }
4587: foreach my $key (@courses_and_groups) {
4588: my %content = %{$$access_hash{$key}};
4589: my $cnum = $content{'number'};
4590: my $cdom = $content{'domain'};
4591: my $cid = $cdom.'_'.$cnum;
4592: if (!exists($allroles{$cid})) {
4593: next;
4594: }
4595: foreach my $role_id (keys(%{$content{'roles'}})) {
4596: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4597: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4598: my @status = @{$content{'roles'}{$role_id}{'access'}};
4599: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4600: foreach my $role (keys(%{$allroles{$cid}})) {
4601: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4602: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4603: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4604: if (grep/^all$/,@sections) {
4605: return 'ok';
4606: } else {
4607: if (grep/^$sec$/,@sections) {
4608: return 'ok';
4609: }
4610: }
4611: }
4612: }
4613: if (keys(%{$allgroups{$cid}}) == 0) {
4614: if (grep/^none$/,@groups) {
4615: return 'ok';
4616: }
4617: } else {
4618: if (grep/^all$/,@groups) {
4619: return 'ok';
4620: }
4621: foreach my $group (keys(%{$allgroups{$cid}})) {
4622: if (grep/^$group$/,@groups) {
4623: return 'ok';
4624: }
4625: }
4626: }
4627: }
4628: }
4629: }
4630: }
4631: }
4632: if ($guest) {
4633: return $guest;
4634: }
4635: }
4636: }
4637: return;
4638: }
4639:
4640: sub course_group_datechecker {
4641: my ($dates,$now,$status) = @_;
4642: my ($start,$end) = split(/\./,$dates);
4643: if (!$start && !$end) {
4644: return 'ok';
4645: }
4646: if (grep/^active$/,@{$status}) {
4647: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4648: return 'ok';
4649: }
4650: }
4651: if (grep/^previous$/,@{$status}) {
4652: if ($end > $now ) {
4653: return 'ok';
4654: }
4655: }
4656: if (grep/^future$/,@{$status}) {
4657: if ($start > $now) {
4658: return 'ok';
4659: }
4660: }
4661: return;
4662: }
4663:
4664: sub parse_portfolio_url {
4665: my ($url) = @_;
4666:
4667: my ($type,$udom,$unum,$group,$file_name);
4668:
4669: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
4670: $type = 1;
4671: $udom = $1;
4672: $unum = $2;
4673: $file_name = $3;
4674: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
4675: $type = 2;
4676: $udom = $1;
4677: $unum = $2;
4678: $group = $3;
4679: $file_name = $3.'/'.$4;
4680: }
4681: if (wantarray) {
4682: return ($type,$udom,$unum,$file_name,$group);
4683: }
4684: return $type;
4685: }
4686:
4687: sub is_portfolio_url {
4688: my ($url) = @_;
4689: return scalar(&parse_portfolio_url($url));
4690: }
4691:
4692: sub is_portfolio_file {
4693: my ($file) = @_;
4694: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
4695: return 1;
4696: }
4697: return;
4698: }
4699:
4700: sub usertools_access {
4701: my ($uname,$udom,$tool,$action,$context) = @_;
4702: my ($access,%tools);
4703: if ($context eq '') {
4704: $context = 'tools';
4705: }
4706: if ($context eq 'requestcourses') {
4707: %tools = (
4708: official => 1,
4709: unofficial => 1,
4710: community => 1,
4711: );
4712: } else {
4713: %tools = (
4714: aboutme => 1,
4715: blog => 1,
4716: portfolio => 1,
4717: );
4718: }
4719: return if (!defined($tools{$tool}));
4720:
4721: if ((!defined($udom)) || (!defined($uname))) {
4722: $udom = $env{'user.domain'};
4723: $uname = $env{'user.name'};
4724: }
4725:
4726: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
4727: if ($action ne 'reload') {
4728: if ($context eq 'requestcourses') {
4729: return $env{'environment.canrequest.'.$tool};
4730: } else {
4731: return $env{'environment.availabletools.'.$tool};
4732: }
4733: }
4734: }
4735:
4736: my ($toolstatus,$inststatus);
4737:
4738: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
4739: ($action ne 'reload')) {
4740: $toolstatus = $env{'environment.'.$context.'.'.$tool};
4741: $inststatus = $env{'environment.inststatus'};
4742: } else {
4743: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
4744: $toolstatus = $userenv{$context.'.'.$tool};
4745: $inststatus = $userenv{'inststatus'};
4746: }
4747:
4748: if ($toolstatus ne '') {
4749: if ($toolstatus) {
4750: $access = 1;
4751: } else {
4752: $access = 0;
4753: }
4754: return $access;
4755: }
4756:
4757: my $is_adv = &is_advanced_user($udom,$uname);
4758: my %domdef = &get_domain_defaults($udom);
4759: if (ref($domdef{$tool}) eq 'HASH') {
4760: if ($is_adv) {
4761: if ($domdef{$tool}{'_LC_adv'} ne '') {
4762: if ($domdef{$tool}{'_LC_adv'}) {
4763: $access = 1;
4764: } else {
4765: $access = 0;
4766: }
4767: return $access;
4768: }
4769: }
4770: if ($inststatus ne '') {
4771: my ($hasaccess,$hasnoaccess);
4772: foreach my $affiliation (split(/:/,$inststatus)) {
4773: if ($domdef{$tool}{$affiliation} ne '') {
4774: if ($domdef{$tool}{$affiliation}) {
4775: $hasaccess = 1;
4776: } else {
4777: $hasnoaccess = 1;
4778: }
4779: }
4780: }
4781: if ($hasaccess || $hasnoaccess) {
4782: if ($hasaccess) {
4783: $access = 1;
4784: } elsif ($hasnoaccess) {
4785: $access = 0;
4786: }
4787: return $access;
4788: }
4789: } else {
4790: if ($domdef{$tool}{'default'} ne '') {
4791: if ($domdef{$tool}{'default'}) {
4792: $access = 1;
4793: } elsif ($domdef{$tool}{'default'} == 0) {
4794: $access = 0;
4795: }
4796: return $access;
4797: }
4798: }
4799: } else {
4800: if ($context eq 'tools') {
4801: $access = 1;
4802: } else {
4803: $access = 0;
4804: }
4805: return $access;
4806: }
4807: }
4808:
4809: sub is_advanced_user {
4810: my ($udom,$uname) = @_;
4811: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
4812: my %allroles;
4813: my $is_adv;
4814: foreach my $role (keys(%roleshash)) {
4815: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
4816: my $area = '/'.$tdomain.'/'.$trest;
4817: if ($sec ne '') {
4818: $area .= '/'.$sec;
4819: }
4820: if (($area ne '') && ($trole ne '')) {
4821: my $spec=$trole.'.'.$area;
4822: if ($trole =~ /^cr\//) {
4823: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4824: } elsif ($trole ne 'gr') {
4825: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4826: }
4827: }
4828: }
4829: foreach my $role (keys(%allroles)) {
4830: last if ($is_adv);
4831: foreach my $item (split(/:/,$allroles{$role})) {
4832: if ($item ne '') {
4833: my ($privilege,$restrictions)=split(/&/,$item);
4834: if ($privilege eq 'adv') {
4835: $is_adv = 1;
4836: last;
4837: }
4838: }
4839: }
4840: }
4841: return $is_adv;
4842: }
4843:
4844: sub check_can_request {
4845: my ($dom,$can_request) = @_;
4846: my $canreq = 0;
4847: my ($types,$typename) = &Apache::loncommon::course_types();
4848: my @options = ('approval','validate','autolimit');
4849: my $optregex = join('|',@options);
4850: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
4851: foreach my $type (@{$types}) {
4852: if (&usertools_access($env{'user.name'},
4853: $env{'user.domain'},
4854: $type,undef,'requestcourses')) {
4855: $canreq ++;
4856: if ($dom eq $env{'user.domain'}) {
4857: $can_request->{$type} = 1;
4858: }
4859: }
4860: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
4861: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
4862: if (@curr > 0) {
4863: $canreq ++;
4864: unless ($dom eq $env{'user.domain'}) {
4865: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
4866: $can_request->{$type} = 1;
4867: }
4868: }
4869: }
4870: }
4871: }
4872: }
4873: return $canreq;
4874: }
4875:
4876: # ---------------------------------------------- Custom access rule evaluation
4877:
4878: sub customaccess {
4879: my ($priv,$uri)=@_;
4880: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
4881: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
4882: $udom = &LONCAPA::clean_domain($udom);
4883: $ucrs = &LONCAPA::clean_username($ucrs);
4884: my $access=0;
4885: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
4886: my ($effect,$realm,$role,$type)=split(/\:/,$right);
4887: if ($type eq 'user') {
4888: foreach my $scope (split(/\s*\,\s*/,$realm)) {
4889: my ($tdom,$tuname)=split(m{/},$scope);
4890: if ($tdom) {
4891: if ($tdom ne $env{'user.domain'}) { next; }
4892: }
4893: if ($tuname) {
4894: if ($tuname ne $env{'user.name'}) { next; }
4895: }
4896: $access=($effect eq 'allow');
4897: last;
4898: }
4899: } else {
4900: if ($role) {
4901: if ($role ne $urole) { next; }
4902: }
4903: foreach my $scope (split(/\s*\,\s*/,$realm)) {
4904: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
4905: if ($tdom) {
4906: if ($tdom ne $udom) { next; }
4907: }
4908: if ($tcrs) {
4909: if ($tcrs ne $ucrs) { next; }
4910: }
4911: if ($tsec) {
4912: if ($tsec ne $usec) { next; }
4913: }
4914: $access=($effect eq 'allow');
4915: last;
4916: }
4917: if ($realm eq '' && $role eq '') {
4918: $access=($effect eq 'allow');
4919: }
4920: }
4921: }
4922: return $access;
4923: }
4924:
4925: # ------------------------------------------------- Check for a user privilege
4926:
4927: sub allowed {
4928: my ($priv,$uri,$symb,$role)=@_;
4929: my $ver_orguri=$uri;
4930: $uri=&deversion($uri);
4931: my $orguri=$uri;
4932: $uri=&declutter($uri);
4933:
4934: if ($priv eq 'evb') {
4935: # Evade communication block restrictions for specified role in a course
4936: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
4937: return $1;
4938: } else {
4939: return;
4940: }
4941: }
4942:
4943: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
4944: # Free bre access to adm and meta resources
4945: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
4946: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
4947: && ($priv eq 'bre')) {
4948: return 'F';
4949: }
4950:
4951: # Free bre access to user's own portfolio contents
4952: my ($space,$domain,$name,@dir)=split('/',$uri);
4953: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
4954: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
4955: my %setters;
4956: my ($startblock,$endblock) =
4957: &Apache::loncommon::blockcheck(\%setters,'port');
4958: if ($startblock && $endblock) {
4959: return 'B';
4960: } else {
4961: return 'F';
4962: }
4963: }
4964:
4965: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
4966: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
4967: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
4968: if (exists($env{'request.course.id'})) {
4969: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4970: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4971: if (($domain eq $cdom) && ($name eq $cnum)) {
4972: my $courseprivid=$env{'request.course.id'};
4973: $courseprivid=~s/\_/\//;
4974: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
4975: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
4976: return $1;
4977: } else {
4978: if ($env{'request.course.sec'}) {
4979: $courseprivid.='/'.$env{'request.course.sec'};
4980: }
4981: if ($env{'user.priv.'.$env{'request.role'}.'./'.
4982: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
4983: return $2;
4984: }
4985: }
4986: }
4987: }
4988: }
4989:
4990: # Free bre to public access
4991:
4992: if ($priv eq 'bre') {
4993: my $copyright=&metadata($uri,'copyright');
4994: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
4995: return 'F';
4996: }
4997: if ($copyright eq 'priv') {
4998: $uri=~/([^\/]+)\/([^\/]+)\//;
4999: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
5000: return '';
5001: }
5002: }
5003: if ($copyright eq 'domain') {
5004: $uri=~/([^\/]+)\/([^\/]+)\//;
5005: unless (($env{'user.domain'} eq $1) ||
5006: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
5007: return '';
5008: }
5009: }
5010: if ($env{'request.role'}=~ /li\.\//) {
5011: # Library role, so allow browsing of resources in this domain.
5012: return 'F';
5013: }
5014: if ($copyright eq 'custom') {
5015: unless (&customaccess($priv,$uri)) { return ''; }
5016: }
5017: }
5018: # Domain coordinator is trying to create a course
5019: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
5020: # uri is the requested domain in this case.
5021: # comparison to 'request.role.domain' shows if the user has selected
5022: # a role of dc for the domain in question.
5023: return 'F' if ($uri eq $env{'request.role.domain'});
5024: }
5025:
5026: my $thisallowed='';
5027: my $statecond=0;
5028: my $courseprivid='';
5029:
5030: # Course
5031:
5032: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
5033: $thisallowed.=$1;
5034: }
5035:
5036: # Domain
5037:
5038: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
5039: =~/\Q$priv\E\&([^\:]*)/) {
5040: $thisallowed.=$1;
5041: }
5042:
5043: # Course: uri itself is a course
5044: my $courseuri=$uri;
5045: $courseuri=~s/\_(\d)/\/$1/;
5046: $courseuri=~s/^([^\/])/\/$1/;
5047:
5048: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
5049: =~/\Q$priv\E\&([^\:]*)/) {
5050: $thisallowed.=$1;
5051: }
5052:
5053: # URI is an uploaded document for this course, default permissions don't matter
5054: # not allowing 'edit' access (editupload) to uploaded course docs
5055: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
5056: $thisallowed='';
5057: my ($match)=&is_on_map($uri);
5058: if ($match) {
5059: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5060: =~/\Q$priv\E\&([^\:]*)/) {
5061: $thisallowed.=$1;
5062: }
5063: } else {
5064: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
5065: if ($refuri) {
5066: if ($refuri =~ m|^/adm/|) {
5067: $thisallowed='F';
5068: } else {
5069: $refuri=&declutter($refuri);
5070: my ($match) = &is_on_map($refuri);
5071: if ($match) {
5072: $thisallowed='F';
5073: }
5074: }
5075: }
5076: }
5077: }
5078:
5079: if ($priv eq 'bre'
5080: && $thisallowed ne 'F'
5081: && $thisallowed ne '2'
5082: && &is_portfolio_url($uri)) {
5083: $thisallowed = &portfolio_access($uri);
5084: }
5085:
5086: # Full access at system, domain or course-wide level? Exit.
5087: if ($thisallowed=~/F/) {
5088: return 'F';
5089: }
5090:
5091: # If this is generating or modifying users, exit with special codes
5092:
5093: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5094: if (($priv eq 'cca') || ($priv eq 'caa')) {
5095: my ($audom,$auname)=split('/',$uri);
5096: # no author name given, so this just checks on the general right to make a co-author in this domain
5097: unless ($auname) { return $thisallowed; }
5098: # an author name is given, so we are about to actually make a co-author for a certain account
5099: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5100: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5101: ($audom ne $env{'request.role.domain'}))) { return ''; }
5102: }
5103: return $thisallowed;
5104: }
5105: #
5106: # Gathered so far: system, domain and course wide privileges
5107: #
5108: # Course: See if uri or referer is an individual resource that is part of
5109: # the course
5110:
5111: if ($env{'request.course.id'}) {
5112:
5113: $courseprivid=$env{'request.course.id'};
5114: if ($env{'request.course.sec'}) {
5115: $courseprivid.='/'.$env{'request.course.sec'};
5116: }
5117: $courseprivid=~s/\_/\//;
5118: my $checkreferer=1;
5119: my ($match,$cond)=&is_on_map($uri);
5120: if ($match) {
5121: $statecond=$cond;
5122: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
5123: =~/\Q$priv\E\&([^\:]*)/) {
5124: $thisallowed.=$1;
5125: $checkreferer=0;
5126: }
5127: }
5128:
5129: if ($checkreferer) {
5130: my $refuri=$env{'httpref.'.$orguri};
5131: unless ($refuri) {
5132: foreach my $key (keys(%env)) {
5133: if ($key=~/^httpref\..*\*/) {
5134: my $pattern=$key;
5135: $pattern=~s/^httpref\.\/res\///;
5136: $pattern=~s/\*/\[\^\/\]\+/g;
5137: $pattern=~s/\//\\\//g;
5138: if ($orguri=~/$pattern/) {
5139: $refuri=$env{$key};
5140: }
5141: }
5142: }
5143: }
5144:
5145: if ($refuri) {
5146: $refuri=&declutter($refuri);
5147: my ($match,$cond)=&is_on_map($refuri);
5148: if ($match) {
5149: my $refstatecond=$cond;
5150: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
5151: =~/\Q$priv\E\&([^\:]*)/) {
5152: $thisallowed.=$1;
5153: $uri=$refuri;
5154: $statecond=$refstatecond;
5155: }
5156: }
5157: }
5158: }
5159: }
5160:
5161: #
5162: # Gathered now: all privileges that could apply, and condition number
5163: #
5164: #
5165: # Full or no access?
5166: #
5167:
5168: if ($thisallowed=~/F/) {
5169: return 'F';
5170: }
5171:
5172: unless ($thisallowed) {
5173: return '';
5174: }
5175:
5176: # Restrictions exist, deal with them
5177: #
5178: # C:according to course preferences
5179: # R:according to resource settings
5180: # L:unless locked
5181: # X:according to user session state
5182: #
5183:
5184: # Possibly locked functionality, check all courses
5185: # Locks might take effect only after 10 minutes cache expiration for other
5186: # courses, and 2 minutes for current course
5187:
5188: my $envkey;
5189: if ($thisallowed=~/L/) {
5190: foreach $envkey (keys(%env)) {
5191: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5192: my $courseid=$2;
5193: my $roleid=$1.'.'.$2;
5194: $courseid=~s/^\///;
5195: my $expiretime=600;
5196: if ($env{'request.role'} eq $roleid) {
5197: $expiretime=120;
5198: }
5199: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5200: my $prefix='course.'.$cdom.'_'.$cnum.'.';
5201: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
5202: &coursedescription($courseid,{'freshen_cache' => 1});
5203: }
5204: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5205: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5206: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5207: &log($env{'user.domain'},$env{'user.name'},
5208: $env{'user.home'},
5209: 'Locked by res: '.$priv.' for '.$uri.' due to '.
5210: $cdom.'/'.$cnum.'/'.$csec.' expire '.
5211: $env{$prefix.'priv.'.$priv.'.lock.expire'});
5212: return '';
5213: }
5214: }
5215: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5216: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5217: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5218: &log($env{'user.domain'},$env{'user.name'},
5219: $env{'user.home'},
5220: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
5221: $cdom.'/'.$cnum.'/'.$csec.' expire '.
5222: $env{$prefix.'priv.'.$priv.'.lock.expire'});
5223: return '';
5224: }
5225: }
5226: }
5227: }
5228: }
5229:
5230: #
5231: # Rest of the restrictions depend on selected course
5232: #
5233:
5234: unless ($env{'request.course.id'}) {
5235: if ($thisallowed eq 'A') {
5236: return 'A';
5237: } elsif ($thisallowed eq 'B') {
5238: return 'B';
5239: } else {
5240: return '1';
5241: }
5242: }
5243:
5244: #
5245: # Now user is definitely in a course
5246: #
5247:
5248:
5249: # Course preferences
5250:
5251: if ($thisallowed=~/C/) {
5252: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5253: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5254: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
5255: =~/\Q$rolecode\E/) {
5256: if ($priv ne 'pch') {
5257: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5258: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5259: $env{'request.course.id'});
5260: }
5261: return '';
5262: }
5263:
5264: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
5265: =~/\Q$unamedom\E/) {
5266: if ($priv ne 'pch') {
5267: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5268: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5269: $env{'request.course.id'});
5270: }
5271: return '';
5272: }
5273: }
5274:
5275: # Resource preferences
5276:
5277: if ($thisallowed=~/R/) {
5278: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5279: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
5280: if ($priv ne 'pch') {
5281: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5282: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5283: }
5284: return '';
5285: }
5286: }
5287:
5288: # Restricted by state or randomout?
5289:
5290: if ($thisallowed=~/X/) {
5291: if ($env{'acc.randomout'}) {
5292: if (!$symb) { $symb=&symbread($uri,1); }
5293: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
5294: return '';
5295: }
5296: }
5297: if (&condval($statecond)) {
5298: return '2';
5299: } else {
5300: return '';
5301: }
5302: }
5303:
5304: if ($thisallowed eq 'A') {
5305: return 'A';
5306: } elsif ($thisallowed eq 'B') {
5307: return 'B';
5308: }
5309: return 'F';
5310: }
5311:
5312: sub split_uri_for_cond {
5313: my $uri=&deversion(&declutter(shift));
5314: my @uriparts=split(/\//,$uri);
5315: my $filename=pop(@uriparts);
5316: my $pathname=join('/',@uriparts);
5317: return ($pathname,$filename);
5318: }
5319: # --------------------------------------------------- Is a resource on the map?
5320:
5321: sub is_on_map {
5322: my ($pathname,$filename) = &split_uri_for_cond(shift);
5323: #Trying to find the conditional for the file
5324: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
5325: /\&\Q$filename\E\:([\d\|]+)\&/);
5326: if ($match) {
5327: return (1,$1);
5328: } else {
5329: return (0,0);
5330: }
5331: }
5332:
5333: # --------------------------------------------------------- Get symb from alias
5334:
5335: sub get_symb_from_alias {
5336: my $symb=shift;
5337: my ($map,$resid,$url)=&decode_symb($symb);
5338: # Already is a symb
5339: if ($url) { return $symb; }
5340: # Must be an alias
5341: my $aliassymb='';
5342: my %bighash;
5343: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
5344: &GDBM_READER(),0640)) {
5345: my $rid=$bighash{'mapalias_'.$symb};
5346: if ($rid) {
5347: my ($mapid,$resid)=split(/\./,$rid);
5348: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5349: $resid,$bighash{'src_'.$rid});
5350: }
5351: untie %bighash;
5352: }
5353: return $aliassymb;
5354: }
5355:
5356: # ----------------------------------------------------------------- Define Role
5357:
5358: sub definerole {
5359: if (allowed('mcr','/')) {
5360: my ($rolename,$sysrole,$domrole,$courole)=@_;
5361: foreach my $role (split(':',$sysrole)) {
5362: my ($crole,$cqual)=split(/\&/,$role);
5363: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5364: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5365: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
5366: return "refused:s:$crole&$cqual";
5367: }
5368: }
5369: }
5370: foreach my $role (split(':',$domrole)) {
5371: my ($crole,$cqual)=split(/\&/,$role);
5372: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5373: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5374: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
5375: return "refused:d:$crole&$cqual";
5376: }
5377: }
5378: }
5379: foreach my $role (split(':',$courole)) {
5380: my ($crole,$cqual)=split(/\&/,$role);
5381: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5382: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5383: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
5384: return "refused:c:$crole&$cqual";
5385: }
5386: }
5387: }
5388: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5389: "$env{'user.domain'}:$env{'user.name'}:".
5390: "rolesdef_$rolename=".
5391: escape($sysrole.'_'.$domrole.'_'.$courole);
5392: return reply($command,$env{'user.home'});
5393: } else {
5394: return 'refused';
5395: }
5396: }
5397:
5398: # ---------------- Make a metadata query against the network of library servers
5399:
5400: sub metadata_query {
5401: my ($query,$custom,$customshow,$server_array)=@_;
5402: my %rhash;
5403: my %libserv = &all_library();
5404: my @server_list = (defined($server_array) ? @$server_array
5405: : keys(%libserv) );
5406: for my $server (@server_list) {
5407: unless ($custom or $customshow) {
5408: my $reply=&reply("querysend:".&escape($query),$server);
5409: $rhash{$server}=$reply;
5410: }
5411: else {
5412: my $reply=&reply("querysend:".&escape($query).':'.
5413: &escape($custom).':'.&escape($customshow),
5414: $server);
5415: $rhash{$server}=$reply;
5416: }
5417: }
5418: return \%rhash;
5419: }
5420:
5421: # ----------------------------------------- Send log queries and wait for reply
5422:
5423: sub log_query {
5424: my ($uname,$udom,$query,%filters)=@_;
5425: my $uhome=&homeserver($uname,$udom);
5426: if ($uhome eq 'no_host') { return 'error: no_host'; }
5427: my $uhost=&hostname($uhome);
5428: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
5429: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5430: $uhome);
5431: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
5432: return get_query_reply($queryid);
5433: }
5434:
5435: # -------------------------- Update MySQL table for portfolio file
5436:
5437: sub update_portfolio_table {
5438: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
5439: if ($group ne '') {
5440: $file_name =~s /^\Q$group\E//;
5441: }
5442: my $homeserver = &homeserver($uname,$udom);
5443: my $queryid=
5444: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5445: ':'.&escape($file_name).':'.$action,$homeserver);
5446: my $reply = &get_query_reply($queryid);
5447: return $reply;
5448: }
5449:
5450: # -------------------------- Update MySQL allusers table
5451:
5452: sub update_allusers_table {
5453: my ($uname,$udom,$names) = @_;
5454: my $homeserver = &homeserver($uname,$udom);
5455: my $queryid=
5456: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5457: 'lastname='.&escape($names->{'lastname'}).'%%'.
5458: 'firstname='.&escape($names->{'firstname'}).'%%'.
5459: 'middlename='.&escape($names->{'middlename'}).'%%'.
5460: 'generation='.&escape($names->{'generation'}).'%%'.
5461: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5462: 'id='.&escape($names->{'id'}),$homeserver);
5463: my $reply = &get_query_reply($queryid);
5464: return $reply;
5465: }
5466:
5467: # ------- Request retrieval of institutional classlists for course(s)
5468:
5469: sub fetch_enrollment_query {
5470: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
5471: my $homeserver;
5472: my $maxtries = 1;
5473: if ($context eq 'automated') {
5474: $homeserver = $perlvar{'lonHostID'};
5475: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
5476: } else {
5477: $homeserver = &homeserver($cnum,$dom);
5478: }
5479: my $host=&hostname($homeserver);
5480: my $cmd = '';
5481: foreach my $affiliate (keys(%{$affiliatesref})) {
5482: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
5483: }
5484: $cmd =~ s/%%$//;
5485: $cmd = &escape($cmd);
5486: my $query = 'fetchenrollment';
5487: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
5488: unless ($queryid=~/^\Q$host\E\_/) {
5489: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5490: return 'error: '.$queryid;
5491: }
5492: my $reply = &get_query_reply($queryid);
5493: my $tries = 1;
5494: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5495: $reply = &get_query_reply($queryid);
5496: $tries ++;
5497: }
5498: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
5499: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
5500: } else {
5501: my @responses = split(/:/,$reply);
5502: if ($homeserver eq $perlvar{'lonHostID'}) {
5503: foreach my $line (@responses) {
5504: my ($key,$value) = split(/=/,$line,2);
5505: $$replyref{$key} = $value;
5506: }
5507: } else {
5508: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
5509: foreach my $line (@responses) {
5510: my ($key,$value) = split(/=/,$line);
5511: $$replyref{$key} = $value;
5512: if ($value > 0) {
5513: foreach my $item (@{$$affiliatesref{$key}}) {
5514: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
5515: my $destname = $pathname.'/'.$filename;
5516: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
5517: if ($xml_classlist =~ /^error/) {
5518: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5519: } else {
5520: if ( open(FILE,">$destname") ) {
5521: print FILE &unescape($xml_classlist);
5522: close(FILE);
5523: } else {
5524: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
5525: }
5526: }
5527: }
5528: }
5529: }
5530: }
5531: return 'ok';
5532: }
5533: return 'error';
5534: }
5535:
5536: sub get_query_reply {
5537: my $queryid=shift;
5538: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
5539: my $reply='';
5540: for (1..100) {
5541: sleep 2;
5542: if (-e $replyfile.'.end') {
5543: if (open(my $fh,$replyfile)) {
5544: $reply = join('',<$fh>);
5545: close($fh);
5546: } else { return 'error: reply_file_error'; }
5547: return &unescape($reply);
5548: }
5549: }
5550: return 'timeout:'.$queryid;
5551: }
5552:
5553: sub courselog_query {
5554: #
5555: # possible filters:
5556: # url: url or symb
5557: # username
5558: # domain
5559: # action: view, submit, grade
5560: # start: timestamp
5561: # end: timestamp
5562: #
5563: my (%filters)=@_;
5564: unless ($env{'request.course.id'}) { return 'no_course'; }
5565: if ($filters{'url'}) {
5566: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
5567: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
5568: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
5569: }
5570: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5571: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5572: return &log_query($cname,$cdom,'courselog',%filters);
5573: }
5574:
5575: sub userlog_query {
5576: #
5577: # possible filters:
5578: # action: log check role
5579: # start: timestamp
5580: # end: timestamp
5581: #
5582: my ($uname,$udom,%filters)=@_;
5583: return &log_query($uname,$udom,'userlog',%filters);
5584: }
5585:
5586: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
5587:
5588: sub auto_run {
5589: my ($cnum,$cdom) = @_;
5590: my $response = 0;
5591: my $settings;
5592: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
5593: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5594: $settings = $domconfig{'autoenroll'};
5595: if ($settings->{'run'} eq '1') {
5596: $response = 1;
5597: }
5598: } else {
5599: my $homeserver;
5600: if (&is_course($cdom,$cnum)) {
5601: $homeserver = &homeserver($cnum,$cdom);
5602: } else {
5603: $homeserver = &domain($cdom,'primary');
5604: }
5605: if ($homeserver ne 'no_host') {
5606: $response = &reply('autorun:'.$cdom,$homeserver);
5607: }
5608: }
5609: return $response;
5610: }
5611:
5612: sub auto_get_sections {
5613: my ($cnum,$cdom,$inst_coursecode) = @_;
5614: my $homeserver;
5615: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5616: $homeserver = &homeserver($cnum,$cdom);
5617: }
5618: if (!defined($homeserver)) {
5619: if ($cdom =~ /^$match_domain$/) {
5620: $homeserver = &domain($cdom,'primary');
5621: }
5622: }
5623: my @secs;
5624: if (defined($homeserver)) {
5625: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
5626: unless ($response eq 'refused') {
5627: @secs = split(/:/,$response);
5628: }
5629: }
5630: return @secs;
5631: }
5632:
5633: sub auto_new_course {
5634: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
5635: my $homeserver = &homeserver($cnum,$cdom);
5636: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
5637: return $response;
5638: }
5639:
5640: sub auto_validate_courseID {
5641: my ($cnum,$cdom,$inst_course_id) = @_;
5642: my $homeserver = &homeserver($cnum,$cdom);
5643: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
5644: return $response;
5645: }
5646:
5647: sub auto_validate_instcode {
5648: my ($cnum,$cdom,$instcode,$owner) = @_;
5649: my ($homeserver,$response);
5650: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5651: $homeserver = &homeserver($cnum,$cdom);
5652: }
5653: if (!defined($homeserver)) {
5654: if ($cdom =~ /^$match_domain$/) {
5655: $homeserver = &domain($cdom,'primary');
5656: }
5657: }
5658: my $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
5659: &escape($instcode).':'.&escape($owner),$homeserver));
5660: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
5661: return ($outcome,$description);
5662: }
5663:
5664: sub auto_create_password {
5665: my ($cnum,$cdom,$authparam,$udom) = @_;
5666: my ($homeserver,$response);
5667: my $create_passwd = 0;
5668: my $authchk = '';
5669: if ($udom =~ /^$match_domain$/) {
5670: $homeserver = &domain($udom,'primary');
5671: }
5672: if ($homeserver eq '') {
5673: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5674: $homeserver = &homeserver($cnum,$cdom);
5675: }
5676: }
5677: if ($homeserver eq '') {
5678: $authchk = 'nodomain';
5679: } else {
5680: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
5681: if ($response eq 'refused') {
5682: $authchk = 'refused';
5683: } else {
5684: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
5685: }
5686: }
5687: return ($authparam,$create_passwd,$authchk);
5688: }
5689:
5690: sub auto_photo_permission {
5691: my ($cnum,$cdom,$students) = @_;
5692: my $homeserver = &homeserver($cnum,$cdom);
5693: my ($outcome,$perm_reqd,$conditions) =
5694: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
5695: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5696: return (undef,undef);
5697: }
5698: return ($outcome,$perm_reqd,$conditions);
5699: }
5700:
5701: sub auto_checkphotos {
5702: my ($uname,$udom,$pid) = @_;
5703: my $homeserver = &homeserver($uname,$udom);
5704: my ($result,$resulttype);
5705: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
5706: &escape($uname).':'.&escape($pid),
5707: $homeserver));
5708: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5709: return (undef,undef);
5710: }
5711: if ($outcome) {
5712: ($result,$resulttype) = split(/:/,$outcome);
5713: }
5714: return ($result,$resulttype);
5715: }
5716:
5717: sub auto_photochoice {
5718: my ($cnum,$cdom) = @_;
5719: my $homeserver = &homeserver($cnum,$cdom);
5720: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
5721: &escape($cdom),
5722: $homeserver)));
5723: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5724: return (undef,undef);
5725: }
5726: return ($update,$comment);
5727: }
5728:
5729: sub auto_photoupdate {
5730: my ($affiliatesref,$dom,$cnum,$photo) = @_;
5731: my $homeserver = &homeserver($cnum,$dom);
5732: my $host=&hostname($homeserver);
5733: my $cmd = '';
5734: my $maxtries = 1;
5735: foreach my $affiliate (keys(%{$affiliatesref})) {
5736: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
5737: }
5738: $cmd =~ s/%%$//;
5739: $cmd = &escape($cmd);
5740: my $query = 'institutionalphotos';
5741: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
5742: unless ($queryid=~/^\Q$host\E\_/) {
5743: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
5744: return 'error: '.$queryid;
5745: }
5746: my $reply = &get_query_reply($queryid);
5747: my $tries = 1;
5748: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5749: $reply = &get_query_reply($queryid);
5750: $tries ++;
5751: }
5752: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
5753: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
5754: } else {
5755: my @responses = split(/:/,$reply);
5756: my $outcome = shift(@responses);
5757: foreach my $item (@responses) {
5758: my ($key,$value) = split(/=/,$item);
5759: $$photo{$key} = $value;
5760: }
5761: return $outcome;
5762: }
5763: return 'error';
5764: }
5765:
5766: sub auto_instcode_format {
5767: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
5768: $cat_order) = @_;
5769: my $courses = '';
5770: my @homeservers;
5771: if ($caller eq 'global') {
5772: my %servers = &get_servers($codedom,'library');
5773: foreach my $tryserver (keys(%servers)) {
5774: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5775: push(@homeservers,$tryserver);
5776: }
5777: }
5778: } elsif ($caller eq 'requests') {
5779: if ($codedom =~ /^$match_domain$/) {
5780: my $chome = &domain($codedom,'primary');
5781: unless ($chome eq 'no_host') {
5782: push(@homeservers,$chome);
5783: }
5784: }
5785: } else {
5786: push(@homeservers,&homeserver($caller,$codedom));
5787: }
5788: foreach my $code (keys(%{$instcodes})) {
5789: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
5790: }
5791: chop($courses);
5792: my $ok_response = 0;
5793: my $response;
5794: while (@homeservers > 0 && $ok_response == 0) {
5795: my $server = shift(@homeservers);
5796: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
5797: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
5798: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
5799: split(/:/,$response);
5800: %{$codes} = (%{$codes},&str2hash($codes_str));
5801: push(@{$codetitles},&str2array($codetitles_str));
5802: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
5803: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
5804: $ok_response = 1;
5805: }
5806: }
5807: if ($ok_response) {
5808: return 'ok';
5809: } else {
5810: return $response;
5811: }
5812: }
5813:
5814: sub auto_instcode_defaults {
5815: my ($domain,$returnhash,$code_order) = @_;
5816: my @homeservers;
5817:
5818: my %servers = &get_servers($domain,'library');
5819: foreach my $tryserver (keys(%servers)) {
5820: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5821: push(@homeservers,$tryserver);
5822: }
5823: }
5824:
5825: my $response;
5826: foreach my $server (@homeservers) {
5827: $response=&reply('autoinstcodedefaults:'.$domain,$server);
5828: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
5829:
5830: foreach my $pair (split(/\&/,$response)) {
5831: my ($name,$value)=split(/\=/,$pair);
5832: if ($name eq 'code_order') {
5833: @{$code_order} = split(/\&/,&unescape($value));
5834: } else {
5835: $returnhash->{&unescape($name)}=&unescape($value);
5836: }
5837: }
5838: return 'ok';
5839: }
5840:
5841: return $response;
5842: }
5843:
5844: sub auto_possible_instcodes {
5845: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
5846: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
5847: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
5848: return;
5849: }
5850: my (@homeservers,$uhome);
5851: if (defined(&domain($domain,'primary'))) {
5852: $uhome=&domain($domain,'primary');
5853: push(@homeservers,&domain($domain,'primary'));
5854: } else {
5855: my %servers = &get_servers($domain,'library');
5856: foreach my $tryserver (keys(%servers)) {
5857: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5858: push(@homeservers,$tryserver);
5859: }
5860: }
5861: }
5862: my $response;
5863: foreach my $server (@homeservers) {
5864: $response=&reply('autopossibleinstcodes:'.$domain,$server);
5865: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
5866: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
5867: split(':',$response);
5868: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
5869: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
5870: foreach my $item (split('&',$cat_title)) {
5871: my ($name,$value)=split('=',$item);
5872: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
5873: }
5874: foreach my $item (split('&',$cat_order)) {
5875: my ($name,$value)=split('=',$item);
5876: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
5877: }
5878: return 'ok';
5879: }
5880: return $response;
5881: }
5882:
5883: sub auto_courserequest_checks {
5884: my ($dom) = @_;
5885: my ($homeserver,%validations);
5886: if ($dom =~ /^$match_domain$/) {
5887: $homeserver = &domain($dom,'primary');
5888: }
5889: unless ($homeserver eq 'no_host') {
5890: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
5891: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
5892: my @items = split(/&/,$response);
5893: foreach my $item (@items) {
5894: my ($key,$value) = split('=',$item);
5895: $validations{&unescape($key)} = &thaw_unescape($value);
5896: }
5897: }
5898: }
5899: return %validations;
5900: }
5901:
5902: sub auto_courserequest_validation {
5903: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
5904: my ($homeserver,$response);
5905: if ($dom =~ /^$match_domain$/) {
5906: $homeserver = &domain($dom,'primary');
5907: }
5908: unless ($homeserver eq 'no_host') {
5909:
5910: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
5911: ':'.&escape($crstype).':'.&escape($inststatuslist).
5912: ':'.&escape($instcode).':'.&escape($instseclist),
5913: $homeserver));
5914: }
5915: return $response;
5916: }
5917:
5918: sub auto_validate_class_sec {
5919: my ($cdom,$cnum,$owners,$inst_class) = @_;
5920: my $homeserver = &homeserver($cnum,$cdom);
5921: my $ownerlist;
5922: if (ref($owners) eq 'ARRAY') {
5923: $ownerlist = join(',',@{$owners});
5924: } else {
5925: $ownerlist = $owners;
5926: }
5927: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
5928: &escape($ownerlist).':'.$cdom,$homeserver);
5929: return $response;
5930: }
5931:
5932: # ------------------------------------------------------- Course Group routines
5933:
5934: sub get_coursegroups {
5935: my ($cdom,$cnum,$group,$namespace) = @_;
5936: return(&dump($namespace,$cdom,$cnum,$group));
5937: }
5938:
5939: sub modify_coursegroup {
5940: my ($cdom,$cnum,$groupsettings) = @_;
5941: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
5942: }
5943:
5944: sub toggle_coursegroup_status {
5945: my ($cdom,$cnum,$group,$action) = @_;
5946: my ($from_namespace,$to_namespace);
5947: if ($action eq 'delete') {
5948: $from_namespace = 'coursegroups';
5949: $to_namespace = 'deleted_groups';
5950: } else {
5951: $from_namespace = 'deleted_groups';
5952: $to_namespace = 'coursegroups';
5953: }
5954: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
5955: if (my $tmp = &error(%curr_group)) {
5956: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
5957: return ('read error',$tmp);
5958: } else {
5959: my %savedsettings = %curr_group;
5960: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
5961: my $deloutcome;
5962: if ($result eq 'ok') {
5963: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
5964: } else {
5965: return ('write error',$result);
5966: }
5967: if ($deloutcome eq 'ok') {
5968: return 'ok';
5969: } else {
5970: return ('delete error',$deloutcome);
5971: }
5972: }
5973: }
5974:
5975: sub modify_group_roles {
5976: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
5977: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
5978: my $role = 'gr/'.&escape($userprivs);
5979: my ($uname,$udom) = split(/:/,$user);
5980: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
5981: if ($result eq 'ok') {
5982: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
5983: }
5984: return $result;
5985: }
5986:
5987: sub modify_coursegroup_membership {
5988: my ($cdom,$cnum,$membership) = @_;
5989: my $result = &put('groupmembership',$membership,$cdom,$cnum);
5990: return $result;
5991: }
5992:
5993: sub get_active_groups {
5994: my ($udom,$uname,$cdom,$cnum) = @_;
5995: my $now = time;
5996: my %groups = ();
5997: foreach my $key (keys(%env)) {
5998: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
5999: my ($start,$end) = split(/\./,$env{$key});
6000: if (($end!=0) && ($end<$now)) { next; }
6001: if (($start!=0) && ($start>$now)) { next; }
6002: if ($1 eq $cdom && $2 eq $cnum) {
6003: $groups{$3} = $env{$key} ;
6004: }
6005: }
6006: }
6007: return %groups;
6008: }
6009:
6010: sub get_group_membership {
6011: my ($cdom,$cnum,$group) = @_;
6012: return(&dump('groupmembership',$cdom,$cnum,$group));
6013: }
6014:
6015: sub get_users_groups {
6016: my ($udom,$uname,$courseid) = @_;
6017: my @usersgroups;
6018: my $cachetime=1800;
6019:
6020: my $hashid="$udom:$uname:$courseid";
6021: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6022: if (defined($cached)) {
6023: @usersgroups = split(/:/,$grouplist);
6024: } else {
6025: $grouplist = '';
6026: my $courseurl = &courseid_to_courseurl($courseid);
6027: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
6028: my $access_end = $env{'course.'.$courseid.
6029: '.default_enrollment_end_date'};
6030: my $now = time;
6031: foreach my $key (keys(%roleshash)) {
6032: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6033: my $group = $1;
6034: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6035: my $start = $2;
6036: my $end = $1;
6037: if ($start == -1) { next; } # deleted from group
6038: if (($start!=0) && ($start>$now)) { next; }
6039: if (($end!=0) && ($end<$now)) {
6040: if ($access_end && $access_end < $now) {
6041: if ($access_end - $end < 86400) {
6042: push(@usersgroups,$group);
6043: }
6044: }
6045: next;
6046: }
6047: push(@usersgroups,$group);
6048: }
6049: }
6050: }
6051: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6052: $grouplist = join(':',@usersgroups);
6053: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
6054: }
6055: return @usersgroups;
6056: }
6057:
6058: sub devalidate_getgroups_cache {
6059: my ($udom,$uname,$cdom,$cnum)=@_;
6060: my $courseid = $cdom.'_'.$cnum;
6061:
6062: my $hashid="$udom:$uname:$courseid";
6063: &devalidate_cache_new('getgroups',$hashid);
6064: }
6065:
6066: # ------------------------------------------------------------------ Plain Text
6067:
6068: sub plaintext {
6069: my ($short,$type,$cid,$forcedefault) = @_;
6070: if ($short =~ /^cr/) {
6071: return (split('/',$short))[-1];
6072: }
6073: if (!defined($cid)) {
6074: $cid = $env{'request.course.id'};
6075: }
6076: if (defined($cid) && ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '')) {
6077: unless ($forcedefault) {
6078: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6079: &Apache::lonlocal::mt_escape(\$roletext);
6080: return &Apache::lonlocal::mt($roletext);
6081: }
6082: }
6083: my %rolenames = (
6084: Course => 'std',
6085: Community => 'alt1',
6086: );
6087: if (defined($type) &&
6088: defined($rolenames{$type}) &&
6089: defined($prp{$short}{$rolenames{$type}})) {
6090: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
6091: } else {
6092: return &Apache::lonlocal::mt($prp{$short}{'std'});
6093: }
6094: }
6095:
6096: # ----------------------------------------------------------------- Assign Role
6097:
6098: sub assignrole {
6099: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6100: $context)=@_;
6101: my $mrole;
6102: if ($role =~ /^cr\//) {
6103: my $cwosec=$url;
6104: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
6105: unless (&allowed('ccr',$cwosec)) {
6106: my $refused = 1;
6107: if ($context eq 'requestcourses') {
6108: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6109: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6110: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6111: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6112: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6113: if ($crsenv{'internal.courseowner'} eq
6114: $env{'user.name'}.':'.$env{'user.domain'}) {
6115: $refused = '';
6116: }
6117: }
6118: }
6119: }
6120: }
6121: if ($refused) {
6122: &logthis('Refused custom assignrole: '.
6123: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6124: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6125: return 'refused';
6126: }
6127: }
6128: $mrole='cr';
6129: } elsif ($role =~ /^gr\//) {
6130: my $cwogrp=$url;
6131: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
6132: unless (&allowed('mdg',$cwogrp)) {
6133: &logthis('Refused group assignrole: '.
6134: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6135: $env{'user.name'}.' at '.$env{'user.domain'});
6136: return 'refused';
6137: }
6138: $mrole='gr';
6139: } else {
6140: my $cwosec=$url;
6141: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
6142: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6143: my $refused;
6144: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6145: if (!(&allowed('c'.$role,$url))) {
6146: $refused = 1;
6147: }
6148: } else {
6149: $refused = 1;
6150: }
6151: if ($refused) {
6152: if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6153: $refused = '';
6154: } elsif ($context eq 'requestcourses') {
6155: my @possroles = ('st','ta','ep','in','cc');
6156: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
6157: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6158: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6159: if ($crsenv{'internal.courseowner'} eq
6160: $env{'user.name'}.':'.$env{'user.domain'}) {
6161: $refused = '';
6162: }
6163: }
6164: }
6165: if ($refused) {
6166: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6167: ' '.$role.' '.$end.' '.$start.' by '.
6168: $env{'user.name'}.' at '.$env{'user.domain'});
6169: return 'refused';
6170: }
6171: }
6172: }
6173: $mrole=$role;
6174: }
6175: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
6176: "$udom:$uname:$url".'_'."$mrole=$role";
6177: if ($end) { $command.='_'.$end; }
6178: if ($start) {
6179: if ($end) {
6180: $command.='_'.$start;
6181: } else {
6182: $command.='_0_'.$start;
6183: }
6184: }
6185: my $origstart = $start;
6186: my $origend = $end;
6187: my $delflag;
6188: # actually delete
6189: if ($deleteflag) {
6190: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
6191: # modify command to delete the role
6192: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
6193: "$udom:$uname:$url".'_'."$mrole";
6194: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
6195: # set start and finish to negative values for userrolelog
6196: $start=-1;
6197: $end=-1;
6198: $delflag = 1;
6199: }
6200: }
6201: # send command
6202: my $answer=&reply($command,&homeserver($uname,$udom));
6203: # log new user role if status is ok
6204: if ($answer eq 'ok') {
6205: &userrolelog($role,$uname,$udom,$url,$start,$end);
6206: # for course roles, perform group memberships changes triggered by role change.
6207: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
6208: unless ($role =~ /^gr/) {
6209: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
6210: $origstart,$selfenroll,$context);
6211: }
6212: }
6213: return $answer;
6214: }
6215:
6216: # -------------------------------------------------- Modify user authentication
6217: # Overrides without validation
6218:
6219: sub modifyuserauth {
6220: my ($udom,$uname,$umode,$upass)=@_;
6221: my $uhome=&homeserver($uname,$udom);
6222: unless (&allowed('mau',$udom)) { return 'refused'; }
6223: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
6224: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6225: ' in domain '.$env{'request.role.domain'});
6226: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6227: &escape($upass),$uhome);
6228: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
6229: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6230: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6231: &log($udom,,$uname,$uhome,
6232: 'Authentication changed by '.$env{'user.domain'}.', '.
6233: $env{'user.name'}.', '.$umode.
6234: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6235: unless ($reply eq 'ok') {
6236: &logthis('Authentication mode error: '.$reply);
6237: return 'error: '.$reply;
6238: }
6239: return 'ok';
6240: }
6241:
6242: # --------------------------------------------------------------- Modify a user
6243:
6244: sub modifyuser {
6245: my ($udom, $uname, $uid,
6246: $umode, $upass, $first,
6247: $middle, $last, $gene,
6248: $forceid, $desiredhome, $email, $inststatus)=@_;
6249: $udom= &LONCAPA::clean_domain($udom);
6250: $uname=&LONCAPA::clean_username($uname);
6251: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
6252: $umode.', '.$first.', '.$middle.', '.
6253: $last.', '.$gene.'(forceid: '.$forceid.')'.
6254: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6255: ' desiredhome not specified').
6256: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6257: ' in domain '.$env{'request.role.domain'});
6258: my $uhome=&homeserver($uname,$udom,'true');
6259: # ----------------------------------------------------------------- Create User
6260: if (($uhome eq 'no_host') &&
6261: (($umode && $upass) || ($umode eq 'localauth'))) {
6262: my $unhome='';
6263: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
6264: $unhome = $desiredhome;
6265: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6266: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
6267: } else { # load balancing routine for determining $unhome
6268: my $loadm=10000000;
6269: my %servers = &get_servers($udom,'library');
6270: foreach my $tryserver (keys(%servers)) {
6271: my $answer=reply('load',$tryserver);
6272: if (($answer=~/\d+/) && ($answer<$loadm)) {
6273: $loadm=$answer;
6274: $unhome=$tryserver;
6275: }
6276: }
6277: }
6278: if (($unhome eq '') || ($unhome eq 'no_host')) {
6279: return 'error: unable to find a home server for '.$uname.
6280: ' in domain '.$udom;
6281: }
6282: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6283: &escape($upass),$unhome);
6284: unless ($reply eq 'ok') {
6285: return 'error: '.$reply;
6286: }
6287: $uhome=&homeserver($uname,$udom,'true');
6288: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
6289: return 'error: unable verify users home machine.';
6290: }
6291: } # End of creation of new user
6292: # ---------------------------------------------------------------------- Add ID
6293: if ($uid) {
6294: $uid=~tr/A-Z/a-z/;
6295: my %uidhash=&idrget($udom,$uname);
6296: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6297: && (!$forceid)) {
6298: unless ($uid eq $uidhash{$uname}) {
6299: return 'error: user id "'.$uid.'" does not match '.
6300: 'current user id "'.$uidhash{$uname}.'".';
6301: }
6302: } else {
6303: &idput($udom,($uname => $uid));
6304: }
6305: }
6306: # -------------------------------------------------------------- Add names, etc
6307: my @tmp=&get('environment',
6308: ['firstname','middlename','lastname','generation','id',
6309: 'permanentemail','inststatus'],
6310: $udom,$uname);
6311: my %names;
6312: if ($tmp[0] =~ m/^error:.*/) {
6313: %names=();
6314: } else {
6315: %names = @tmp;
6316: }
6317: #
6318: # Make sure to not trash student environment if instructor does not bother
6319: # to supply name and email information
6320: #
6321: if ($first) { $names{'firstname'} = $first; }
6322: if (defined($middle)) { $names{'middlename'} = $middle; }
6323: if ($last) { $names{'lastname'} = $last; }
6324: if (defined($gene)) { $names{'generation'} = $gene; }
6325: if ($email) {
6326: $email=~s/[^\w\@\.\-\,]//gs;
6327: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
6328: }
6329: if ($uid) { $names{'id'} = $uid; }
6330: if (defined($inststatus)) {
6331: $names{'inststatus'} = '';
6332: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
6333: if (ref($usertypes) eq 'HASH') {
6334: my @okstatuses;
6335: foreach my $item (split(/:/,$inststatus)) {
6336: if (defined($usertypes->{$item})) {
6337: push(@okstatuses,$item);
6338: }
6339: }
6340: if (@okstatuses) {
6341: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
6342: }
6343: }
6344: }
6345: my $reply = &put('environment', \%names, $udom,$uname);
6346: if ($reply ne 'ok') { return 'error: '.$reply; }
6347: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
6348: &devalidate_cache_new('namescache',$uname.':'.$udom);
6349: my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
6350: $umode.', '.$first.', '.$middle.', '.
6351: $last.', '.$gene.', '.$email.', '.$inststatus;
6352: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
6353: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
6354: } else {
6355: $logmsg .= ' during self creation';
6356: }
6357: &logthis($logmsg);
6358: return 'ok';
6359: }
6360:
6361: # -------------------------------------------------------------- Modify student
6362:
6363: sub modifystudent {
6364: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
6365: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
6366: $selfenroll,$context,$inststatus)=@_;
6367: if (!$cid) {
6368: unless ($cid=$env{'request.course.id'}) {
6369: return 'not_in_class';
6370: }
6371: }
6372: # --------------------------------------------------------------- Make the user
6373: my $reply=&modifyuser
6374: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
6375: $desiredhome,$email,$inststatus);
6376: unless ($reply eq 'ok') { return $reply; }
6377: # This will cause &modify_student_enrollment to get the uid from the
6378: # students environment
6379: $uid = undef if (!$forceid);
6380: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
6381: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
6382: return $reply;
6383: }
6384:
6385: sub modify_student_enrollment {
6386: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
6387: my ($cdom,$cnum,$chome);
6388: if (!$cid) {
6389: unless ($cid=$env{'request.course.id'}) {
6390: return 'not_in_class';
6391: }
6392: $cdom=$env{'course.'.$cid.'.domain'};
6393: $cnum=$env{'course.'.$cid.'.num'};
6394: } else {
6395: ($cdom,$cnum)=split(/_/,$cid);
6396: }
6397: $chome=$env{'course.'.$cid.'.home'};
6398: if (!$chome) {
6399: $chome=&homeserver($cnum,$cdom);
6400: }
6401: if (!$chome) { return 'unknown_course'; }
6402: # Make sure the user exists
6403: my $uhome=&homeserver($uname,$udom);
6404: if (($uhome eq '') || ($uhome eq 'no_host')) {
6405: return 'error: no such user';
6406: }
6407: # Get student data if we were not given enough information
6408: if (!defined($first) || $first eq '' ||
6409: !defined($last) || $last eq '' ||
6410: !defined($uid) || $uid eq '' ||
6411: !defined($middle) || $middle eq '' ||
6412: !defined($gene) || $gene eq '') {
6413: # They did not supply us with enough data to enroll the student, so
6414: # we need to pick up more information.
6415: my %tmp = &get('environment',
6416: ['firstname','middlename','lastname', 'generation','id']
6417: ,$udom,$uname);
6418:
6419: #foreach my $key (keys(%tmp)) {
6420: # &logthis("key $key = ".$tmp{$key});
6421: #}
6422: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
6423: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
6424: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
6425: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
6426: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
6427: }
6428: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
6429: my $reply=cput('classlist',
6430: {"$uname:$udom" =>
6431: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
6432: $cdom,$cnum);
6433: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
6434: return 'error: '.$reply;
6435: } else {
6436: &devalidate_getsection_cache($udom,$uname,$cid);
6437: }
6438: # Add student role to user
6439: my $uurl='/'.$cid;
6440: $uurl=~s/\_/\//g;
6441: if ($usec) {
6442: $uurl.='/'.$usec;
6443: }
6444: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
6445: }
6446:
6447: sub format_name {
6448: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
6449: my $name;
6450: if ($first ne 'lastname') {
6451: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
6452: } else {
6453: if ($lastname=~/\S/) {
6454: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
6455: $name=~s/\s+,/,/;
6456: } else {
6457: $name.= $firstname.' '.$middlename.' '.$generation;
6458: }
6459: }
6460: $name=~s/^\s+//;
6461: $name=~s/\s+$//;
6462: $name=~s/\s+/ /g;
6463: return $name;
6464: }
6465:
6466: # ------------------------------------------------- Write to course preferences
6467:
6468: sub writecoursepref {
6469: my ($courseid,%prefs)=@_;
6470: $courseid=~s/^\///;
6471: $courseid=~s/\_/\//g;
6472: my ($cdomain,$cnum)=split(/\//,$courseid);
6473: my $chome=homeserver($cnum,$cdomain);
6474: if (($chome eq '') || ($chome eq 'no_host')) {
6475: return 'error: no such course';
6476: }
6477: my $cstring='';
6478: foreach my $pref (keys(%prefs)) {
6479: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
6480: }
6481: $cstring=~s/\&$//;
6482: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
6483: }
6484:
6485: # ---------------------------------------------------------- Make/modify course
6486:
6487: sub createcourse {
6488: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
6489: $course_owner,$crstype,$cnum,$context,$category)=@_;
6490: $url=&declutter($url);
6491: my $cid='';
6492: if ($context eq 'requestcourses') {
6493: my $can_create = 0;
6494: my ($ownername,$ownerdom) = split(':',$course_owner);
6495: if ($udom eq $ownerdom) {
6496: if (&usertools_access($ownername,$ownerdom,$category,undef,
6497: $context)) {
6498: $can_create = 1;
6499: }
6500: } else {
6501: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
6502: $category);
6503: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
6504: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
6505: if (@curr > 0) {
6506: my @options = qw(approval validate autolimit);
6507: my $optregex = join('|',@options);
6508: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
6509: $can_create = 1;
6510: }
6511: }
6512: }
6513: }
6514: if ($can_create) {
6515: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
6516: unless (&allowed('ccc',$udom)) {
6517: return 'refused';
6518: }
6519: }
6520: } else {
6521: return 'refused';
6522: }
6523: } elsif (!&allowed('ccc',$udom)) {
6524: return 'refused';
6525: }
6526: # --------------------------------------------------------------- Get Unique ID
6527: my $uname;
6528: if ($cnum =~ /^$match_courseid$/) {
6529: my $chome=&homeserver($cnum,$udom,'true');
6530: if (($chome eq '') || ($chome eq 'no_host')) {
6531: $uname = $cnum;
6532: } else {
6533: $uname = &generate_coursenum($udom);
6534: }
6535: } else {
6536: $uname = &generate_coursenum($udom);
6537: }
6538: return $uname if ($uname =~ /^error/);
6539: # -------------------------------------------------- Check supplied server name
6540: $course_server = $env{'user.homeserver'} if (! defined($course_server));
6541: if (! &is_library($course_server)) {
6542: return 'error:bad server name '.$course_server;
6543: }
6544: # ------------------------------------------------------------- Make the course
6545: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
6546: $course_server);
6547: unless ($reply eq 'ok') { return 'error: '.$reply; }
6548: my $uhome=&homeserver($uname,$udom,'true');
6549: if (($uhome eq '') || ($uhome eq 'no_host')) {
6550: return 'error: no such course';
6551: }
6552: # ----------------------------------------------------------------- Course made
6553: # log existence
6554: my $now = time;
6555: my $newcourse = {
6556: $udom.'_'.$uname => {
6557: description => $description,
6558: inst_code => $inst_code,
6559: owner => $course_owner,
6560: type => $crstype,
6561: creator => $env{'user.name'}.':'.
6562: $env{'user.domain'},
6563: created => $now,
6564: context => $context,
6565: },
6566: };
6567: &courseidput($udom,$newcourse,$uhome,'notime');
6568: # set toplevel url
6569: my $topurl=$url;
6570: unless ($nonstandard) {
6571: # ------------------------------------------ For standard courses, make top url
6572: my $mapurl=&clutter($url);
6573: if ($mapurl eq '/res/') { $mapurl=''; }
6574: $env{'form.initmap'}=(<<ENDINITMAP);
6575: <map>
6576: <resource id="1" type="start"></resource>
6577: <resource id="2" src="$mapurl"></resource>
6578: <resource id="3" type="finish"></resource>
6579: <link index="1" from="1" to="2"></link>
6580: <link index="2" from="2" to="3"></link>
6581: </map>
6582: ENDINITMAP
6583: $topurl=&declutter(
6584: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
6585: );
6586: }
6587: # ----------------------------------------------------------- Write preferences
6588: &writecoursepref($udom.'_'.$uname,
6589: ('description' => $description,
6590: 'url' => $topurl));
6591: return '/'.$udom.'/'.$uname;
6592: }
6593:
6594: # ------------------------------------------------------------------- Create ID
6595: sub generate_coursenum {
6596: my ($udom) = @_;
6597: my $domdesc = &domain($udom);
6598: return 'error: invalid domain' if ($domdesc eq '');
6599: my $uname=int(1+rand(9)).
6600: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
6601: substr($$.time,0,5).unpack("H8",pack("I32",time)).
6602: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
6603: # ----------------------------------------------- Make sure that does not exist
6604: my $uhome=&homeserver($uname,$udom,'true');
6605: unless (($uhome eq '') || ($uhome eq 'no_host')) {
6606: $uname=int(1+rand(9)).
6607: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
6608: substr($$.time,0,5).unpack("H8",pack("I32",time)).
6609: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
6610: $uhome=&homeserver($uname,$udom,'true');
6611: unless (($uhome eq '') || ($uhome eq 'no_host')) {
6612: return 'error: unable to generate unique course-ID';
6613: }
6614: }
6615: return $uname;
6616: }
6617:
6618: sub is_course {
6619: my ($cdom,$cnum) = @_;
6620: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
6621: undef,'.');
6622: if (exists($courses{$cdom.'_'.$cnum})) {
6623: return 1;
6624: }
6625: return 0;
6626: }
6627:
6628: sub store_userdata {
6629: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
6630: my $result;
6631: if ($datakey ne '') {
6632: if (ref($storehash) eq 'HASH') {
6633: if ($udom eq '' || $uname eq '') {
6634: $udom = $env{'user.domain'};
6635: $uname = $env{'user.name'};
6636: }
6637: my $uhome=&homeserver($uname,$udom);
6638: if (($uhome eq '') || ($uhome eq 'no_host')) {
6639: $result = 'error: no_host';
6640: } else {
6641: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
6642: $storehash->{'host'} = $perlvar{'lonHostID'};
6643:
6644: my $namevalue='';
6645: foreach my $key (keys(%{$storehash})) {
6646: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6647: }
6648: $namevalue=~s/\&$//;
6649: $result = &reply("store:$env{'user.domain'}:$env{'user.name'}:".
6650: "$namespace:$datakey:$namevalue",$uhome);
6651: }
6652: } else {
6653: $result = 'error: data to store was not a hash reference';
6654: }
6655: } else {
6656: $result= 'error: invalid requestkey';
6657: }
6658: return $result;
6659: }
6660:
6661: # ---------------------------------------------------------- Assign Custom Role
6662:
6663: sub assigncustomrole {
6664: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
6665: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
6666: $end,$start,$deleteflag,$selfenroll,$context);
6667: }
6668:
6669: # ----------------------------------------------------------------- Revoke Role
6670:
6671: sub revokerole {
6672: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
6673: my $now=time;
6674: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
6675: }
6676:
6677: # ---------------------------------------------------------- Revoke Custom Role
6678:
6679: sub revokecustomrole {
6680: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
6681: my $now=time;
6682: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
6683: $deleteflag,$selfenroll,$context);
6684: }
6685:
6686: # ------------------------------------------------------------ Disk usage
6687: sub diskusage {
6688: my ($udom,$uname,$directorypath,$getpropath)=@_;
6689: $directorypath =~ s/\/$//;
6690: my $listing=&reply('du2:'.&escape($directorypath).':'
6691: .&escape($getpropath).':'.&escape($uname).':'
6692: .&escape($udom),homeserver($uname,$udom));
6693: if ($listing eq 'unknown_cmd') {
6694: if ($getpropath) {
6695: $directorypath = &propath($udom,$uname).'/'.$directorypath;
6696: }
6697: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
6698: }
6699: return $listing;
6700: }
6701:
6702: sub is_locked {
6703: my ($file_name, $domain, $user) = @_;
6704: my @check;
6705: my $is_locked;
6706: push @check, $file_name;
6707: my %locked = &get('file_permissions',\@check,
6708: $env{'user.domain'},$env{'user.name'});
6709: my ($tmp)=keys(%locked);
6710: if ($tmp=~/^error:/) { undef(%locked); }
6711:
6712: if (ref($locked{$file_name}) eq 'ARRAY') {
6713: $is_locked = 'false';
6714: foreach my $entry (@{$locked{$file_name}}) {
6715: if (ref($entry) eq 'ARRAY') {
6716: $is_locked = 'true';
6717: last;
6718: }
6719: }
6720: } else {
6721: $is_locked = 'false';
6722: }
6723: }
6724:
6725: sub declutter_portfile {
6726: my ($file) = @_;
6727: $file =~ s{^(/portfolio/|portfolio/)}{/};
6728: return $file;
6729: }
6730:
6731: # ------------------------------------------------------------- Mark as Read Only
6732:
6733: sub mark_as_readonly {
6734: my ($domain,$user,$files,$what) = @_;
6735: my %current_permissions = &dump('file_permissions',$domain,$user);
6736: my ($tmp)=keys(%current_permissions);
6737: if ($tmp=~/^error:/) { undef(%current_permissions); }
6738: foreach my $file (@{$files}) {
6739: $file = &declutter_portfile($file);
6740: push(@{$current_permissions{$file}},$what);
6741: }
6742: &put('file_permissions',\%current_permissions,$domain,$user);
6743: return;
6744: }
6745:
6746: # ------------------------------------------------------------Save Selected Files
6747:
6748: sub save_selected_files {
6749: my ($user, $path, @files) = @_;
6750: my $filename = $user."savedfiles";
6751: my @other_files = &files_not_in_path($user, $path);
6752: open (OUT, '>'.$tmpdir.$filename);
6753: foreach my $file (@files) {
6754: print (OUT $env{'form.currentpath'}.$file."\n");
6755: }
6756: foreach my $file (@other_files) {
6757: print (OUT $file."\n");
6758: }
6759: close (OUT);
6760: return 'ok';
6761: }
6762:
6763: sub clear_selected_files {
6764: my ($user) = @_;
6765: my $filename = $user."savedfiles";
6766: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6767: print (OUT undef);
6768: close (OUT);
6769: return ("ok");
6770: }
6771:
6772: sub files_in_path {
6773: my ($user, $path) = @_;
6774: my $filename = $user."savedfiles";
6775: my %return_files;
6776: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6777: while (my $line_in = <IN>) {
6778: chomp ($line_in);
6779: my @paths_and_file = split (m!/!, $line_in);
6780: my $file_part = pop (@paths_and_file);
6781: my $path_part = join ('/', @paths_and_file);
6782: $path_part.='/';
6783: my $path_and_file = $path_part.$file_part;
6784: if ($path_part eq $path) {
6785: $return_files{$file_part}= 'selected';
6786: }
6787: }
6788: close (IN);
6789: return (\%return_files);
6790: }
6791:
6792: # called in portfolio select mode, to show files selected NOT in current directory
6793: sub files_not_in_path {
6794: my ($user, $path) = @_;
6795: my $filename = $user."savedfiles";
6796: my @return_files;
6797: my $path_part;
6798: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6799: while (my $line = <IN>) {
6800: #ok, I know it's clunky, but I want it to work
6801: my @paths_and_file = split(m|/|, $line);
6802: my $file_part = pop(@paths_and_file);
6803: chomp($file_part);
6804: my $path_part = join('/', @paths_and_file);
6805: $path_part .= '/';
6806: my $path_and_file = $path_part.$file_part;
6807: if ($path_part ne $path) {
6808: push(@return_files, ($path_and_file));
6809: }
6810: }
6811: close(OUT);
6812: return (@return_files);
6813: }
6814:
6815: #----------------------------------------------Get portfolio file permissions
6816:
6817: sub get_portfile_permissions {
6818: my ($domain,$user) = @_;
6819: my %current_permissions = &dump('file_permissions',$domain,$user);
6820: my ($tmp)=keys(%current_permissions);
6821: if ($tmp=~/^error:/) { undef(%current_permissions); }
6822: return \%current_permissions;
6823: }
6824:
6825: #---------------------------------------------Get portfolio file access controls
6826:
6827: sub get_access_controls {
6828: my ($current_permissions,$group,$file) = @_;
6829: my %access;
6830: my $real_file = $file;
6831: $file =~ s/\.meta$//;
6832: if (defined($file)) {
6833: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
6834: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
6835: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
6836: }
6837: }
6838: } else {
6839: foreach my $key (keys(%{$current_permissions})) {
6840: if ($key =~ /\0accesscontrol$/) {
6841: if (defined($group)) {
6842: if ($key !~ m-^\Q$group\E/-) {
6843: next;
6844: }
6845: }
6846: my ($fullpath) = split(/\0/,$key);
6847: if (ref($$current_permissions{$key}) eq 'HASH') {
6848: foreach my $control (keys(%{$$current_permissions{$key}})) {
6849: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
6850: }
6851: }
6852: }
6853: }
6854: }
6855: return %access;
6856: }
6857:
6858: sub modify_access_controls {
6859: my ($file_name,$changes,$domain,$user)=@_;
6860: my ($outcome,$deloutcome);
6861: my %store_permissions;
6862: my %new_values;
6863: my %new_control;
6864: my %translation;
6865: my @deletions = ();
6866: my $now = time;
6867: if (exists($$changes{'activate'})) {
6868: if (ref($$changes{'activate'}) eq 'HASH') {
6869: my @newitems = sort(keys(%{$$changes{'activate'}}));
6870: my $numnew = scalar(@newitems);
6871: for (my $i=0; $i<$numnew; $i++) {
6872: my $newkey = $newitems[$i];
6873: my $newid = &Apache::loncommon::get_cgi_id();
6874: if ($newkey =~ /^\d+:/) {
6875: $newkey =~ s/^(\d+)/$newid/;
6876: $translation{$1} = $newid;
6877: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
6878: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
6879: $translation{$1} = $newid;
6880: }
6881: $new_values{$file_name."\0".$newkey} =
6882: $$changes{'activate'}{$newitems[$i]};
6883: $new_control{$newkey} = $now;
6884: }
6885: }
6886: }
6887: my %todelete;
6888: my %changed_items;
6889: foreach my $action ('delete','update') {
6890: if (exists($$changes{$action})) {
6891: if (ref($$changes{$action}) eq 'HASH') {
6892: foreach my $key (keys(%{$$changes{$action}})) {
6893: my ($itemnum) = ($key =~ /^([^:]+):/);
6894: if ($action eq 'delete') {
6895: $todelete{$itemnum} = 1;
6896: } else {
6897: $changed_items{$itemnum} = $key;
6898: }
6899: }
6900: }
6901: }
6902: }
6903: # get lock on access controls for file.
6904: my $lockhash = {
6905: $file_name."\0".'locked_access_records' => $env{'user.name'}.
6906: ':'.$env{'user.domain'},
6907: };
6908: my $tries = 0;
6909: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
6910:
6911: while (($gotlock ne 'ok') && $tries <3) {
6912: $tries ++;
6913: sleep 1;
6914: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
6915: }
6916: if ($gotlock eq 'ok') {
6917: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
6918: my ($tmp)=keys(%curr_permissions);
6919: if ($tmp=~/^error:/) { undef(%curr_permissions); }
6920: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
6921: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
6922: if (ref($curr_controls) eq 'HASH') {
6923: foreach my $control_item (keys(%{$curr_controls})) {
6924: my ($itemnum) = ($control_item =~ /^([^:]+):/);
6925: if (defined($todelete{$itemnum})) {
6926: push(@deletions,$file_name."\0".$control_item);
6927: } else {
6928: if (defined($changed_items{$itemnum})) {
6929: $new_control{$changed_items{$itemnum}} = $now;
6930: push(@deletions,$file_name."\0".$control_item);
6931: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
6932: } else {
6933: $new_control{$control_item} = $$curr_controls{$control_item};
6934: }
6935: }
6936: }
6937: }
6938: }
6939: my ($group);
6940: if (&is_course($domain,$user)) {
6941: ($group,my $file) = split(/\//,$file_name,2);
6942: }
6943: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
6944: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
6945: $outcome = &put('file_permissions',\%new_values,$domain,$user);
6946: # remove lock
6947: my @del_lock = ($file_name."\0".'locked_access_records');
6948: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
6949: my $sqlresult =
6950: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
6951: $group);
6952: } else {
6953: $outcome = "error: could not obtain lockfile\n";
6954: }
6955: return ($outcome,$deloutcome,\%new_values,\%translation);
6956: }
6957:
6958: sub make_public_indefinitely {
6959: my ($requrl) = @_;
6960: my $now = time;
6961: my $action = 'activate';
6962: my $aclnum = 0;
6963: if (&is_portfolio_url($requrl)) {
6964: my (undef,$udom,$unum,$file_name,$group) =
6965: &parse_portfolio_url($requrl);
6966: my $current_perms = &get_portfile_permissions($udom,$unum);
6967: my %access_controls = &get_access_controls($current_perms,
6968: $group,$file_name);
6969: foreach my $key (keys(%{$access_controls{$file_name}})) {
6970: my ($num,$scope,$end,$start) =
6971: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6972: if ($scope eq 'public') {
6973: if ($start <= $now && $end == 0) {
6974: $action = 'none';
6975: } else {
6976: $action = 'update';
6977: $aclnum = $num;
6978: }
6979: last;
6980: }
6981: }
6982: if ($action eq 'none') {
6983: return 'ok';
6984: } else {
6985: my %changes;
6986: my $newend = 0;
6987: my $newstart = $now;
6988: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
6989: $changes{$action}{$newkey} = {
6990: type => 'public',
6991: time => {
6992: start => $newstart,
6993: end => $newend,
6994: },
6995: };
6996: my ($outcome,$deloutcome,$new_values,$translation) =
6997: &modify_access_controls($file_name,\%changes,$udom,$unum);
6998: return $outcome;
6999: }
7000: } else {
7001: return 'invalid';
7002: }
7003: }
7004:
7005: #------------------------------------------------------Get Marked as Read Only
7006:
7007: sub get_marked_as_readonly {
7008: my ($domain,$user,$what,$group) = @_;
7009: my $current_permissions = &get_portfile_permissions($domain,$user);
7010: my @readonly_files;
7011: my $cmp1=$what;
7012: if (ref($what)) { $cmp1=join('',@{$what}) };
7013: while (my ($file_name,$value) = each(%{$current_permissions})) {
7014: if (defined($group)) {
7015: if ($file_name !~ m-^\Q$group\E/-) {
7016: next;
7017: }
7018: }
7019: if (ref($value) eq "ARRAY"){
7020: foreach my $stored_what (@{$value}) {
7021: my $cmp2=$stored_what;
7022: if (ref($stored_what) eq 'ARRAY') {
7023: $cmp2=join('',@{$stored_what});
7024: }
7025: if ($cmp1 eq $cmp2) {
7026: push(@readonly_files, $file_name);
7027: last;
7028: } elsif (!defined($what)) {
7029: push(@readonly_files, $file_name);
7030: last;
7031: }
7032: }
7033: }
7034: }
7035: return @readonly_files;
7036: }
7037: #-----------------------------------------------------------Get Marked as Read Only Hash
7038:
7039: sub get_marked_as_readonly_hash {
7040: my ($current_permissions,$group,$what) = @_;
7041: my %readonly_files;
7042: while (my ($file_name,$value) = each(%{$current_permissions})) {
7043: if (defined($group)) {
7044: if ($file_name !~ m-^\Q$group\E/-) {
7045: next;
7046: }
7047: }
7048: if (ref($value) eq "ARRAY"){
7049: foreach my $stored_what (@{$value}) {
7050: if (ref($stored_what) eq 'ARRAY') {
7051: foreach my $lock_descriptor(@{$stored_what}) {
7052: if ($lock_descriptor eq 'graded') {
7053: $readonly_files{$file_name} = 'graded';
7054: } elsif ($lock_descriptor eq 'handback') {
7055: $readonly_files{$file_name} = 'handback';
7056: } else {
7057: if (!exists($readonly_files{$file_name})) {
7058: $readonly_files{$file_name} = 'locked';
7059: }
7060: }
7061: }
7062: }
7063: }
7064: }
7065: }
7066: return %readonly_files;
7067: }
7068: # ------------------------------------------------------------ Unmark as Read Only
7069:
7070: sub unmark_as_readonly {
7071: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7072: # for portfolio submissions, $what contains [$symb,$crsid]
7073: my ($domain,$user,$what,$file_name,$group) = @_;
7074: $file_name = &declutter_portfile($file_name);
7075: my $symb_crs = $what;
7076: if (ref($what)) { $symb_crs=join('',@$what); }
7077: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
7078: my ($tmp)=keys(%current_permissions);
7079: if ($tmp=~/^error:/) { undef(%current_permissions); }
7080: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
7081: foreach my $file (@readonly_files) {
7082: my $clean_file = &declutter_portfile($file);
7083: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
7084: my $current_locks = $current_permissions{$file};
7085: my @new_locks;
7086: my @del_keys;
7087: if (ref($current_locks) eq "ARRAY"){
7088: foreach my $locker (@{$current_locks}) {
7089: my $compare=$locker;
7090: if (ref($locker) eq 'ARRAY') {
7091: $compare=join('',@{$locker});
7092: if ($compare ne $symb_crs) {
7093: push(@new_locks, $locker);
7094: }
7095: }
7096: }
7097: if (scalar(@new_locks) > 0) {
7098: $current_permissions{$file} = \@new_locks;
7099: } else {
7100: push(@del_keys, $file);
7101: &del('file_permissions',\@del_keys, $domain, $user);
7102: delete($current_permissions{$file});
7103: }
7104: }
7105: }
7106: &put('file_permissions',\%current_permissions,$domain,$user);
7107: return;
7108: }
7109:
7110: # ------------------------------------------------------------ Directory lister
7111:
7112: sub dirlist {
7113: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
7114: $uri=~s/^\///;
7115: $uri=~s/\/$//;
7116: my ($udom, $uname);
7117: if ($getuserdir) {
7118: $udom = $userdomain;
7119: $uname = $username;
7120: } else {
7121: (undef,$udom,$uname)=split(/\//,$uri);
7122: if(defined($userdomain)) {
7123: $udom = $userdomain;
7124: }
7125: if(defined($username)) {
7126: $uname = $username;
7127: }
7128: }
7129: my ($dirRoot,$listing,@listing_results);
7130:
7131: $dirRoot = $perlvar{'lonDocRoot'};
7132: if (defined($getpropath)) {
7133: $dirRoot = &propath($udom,$uname);
7134: $dirRoot =~ s/\/$//;
7135: } elsif (defined($getuserdir)) {
7136: my $subdir=$uname.'__';
7137: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7138: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7139: ."/$udom/$subdir/$uname";
7140: } elsif (defined($alternateRoot)) {
7141: $dirRoot = $alternateRoot;
7142: }
7143:
7144: if($udom) {
7145: if($uname) {
7146: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
7147: .$getuserdir.':'.&escape($dirRoot)
7148: .':'.&escape($uname).':'.&escape($udom),
7149: &homeserver($uname,$udom));
7150: if ($listing eq 'unknown_cmd') {
7151: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7152: &homeserver($uname,$udom));
7153: } else {
7154: @listing_results = map { &unescape($_); } split(/:/,$listing);
7155: }
7156: if ($listing eq 'unknown_cmd') {
7157: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7158: &homeserver($uname,$udom));
7159: @listing_results = split(/:/,$listing);
7160: } else {
7161: @listing_results = map { &unescape($_); } split(/:/,$listing);
7162: }
7163: return @listing_results;
7164: } elsif(!$alternateRoot) {
7165: my %allusers;
7166: my %servers = &get_servers($udom,'library');
7167: foreach my $tryserver (keys(%servers)) {
7168: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7169: &escape($udom),$tryserver);
7170: if ($listing eq 'unknown_cmd') {
7171: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7172: $udom, $tryserver);
7173: } else {
7174: @listing_results = map { &unescape($_); } split(/:/,$listing);
7175: }
7176: if ($listing eq 'unknown_cmd') {
7177: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7178: $udom, $tryserver);
7179: @listing_results = split(/:/,$listing);
7180: } else {
7181: @listing_results =
7182: map { &unescape($_); } split(/:/,$listing);
7183: }
7184: if ($listing_results[0] ne 'no_such_dir' &&
7185: $listing_results[0] ne 'empty' &&
7186: $listing_results[0] ne 'con_lost') {
7187: foreach my $line (@listing_results) {
7188: my ($entry) = split(/&/,$line,2);
7189: $allusers{$entry} = 1;
7190: }
7191: }
7192: }
7193: my $alluserstr='';
7194: foreach my $user (sort(keys(%allusers))) {
7195: $alluserstr.=$user.'&user:';
7196: }
7197: $alluserstr=~s/:$//;
7198: return split(/:/,$alluserstr);
7199: } else {
7200: return ('missing user name');
7201: }
7202: } elsif(!defined($getpropath)) {
7203: my @all_domains = sort(&all_domains());
7204: foreach my $domain (@all_domains) {
7205: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7206: }
7207: return @all_domains;
7208: } else {
7209: return ('missing domain');
7210: }
7211: }
7212:
7213: # --------------------------------------------- GetFileTimestamp
7214: # This function utilizes dirlist and returns the date stamp for
7215: # when it was last modified. It will also return an error of -1
7216: # if an error occurs
7217:
7218: sub GetFileTimestamp {
7219: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
7220: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7221: $studentName = &LONCAPA::clean_username($studentName);
7222: my ($fileStat) =
7223: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7224: undef,$getuserdir);
7225: my @stats = split('&', $fileStat);
7226: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7227: # @stats contains first the filename, then the stat output
7228: return $stats[10]; # so this is 10 instead of 9.
7229: } else {
7230: return -1;
7231: }
7232: }
7233:
7234: sub stat_file {
7235: my ($uri) = @_;
7236: $uri = &clutter_with_no_wrapper($uri);
7237:
7238: my ($udom,$uname,$file);
7239: if ($uri =~ m-^/(uploaded|editupload)/-) {
7240: ($udom,$uname,$file) =
7241: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
7242: $file = 'userfiles/'.$file;
7243: }
7244: if ($uri =~ m-^/res/-) {
7245: ($udom,$uname) =
7246: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
7247: $file = $uri;
7248: }
7249:
7250: if (!$udom || !$uname || !$file) {
7251: # unable to handle the uri
7252: return ();
7253: }
7254: my $getpropath;
7255: if ($file =~ /^userfiles\//) {
7256: $getpropath = 1;
7257: }
7258: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
7259: my @stats = split('&', $result);
7260:
7261: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7262: shift(@stats); #filename is first
7263: return @stats;
7264: }
7265: return ();
7266: }
7267:
7268: # -------------------------------------------------------- Value of a Condition
7269:
7270: # gets the value of a specific preevaluated condition
7271: # stored in the string $env{user.state.<cid>}
7272: # or looks up a condition reference in the bighash and if if hasn't
7273: # already been evaluated recurses into docondval to get the value of
7274: # the condition, then memoizing it to
7275: # $env{user.state.<cid>.<condition>}
7276: sub directcondval {
7277: my $number=shift;
7278: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
7279: &Apache::lonuserstate::evalstate();
7280: }
7281: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
7282: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
7283: } elsif ($number =~ /^_/) {
7284: my $sub_condition;
7285: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7286: &GDBM_READER(),0640)) {
7287: $sub_condition=$bighash{'conditions'.$number};
7288: untie(%bighash);
7289: }
7290: my $value = &docondval($sub_condition);
7291: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
7292: return $value;
7293: }
7294: if ($env{'user.state.'.$env{'request.course.id'}}) {
7295: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
7296: } else {
7297: return 2;
7298: }
7299: }
7300:
7301: # get the collection of conditions for this resource
7302: sub condval {
7303: my $condidx=shift;
7304: my $allpathcond='';
7305: foreach my $cond (split(/\|/,$condidx)) {
7306: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
7307: $allpathcond.=
7308: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
7309: }
7310: }
7311: $allpathcond=~s/\|$//;
7312: return &docondval($allpathcond);
7313: }
7314:
7315: #evaluates an expression of conditions
7316: sub docondval {
7317: my ($allpathcond) = @_;
7318: my $result=0;
7319: if ($env{'request.course.id'}
7320: && defined($allpathcond)) {
7321: my $operand='|';
7322: my @stack;
7323: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
7324: if ($chunk eq '(') {
7325: push @stack,($operand,$result);
7326: } elsif ($chunk eq ')') {
7327: my $before=pop @stack;
7328: if (pop @stack eq '&') {
7329: $result=$result>$before?$before:$result;
7330: } else {
7331: $result=$result>$before?$result:$before;
7332: }
7333: } elsif (($chunk eq '&') || ($chunk eq '|')) {
7334: $operand=$chunk;
7335: } else {
7336: my $new=directcondval($chunk);
7337: if ($operand eq '&') {
7338: $result=$result>$new?$new:$result;
7339: } else {
7340: $result=$result>$new?$result:$new;
7341: }
7342: }
7343: }
7344: }
7345: return $result;
7346: }
7347:
7348: # ---------------------------------------------------- Devalidate courseresdata
7349:
7350: sub devalidatecourseresdata {
7351: my ($coursenum,$coursedomain)=@_;
7352: my $hashid=$coursenum.':'.$coursedomain;
7353: &devalidate_cache_new('courseres',$hashid);
7354: }
7355:
7356:
7357: # --------------------------------------------------- Course Resourcedata Query
7358: #
7359: # Parameters:
7360: # $coursenum - Number of the course.
7361: # $coursedomain - Domain at which the course was created.
7362: # Returns:
7363: # A hash of the course parameters along (I think) with timestamps
7364: # and version info.
7365:
7366: sub get_courseresdata {
7367: my ($coursenum,$coursedomain)=@_;
7368: my $coursehom=&homeserver($coursenum,$coursedomain);
7369: my $hashid=$coursenum.':'.$coursedomain;
7370: my ($result,$cached)=&is_cached_new('courseres',$hashid);
7371: my %dumpreply;
7372: unless (defined($cached)) {
7373: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
7374: $result=\%dumpreply;
7375: my ($tmp) = keys(%dumpreply);
7376: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
7377: &do_cache_new('courseres',$hashid,$result,600);
7378: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
7379: return $tmp;
7380: } elsif ($tmp =~ /^(error)/) {
7381: $result=undef;
7382: &do_cache_new('courseres',$hashid,$result,600);
7383: }
7384: }
7385: return $result;
7386: }
7387:
7388: sub devalidateuserresdata {
7389: my ($uname,$udom)=@_;
7390: my $hashid="$udom:$uname";
7391: &devalidate_cache_new('userres',$hashid);
7392: }
7393:
7394: sub get_userresdata {
7395: my ($uname,$udom)=@_;
7396: #most student don\'t have any data set, check if there is some data
7397: if (&EXT_cache_status($udom,$uname)) { return undef; }
7398:
7399: my $hashid="$udom:$uname";
7400: my ($result,$cached)=&is_cached_new('userres',$hashid);
7401: if (!defined($cached)) {
7402: my %resourcedata=&dump('resourcedata',$udom,$uname);
7403: $result=\%resourcedata;
7404: &do_cache_new('userres',$hashid,$result,600);
7405: }
7406: my ($tmp)=keys(%$result);
7407: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
7408: return $result;
7409: }
7410: #error 2 occurs when the .db doesn't exist
7411: if ($tmp!~/error: 2 /) {
7412: &logthis("<font color=\"blue\">WARNING:".
7413: " Trying to get resource data for ".
7414: $uname." at ".$udom.": ".
7415: $tmp."</font>");
7416: } elsif ($tmp=~/error: 2 /) {
7417: #&EXT_cache_set($udom,$uname);
7418: &do_cache_new('userres',$hashid,undef,600);
7419: undef($tmp); # not really an error so don't send it back
7420: }
7421: return $tmp;
7422: }
7423: #----------------------------------------------- resdata - return resource data
7424: # Purpose:
7425: # Return resource data for either users or for a course.
7426: # Parameters:
7427: # $name - Course/user name.
7428: # $domain - Name of the domain the user/course is registered on.
7429: # $type - Type of thing $name is (must be 'course' or 'user'
7430: # @which - Array of names of resources desired.
7431: # Returns:
7432: # The value of the first reasource in @which that is found in the
7433: # resource hash.
7434: # Exceptional Conditions:
7435: # If the $type passed in is not valid (not the string 'course' or
7436: # 'user', an undefined reference is returned.
7437: # If none of the resources are found, an undef is returned
7438: sub resdata {
7439: my ($name,$domain,$type,@which)=@_;
7440: my $result;
7441: if ($type eq 'course') {
7442: $result=&get_courseresdata($name,$domain);
7443: } elsif ($type eq 'user') {
7444: $result=&get_userresdata($name,$domain);
7445: }
7446: if (!ref($result)) { return $result; }
7447: foreach my $item (@which) {
7448: if (defined($result->{$item->[0]})) {
7449: return [$result->{$item->[0]},$item->[1]];
7450: }
7451: }
7452: return undef;
7453: }
7454:
7455: #
7456: # EXT resource caching routines
7457: #
7458:
7459: sub clear_EXT_cache_status {
7460: &delenv('cache.EXT.');
7461: }
7462:
7463: sub EXT_cache_status {
7464: my ($target_domain,$target_user) = @_;
7465: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
7466: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
7467: # We know already the user has no data
7468: return 1;
7469: } else {
7470: return 0;
7471: }
7472: }
7473:
7474: sub EXT_cache_set {
7475: my ($target_domain,$target_user) = @_;
7476: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
7477: #&appenv({$cachename => time});
7478: }
7479:
7480: # --------------------------------------------------------- Value of a Variable
7481: sub EXT {
7482:
7483: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
7484: unless ($varname) { return ''; }
7485: #get real user name/domain, courseid and symb
7486: my $courseid;
7487: my $publicuser;
7488: if ($symbparm) {
7489: $symbparm=&get_symb_from_alias($symbparm);
7490: }
7491: if (!($uname && $udom)) {
7492: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
7493: if (!$symbparm) { $symbparm=$cursymb; }
7494: } else {
7495: $courseid=$env{'request.course.id'};
7496: }
7497: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
7498: my $rest;
7499: if (defined($therest[0])) {
7500: $rest=join('.',@therest);
7501: } else {
7502: $rest='';
7503: }
7504:
7505: my $qualifierrest=$qualifier;
7506: if ($rest) { $qualifierrest.='.'.$rest; }
7507: my $spacequalifierrest=$space;
7508: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
7509: if ($realm eq 'user') {
7510: # --------------------------------------------------------------- user.resource
7511: if ($space eq 'resource') {
7512: if ( (defined($Apache::lonhomework::parsing_a_problem)
7513: || defined($Apache::lonhomework::parsing_a_task))
7514: &&
7515: ($symbparm eq &symbread()) ) {
7516: # if we are in the middle of processing the resource the
7517: # get the value we are planning on committing
7518: if (defined($Apache::lonhomework::results{$qualifierrest})) {
7519: return $Apache::lonhomework::results{$qualifierrest};
7520: } else {
7521: return $Apache::lonhomework::history{$qualifierrest};
7522: }
7523: } else {
7524: my %restored;
7525: if ($publicuser || $env{'request.state'} eq 'construct') {
7526: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
7527: } else {
7528: %restored=&restore($symbparm,$courseid,$udom,$uname);
7529: }
7530: return $restored{$qualifierrest};
7531: }
7532: # ----------------------------------------------------------------- user.access
7533: } elsif ($space eq 'access') {
7534: # FIXME - not supporting calls for a specific user
7535: return &allowed($qualifier,$rest);
7536: # ------------------------------------------ user.preferences, user.environment
7537: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
7538: if (($uname eq $env{'user.name'}) &&
7539: ($udom eq $env{'user.domain'})) {
7540: return $env{join('.',('environment',$qualifierrest))};
7541: } else {
7542: my %returnhash;
7543: if (!$publicuser) {
7544: %returnhash=&userenvironment($udom,$uname,
7545: $qualifierrest);
7546: }
7547: return $returnhash{$qualifierrest};
7548: }
7549: # ----------------------------------------------------------------- user.course
7550: } elsif ($space eq 'course') {
7551: # FIXME - not supporting calls for a specific user
7552: return $env{join('.',('request.course',$qualifier))};
7553: # ------------------------------------------------------------------- user.role
7554: } elsif ($space eq 'role') {
7555: # FIXME - not supporting calls for a specific user
7556: my ($role,$where)=split(/\./,$env{'request.role'});
7557: if ($qualifier eq 'value') {
7558: return $role;
7559: } elsif ($qualifier eq 'extent') {
7560: return $where;
7561: }
7562: # ----------------------------------------------------------------- user.domain
7563: } elsif ($space eq 'domain') {
7564: return $udom;
7565: # ------------------------------------------------------------------- user.name
7566: } elsif ($space eq 'name') {
7567: return $uname;
7568: # ---------------------------------------------------- Any other user namespace
7569: } else {
7570: my %reply;
7571: if (!$publicuser) {
7572: %reply=&get($space,[$qualifierrest],$udom,$uname);
7573: }
7574: return $reply{$qualifierrest};
7575: }
7576: } elsif ($realm eq 'query') {
7577: # ---------------------------------------------- pull stuff out of query string
7578: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
7579: [$spacequalifierrest]);
7580: return $env{'form.'.$spacequalifierrest};
7581: } elsif ($realm eq 'request') {
7582: # ------------------------------------------------------------- request.browser
7583: if ($space eq 'browser') {
7584: if ($qualifier eq 'textremote') {
7585: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
7586: return 1;
7587: } else {
7588: return 0;
7589: }
7590: } else {
7591: return $env{'browser.'.$qualifier};
7592: }
7593: # ------------------------------------------------------------ request.filename
7594: } else {
7595: return $env{'request.'.$spacequalifierrest};
7596: }
7597: } elsif ($realm eq 'course') {
7598: # ---------------------------------------------------------- course.description
7599: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
7600: } elsif ($realm eq 'resource') {
7601:
7602: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
7603: if (!$symbparm) { $symbparm=&symbread(); }
7604: }
7605:
7606: if ($space eq 'title') {
7607: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
7608: return &gettitle($symbparm);
7609: }
7610:
7611: if ($space eq 'map') {
7612: my ($map) = &decode_symb($symbparm);
7613: return &symbread($map);
7614: }
7615: if ($space eq 'filename') {
7616: if ($symbparm) {
7617: return &clutter((&decode_symb($symbparm))[2]);
7618: }
7619: return &hreflocation('',$env{'request.filename'});
7620: }
7621:
7622: my ($section, $group, @groups);
7623: my ($courselevelm,$courselevel);
7624: if ($symbparm && defined($courseid) &&
7625: $courseid eq $env{'request.course.id'}) {
7626:
7627: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
7628:
7629: # ----------------------------------------------------- Cascading lookup scheme
7630: my $symbp=$symbparm;
7631: my $mapp=&deversion((&decode_symb($symbp))[0]);
7632:
7633: my $symbparm=$symbp.'.'.$spacequalifierrest;
7634: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
7635:
7636: if (($env{'user.name'} eq $uname) &&
7637: ($env{'user.domain'} eq $udom)) {
7638: $section=$env{'request.course.sec'};
7639: @groups = split(/:/,$env{'request.course.groups'});
7640: @groups=&sort_course_groups($courseid,@groups);
7641: } else {
7642: if (! defined($usection)) {
7643: $section=&getsection($udom,$uname,$courseid);
7644: } else {
7645: $section = $usection;
7646: }
7647: @groups = &get_users_groups($udom,$uname,$courseid);
7648: }
7649:
7650: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
7651: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
7652: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
7653:
7654: $courselevel=$courseid.'.'.$spacequalifierrest;
7655: my $courselevelr=$courseid.'.'.$symbparm;
7656: $courselevelm=$courseid.'.'.$mapparm;
7657:
7658: # ----------------------------------------------------------- first, check user
7659:
7660: my $userreply=&resdata($uname,$udom,'user',
7661: ([$courselevelr,'resource'],
7662: [$courselevelm,'map' ],
7663: [$courselevel, 'course' ]));
7664: if (defined($userreply)) { return &get_reply($userreply); }
7665:
7666: # ------------------------------------------------ second, check some of course
7667: my $coursereply;
7668: if (@groups > 0) {
7669: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
7670: $mapparm,$spacequalifierrest);
7671: if (defined($coursereply)) { return &get_reply($coursereply); }
7672: }
7673:
7674: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
7675: $env{'course.'.$courseid.'.domain'},
7676: 'course',
7677: ([$seclevelr, 'resource'],
7678: [$seclevelm, 'map' ],
7679: [$seclevel, 'course' ],
7680: [$courselevelr,'resource']));
7681: if (defined($coursereply)) { return &get_reply($coursereply); }
7682:
7683: # ------------------------------------------------------ third, check map parms
7684: my %parmhash=();
7685: my $thisparm='';
7686: if (tie(%parmhash,'GDBM_File',
7687: $env{'request.course.fn'}.'_parms.db',
7688: &GDBM_READER(),0640)) {
7689: $thisparm=$parmhash{$symbparm};
7690: untie(%parmhash);
7691: }
7692: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
7693: }
7694: # ------------------------------------------ fourth, look in resource metadata
7695:
7696: $spacequalifierrest=~s/\./\_/;
7697: my $filename;
7698: if (!$symbparm) { $symbparm=&symbread(); }
7699: if ($symbparm) {
7700: $filename=(&decode_symb($symbparm))[2];
7701: } else {
7702: $filename=$env{'request.filename'};
7703: }
7704: my $metadata=&metadata($filename,$spacequalifierrest);
7705: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
7706: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
7707: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
7708:
7709: # ---------------------------------------------- fourth, look in rest of course
7710: if ($symbparm && defined($courseid) &&
7711: $courseid eq $env{'request.course.id'}) {
7712: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
7713: $env{'course.'.$courseid.'.domain'},
7714: 'course',
7715: ([$courselevelm,'map' ],
7716: [$courselevel, 'course']));
7717: if (defined($coursereply)) { return &get_reply($coursereply); }
7718: }
7719: # ------------------------------------------------------------------ Cascade up
7720: unless ($space eq '0') {
7721: my @parts=split(/_/,$space);
7722: my $id=pop(@parts);
7723: my $part=join('_',@parts);
7724: if ($part eq '') { $part='0'; }
7725: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
7726: $symbparm,$udom,$uname,$section,1);
7727: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
7728: }
7729: if ($recurse) { return undef; }
7730: my $pack_def=&packages_tab_default($filename,$varname);
7731: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
7732: # ---------------------------------------------------- Any other user namespace
7733: } elsif ($realm eq 'environment') {
7734: # ----------------------------------------------------------------- environment
7735: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
7736: return $env{'environment.'.$spacequalifierrest};
7737: } else {
7738: if ($uname eq 'anonymous' && $udom eq '') {
7739: return '';
7740: }
7741: my %returnhash=&userenvironment($udom,$uname,
7742: $spacequalifierrest);
7743: return $returnhash{$spacequalifierrest};
7744: }
7745: } elsif ($realm eq 'system') {
7746: # ----------------------------------------------------------------- system.time
7747: if ($space eq 'time') {
7748: return time;
7749: }
7750: } elsif ($realm eq 'server') {
7751: # ----------------------------------------------------------------- system.time
7752: if ($space eq 'name') {
7753: return $ENV{'SERVER_NAME'};
7754: }
7755: }
7756: return '';
7757: }
7758:
7759: sub get_reply {
7760: my ($reply_value) = @_;
7761: if (ref($reply_value) eq 'ARRAY') {
7762: if (wantarray) {
7763: return @$reply_value;
7764: }
7765: return $reply_value->[0];
7766: } else {
7767: return $reply_value;
7768: }
7769: }
7770:
7771: sub check_group_parms {
7772: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
7773: my @groupitems = ();
7774: my $resultitem;
7775: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
7776: foreach my $group (@{$groups}) {
7777: foreach my $level (@levels) {
7778: my $item = $courseid.'.['.$group.'].'.$level->[0];
7779: push(@groupitems,[$item,$level->[1]]);
7780: }
7781: }
7782: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
7783: $env{'course.'.$courseid.'.domain'},
7784: 'course',@groupitems);
7785: return $coursereply;
7786: }
7787:
7788: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
7789: my ($courseid,@groups) = @_;
7790: @groups = sort(@groups);
7791: return @groups;
7792: }
7793:
7794: sub packages_tab_default {
7795: my ($uri,$varname)=@_;
7796: my (undef,$part,$name)=split(/\./,$varname);
7797:
7798: my (@extension,@specifics,$do_default);
7799: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
7800: my ($pack_type,$pack_part)=split(/_/,$package,2);
7801: if ($pack_type eq 'default') {
7802: $do_default=1;
7803: } elsif ($pack_type eq 'extension') {
7804: push(@extension,[$package,$pack_type,$pack_part]);
7805: } elsif ($pack_part eq $part || $pack_type eq 'part') {
7806: # only look at packages defaults for packages that this id is
7807: push(@specifics,[$package,$pack_type,$pack_part]);
7808: }
7809: }
7810: # first look for a package that matches the requested part id
7811: foreach my $package (@specifics) {
7812: my (undef,$pack_type,$pack_part)=@{$package};
7813: next if ($pack_part ne $part);
7814: if (defined($packagetab{"$pack_type&$name&default"})) {
7815: return $packagetab{"$pack_type&$name&default"};
7816: }
7817: }
7818: # look for any possible matching non extension_ package
7819: foreach my $package (@specifics) {
7820: my (undef,$pack_type,$pack_part)=@{$package};
7821: if (defined($packagetab{"$pack_type&$name&default"})) {
7822: return $packagetab{"$pack_type&$name&default"};
7823: }
7824: if ($pack_type eq 'part') { $pack_part='0'; }
7825: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
7826: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
7827: }
7828: }
7829: # look for any posible extension_ match
7830: foreach my $package (@extension) {
7831: my ($package,$pack_type)=@{$package};
7832: if (defined($packagetab{"$pack_type&$name&default"})) {
7833: return $packagetab{"$pack_type&$name&default"};
7834: }
7835: if (defined($packagetab{$package."&$name&default"})) {
7836: return $packagetab{$package."&$name&default"};
7837: }
7838: }
7839: # look for a global default setting
7840: if ($do_default && defined($packagetab{"default&$name&default"})) {
7841: return $packagetab{"default&$name&default"};
7842: }
7843: return undef;
7844: }
7845:
7846: sub add_prefix_and_part {
7847: my ($prefix,$part)=@_;
7848: my $keyroot;
7849: if (defined($prefix) && $prefix !~ /^__/) {
7850: # prefix that has a part already
7851: $keyroot=$prefix;
7852: } elsif (defined($prefix)) {
7853: # prefix that is missing a part
7854: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
7855: } else {
7856: # no prefix at all
7857: if (defined($part)) { $keyroot='_'.$part; }
7858: }
7859: return $keyroot;
7860: }
7861:
7862: # ---------------------------------------------------------------- Get metadata
7863:
7864: my %metaentry;
7865: sub metadata {
7866: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
7867: $uri=&declutter($uri);
7868: # if it is a non metadata possible uri return quickly
7869: if (($uri eq '') ||
7870: (($uri =~ m|^/*adm/|) &&
7871: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
7872: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
7873: return undef;
7874: }
7875: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
7876: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
7877: return undef;
7878: }
7879: my $filename=$uri;
7880: $uri=~s/\.meta$//;
7881: #
7882: # Is the metadata already cached?
7883: # Look at timestamp of caching
7884: # Everything is cached by the main uri, libraries are never directly cached
7885: #
7886: if (!defined($liburi)) {
7887: my ($result,$cached)=&is_cached_new('meta',$uri);
7888: if (defined($cached)) { return $result->{':'.$what}; }
7889: }
7890: {
7891: #
7892: # Is this a recursive call for a library?
7893: #
7894: # if (! exists($metacache{$uri})) {
7895: # $metacache{$uri}={};
7896: # }
7897: my $cachetime = 60*60;
7898: if ($liburi) {
7899: $liburi=&declutter($liburi);
7900: $filename=$liburi;
7901: } else {
7902: &devalidate_cache_new('meta',$uri);
7903: undef(%metaentry);
7904: }
7905: my %metathesekeys=();
7906: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
7907: my $metastring;
7908: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
7909: my $which = &hreflocation('','/'.($liburi || $uri));
7910: $metastring =
7911: &Apache::lonnet::ssi_body($which,
7912: ('grade_target' => 'meta'));
7913: $cachetime = 1; # only want this cached in the child not long term
7914: } elsif ($uri !~ m -^(editupload)/-) {
7915: my $file=&filelocation('',&clutter($filename));
7916: #push(@{$metaentry{$uri.'.file'}},$file);
7917: $metastring=&getfile($file);
7918: }
7919: my $parser=HTML::LCParser->new(\$metastring);
7920: my $token;
7921: undef %metathesekeys;
7922: while ($token=$parser->get_token) {
7923: if ($token->[0] eq 'S') {
7924: if (defined($token->[2]->{'package'})) {
7925: #
7926: # This is a package - get package info
7927: #
7928: my $package=$token->[2]->{'package'};
7929: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
7930: if (defined($token->[2]->{'id'})) {
7931: $keyroot.='_'.$token->[2]->{'id'};
7932: }
7933: if ($metaentry{':packages'}) {
7934: $metaentry{':packages'}.=','.$package.$keyroot;
7935: } else {
7936: $metaentry{':packages'}=$package.$keyroot;
7937: }
7938: foreach my $pack_entry (keys(%packagetab)) {
7939: my $part=$keyroot;
7940: $part=~s/^\_//;
7941: if ($pack_entry=~/^\Q$package\E\&/ ||
7942: $pack_entry=~/^\Q$package\E_0\&/) {
7943: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
7944: # ignore package.tab specified default values
7945: # here &package_tab_default() will fetch those
7946: if ($subp eq 'default') { next; }
7947: my $value=$packagetab{$pack_entry};
7948: my $unikey;
7949: if ($pack =~ /_0$/) {
7950: $unikey='parameter_0_'.$name;
7951: $part=0;
7952: } else {
7953: $unikey='parameter'.$keyroot.'_'.$name;
7954: }
7955: if ($subp eq 'display') {
7956: $value.=' [Part: '.$part.']';
7957: }
7958: $metaentry{':'.$unikey.'.part'}=$part;
7959: $metathesekeys{$unikey}=1;
7960: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
7961: $metaentry{':'.$unikey.'.'.$subp}=$value;
7962: }
7963: if (defined($metaentry{':'.$unikey.'.default'})) {
7964: $metaentry{':'.$unikey}=
7965: $metaentry{':'.$unikey.'.default'};
7966: }
7967: }
7968: }
7969: } else {
7970: #
7971: # This is not a package - some other kind of start tag
7972: #
7973: my $entry=$token->[1];
7974: my $unikey;
7975: if ($entry eq 'import') {
7976: $unikey='';
7977: } else {
7978: $unikey=$entry;
7979: }
7980: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
7981:
7982: if (defined($token->[2]->{'id'})) {
7983: $unikey.='_'.$token->[2]->{'id'};
7984: }
7985:
7986: if ($entry eq 'import') {
7987: #
7988: # Importing a library here
7989: #
7990: if ($depthcount<20) {
7991: my $location=$parser->get_text('/import');
7992: my $dir=$filename;
7993: $dir=~s|[^/]*$||;
7994: $location=&filelocation($dir,$location);
7995: my $metadata =
7996: &metadata($uri,'keys', $location,$unikey,
7997: $depthcount+1);
7998: foreach my $meta (split(',',$metadata)) {
7999: $metaentry{':'.$meta}=$metaentry{':'.$meta};
8000: $metathesekeys{$meta}=1;
8001: }
8002: }
8003: } else {
8004:
8005: if (defined($token->[2]->{'name'})) {
8006: $unikey.='_'.$token->[2]->{'name'};
8007: }
8008: $metathesekeys{$unikey}=1;
8009: foreach my $param (@{$token->[3]}) {
8010: $metaentry{':'.$unikey.'.'.$param} =
8011: $token->[2]->{$param};
8012: }
8013: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
8014: my $default=$metaentry{':'.$unikey.'.default'};
8015: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
8016: # only ws inside the tag, and not in default, so use default
8017: # as value
8018: $metaentry{':'.$unikey}=$default;
8019: } elsif ( $internaltext =~ /\S/ ) {
8020: # something interesting inside the tag
8021: $metaentry{':'.$unikey}=$internaltext;
8022: } else {
8023: # no interesting values, don't set a default
8024: }
8025: # end of not-a-package not-a-library import
8026: }
8027: # end of not-a-package start tag
8028: }
8029: # the next is the end of "start tag"
8030: }
8031: }
8032: my ($extension) = ($uri =~ /\.(\w+)$/);
8033: $extension = lc($extension);
8034: if ($extension eq 'htm') { $extension='html'; }
8035:
8036: foreach my $key (keys(%packagetab)) {
8037: #no specific packages #how's our extension
8038: if ($key!~/^extension_\Q$extension\E&/) { next; }
8039: &metadata_create_package_def($uri,$key,'extension_'.$extension,
8040: \%metathesekeys);
8041: }
8042:
8043: if (!exists($metaentry{':packages'})
8044: || $packagetab{"import_defaults&extension_$extension"}) {
8045: foreach my $key (keys(%packagetab)) {
8046: #no specific packages well let's get default then
8047: if ($key!~/^default&/) { next; }
8048: &metadata_create_package_def($uri,$key,'default',
8049: \%metathesekeys);
8050: }
8051: }
8052: # are there custom rights to evaluate
8053: if ($metaentry{':copyright'} eq 'custom') {
8054:
8055: #
8056: # Importing a rights file here
8057: #
8058: unless ($depthcount) {
8059: my $location=$metaentry{':customdistributionfile'};
8060: my $dir=$filename;
8061: $dir=~s|[^/]*$||;
8062: $location=&filelocation($dir,$location);
8063: my $rights_metadata =
8064: &metadata($uri,'keys',$location,'_rights',
8065: $depthcount+1);
8066: foreach my $rights (split(',',$rights_metadata)) {
8067: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8068: $metathesekeys{$rights}=1;
8069: }
8070: }
8071: }
8072: # uniqifiy package listing
8073: my %seen;
8074: my @uniq_packages =
8075: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8076: $metaentry{':packages'} = join(',',@uniq_packages);
8077:
8078: $metaentry{':keys'} = join(',',keys(%metathesekeys));
8079: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8080: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
8081: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
8082: # this is the end of "was not already recently cached
8083: }
8084: return $metaentry{':'.$what};
8085: }
8086:
8087: sub metadata_create_package_def {
8088: my ($uri,$key,$package,$metathesekeys)=@_;
8089: my ($pack,$name,$subp)=split(/\&/,$key);
8090: if ($subp eq 'default') { next; }
8091:
8092: if (defined($metaentry{':packages'})) {
8093: $metaentry{':packages'}.=','.$package;
8094: } else {
8095: $metaentry{':packages'}=$package;
8096: }
8097: my $value=$packagetab{$key};
8098: my $unikey;
8099: $unikey='parameter_0_'.$name;
8100: $metaentry{':'.$unikey.'.part'}=0;
8101: $$metathesekeys{$unikey}=1;
8102: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8103: $metaentry{':'.$unikey.'.'.$subp}=$value;
8104: }
8105: if (defined($metaentry{':'.$unikey.'.default'})) {
8106: $metaentry{':'.$unikey}=
8107: $metaentry{':'.$unikey.'.default'};
8108: }
8109: }
8110:
8111: sub metadata_generate_part0 {
8112: my ($metadata,$metacache,$uri) = @_;
8113: my %allnames;
8114: foreach my $metakey (keys(%$metadata)) {
8115: if ($metakey=~/^parameter\_(.*)/) {
8116: my $part=$$metacache{':'.$metakey.'.part'};
8117: my $name=$$metacache{':'.$metakey.'.name'};
8118: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
8119: $allnames{$name}=$part;
8120: }
8121: }
8122: }
8123: foreach my $name (keys(%allnames)) {
8124: $$metadata{"parameter_0_$name"}=1;
8125: my $key=":parameter_0_$name";
8126: $$metacache{"$key.part"}='0';
8127: $$metacache{"$key.name"}=$name;
8128: $$metacache{"$key.type"}=$$metacache{':parameter_'.
8129: $allnames{$name}.'_'.$name.
8130: '.type'};
8131: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
8132: '.display'};
8133: my $expr='[Part: '.$allnames{$name}.']';
8134: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
8135: $$metacache{"$key.display"}=$olddis;
8136: }
8137: }
8138:
8139: # ------------------------------------------------------ Devalidate title cache
8140:
8141: sub devalidate_title_cache {
8142: my ($url)=@_;
8143: if (!$env{'request.course.id'}) { return; }
8144: my $symb=&symbread($url);
8145: if (!$symb) { return; }
8146: my $key=$env{'request.course.id'}."\0".$symb;
8147: &devalidate_cache_new('title',$key);
8148: }
8149:
8150: # ------------------------------------------------- Get the title of a course
8151:
8152: sub current_course_title {
8153: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8154: }
8155: # ------------------------------------------------- Get the title of a resource
8156:
8157: sub gettitle {
8158: my $urlsymb=shift;
8159: my $symb=&symbread($urlsymb);
8160: if ($symb) {
8161: my $key=$env{'request.course.id'}."\0".$symb;
8162: my ($result,$cached)=&is_cached_new('title',$key);
8163: if (defined($cached)) {
8164: return $result;
8165: }
8166: my ($map,$resid,$url)=&decode_symb($symb);
8167: my $title='';
8168: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8169: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8170: } else {
8171: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8172: &GDBM_READER(),0640)) {
8173: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8174: $title=$bighash{'title_'.$mapid.'.'.$resid};
8175: untie(%bighash);
8176: }
8177: }
8178: $title=~s/\&colon\;/\:/gs;
8179: if ($title) {
8180: return &do_cache_new('title',$key,$title,600);
8181: }
8182: $urlsymb=$url;
8183: }
8184: my $title=&metadata($urlsymb,'title');
8185: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8186: return $title;
8187: }
8188:
8189: sub get_slot {
8190: my ($which,$cnum,$cdom)=@_;
8191: if (!$cnum || !$cdom) {
8192: (undef,my $courseid)=&whichuser();
8193: $cdom=$env{'course.'.$courseid.'.domain'};
8194: $cnum=$env{'course.'.$courseid.'.num'};
8195: }
8196: my $key=join("\0",'slots',$cdom,$cnum,$which);
8197: my %slotinfo;
8198: if (exists($remembered{$key})) {
8199: $slotinfo{$which} = $remembered{$key};
8200: } else {
8201: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8202: &Apache::lonhomework::showhash(%slotinfo);
8203: my ($tmp)=keys(%slotinfo);
8204: if ($tmp=~/^error:/) { return (); }
8205: $remembered{$key} = $slotinfo{$which};
8206: }
8207: if (ref($slotinfo{$which}) eq 'HASH') {
8208: return %{$slotinfo{$which}};
8209: }
8210: return $slotinfo{$which};
8211: }
8212: # ------------------------------------------------- Update symbolic store links
8213:
8214: sub symblist {
8215: my ($mapname,%newhash)=@_;
8216: $mapname=&deversion(&declutter($mapname));
8217: my %hash;
8218: if (($env{'request.course.fn'}) && (%newhash)) {
8219: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
8220: &GDBM_WRCREAT(),0640)) {
8221: foreach my $url (keys(%newhash)) {
8222: next if ($url eq 'last_known'
8223: && $env{'form.no_update_last_known'});
8224: $hash{declutter($url)}=&encode_symb($mapname,
8225: $newhash{$url}->[1],
8226: $newhash{$url}->[0]);
8227: }
8228: if (untie(%hash)) {
8229: return 'ok';
8230: }
8231: }
8232: }
8233: return 'error';
8234: }
8235:
8236: # --------------------------------------------------------------- Verify a symb
8237:
8238: sub symbverify {
8239: my ($symb,$thisurl)=@_;
8240: my $thisfn=$thisurl;
8241: $thisfn=&declutter($thisfn);
8242: # direct jump to resource in page or to a sequence - will construct own symbs
8243: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
8244: # check URL part
8245: my ($map,$resid,$url)=&decode_symb($symb);
8246:
8247: unless ($url eq $thisfn) { return 0; }
8248:
8249: $symb=&symbclean($symb);
8250: $thisurl=&deversion($thisurl);
8251: $thisfn=&deversion($thisfn);
8252:
8253: my %bighash;
8254: my $okay=0;
8255:
8256: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8257: &GDBM_READER(),0640)) {
8258: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
8259: $thisurl =~ s/\?.+$//;
8260: }
8261: my $ids=$bighash{'ids_'.&clutter($thisurl)};
8262: unless ($ids) {
8263: $ids=$bighash{'ids_/'.$thisurl};
8264: }
8265: if ($ids) {
8266: # ------------------------------------------------------------------- Has ID(s)
8267: foreach my $id (split(/\,/,$ids)) {
8268: my ($mapid,$resid)=split(/\./,$id);
8269: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
8270: $symb =~ s/\?.+$//;
8271: }
8272: if (
8273: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
8274: eq $symb) {
8275: if (($env{'request.role.adv'}) ||
8276: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
8277: $okay=1;
8278: }
8279: }
8280: }
8281: }
8282: untie(%bighash);
8283: }
8284: return $okay;
8285: }
8286:
8287: # --------------------------------------------------------------- Clean-up symb
8288:
8289: sub symbclean {
8290: my $symb=shift;
8291: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
8292: # remove version from map
8293: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
8294:
8295: # remove version from URL
8296: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
8297:
8298: # remove wrapper
8299:
8300: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
8301: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
8302: return $symb;
8303: }
8304:
8305: # ---------------------------------------------- Split symb to find map and url
8306:
8307: sub encode_symb {
8308: my ($map,$resid,$url)=@_;
8309: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
8310: }
8311:
8312: sub decode_symb {
8313: my $symb=shift;
8314: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
8315: my ($map,$resid,$url)=split(/___/,$symb);
8316: return (&fixversion($map),$resid,&fixversion($url));
8317: }
8318:
8319: sub fixversion {
8320: my $fn=shift;
8321: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
8322: my %bighash;
8323: my $uri=&clutter($fn);
8324: my $key=$env{'request.course.id'}.'_'.$uri;
8325: # is this cached?
8326: my ($result,$cached)=&is_cached_new('courseresversion',$key);
8327: if (defined($cached)) { return $result; }
8328: # unfortunately not cached, or expired
8329: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8330: &GDBM_READER(),0640)) {
8331: if ($bighash{'version_'.$uri}) {
8332: my $version=$bighash{'version_'.$uri};
8333: unless (($version eq 'mostrecent') ||
8334: ($version==&getversion($uri))) {
8335: $uri=~s/\.(\w+)$/\.$version\.$1/;
8336: }
8337: }
8338: untie %bighash;
8339: }
8340: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
8341: }
8342:
8343: sub deversion {
8344: my $url=shift;
8345: $url=~s/\.\d+\.(\w+)$/\.$1/;
8346: return $url;
8347: }
8348:
8349: # ------------------------------------------------------ Return symb list entry
8350:
8351: sub symbread {
8352: my ($thisfn,$donotrecurse)=@_;
8353: my $cache_str='request.symbread.cached.'.$thisfn;
8354: if (defined($env{$cache_str})) { return $env{$cache_str}; }
8355: # no filename provided? try from environment
8356: unless ($thisfn) {
8357: if ($env{'request.symb'}) {
8358: return $env{$cache_str}=&symbclean($env{'request.symb'});
8359: }
8360: $thisfn=$env{'request.filename'};
8361: }
8362: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
8363: # is that filename actually a symb? Verify, clean, and return
8364: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
8365: if (&symbverify($thisfn,$1)) {
8366: return $env{$cache_str}=&symbclean($thisfn);
8367: }
8368: }
8369: $thisfn=declutter($thisfn);
8370: my %hash;
8371: my %bighash;
8372: my $syval='';
8373: if (($env{'request.course.fn'}) && ($thisfn)) {
8374: my $targetfn = $thisfn;
8375: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
8376: $targetfn = 'adm/wrapper/'.$thisfn;
8377: }
8378: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
8379: $targetfn=$1;
8380: }
8381: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
8382: &GDBM_READER(),0640)) {
8383: $syval=$hash{$targetfn};
8384: untie(%hash);
8385: }
8386: # ---------------------------------------------------------- There was an entry
8387: if ($syval) {
8388: #unless ($syval=~/\_\d+$/) {
8389: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
8390: #&appenv({'request.ambiguous' => $thisfn});
8391: #return $env{$cache_str}='';
8392: #}
8393: #$syval.=$1;
8394: #}
8395: } else {
8396: # ------------------------------------------------------- Was not in symb table
8397: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8398: &GDBM_READER(),0640)) {
8399: # ---------------------------------------------- Get ID(s) for current resource
8400: my $ids=$bighash{'ids_'.&clutter($thisfn)};
8401: unless ($ids) {
8402: $ids=$bighash{'ids_/'.$thisfn};
8403: }
8404: unless ($ids) {
8405: # alias?
8406: $ids=$bighash{'mapalias_'.$thisfn};
8407: }
8408: if ($ids) {
8409: # ------------------------------------------------------------------- Has ID(s)
8410: my @possibilities=split(/\,/,$ids);
8411: if ($#possibilities==0) {
8412: # ----------------------------------------------- There is only one possibility
8413: my ($mapid,$resid)=split(/\./,$ids);
8414: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8415: $resid,$thisfn);
8416: } elsif (!$donotrecurse) {
8417: # ------------------------------------------ There is more than one possibility
8418: my $realpossible=0;
8419: foreach my $id (@possibilities) {
8420: my $file=$bighash{'src_'.$id};
8421: if (&allowed('bre',$file)) {
8422: my ($mapid,$resid)=split(/\./,$id);
8423: if ($bighash{'map_type_'.$mapid} ne 'page') {
8424: $realpossible++;
8425: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8426: $resid,$thisfn);
8427: }
8428: }
8429: }
8430: if ($realpossible!=1) { $syval=''; }
8431: } else {
8432: $syval='';
8433: }
8434: }
8435: untie(%bighash)
8436: }
8437: }
8438: if ($syval) {
8439: return $env{$cache_str}=$syval;
8440: }
8441: }
8442: &appenv({'request.ambiguous' => $thisfn});
8443: return $env{$cache_str}='';
8444: }
8445:
8446: # ---------------------------------------------------------- Return random seed
8447:
8448: sub numval {
8449: my $txt=shift;
8450: $txt=~tr/A-J/0-9/;
8451: $txt=~tr/a-j/0-9/;
8452: $txt=~tr/K-T/0-9/;
8453: $txt=~tr/k-t/0-9/;
8454: $txt=~tr/U-Z/0-5/;
8455: $txt=~tr/u-z/0-5/;
8456: $txt=~s/\D//g;
8457: if ($_64bit) { if ($txt > 2**32) { return -1; } }
8458: return int($txt);
8459: }
8460:
8461: sub numval2 {
8462: my $txt=shift;
8463: $txt=~tr/A-J/0-9/;
8464: $txt=~tr/a-j/0-9/;
8465: $txt=~tr/K-T/0-9/;
8466: $txt=~tr/k-t/0-9/;
8467: $txt=~tr/U-Z/0-5/;
8468: $txt=~tr/u-z/0-5/;
8469: $txt=~s/\D//g;
8470: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
8471: my $total;
8472: foreach my $val (@txts) { $total+=$val; }
8473: if ($_64bit) { if ($total > 2**32) { return -1; } }
8474: return int($total);
8475: }
8476:
8477: sub numval3 {
8478: use integer;
8479: my $txt=shift;
8480: $txt=~tr/A-J/0-9/;
8481: $txt=~tr/a-j/0-9/;
8482: $txt=~tr/K-T/0-9/;
8483: $txt=~tr/k-t/0-9/;
8484: $txt=~tr/U-Z/0-5/;
8485: $txt=~tr/u-z/0-5/;
8486: $txt=~s/\D//g;
8487: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
8488: my $total;
8489: foreach my $val (@txts) { $total+=$val; }
8490: if ($_64bit) { $total=(($total<<32)>>32); }
8491: return $total;
8492: }
8493:
8494: sub digest {
8495: my ($data)=@_;
8496: my $digest=&Digest::MD5::md5($data);
8497: my ($a,$b,$c,$d)=unpack("iiii",$digest);
8498: my ($e,$f);
8499: {
8500: use integer;
8501: $e=($a+$b);
8502: $f=($c+$d);
8503: if ($_64bit) {
8504: $e=(($e<<32)>>32);
8505: $f=(($f<<32)>>32);
8506: }
8507: }
8508: if (wantarray) {
8509: return ($e,$f);
8510: } else {
8511: my $g;
8512: {
8513: use integer;
8514: $g=($e+$f);
8515: if ($_64bit) {
8516: $g=(($g<<32)>>32);
8517: }
8518: }
8519: return $g;
8520: }
8521: }
8522:
8523: sub latest_rnd_algorithm_id {
8524: return '64bit5';
8525: }
8526:
8527: sub get_rand_alg {
8528: my ($courseid)=@_;
8529: if (!$courseid) { $courseid=(&whichuser())[1]; }
8530: if ($courseid) {
8531: return $env{"course.$courseid.rndseed"};
8532: }
8533: return &latest_rnd_algorithm_id();
8534: }
8535:
8536: sub validCODE {
8537: my ($CODE)=@_;
8538: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
8539: return 0;
8540: }
8541:
8542: sub getCODE {
8543: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
8544: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
8545: defined($Apache::lonhomework::parsing_a_task) ) &&
8546: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
8547: return $Apache::lonhomework::history{'resource.CODE'};
8548: }
8549: return undef;
8550: }
8551:
8552: sub rndseed {
8553: my ($symb,$courseid,$domain,$username)=@_;
8554: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
8555: if (!defined($symb)) {
8556: unless ($symb=$wsymb) { return time; }
8557: }
8558: if (!$courseid) { $courseid=$wcourseid; }
8559: if (!$domain) { $domain=$wdomain; }
8560: if (!$username) { $username=$wusername }
8561: my $which=&get_rand_alg();
8562:
8563: if (defined(&getCODE())) {
8564: if ($which eq '64bit5') {
8565: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
8566: } elsif ($which eq '64bit4') {
8567: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
8568: } else {
8569: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
8570: }
8571: } elsif ($which eq '64bit5') {
8572: return &rndseed_64bit5($symb,$courseid,$domain,$username);
8573: } elsif ($which eq '64bit4') {
8574: return &rndseed_64bit4($symb,$courseid,$domain,$username);
8575: } elsif ($which eq '64bit3') {
8576: return &rndseed_64bit3($symb,$courseid,$domain,$username);
8577: } elsif ($which eq '64bit2') {
8578: return &rndseed_64bit2($symb,$courseid,$domain,$username);
8579: } elsif ($which eq '64bit') {
8580: return &rndseed_64bit($symb,$courseid,$domain,$username);
8581: }
8582: return &rndseed_32bit($symb,$courseid,$domain,$username);
8583: }
8584:
8585: sub rndseed_32bit {
8586: my ($symb,$courseid,$domain,$username)=@_;
8587: {
8588: use integer;
8589: my $symbchck=unpack("%32C*",$symb) << 27;
8590: my $symbseed=numval($symb) << 22;
8591: my $namechck=unpack("%32C*",$username) << 17;
8592: my $nameseed=numval($username) << 12;
8593: my $domainseed=unpack("%32C*",$domain) << 7;
8594: my $courseseed=unpack("%32C*",$courseid);
8595: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
8596: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8597: #&logthis("rndseed :$num:$symb");
8598: if ($_64bit) { $num=(($num<<32)>>32); }
8599: return $num;
8600: }
8601: }
8602:
8603: sub rndseed_64bit {
8604: my ($symb,$courseid,$domain,$username)=@_;
8605: {
8606: use integer;
8607: my $symbchck=unpack("%32S*",$symb) << 21;
8608: my $symbseed=numval($symb) << 10;
8609: my $namechck=unpack("%32S*",$username);
8610:
8611: my $nameseed=numval($username) << 21;
8612: my $domainseed=unpack("%32S*",$domain) << 10;
8613: my $courseseed=unpack("%32S*",$courseid);
8614:
8615: my $num1=$symbchck+$symbseed+$namechck;
8616: my $num2=$nameseed+$domainseed+$courseseed;
8617: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8618: #&logthis("rndseed :$num:$symb");
8619: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8620: return "$num1,$num2";
8621: }
8622: }
8623:
8624: sub rndseed_64bit2 {
8625: my ($symb,$courseid,$domain,$username)=@_;
8626: {
8627: use integer;
8628: # strings need to be an even # of cahracters long, it it is odd the
8629: # last characters gets thrown away
8630: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8631: my $symbseed=numval($symb) << 10;
8632: my $namechck=unpack("%32S*",$username.' ');
8633:
8634: my $nameseed=numval($username) << 21;
8635: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8636: my $courseseed=unpack("%32S*",$courseid.' ');
8637:
8638: my $num1=$symbchck+$symbseed+$namechck;
8639: my $num2=$nameseed+$domainseed+$courseseed;
8640: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8641: #&logthis("rndseed :$num:$symb");
8642: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8643: return "$num1,$num2";
8644: }
8645: }
8646:
8647: sub rndseed_64bit3 {
8648: my ($symb,$courseid,$domain,$username)=@_;
8649: {
8650: use integer;
8651: # strings need to be an even # of cahracters long, it it is odd the
8652: # last characters gets thrown away
8653: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8654: my $symbseed=numval2($symb) << 10;
8655: my $namechck=unpack("%32S*",$username.' ');
8656:
8657: my $nameseed=numval2($username) << 21;
8658: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8659: my $courseseed=unpack("%32S*",$courseid.' ');
8660:
8661: my $num1=$symbchck+$symbseed+$namechck;
8662: my $num2=$nameseed+$domainseed+$courseseed;
8663: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8664: #&logthis("rndseed :$num1:$num2:$_64bit");
8665: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8666:
8667: return "$num1:$num2";
8668: }
8669: }
8670:
8671: sub rndseed_64bit4 {
8672: my ($symb,$courseid,$domain,$username)=@_;
8673: {
8674: use integer;
8675: # strings need to be an even # of cahracters long, it it is odd the
8676: # last characters gets thrown away
8677: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8678: my $symbseed=numval3($symb) << 10;
8679: my $namechck=unpack("%32S*",$username.' ');
8680:
8681: my $nameseed=numval3($username) << 21;
8682: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8683: my $courseseed=unpack("%32S*",$courseid.' ');
8684:
8685: my $num1=$symbchck+$symbseed+$namechck;
8686: my $num2=$nameseed+$domainseed+$courseseed;
8687: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8688: #&logthis("rndseed :$num1:$num2:$_64bit");
8689: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8690:
8691: return "$num1:$num2";
8692: }
8693: }
8694:
8695: sub rndseed_64bit5 {
8696: my ($symb,$courseid,$domain,$username)=@_;
8697: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
8698: return "$num1:$num2";
8699: }
8700:
8701: sub rndseed_CODE_64bit {
8702: my ($symb,$courseid,$domain,$username)=@_;
8703: {
8704: use integer;
8705: my $symbchck=unpack("%32S*",$symb.' ') << 16;
8706: my $symbseed=numval2($symb);
8707: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
8708: my $CODEseed=numval(&getCODE());
8709: my $courseseed=unpack("%32S*",$courseid.' ');
8710: my $num1=$symbseed+$CODEchck;
8711: my $num2=$CODEseed+$courseseed+$symbchck;
8712: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
8713: #&logthis("rndseed :$num1:$num2:$symb");
8714: if ($_64bit) { $num1=(($num1<<32)>>32); }
8715: if ($_64bit) { $num2=(($num2<<32)>>32); }
8716: return "$num1:$num2";
8717: }
8718: }
8719:
8720: sub rndseed_CODE_64bit4 {
8721: my ($symb,$courseid,$domain,$username)=@_;
8722: {
8723: use integer;
8724: my $symbchck=unpack("%32S*",$symb.' ') << 16;
8725: my $symbseed=numval3($symb);
8726: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
8727: my $CODEseed=numval3(&getCODE());
8728: my $courseseed=unpack("%32S*",$courseid.' ');
8729: my $num1=$symbseed+$CODEchck;
8730: my $num2=$CODEseed+$courseseed+$symbchck;
8731: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
8732: #&logthis("rndseed :$num1:$num2:$symb");
8733: if ($_64bit) { $num1=(($num1<<32)>>32); }
8734: if ($_64bit) { $num2=(($num2<<32)>>32); }
8735: return "$num1:$num2";
8736: }
8737: }
8738:
8739: sub rndseed_CODE_64bit5 {
8740: my ($symb,$courseid,$domain,$username)=@_;
8741: my $code = &getCODE();
8742: my ($num1,$num2)=&digest("$symb,$courseid,$code");
8743: return "$num1:$num2";
8744: }
8745:
8746: sub setup_random_from_rndseed {
8747: my ($rndseed)=@_;
8748: if ($rndseed =~/([,:])/) {
8749: my ($num1,$num2)=split(/[,:]/,$rndseed);
8750: &Math::Random::random_set_seed(abs($num1),abs($num2));
8751: } else {
8752: &Math::Random::random_set_seed_from_phrase($rndseed);
8753: }
8754: }
8755:
8756: sub latest_receipt_algorithm_id {
8757: return 'receipt3';
8758: }
8759:
8760: sub recunique {
8761: my $fucourseid=shift;
8762: my $unique;
8763: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
8764: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
8765: $unique=$env{"course.$fucourseid.internal.encseed"};
8766: } else {
8767: $unique=$perlvar{'lonReceipt'};
8768: }
8769: return unpack("%32C*",$unique);
8770: }
8771:
8772: sub recprefix {
8773: my $fucourseid=shift;
8774: my $prefix;
8775: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
8776: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
8777: $prefix=$env{"course.$fucourseid.internal.encpref"};
8778: } else {
8779: $prefix=$perlvar{'lonHostID'};
8780: }
8781: return unpack("%32C*",$prefix);
8782: }
8783:
8784: sub ireceipt {
8785: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
8786:
8787: my $return =&recprefix($fucourseid).'-';
8788:
8789: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
8790: $env{'request.state'} eq 'construct') {
8791: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
8792: return $return;
8793: }
8794:
8795: my $cuname=unpack("%32C*",$funame);
8796: my $cudom=unpack("%32C*",$fudom);
8797: my $cucourseid=unpack("%32C*",$fucourseid);
8798: my $cusymb=unpack("%32C*",$fusymb);
8799: my $cunique=&recunique($fucourseid);
8800: my $cpart=unpack("%32S*",$part);
8801: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
8802:
8803: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
8804:
8805: $return.= ($cunique%$cuname+
8806: $cunique%$cudom+
8807: $cusymb%$cuname+
8808: $cusymb%$cudom+
8809: $cucourseid%$cuname+
8810: $cucourseid%$cudom+
8811: $cpart%$cuname+
8812: $cpart%$cudom);
8813: } else {
8814: $return.= ($cunique%$cuname+
8815: $cunique%$cudom+
8816: $cusymb%$cuname+
8817: $cusymb%$cudom+
8818: $cucourseid%$cuname+
8819: $cucourseid%$cudom);
8820: }
8821: return $return;
8822: }
8823:
8824: sub receipt {
8825: my ($part)=@_;
8826: my ($symb,$courseid,$domain,$name) = &whichuser();
8827: return &ireceipt($name,$domain,$courseid,$symb,$part);
8828: }
8829:
8830: sub whichuser {
8831: my ($passedsymb)=@_;
8832: my ($symb,$courseid,$domain,$name,$publicuser);
8833: if (defined($env{'form.grade_symb'})) {
8834: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
8835: my $allowed=&allowed('vgr',$tmp_courseid);
8836: if (!$allowed &&
8837: exists($env{'request.course.sec'}) &&
8838: $env{'request.course.sec'} !~ /^\s*$/) {
8839: $allowed=&allowed('vgr',$tmp_courseid.
8840: '/'.$env{'request.course.sec'});
8841: }
8842: if ($allowed) {
8843: ($symb)=&get_env_multiple('form.grade_symb');
8844: $courseid=$tmp_courseid;
8845: ($domain)=&get_env_multiple('form.grade_domain');
8846: ($name)=&get_env_multiple('form.grade_username');
8847: return ($symb,$courseid,$domain,$name,$publicuser);
8848: }
8849: }
8850: if (!$passedsymb) {
8851: $symb=&symbread();
8852: } else {
8853: $symb=$passedsymb;
8854: }
8855: $courseid=$env{'request.course.id'};
8856: $domain=$env{'user.domain'};
8857: $name=$env{'user.name'};
8858: if ($name eq 'public' && $domain eq 'public') {
8859: if (!defined($env{'form.username'})) {
8860: $env{'form.username'}.=time.rand(10000000);
8861: }
8862: $name.=$env{'form.username'};
8863: }
8864: return ($symb,$courseid,$domain,$name,$publicuser);
8865:
8866: }
8867:
8868: # ------------------------------------------------------------ Serves up a file
8869: # returns either the contents of the file or
8870: # -1 if the file doesn't exist
8871: #
8872: # if the target is a file that was uploaded via DOCS,
8873: # a check will be made to see if a current copy exists on the local server,
8874: # if it does this will be served, otherwise a copy will be retrieved from
8875: # the home server for the course and stored in /home/httpd/html/userfiles on
8876: # the local server.
8877:
8878: sub getfile {
8879: my ($file) = @_;
8880: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
8881: &repcopy($file);
8882: return &readfile($file);
8883: }
8884:
8885: sub repcopy_userfile {
8886: my ($file)=@_;
8887: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
8888: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
8889: my ($cdom,$cnum,$filename) =
8890: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
8891: my $uri="/uploaded/$cdom/$cnum/$filename";
8892: if (-e "$file") {
8893: # we already have a local copy, check it out
8894: my @fileinfo = stat($file);
8895: my $rtncode;
8896: my $info;
8897: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
8898: if ($lwpresp ne 'ok') {
8899: # there is no such file anymore, even though we had a local copy
8900: if ($rtncode eq '404') {
8901: unlink($file);
8902: }
8903: return -1;
8904: }
8905: if ($info < $fileinfo[9]) {
8906: # nice, the file we have is up-to-date, just say okay
8907: return 'ok';
8908: } else {
8909: # the file is outdated, get rid of it
8910: unlink($file);
8911: }
8912: }
8913: # one way or the other, at this point, we don't have the file
8914: # construct the correct path for the file
8915: my @parts = ($cdom,$cnum);
8916: if ($filename =~ m|^(.+)/[^/]+$|) {
8917: push @parts, split(/\//,$1);
8918: }
8919: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
8920: foreach my $part (@parts) {
8921: $path .= '/'.$part;
8922: if (!-e $path) {
8923: mkdir($path,0770);
8924: }
8925: }
8926: # now the path exists for sure
8927: # get a user agent
8928: my $ua=new LWP::UserAgent;
8929: my $transferfile=$file.'.in.transfer';
8930: # FIXME: this should flock
8931: if (-e $transferfile) { return 'ok'; }
8932: my $request;
8933: $uri=~s/^\///;
8934: my $homeserver = &homeserver($cnum,$cdom);
8935: my $protocol = $protocol{$homeserver};
8936: $protocol = 'http' if ($protocol ne 'https');
8937: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
8938: my $response=$ua->request($request,$transferfile);
8939: # did it work?
8940: if ($response->is_error()) {
8941: unlink($transferfile);
8942: &logthis("Userfile repcopy failed for $uri");
8943: return -1;
8944: }
8945: # worked, rename the transfer file
8946: rename($transferfile,$file);
8947: return 'ok';
8948: }
8949:
8950: sub tokenwrapper {
8951: my $uri=shift;
8952: $uri=~s|^https?\://([^/]+)||;
8953: $uri=~s|^/||;
8954: $env{'user.environment'}=~/\/([^\/]+)\.id/;
8955: my $token=$1;
8956: my (undef,$udom,$uname,$file)=split('/',$uri,4);
8957: if ($udom && $uname && $file) {
8958: $file=~s|(\?\.*)*$||;
8959: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
8960: my $homeserver = &homeserver($uname,$udom);
8961: my $protocol = $protocol{$homeserver};
8962: $protocol = 'http' if ($protocol ne 'https');
8963: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
8964: (($uri=~/\?/)?'&':'?').'token='.$token.
8965: '&tokenissued='.$perlvar{'lonHostID'};
8966: } else {
8967: return '/adm/notfound.html';
8968: }
8969: }
8970:
8971: # call with reqtype HEAD: get last modification time
8972: # call with reqtype GET: get the file contents
8973: # Do not call this with reqtype GET for large files! It loads everything into memory
8974: #
8975: sub getuploaded {
8976: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
8977: $uri=~s/^\///;
8978: my $homeserver = &homeserver($cnum,$cdom);
8979: my $protocol = $protocol{$homeserver};
8980: $protocol = 'http' if ($protocol ne 'https');
8981: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
8982: my $ua=new LWP::UserAgent;
8983: my $request=new HTTP::Request($reqtype,$uri);
8984: my $response=$ua->request($request);
8985: $$rtncode = $response->code;
8986: if (! $response->is_success()) {
8987: return 'failed';
8988: }
8989: if ($reqtype eq 'HEAD') {
8990: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
8991: } elsif ($reqtype eq 'GET') {
8992: $$info = $response->content;
8993: }
8994: return 'ok';
8995: }
8996:
8997: sub readfile {
8998: my $file = shift;
8999: if ( (! -e $file ) || ($file eq '') ) { return -1; };
9000: my $fh;
9001: open($fh,"<$file");
9002: my $a='';
9003: while (my $line = <$fh>) { $a .= $line; }
9004: return $a;
9005: }
9006:
9007: sub filelocation {
9008: my ($dir,$file) = @_;
9009: my $location;
9010: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
9011:
9012: if ($file =~ m-^/adm/-) {
9013: $file=~s-^/adm/wrapper/-/-;
9014: $file=~s-^/adm/coursedocs/showdoc/-/-;
9015: }
9016:
9017: if ($file=~m:^/~:) { # is a contruction space reference
9018: $location = $file;
9019: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
9020: } elsif ($file=~m{^/home/$match_username/public_html/}) {
9021: # is a correct contruction space reference
9022: $location = $file;
9023: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
9024: $location = $file;
9025: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
9026: my ($udom,$uname,$filename)=
9027: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
9028: my $home=&homeserver($uname,$udom);
9029: my $is_me=0;
9030: my @ids=¤t_machine_ids();
9031: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
9032: if ($is_me) {
9033: $location=&propath($udom,$uname).'/userfiles/'.$filename;
9034: } else {
9035: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
9036: $udom.'/'.$uname.'/'.$filename;
9037: }
9038: } elsif ($file =~ m-^/adm/-) {
9039: $location = $perlvar{'lonDocRoot'}.'/'.$file;
9040: } else {
9041: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9042: $file=~s:^/res/:/:;
9043: if ( !( $file =~ m:^/:) ) {
9044: $location = $dir. '/'.$file;
9045: } else {
9046: $location = '/home/httpd/html/res'.$file;
9047: }
9048: }
9049: $location=~s://+:/:g; # remove duplicate /
9050: while ($location=~m{/\.\./}) {
9051: if ($location =~ m{/[^/]+/\.\./}) {
9052: $location=~ s{/[^/]+/\.\./}{/}g;
9053: } else {
9054: $location=~ s{/\.\./}{/}g;
9055: }
9056: } #remove dir/..
9057: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9058: return $location;
9059: }
9060:
9061: sub hreflocation {
9062: my ($dir,$file)=@_;
9063: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
9064: $file=filelocation($dir,$file);
9065: } elsif ($file=~m-^/adm/-) {
9066: $file=~s-^/adm/wrapper/-/-;
9067: $file=~s-^/adm/coursedocs/showdoc/-/-;
9068: }
9069: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9070: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
9071: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9072: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
9073: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
9074: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
9075: -/uploaded/$1/$2/-x;
9076: }
9077: if ($file=~ m{^/userfiles/}) {
9078: $file =~ s{^/userfiles/}{/uploaded/};
9079: }
9080: return $file;
9081: }
9082:
9083: sub current_machine_domains {
9084: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9085: }
9086:
9087: sub machine_domains {
9088: my ($hostname) = @_;
9089: my @domains;
9090: my %hostname = &all_hostnames();
9091: while( my($id, $name) = each(%hostname)) {
9092: # &logthis("-$id-$name-$hostname-");
9093: if ($hostname eq $name) {
9094: push(@domains,&host_domain($id));
9095: }
9096: }
9097: return @domains;
9098: }
9099:
9100: sub current_machine_ids {
9101: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9102: }
9103:
9104: sub machine_ids {
9105: my ($hostname) = @_;
9106: $hostname ||= &hostname($perlvar{'lonHostID'});
9107: my @ids;
9108: my %name_to_host = &all_names();
9109: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9110: return @{ $name_to_host{$hostname} };
9111: }
9112: return;
9113: }
9114:
9115: sub additional_machine_domains {
9116: my @domains;
9117: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9118: while( my $line = <$fh>) {
9119: $line =~ s/\s//g;
9120: push(@domains,$line);
9121: }
9122: return @domains;
9123: }
9124:
9125: sub default_login_domain {
9126: my $domain = $perlvar{'lonDefDomain'};
9127: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9128: foreach my $posdom (¤t_machine_domains(),
9129: &additional_machine_domains()) {
9130: if (lc($posdom) eq lc($testdomain)) {
9131: $domain=$posdom;
9132: last;
9133: }
9134: }
9135: return $domain;
9136: }
9137:
9138: # ------------------------------------------------------------- Declutters URLs
9139:
9140: sub declutter {
9141: my $thisfn=shift;
9142: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
9143: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9144: $thisfn=~s/^\///;
9145: $thisfn=~s|^adm/wrapper/||;
9146: $thisfn=~s|^adm/coursedocs/showdoc/||;
9147: $thisfn=~s/^res\///;
9148: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
9149: $thisfn=~s/\?.+$//;
9150: }
9151: return $thisfn;
9152: }
9153:
9154: # ------------------------------------------------------------- Clutter up URLs
9155:
9156: sub clutter {
9157: my $thisfn='/'.&declutter(shift);
9158: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
9159: || $thisfn =~ m{^/adm/(includes|pages)} ) {
9160: $thisfn='/res'.$thisfn;
9161: }
9162: if ($thisfn !~m|^/adm|) {
9163: if ($thisfn =~ m|^/ext/|) {
9164: $thisfn='/adm/wrapper'.$thisfn;
9165: } else {
9166: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9167: my $embstyle=&Apache::loncommon::fileembstyle($ext);
9168: if ($embstyle eq 'ssi'
9169: || ($embstyle eq 'hdn')
9170: || ($embstyle eq 'rat')
9171: || ($embstyle eq 'prv')
9172: || ($embstyle eq 'ign')) {
9173: #do nothing with these
9174: } elsif (($embstyle eq 'img')
9175: || ($embstyle eq 'emb')
9176: || ($embstyle eq 'wrp')) {
9177: $thisfn='/adm/wrapper'.$thisfn;
9178: } elsif ($embstyle eq 'unk'
9179: && $thisfn!~/\.(sequence|page)$/) {
9180: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
9181: } else {
9182: # &logthis("Got a blank emb style");
9183: }
9184: }
9185: }
9186: return $thisfn;
9187: }
9188:
9189: sub clutter_with_no_wrapper {
9190: my $uri = &clutter(shift);
9191: if ($uri =~ m-^/adm/-) {
9192: $uri =~ s-^/adm/wrapper/-/-;
9193: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9194: }
9195: return $uri;
9196: }
9197:
9198: sub freeze_escape {
9199: my ($value)=@_;
9200: if (ref($value)) {
9201: $value=&nfreeze($value);
9202: return '__FROZEN__'.&escape($value);
9203: }
9204: return &escape($value);
9205: }
9206:
9207:
9208: sub thaw_unescape {
9209: my ($value)=@_;
9210: if ($value =~ /^__FROZEN__/) {
9211: substr($value,0,10,undef);
9212: $value=&unescape($value);
9213: return &thaw($value);
9214: }
9215: return &unescape($value);
9216: }
9217:
9218: sub correct_line_ends {
9219: my ($result)=@_;
9220: $$result =~s/\r\n/\n/mg;
9221: $$result =~s/\r/\n/mg;
9222: }
9223: # ================================================================ Main Program
9224:
9225: sub goodbye {
9226: &logthis("Starting Shut down");
9227: #not converted to using infrastruture and probably shouldn't be
9228: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
9229: #converted
9230: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
9231: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9232: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9233: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
9234: #1.1 only
9235: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9236: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
9237: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
9238: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
9239: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
9240: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
9241: &logthis(sprintf("%-20s is %s",'hits',$hits));
9242: &flushcourselogs();
9243: &logthis("Shutting down");
9244: }
9245:
9246: sub get_dns {
9247: my ($url,$func,$ignore_cache) = @_;
9248: if (!$ignore_cache) {
9249: my ($content,$cached)=
9250: &Apache::lonnet::is_cached_new('dns',$url);
9251: if ($cached) {
9252: &$func($content);
9253: return;
9254: }
9255: }
9256:
9257: my %alldns;
9258: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9259: foreach my $dns (<$config>) {
9260: next if ($dns !~ /^\^(\S*)/x);
9261: my $line = $1;
9262: my ($host,$protocol) = split(/:/,$line);
9263: if ($protocol ne 'https') {
9264: $protocol = 'http';
9265: }
9266: $alldns{$host} = $protocol;
9267: }
9268: while (%alldns) {
9269: my ($dns) = keys(%alldns);
9270: my $ua=new LWP::UserAgent;
9271: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
9272: my $response=$ua->request($request);
9273: delete($alldns{$dns});
9274: next if ($response->is_error());
9275: my @content = split("\n",$response->content);
9276: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
9277: &$func(\@content);
9278: return;
9279: }
9280: close($config);
9281: my $which = (split('/',$url))[3];
9282: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
9283: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
9284: my @content = <$config>;
9285: &$func(\@content);
9286: return;
9287: }
9288: # ------------------------------------------------------------ Read domain file
9289: {
9290: my $loaded;
9291: my %domain;
9292:
9293: sub parse_domain_tab {
9294: my ($lines) = @_;
9295: foreach my $line (@$lines) {
9296: next if ($line =~ /^(\#|\s*$ )/x);
9297:
9298: chomp($line);
9299: my ($name,@elements) = split(/:/,$line,9);
9300: my %this_domain;
9301: foreach my $field ('description', 'auth_def', 'auth_arg_def',
9302: 'lang_def', 'city', 'longi', 'lati',
9303: 'primary') {
9304: $this_domain{$field} = shift(@elements);
9305: }
9306: $domain{$name} = \%this_domain;
9307: }
9308: }
9309:
9310: sub reset_domain_info {
9311: undef($loaded);
9312: undef(%domain);
9313: }
9314:
9315: sub load_domain_tab {
9316: my ($ignore_cache) = @_;
9317: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
9318: my $fh;
9319: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
9320: my @lines = <$fh>;
9321: &parse_domain_tab(\@lines);
9322: }
9323: close($fh);
9324: $loaded = 1;
9325: }
9326:
9327: sub domain {
9328: &load_domain_tab() if (!$loaded);
9329:
9330: my ($name,$what) = @_;
9331: return if ( !exists($domain{$name}) );
9332:
9333: if (!$what) {
9334: return $domain{$name}{'description'};
9335: }
9336: return $domain{$name}{$what};
9337: }
9338:
9339: sub domain_info {
9340: &load_domain_tab() if (!$loaded);
9341: return %domain;
9342: }
9343:
9344: }
9345:
9346:
9347: # ------------------------------------------------------------- Read hosts file
9348: {
9349: my %hostname;
9350: my %hostdom;
9351: my %libserv;
9352: my $loaded;
9353: my %name_to_host;
9354:
9355: sub parse_hosts_tab {
9356: my ($file) = @_;
9357: foreach my $configline (@$file) {
9358: next if ($configline =~ /^(\#|\s*$ )/x);
9359: next if ($configline =~ /^\^/);
9360: chomp($configline);
9361: my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
9362: $name=~s/\s//g;
9363: if ($id && $domain && $role && $name) {
9364: $hostname{$id}=$name;
9365: push(@{$name_to_host{$name}}, $id);
9366: $hostdom{$id}=$domain;
9367: if ($role eq 'library') { $libserv{$id}=$name; }
9368: if (defined($protocol)) {
9369: if ($protocol eq 'https') {
9370: $protocol{$id} = $protocol;
9371: } else {
9372: $protocol{$id} = 'http';
9373: }
9374: } else {
9375: $protocol{$id} = 'http';
9376: }
9377: }
9378: }
9379: }
9380:
9381: sub reset_hosts_info {
9382: &purge_remembered();
9383: &reset_domain_info();
9384: &reset_hosts_ip_info();
9385: undef(%name_to_host);
9386: undef(%hostname);
9387: undef(%hostdom);
9388: undef(%libserv);
9389: undef($loaded);
9390: }
9391:
9392: sub load_hosts_tab {
9393: my ($ignore_cache) = @_;
9394: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
9395: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9396: my @config = <$config>;
9397: &parse_hosts_tab(\@config);
9398: close($config);
9399: $loaded=1;
9400: }
9401:
9402: sub hostname {
9403: &load_hosts_tab() if (!$loaded);
9404:
9405: my ($lonid) = @_;
9406: return $hostname{$lonid};
9407: }
9408:
9409: sub all_hostnames {
9410: &load_hosts_tab() if (!$loaded);
9411:
9412: return %hostname;
9413: }
9414:
9415: sub all_names {
9416: &load_hosts_tab() if (!$loaded);
9417:
9418: return %name_to_host;
9419: }
9420:
9421: sub all_host_domain {
9422: &load_hosts_tab() if (!$loaded);
9423: return %hostdom;
9424: }
9425:
9426: sub is_library {
9427: &load_hosts_tab() if (!$loaded);
9428:
9429: return exists($libserv{$_[0]});
9430: }
9431:
9432: sub all_library {
9433: &load_hosts_tab() if (!$loaded);
9434:
9435: return %libserv;
9436: }
9437:
9438: sub get_servers {
9439: &load_hosts_tab() if (!$loaded);
9440:
9441: my ($domain,$type) = @_;
9442: my %possible_hosts = ($type eq 'library') ? %libserv
9443: : %hostname;
9444: my %result;
9445: if (ref($domain) eq 'ARRAY') {
9446: while ( my ($host,$hostname) = each(%possible_hosts)) {
9447: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
9448: $result{$host} = $hostname;
9449: }
9450: }
9451: } else {
9452: while ( my ($host,$hostname) = each(%possible_hosts)) {
9453: if ($hostdom{$host} eq $domain) {
9454: $result{$host} = $hostname;
9455: }
9456: }
9457: }
9458: return %result;
9459: }
9460:
9461: sub host_domain {
9462: &load_hosts_tab() if (!$loaded);
9463:
9464: my ($lonid) = @_;
9465: return $hostdom{$lonid};
9466: }
9467:
9468: sub all_domains {
9469: &load_hosts_tab() if (!$loaded);
9470:
9471: my %seen;
9472: my @uniq = grep(!$seen{$_}++, values(%hostdom));
9473: return @uniq;
9474: }
9475: }
9476:
9477: {
9478: my %iphost;
9479: my %name_to_ip;
9480: my %lonid_to_ip;
9481:
9482: sub get_hosts_from_ip {
9483: my ($ip) = @_;
9484: my %iphosts = &get_iphost();
9485: if (ref($iphosts{$ip})) {
9486: return @{$iphosts{$ip}};
9487: }
9488: return;
9489: }
9490:
9491: sub reset_hosts_ip_info {
9492: undef(%iphost);
9493: undef(%name_to_ip);
9494: undef(%lonid_to_ip);
9495: }
9496:
9497: sub get_host_ip {
9498: my ($lonid) = @_;
9499: if (exists($lonid_to_ip{$lonid})) {
9500: return $lonid_to_ip{$lonid};
9501: }
9502: my $name=&hostname($lonid);
9503: my $ip = gethostbyname($name);
9504: return if (!$ip || length($ip) ne 4);
9505: $ip=inet_ntoa($ip);
9506: $name_to_ip{$name} = $ip;
9507: $lonid_to_ip{$lonid} = $ip;
9508: return $ip;
9509: }
9510:
9511: sub get_iphost {
9512: my ($ignore_cache) = @_;
9513:
9514: if (!$ignore_cache) {
9515: if (%iphost) {
9516: return %iphost;
9517: }
9518: my ($ip_info,$cached)=
9519: &Apache::lonnet::is_cached_new('iphost','iphost');
9520: if ($cached) {
9521: %iphost = %{$ip_info->[0]};
9522: %name_to_ip = %{$ip_info->[1]};
9523: %lonid_to_ip = %{$ip_info->[2]};
9524: return %iphost;
9525: }
9526: }
9527:
9528: # get yesterday's info for fallback
9529: my %old_name_to_ip;
9530: my ($ip_info,$cached)=
9531: &Apache::lonnet::is_cached_new('iphost','iphost');
9532: if ($cached) {
9533: %old_name_to_ip = %{$ip_info->[1]};
9534: }
9535:
9536: my %name_to_host = &all_names();
9537: foreach my $name (keys(%name_to_host)) {
9538: my $ip;
9539: if (!exists($name_to_ip{$name})) {
9540: $ip = gethostbyname($name);
9541: if (!$ip || length($ip) ne 4) {
9542: if (defined($old_name_to_ip{$name})) {
9543: $ip = $old_name_to_ip{$name};
9544: &logthis("Can't find $name defaulting to old $ip");
9545: } else {
9546: &logthis("Name $name no IP found");
9547: next;
9548: }
9549: } else {
9550: $ip=inet_ntoa($ip);
9551: }
9552: $name_to_ip{$name} = $ip;
9553: } else {
9554: $ip = $name_to_ip{$name};
9555: }
9556: foreach my $id (@{ $name_to_host{$name} }) {
9557: $lonid_to_ip{$id} = $ip;
9558: }
9559: push(@{$iphost{$ip}},@{$name_to_host{$name}});
9560: }
9561: &Apache::lonnet::do_cache_new('iphost','iphost',
9562: [\%iphost,\%name_to_ip,\%lonid_to_ip],
9563: 48*60*60);
9564:
9565: return %iphost;
9566: }
9567:
9568: #
9569: # Given a DNS returns the loncapa host name for that DNS
9570: #
9571: sub host_from_dns {
9572: my ($dns) = @_;
9573: my @hosts;
9574: my $ip;
9575:
9576: if (exists($name_to_ip{$dns})) {
9577: $ip = $name_to_ip{$dns};
9578: }
9579: if (!$ip) {
9580: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
9581: if (length($ip) == 4) {
9582: $ip = &IO::Socket::inet_ntoa($ip);
9583: }
9584: }
9585: if ($ip) {
9586: @hosts = get_hosts_from_ip($ip);
9587: return $hosts[0];
9588: }
9589: return undef;
9590: }
9591:
9592: }
9593:
9594: BEGIN {
9595:
9596: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
9597: unless ($readit) {
9598: {
9599: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
9600: %perlvar = (%perlvar,%{$configvars});
9601: }
9602:
9603:
9604: # ------------------------------------------------------ Read spare server file
9605: {
9606: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
9607:
9608: while (my $configline=<$config>) {
9609: chomp($configline);
9610: if ($configline) {
9611: my ($host,$type) = split(':',$configline,2);
9612: if (!defined($type) || $type eq '') { $type = 'default' };
9613: push(@{ $spareid{$type} }, $host);
9614: }
9615: }
9616: close($config);
9617: }
9618: # ------------------------------------------------------------ Read permissions
9619: {
9620: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
9621:
9622: while (my $configline=<$config>) {
9623: chomp($configline);
9624: if ($configline) {
9625: my ($role,$perm)=split(/ /,$configline);
9626: if ($perm ne '') { $pr{$role}=$perm; }
9627: }
9628: }
9629: close($config);
9630: }
9631:
9632: # -------------------------------------------- Read plain texts for permissions
9633: {
9634: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
9635:
9636: while (my $configline=<$config>) {
9637: chomp($configline);
9638: if ($configline) {
9639: my ($short,@plain)=split(/:/,$configline);
9640: %{$prp{$short}} = ();
9641: if (@plain > 0) {
9642: $prp{$short}{'std'} = $plain[0];
9643: for (my $i=1; $i<@plain; $i++) {
9644: $prp{$short}{'alt'.$i} = $plain[$i];
9645: }
9646: }
9647: }
9648: }
9649: close($config);
9650: }
9651:
9652: # ---------------------------------------------------------- Read package table
9653: {
9654: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
9655:
9656: while (my $configline=<$config>) {
9657: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
9658: chomp($configline);
9659: my ($short,$plain)=split(/:/,$configline);
9660: my ($pack,$name)=split(/\&/,$short);
9661: if ($plain ne '') {
9662: $packagetab{$pack.'&'.$name.'&name'}=$name;
9663: $packagetab{$short}=$plain;
9664: }
9665: }
9666: close($config);
9667: }
9668:
9669: # ------------- set up temporary directory
9670: {
9671: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
9672:
9673: }
9674:
9675: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
9676: 'compress_threshold'=> 20_000,
9677: });
9678:
9679: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
9680: $dumpcount=0;
9681: $locknum=0;
9682:
9683: &logtouch();
9684: &logthis('<font color="yellow">INFO: Read configuration</font>');
9685: $readit=1;
9686: {
9687: use integer;
9688: my $test=(2**32)+1;
9689: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
9690: &logthis(" Detected 64bit platform ($_64bit)");
9691: }
9692: }
9693: }
9694:
9695: 1;
9696: __END__
9697:
9698: =pod
9699:
9700: =head1 NAME
9701:
9702: Apache::lonnet - Subroutines to ask questions about things in the network.
9703:
9704: =head1 SYNOPSIS
9705:
9706: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
9707:
9708: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
9709:
9710: Common parameters:
9711:
9712: =over 4
9713:
9714: =item *
9715:
9716: $uname : an internal username (if $cname expecting a course Id specifically)
9717:
9718: =item *
9719:
9720: $udom : a domain (if $cdom expecting a course's domain specifically)
9721:
9722: =item *
9723:
9724: $symb : a resource instance identifier
9725:
9726: =item *
9727:
9728: $namespace : the name of a .db file that contains the data needed or
9729: being set.
9730:
9731: =back
9732:
9733: =head1 OVERVIEW
9734:
9735: lonnet provides subroutines which interact with the
9736: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
9737: about classes, users, and resources.
9738:
9739: For many of these objects you can also use this to store data about
9740: them or modify them in various ways.
9741:
9742: =head2 Symbs
9743:
9744: To identify a specific instance of a resource, LON-CAPA uses symbols
9745: or "symbs"X<symb>. These identifiers are built from the URL of the
9746: map, the resource number of the resource in the map, and the URL of
9747: the resource itself. The latter is somewhat redundant, but might help
9748: if maps change.
9749:
9750: An example is
9751:
9752: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
9753:
9754: The respective map entry is
9755:
9756: <resource id="19" src="/res/msu/korte/tests/part12.problem"
9757: title="Problem 2">
9758: </resource>
9759:
9760: Symbs are used by the random number generator, as well as to store and
9761: restore data specific to a certain instance of for example a problem.
9762:
9763: =head2 Storing And Retrieving Data
9764:
9765: X<store()>X<cstore()>X<restore()>Three of the most important functions
9766: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
9767: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
9768: is is the non-critical message twin of cstore. These functions are for
9769: handlers to store a perl hash to a user's permanent data space in an
9770: easy manner, and to retrieve it again on another call. It is expected
9771: that a handler would use this once at the beginning to retrieve data,
9772: and then again once at the end to send only the new data back.
9773:
9774: The data is stored in the user's data directory on the user's
9775: homeserver under the ID of the course.
9776:
9777: The hash that is returned by restore will have all of the previous
9778: value for all of the elements of the hash.
9779:
9780: Example:
9781:
9782: #creating a hash
9783: my %hash;
9784: $hash{'foo'}='bar';
9785:
9786: #storing it
9787: &Apache::lonnet::cstore(\%hash);
9788:
9789: #changing a value
9790: $hash{'foo'}='notbar';
9791:
9792: #adding a new value
9793: $hash{'bar'}='foo';
9794: &Apache::lonnet::cstore(\%hash);
9795:
9796: #retrieving the hash
9797: my %history=&Apache::lonnet::restore();
9798:
9799: #print the hash
9800: foreach my $key (sort(keys(%history))) {
9801: print("\%history{$key} = $history{$key}");
9802: }
9803:
9804: Will print out:
9805:
9806: %history{1:foo} = bar
9807: %history{1:keys} = foo:timestamp
9808: %history{1:timestamp} = 990455579
9809: %history{2:bar} = foo
9810: %history{2:foo} = notbar
9811: %history{2:keys} = foo:bar:timestamp
9812: %history{2:timestamp} = 990455580
9813: %history{bar} = foo
9814: %history{foo} = notbar
9815: %history{timestamp} = 990455580
9816: %history{version} = 2
9817:
9818: Note that the special hash entries C<keys>, C<version> and
9819: C<timestamp> were added to the hash. C<version> will be equal to the
9820: total number of versions of the data that have been stored. The
9821: C<timestamp> attribute will be the UNIX time the hash was
9822: stored. C<keys> is available in every historical section to list which
9823: keys were added or changed at a specific historical revision of a
9824: hash.
9825:
9826: B<Warning>: do not store the hash that restore returns directly. This
9827: will cause a mess since it will restore the historical keys as if the
9828: were new keys. I.E. 1:foo will become 1:1:foo etc.
9829:
9830: Calling convention:
9831:
9832: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
9833: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
9834:
9835: For more detailed information, see lonnet specific documentation.
9836:
9837: =head1 RETURN MESSAGES
9838:
9839: =over 4
9840:
9841: =item * B<con_lost>: unable to contact remote host
9842:
9843: =item * B<con_delayed>: unable to contact remote host, message will be delivered
9844: when the connection is brought back up
9845:
9846: =item * B<con_failed>: unable to contact remote host and unable to save message
9847: for later delivery
9848:
9849: =item * B<error:>: an error a occurred, a description of the error follows the :
9850:
9851: =item * B<no_such_host>: unable to fund a host associated with the user/domain
9852: that was requested
9853:
9854: =back
9855:
9856: =head1 PUBLIC SUBROUTINES
9857:
9858: =head2 Session Environment Functions
9859:
9860: =over 4
9861:
9862: =item *
9863: X<appenv()>
9864: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
9865: the user envirnoment file, and will be restored for each access this
9866: user makes during this session, also modifies the %env for the current
9867: process. Optional rolesarrayref - if defined contains a reference to an array
9868: of roles which are exempt from the restriction on modifying user.role entries
9869: in the user's environment.db and in %env.
9870:
9871: =item *
9872: X<delenv()>
9873: B<delenv($delthis,$regexp)>: removes all items from the session
9874: environment file that begin with $delthis. If the
9875: optional second arg - $regexp - is true, $delthis is treated as a
9876: regular expression, otherwise \Q$delthis\E is used.
9877: The values are also deleted from the current processes %env.
9878:
9879: =item * get_env_multiple($name)
9880:
9881: gets $name from the %env hash, it seemlessly handles the cases where multiple
9882: values may be defined and end up as an array ref.
9883:
9884: returns an array of values
9885:
9886: =back
9887:
9888: =head2 User Information
9889:
9890: =over 4
9891:
9892: =item *
9893: X<queryauthenticate()>
9894: B<queryauthenticate($uname,$udom)>: try to determine user's current
9895: authentication scheme
9896:
9897: =item *
9898: X<authenticate()>
9899: B<authenticate($uname,$upass,$udom)>: try to
9900: authenticate user from domain's lib servers (first use the current
9901: one). C<$upass> should be the users password.
9902:
9903: =item *
9904: X<homeserver()>
9905: B<homeserver($uname,$udom)>: find the server which has
9906: the user's directory and files (there must be only one), this caches
9907: the answer, and also caches if there is a borken connection.
9908:
9909: =item *
9910: X<idget()>
9911: B<idget($udom,@ids)>: find the usernames behind a list of IDs
9912: (IDs are a unique resource in a domain, there must be only 1 ID per
9913: username, and only 1 username per ID in a specific domain) (returns
9914: hash: id=>name,id=>name)
9915:
9916: =item *
9917: X<idrget()>
9918: B<idrget($udom,@unames)>: find the IDs behind a list of
9919: usernames (returns hash: name=>id,name=>id)
9920:
9921: =item *
9922: X<idput()>
9923: B<idput($udom,%ids)>: store away a list of names and associated IDs
9924:
9925: =item *
9926: X<rolesinit()>
9927: B<rolesinit($udom,$username,$authhost)>: get user privileges
9928:
9929: =item *
9930: X<getsection()>
9931: B<getsection($udom,$uname,$cname)>: finds the section of student in the
9932: course $cname, return section name/number or '' for "not in course"
9933: and '-1' for "no section"
9934:
9935: =item *
9936: X<userenvironment()>
9937: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
9938: passed in @what from the requested user's environment, returns a hash
9939:
9940: =item *
9941: X<userlog_query()>
9942: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
9943: activity.log file. %filters defines filters applied when parsing the
9944: log file. These can be start or end timestamps, or the type of action
9945: - log to look for Login or Logout events, check for Checkin or
9946: Checkout, role for role selection. The response is in the form
9947: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
9948: escaped strings of the action recorded in the activity.log file.
9949:
9950: =back
9951:
9952: =head2 User Roles
9953:
9954: =over 4
9955:
9956: =item *
9957:
9958: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
9959: F: full access
9960: U,I,K: authentication modes (cxx only)
9961: '': forbidden
9962: 1: user needs to choose course
9963: 2: browse allowed
9964: A: passphrase authentication needed
9965:
9966: =item *
9967:
9968: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
9969: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
9970: and course level
9971:
9972: =item *
9973:
9974: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
9975: (rolesplain.tab); plain text explanation of a user role term.
9976: $type is Course (default) or Community.
9977: If $forcedefault evaluates to true, text returned will be default
9978: text for $type. Otherwise, if this is a course, the text returned
9979: will be a custom name for the role (if defined in the course's
9980: environment). If no custom name is defined the default is returned.
9981:
9982: =item *
9983:
9984: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
9985: All arguments are optional. Returns a hash of a roles, either for
9986: co-author/assistant author roles for a user's Construction Space
9987: (default), or if $context is 'userroles', roles for the user himself,
9988: In the hash, keys are set to colon-separated $uname,$udom,$role, and
9989: (optionally) if $withsec is true, a fourth colon-separated item - $section.
9990: For each key, value is set to colon-separated start and end times for
9991: the role. If no username and domain are specified, will default to
9992: current user/domain. Types, roles, and roledoms are references to arrays
9993: of role statuses (active, future or previous), roles
9994: (e.g., cc,in, st etc.) and domains of the roles which can be used
9995: to restrict the list of roles reported. If no array ref is
9996: provided for types, will default to return only active roles.
9997:
9998: =back
9999:
10000: =head2 User Modification
10001:
10002: =over 4
10003:
10004: =item *
10005:
10006: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
10007: user for the level given by URL. Optional start and end dates (leave empty
10008: string or zero for "no date")
10009:
10010: =item *
10011:
10012: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10013: change a users, password, possible return values are: ok,
10014: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10015: refused
10016:
10017: =item *
10018:
10019: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
10020:
10021: =item *
10022:
10023: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
10024: $forceid,$desiredhome,$email,$inststatus) :
10025: modify user
10026:
10027: =item *
10028:
10029: modifystudent
10030:
10031: modify a student's enrollment and identification information.
10032: The course id is resolved based on the current users environment.
10033: This means the envoking user must be a course coordinator or otherwise
10034: associated with a course.
10035:
10036: This call is essentially a wrapper for lonnet::modifyuser and
10037: lonnet::modify_student_enrollment
10038:
10039: Inputs:
10040:
10041: =over 4
10042:
10043: =item B<$udom> Student's loncapa domain
10044:
10045: =item B<$uname> Student's loncapa login name
10046:
10047: =item B<$uid> Student/Employee ID
10048:
10049: =item B<$umode> Student's authentication mode
10050:
10051: =item B<$upass> Student's password
10052:
10053: =item B<$first> Student's first name
10054:
10055: =item B<$middle> Student's middle name
10056:
10057: =item B<$last> Student's last name
10058:
10059: =item B<$gene> Student's generation
10060:
10061: =item B<$usec> Student's section in course
10062:
10063: =item B<$end> Unix time of the roles expiration
10064:
10065: =item B<$start> Unix time of the roles start date
10066:
10067: =item B<$forceid> If defined, allow $uid to be changed
10068:
10069: =item B<$desiredhome> server to use as home server for student
10070:
10071: =item B<$email> Student's permanent e-mail address
10072:
10073: =item B<$type> Type of enrollment (auto or manual)
10074:
10075: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10076:
10077: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
10078:
10079: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
10080:
10081: =item B<$context> role change context (shown in User Management Logs display in a course)
10082:
10083: =item B<$inststatus> institutional status of user - : separated string of escaped status types
10084:
10085: =back
10086:
10087: =item *
10088:
10089: modify_student_enrollment
10090:
10091: Change a students enrollment status in a class. The environment variable
10092: 'role.request.course' must be defined for this function to proceed.
10093:
10094: Inputs:
10095:
10096: =over 4
10097:
10098: =item $udom, students domain
10099:
10100: =item $uname, students name
10101:
10102: =item $uid, students user id
10103:
10104: =item $first, students first name
10105:
10106: =item $middle
10107:
10108: =item $last
10109:
10110: =item $gene
10111:
10112: =item $usec
10113:
10114: =item $end
10115:
10116: =item $start
10117:
10118: =item $type
10119:
10120: =item $locktype
10121:
10122: =item $cid
10123:
10124: =item $selfenroll
10125:
10126: =item $context
10127:
10128: =back
10129:
10130:
10131: =item *
10132:
10133: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10134: custom role; give a custom role to a user for the level given by URL. Specify
10135: name and domain of role author, and role name
10136:
10137: =item *
10138:
10139: revokerole($udom,$uname,$url,$role) : revoke a role for url
10140:
10141: =item *
10142:
10143: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10144:
10145: =back
10146:
10147: =head2 Course Infomation
10148:
10149: =over 4
10150:
10151: =item *
10152:
10153: coursedescription($courseid) : returns a hash of information about the
10154: specified course id, including all environment settings for the
10155: course, the description of the course will be in the hash under the
10156: key 'description'
10157:
10158: =item *
10159:
10160: resdata($name,$domain,$type,@which) : request for current parameter
10161: setting for a specific $type, where $type is either 'course' or 'user',
10162: @what should be a list of parameters to ask about. This routine caches
10163: answers for 5 minutes.
10164:
10165: =item *
10166:
10167: get_courseresdata($courseid, $domain) : dump the entire course resource
10168: data base, returning a hash that is keyed by the resource name and has
10169: values that are the resource value. I believe that the timestamps and
10170: versions are also returned.
10171:
10172:
10173: =back
10174:
10175: =head2 Course Modification
10176:
10177: =over 4
10178:
10179: =item *
10180:
10181: writecoursepref($courseid,%prefs) : write preferences (environment
10182: database) for a course
10183:
10184: =item *
10185:
10186: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10187:
10188: =item *
10189:
10190: generate_coursenum($udom) : get a unique (unused) course number in domain $udom
10191:
10192: =back
10193:
10194: =head2 Resource Subroutines
10195:
10196: =over 4
10197:
10198: =item *
10199:
10200: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
10201:
10202: =item *
10203:
10204: repcopy($filename) : subscribes to the requested file, and attempts to
10205: replicate from the owning library server, Might return
10206: 'unavailable', 'not_found', 'forbidden', 'ok', or
10207: 'bad_request', also attempts to grab the metadata for the
10208: resource. Expects the local filesystem pathname
10209: (/home/httpd/html/res/....)
10210:
10211: =back
10212:
10213: =head2 Resource Information
10214:
10215: =over 4
10216:
10217: =item *
10218:
10219: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10220: a vairety of different possible values, $varname should be a request
10221: string, and the other parameters can be used to specify who and what
10222: one is asking about.
10223:
10224: Possible values for $varname are environment.lastname (or other item
10225: from the envirnment hash), user.name (or someother aspect about the
10226: user), resource.0.maxtries (or some other part and parameter of a
10227: resource)
10228:
10229: =item *
10230:
10231: directcondval($number) : get current value of a condition; reads from a state
10232: string
10233:
10234: =item *
10235:
10236: condval($condidx) : value of condition index based on state
10237:
10238: =item *
10239:
10240: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
10241: resource's metadata, $what should be either a specific key, or either
10242: 'keys' (to get a list of possible keys) or 'packages' to get a list of
10243: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
10244:
10245: this function automatically caches all requests
10246:
10247: =item *
10248:
10249: metadata_query($query,$custom,$customshow) : make a metadata query against the
10250: network of library servers; returns file handle of where SQL and regex results
10251: will be stored for query
10252:
10253: =item *
10254:
10255: symbread($filename) : return symbolic list entry (filename argument optional);
10256: returns the data handle
10257:
10258: =item *
10259:
10260: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
10261: a possible symb for the URL in $thisfn, and if is an encryypted
10262: resource that the user accessed using /enc/ returns a 1 on success, 0
10263: on failure, user must be in a course, as it assumes the existance of
10264: the course initial hash, and uses $env('request.course.id'}
10265:
10266:
10267: =item *
10268:
10269: symbclean($symb) : removes versions numbers from a symb, returns the
10270: cleaned symb
10271:
10272: =item *
10273:
10274: is_on_map($uri) : checks if the $uri is somewhere on the current
10275: course map, user must be in a course for it to work.
10276:
10277: =item *
10278:
10279: numval($salt) : return random seed value (addend for rndseed)
10280:
10281: =item *
10282:
10283: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10284: a random seed, all arguments are optional, if they aren't sent it uses the
10285: environment to derive them. Note: if symb isn't sent and it can't get one
10286: from &symbread it will use the current time as its return value
10287:
10288: =item *
10289:
10290: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10291: unfakeable, receipt
10292:
10293: =item *
10294:
10295: receipt() : API to ireceipt working off of env values; given out to users
10296:
10297: =item *
10298:
10299: countacc($url) : count the number of accesses to a given URL
10300:
10301: =item *
10302:
10303: 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
10304:
10305: =item *
10306:
10307: 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)
10308:
10309: =item *
10310:
10311: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
10312:
10313: =item *
10314:
10315: devalidate($symb) : devalidate temporary spreadsheet calculations,
10316: forcing spreadsheet to reevaluate the resource scores next time.
10317:
10318: =back
10319:
10320: =head2 Storing/Retreiving Data
10321:
10322: =over 4
10323:
10324: =item *
10325:
10326: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
10327: for this url; hashref needs to be given and should be a \%hashname; the
10328: remaining args aren't required and if they aren't passed or are '' they will
10329: be derived from the env
10330:
10331: =item *
10332:
10333: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
10334: uses critical subroutine
10335:
10336: =item *
10337:
10338: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
10339: all args are optional
10340:
10341: =item *
10342:
10343: dumpstore($namespace,$udom,$uname,$regexp,$range) :
10344: dumps the complete (or key matching regexp) namespace into a hash
10345: ($udom, $uname, $regexp, $range are optional) for a namespace that is
10346: normally &store()ed into
10347:
10348: $range should be either an integer '100' (give me the first 100
10349: matching records)
10350: or be two integers sperated by a - with no spaces
10351: '30-50' (give me the 30th through the 50th matching
10352: records)
10353:
10354:
10355: =item *
10356:
10357: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
10358: replaces a &store() version of data with a replacement set of data
10359: for a particular resource in a namespace passed in the $storehash hash
10360: reference
10361:
10362: =item *
10363:
10364: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
10365: works very similar to store/cstore, but all data is stored in a
10366: temporary location and can be reset using tmpreset, $storehash should
10367: be a hash reference, returns nothing on success
10368:
10369: =item *
10370:
10371: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
10372: similar to restore, but all data is stored in a temporary location and
10373: can be reset using tmpreset. Returns a hash of values on success,
10374: error string otherwise.
10375:
10376: =item *
10377:
10378: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
10379: deltes all keys for $symb form the temporary storage hash.
10380:
10381: =item *
10382:
10383: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10384: reference filled in from namesp ($udom and $uname are optional)
10385:
10386: =item *
10387:
10388: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
10389: namesp ($udom and $uname are optional)
10390:
10391: =item *
10392:
10393: dump($namespace,$udom,$uname,$regexp,$range) :
10394: dumps the complete (or key matching regexp) namespace into a hash
10395: ($udom, $uname, $regexp, $range are optional)
10396:
10397: $range should be either an integer '100' (give me the first 100
10398: matching records)
10399: or be two integers sperated by a - with no spaces
10400: '30-50' (give me the 30th through the 50th matching
10401: records)
10402: =item *
10403:
10404: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
10405: $store can be a scalar, an array reference, or if the amount to be
10406: incremented is > 1, a hash reference.
10407:
10408: ($udom and $uname are optional)
10409:
10410: =item *
10411:
10412: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
10413: ($udom and $uname are optional)
10414:
10415: =item *
10416:
10417: cput($namespace,$storehash,$udom,$uname) : critical put
10418: ($udom and $uname are optional)
10419:
10420: =item *
10421:
10422: newput($namespace,$storehash,$udom,$uname) :
10423:
10424: Attempts to store the items in the $storehash, but only if they don't
10425: currently exist, if this succeeds you can be certain that you have
10426: successfully created a new key value pair in the $namespace db.
10427:
10428:
10429: Args:
10430: $namespace: name of database to store values to
10431: $storehash: hashref to store to the db
10432: $udom: (optional) domain of user containing the db
10433: $uname: (optional) name of user caontaining the db
10434:
10435: Returns:
10436: 'ok' -> succeeded in storing all keys of $storehash
10437: 'key_exists: <key>' -> failed to anything out of $storehash, as at
10438: least <key> already existed in the db (other
10439: requested keys may also already exist)
10440: 'error: <msg>' -> unable to tie the DB or other error occurred
10441: 'con_lost' -> unable to contact request server
10442: 'refused' -> action was not allowed by remote machine
10443:
10444:
10445: =item *
10446:
10447: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10448: reference filled in from namesp (encrypts the return communication)
10449: ($udom and $uname are optional)
10450:
10451: =item *
10452:
10453: log($udom,$name,$home,$message) : write to permanent log for user; use
10454: critical subroutine
10455:
10456: =item *
10457:
10458: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
10459: array reference filled in from namespace found in domain level on either
10460: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
10461:
10462: =item *
10463:
10464: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
10465: domain level either on specified domain server ($uhome) or primary domain
10466: server ($udom and $uhome are optional)
10467:
10468: =item *
10469:
10470: get_domain_defaults($target_domain) : returns hash with defaults for
10471: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
10472: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
10473: or localauth), initial password or a kerberos realm, language (e.g., en-us).
10474: Values are retrieved from cache (if current), or from domain's configuration.db
10475: (if available), or lastly from values in lonTabs/dns_domain,tab,
10476: or lonTabs/domain.tab.
10477:
10478: %domdefaults = &get_auth_defaults($target_domain);
10479:
10480: =back
10481:
10482: =head2 Network Status Functions
10483:
10484: =over 4
10485:
10486: =item *
10487:
10488: dirlist($uri) : return directory list based on URI
10489:
10490: =item *
10491:
10492: spareserver() : find server with least workload from spare.tab
10493:
10494:
10495: =item *
10496:
10497: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
10498: if there is no corresponding loncapa host.
10499:
10500: =back
10501:
10502:
10503: =head2 Apache Request
10504:
10505: =over 4
10506:
10507: =item *
10508:
10509: ssi($url,%hash) : server side include, does a complete request cycle on url to
10510: localhost, posts hash
10511:
10512: =back
10513:
10514: =head2 Data to String to Data
10515:
10516: =over 4
10517:
10518: =item *
10519:
10520: hash2str(%hash) : convert a hash into a string complete with escaping and '='
10521: and '&' separators, supports elements that are arrayrefs and hashrefs
10522:
10523: =item *
10524:
10525: hashref2str($hashref) : convert a hashref into a string complete with
10526: escaping and '=' and '&' separators, supports elements that are
10527: arrayrefs and hashrefs
10528:
10529: =item *
10530:
10531: arrayref2str($arrayref) : convert an arrayref into a string complete
10532: with escaping and '&' separators, supports elements that are arrayrefs
10533: and hashrefs
10534:
10535: =item *
10536:
10537: str2hash($string) : convert string to hash using unescaping and
10538: splitting on '=' and '&', supports elements that are arrayrefs and
10539: hashrefs
10540:
10541: =item *
10542:
10543: str2array($string) : convert string to hash using unescaping and
10544: splitting on '&', supports elements that are arrayrefs and hashrefs
10545:
10546: =back
10547:
10548: =head2 Logging Routines
10549:
10550: =over 4
10551:
10552: These routines allow one to make log messages in the lonnet.log and
10553: lonnet.perm logfiles.
10554:
10555: =item *
10556:
10557: logtouch() : make sure the logfile, lonnet.log, exists
10558:
10559: =item *
10560:
10561: logthis() : append message to the normal lonnet.log file, it gets
10562: preiodically rolled over and deleted.
10563:
10564: =item *
10565:
10566: logperm() : append a permanent message to lonnet.perm.log, this log
10567: file never gets deleted by any automated portion of the system, only
10568: messages of critical importance should go in here.
10569:
10570: =back
10571:
10572: =head2 General File Helper Routines
10573:
10574: =over 4
10575:
10576: =item *
10577:
10578: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10579: (a) files in /uploaded
10580: (i) If a local copy of the file exists -
10581: compares modification date of local copy with last-modified date for
10582: definitive version stored on home server for course. If local copy is
10583: stale, requests a new version from the home server and stores it.
10584: If the original has been removed from the home server, then local copy
10585: is unlinked.
10586: (ii) If local copy does not exist -
10587: requests the file from the home server and stores it.
10588:
10589: If $caller is 'uploadrep':
10590: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10591: for request for files originally uploaded via DOCS.
10592: - returns 'ok' if fresh local copy now available, -1 otherwise.
10593:
10594: Otherwise:
10595: This indicates a call from the content generation phase of the request.
10596: - returns the entire contents of the file or -1.
10597:
10598: (b) files in /res
10599: - returns the entire contents of a file or -1;
10600: it properly subscribes to and replicates the file if neccessary.
10601:
10602:
10603: =item *
10604:
10605: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10606: reference
10607:
10608: returns either a stat() list of data about the file or an empty list
10609: if the file doesn't exist or couldn't find out about it (connection
10610: problems or user unknown)
10611:
10612: =item *
10613:
10614: filelocation($dir,$file) : returns file system location of a file
10615: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10616: directory that relative $file lookups are to looked in ($dir of /a/dir
10617: and a file of ../bob will become /a/bob)
10618:
10619: =item *
10620:
10621: hreflocation($dir,$file) : returns file system location or a URL; same as
10622: filelocation except for hrefs
10623:
10624: =item *
10625:
10626: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10627:
10628: =back
10629:
10630: =head2 Usererfile file routines (/uploaded*)
10631:
10632: =over 4
10633:
10634: =item *
10635:
10636: userfileupload(): main rotine for putting a file in a user or course's
10637: filespace, arguments are,
10638:
10639: formname - required - this is the name of the element in $env where the
10640: filename, and the contents of the file to create/modifed exist
10641: the filename is in $env{'form.'.$formname.'.filename'} and the
10642: contents of the file is located in $env{'form.'.$formname}
10643: coursedoc - if true, store the file in the course of the active role
10644: of the current user
10645: subdir - required - subdirectory to put the file in under ../userfiles/
10646: if undefined, it will be placed in "unknown"
10647:
10648: (This routine calls clean_filename() to remove any dangerous
10649: characters from the filename, and then calls finuserfileupload() to
10650: complete the transaction)
10651:
10652: returns either the url of the uploaded file (/uploaded/....) if successful
10653: and /adm/notfound.html if unsuccessful
10654:
10655: =item *
10656:
10657: clean_filename(): routine for cleaing a filename up for storage in
10658: userfile space, argument is:
10659:
10660: filename - proposed filename
10661:
10662: returns: the new clean filename
10663:
10664: =item *
10665:
10666: finishuserfileupload(): routine that creaes and sends the file to
10667: userspace, probably shouldn't be called directly
10668:
10669: docuname: username or courseid of destination for the file
10670: docudom: domain of user/course of destination for the file
10671: formname: same as for userfileupload()
10672: fname: filename (inculding subdirectories) for the file
10673:
10674: returns either the url of the uploaded file (/uploaded/....) if successful
10675: and /adm/notfound.html if unsuccessful
10676:
10677: =item *
10678:
10679: renameuserfile(): renames an existing userfile to a new name
10680:
10681: Args:
10682: docuname: username or courseid of destination for the file
10683: docudom: domain of user/course of destination for the file
10684: old: current file name (including any subdirs under userfiles)
10685: new: desired file name (including any subdirs under userfiles)
10686:
10687: =item *
10688:
10689: mkdiruserfile(): creates a directory is a userfiles dir
10690:
10691: Args:
10692: docuname: username or courseid of destination for the file
10693: docudom: domain of user/course of destination for the file
10694: dir: dir to create (including any subdirs under userfiles)
10695:
10696: =item *
10697:
10698: removeuserfile(): removes a file that exists in userfiles
10699:
10700: Args:
10701: docuname: username or courseid of destination for the file
10702: docudom: domain of user/course of destination for the file
10703: fname: filname to delete (including any subdirs under userfiles)
10704:
10705: =item *
10706:
10707: removeuploadedurl(): convience function for removeuserfile()
10708:
10709: Args:
10710: url: a full /uploaded/... url to delete
10711:
10712: =item *
10713:
10714: get_portfile_permissions():
10715: Args:
10716: domain: domain of user or course contain the portfolio files
10717: user: name of user or num of course contain the portfolio files
10718: Returns:
10719: hashref of a dump of the proper file_permissions.db
10720:
10721:
10722: =item *
10723:
10724: get_access_controls():
10725:
10726: Args:
10727: current_permissions: the hash ref returned from get_portfile_permissions()
10728: group: (optional) the group you want the files associated with
10729: file: (optional) the file you want access info on
10730:
10731: Returns:
10732: a hash (keys are file names) of hashes containing
10733: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10734: values are XML containing access control settings (see below)
10735:
10736: Internal notes:
10737:
10738: access controls are stored in file_permissions.db as key=value pairs.
10739: key -> path to file/file_name\0uniqueID:scope_end_start
10740: where scope -> public,guest,course,group,domains or users.
10741: end -> UNIX time for end of access (0 -> no end date)
10742: start -> UNIX time for start of access
10743:
10744: value -> XML description of access control
10745: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10746: <start></start>
10747: <end></end>
10748:
10749: <password></password> for scope type = guest
10750:
10751: <domain></domain> for scope type = course or group
10752: <number></number>
10753: <roles id="">
10754: <role></role>
10755: <access></access>
10756: <section></section>
10757: <group></group>
10758: </roles>
10759:
10760: <dom></dom> for scope type = domains
10761:
10762: <users> for scope type = users
10763: <user>
10764: <uname></uname>
10765: <udom></udom>
10766: </user>
10767: </users>
10768: </scope>
10769:
10770: Access data is also aggregated for each file in an additional key=value pair:
10771: key -> path to file/file_name\0accesscontrol
10772: value -> reference to hash
10773: hash contains key = value pairs
10774: where key = uniqueID:scope_end_start
10775: value = UNIX time record was last updated
10776:
10777: Used to improve speed of look-ups of access controls for each file.
10778:
10779: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10780:
10781: modify_access_controls():
10782:
10783: Modifies access controls for a portfolio file
10784: Args
10785: 1. file name
10786: 2. reference to hash of required changes,
10787: 3. domain
10788: 4. username
10789: where domain,username are the domain of the portfolio owner
10790: (either a user or a course)
10791:
10792: Returns:
10793: 1. result of additions or updates ('ok' or 'error', with error message).
10794: 2. result of deletions ('ok' or 'error', with error message).
10795: 3. reference to hash of any new or updated access controls.
10796: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10797: key = integer (inbound ID)
10798: value = uniqueID
10799:
10800: =back
10801:
10802: =head2 HTTP Helper Routines
10803:
10804: =over 4
10805:
10806: =item *
10807:
10808: escape() : unpack non-word characters into CGI-compatible hex codes
10809:
10810: =item *
10811:
10812: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10813:
10814: =back
10815:
10816: =head1 PRIVATE SUBROUTINES
10817:
10818: =head2 Underlying communication routines (Shouldn't call)
10819:
10820: =over 4
10821:
10822: =item *
10823:
10824: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10825:
10826: =item *
10827:
10828: reply() : uses subreply to send a message to remote machine, logs all failures
10829:
10830: =item *
10831:
10832: critical() : passes a critical message to another server; if cannot
10833: get through then place message in connection buffer directory and
10834: returns con_delayed, if incapable of saving message, returns
10835: con_failed
10836:
10837: =item *
10838:
10839: reconlonc() : tries to reconnect lonc client processes.
10840:
10841: =back
10842:
10843: =head2 Resource Access Logging
10844:
10845: =over 4
10846:
10847: =item *
10848:
10849: flushcourselogs() : flush (save) buffer logs and access logs
10850:
10851: =item *
10852:
10853: courselog($what) : save message for course in hash
10854:
10855: =item *
10856:
10857: courseacclog($what) : save message for course using &courselog(). Perform
10858: special processing for specific resource types (problems, exams, quizzes, etc).
10859:
10860: =item *
10861:
10862: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10863: as a PerlChildExitHandler
10864:
10865: =back
10866:
10867: =head2 Other
10868:
10869: =over 4
10870:
10871: =item *
10872:
10873: symblist($mapname,%newhash) : update symbolic storage links
10874:
10875: =back
10876:
10877: =cut
10878:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>