Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1117
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1117 ! foxr 4: # $Id: lonnet.pm,v 1.1116 2011/06/13 17:41:04 raeburn Exp $
1.178 www 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: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 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:
1.971 jms 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:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.871 albertel 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1079 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease);
1.871 albertel 80:
81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
82: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
83: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 84: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 85:
1.1 albertel 86: use IO::Socket;
1.31 www 87: use GDBM_File;
1.208 albertel 88: use HTML::LCParser;
1.88 www 89: use Fcntl qw(:flock);
1.870 albertel 90: use Storable qw(thaw nfreeze);
1.539 albertel 91: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 92: use Cache::Memcached;
1.676 albertel 93: use Digest::MD5;
1.790 albertel 94: use Math::Random;
1.1024 raeburn 95: use File::MMagic;
1.807 albertel 96: use LONCAPA qw(:DEFAULT :match);
1.740 www 97: use LONCAPA::Configuration;
1.1117 ! foxr 98:
1.1090 raeburn 99: use File::Copy;
1.676 albertel 100:
1.195 www 101: my $readit;
1.550 foxr 102: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 103:
1.619 albertel 104: require Exporter;
105:
106: our @ISA = qw (Exporter);
107: our @EXPORT = qw(%env);
108:
1.449 matthew 109:
1.1 albertel 110: # --------------------------------------------------------------------- Logging
1.729 www 111: {
112: my $logid;
113: sub instructor_log {
1.957 raeburn 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: }
1.729 www 119: $logid++;
1.957 raeburn 120: my $now = time();
121: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 122: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 123: { $id => {
124: 'exe_uname' => $env{'user.name'},
125: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 126: 'exe_time' => $now,
1.730 www 127: 'exe_ip' => $ENV{'REMOTE_ADDR'},
128: 'delflag' => $delflag,
129: 'logentry' => $storehash,
130: 'uname' => $uname,
131: 'udom' => $udom,
132: }
1.957 raeburn 133: },$cdom,$cnum);
1.729 www 134: }
135: }
1.1 albertel 136:
1.163 harris41 137: sub logtouch {
138: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 139: unless (-e "$execdir/logs/lonnet.log") {
140: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 141: close $fh;
142: }
143: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
144: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
145: }
146:
1.1 albertel 147: sub logthis {
148: my $message=shift;
149: my $execdir=$perlvar{'lonDaemons'};
150: my $now=time;
151: my $local=localtime($now);
1.448 albertel 152: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 153: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
154: print $fh $logstring;
1.448 albertel 155: close($fh);
156: }
1.1 albertel 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);
1.448 albertel 165: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
166: print $fh "$now:$message:$local\n";
167: close($fh);
168: }
1.1 albertel 169: return 1;
170: }
171:
1.850 albertel 172: sub create_connection {
1.853 albertel 173: my ($hostname,$lonid) = @_;
1.851 albertel 174: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 175: Type => SOCK_STREAM,
176: Timeout => 10);
177: return 0 if (!$client);
1.890 albertel 178: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 179: my $result = <$client>;
180: chomp($result);
181: return 1 if ($result eq 'done');
182: return 0;
183: }
184:
1.983 raeburn 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: }
1.850 albertel 199:
1.1106 raeburn 200: sub get_server_distarch {
201: my ($lonhost,$ignore_cache) = @_;
202: if (defined($lonhost)) {
203: if (!defined(&hostname($lonhost))) {
204: return;
205: }
206: my $cachetime = 12*3600;
207: if (!$ignore_cache) {
208: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
209: if (defined($cached)) {
210: return $distarch;
211: }
212: }
213: my $rep = &reply('serverdistarch',$lonhost);
214: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
215: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
216: $rep eq '') {
217: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
218: }
219: }
220: return;
221: }
222:
1.993 raeburn 223: sub get_server_loncaparev {
1.1073 raeburn 224: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 225: if (defined($lonhost)) {
226: if (!defined(&hostname($lonhost))) {
227: undef($lonhost);
228: }
229: }
230: if (!defined($lonhost)) {
231: if (defined(&domain($dom,'primary'))) {
232: $lonhost=&domain($dom,'primary');
233: if ($lonhost eq 'no_host') {
234: undef($lonhost);
235: }
236: }
237: }
238: if (defined($lonhost)) {
1.1073 raeburn 239: my $cachetime = 12*3600;
240: if (!$ignore_cache) {
241: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
242: if (defined($cached)) {
243: return $loncaparev;
244: }
245: }
246: my ($answer,$loncaparev);
247: my @ids=¤t_machine_ids();
248: if (grep(/^\Q$lonhost\E$/,@ids)) {
249: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 250: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 251: $loncaparev = $1;
252: }
253: } else {
254: $answer = &reply('serverloncaparev',$lonhost);
255: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
256: if ($caller eq 'loncron') {
257: my $ua=new LWP::UserAgent;
1.1082 raeburn 258: $ua->timeout(4);
1.1073 raeburn 259: my $protocol = $protocol{$lonhost};
260: $protocol = 'http' if ($protocol ne 'https');
261: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
262: my $request=new HTTP::Request('GET',$url);
263: my $response=$ua->request($request);
264: unless ($response->is_error()) {
265: my $content = $response->content;
1.1081 raeburn 266: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 267: $loncaparev = $1;
268: }
269: }
270: } else {
271: $loncaparev = $loncaparevs{$lonhost};
272: }
1.1081 raeburn 273: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 274: $loncaparev = $1;
275: }
1.993 raeburn 276: }
1.1073 raeburn 277: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 278: }
279: }
280:
1.1074 raeburn 281: sub get_server_homeID {
282: my ($hostname,$ignore_cache,$caller) = @_;
283: unless ($ignore_cache) {
284: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
285: if (defined($cached)) {
286: return $serverhomeID;
287: }
288: }
289: my $cachetime = 12*3600;
290: my $serverhomeID;
291: if ($caller eq 'loncron') {
292: my @machine_ids = &machine_ids($hostname);
293: foreach my $id (@machine_ids) {
294: my $response = &reply('serverhomeID',$id);
295: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
296: $serverhomeID = $response;
297: last;
298: }
299: }
300: if ($serverhomeID eq '') {
301: $serverhomeID = $machine_ids[-1];
302: }
303: } else {
304: $serverhomeID = $serverhomeIDs{$hostname};
305: }
306: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
307: }
308:
1.1 albertel 309: # -------------------------------------------------- Non-critical communication
310: sub subreply {
311: my ($cmd,$server)=@_;
1.838 albertel 312: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 313: #
314: # With loncnew process trimming, there's a timing hole between lonc server
315: # process exit and the master server picking up the listen on the AF_UNIX
316: # socket. In that time interval, a lock file will exist:
317:
318: my $lockfile=$peerfile.".lock";
319: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
320: sleep(1);
321: }
322: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 323: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 324: #
1.550 foxr 325: # We'll give the connection a few tries before abandoning it. If
326: # connection is not possible, we'll con_lost back to the client.
327: #
328: my $client;
329: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
330: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
331: Type => SOCK_STREAM,
332: Timeout => 10);
1.869 albertel 333: if ($client) {
1.550 foxr 334: last; # Connected!
1.850 albertel 335: } else {
1.853 albertel 336: &create_connection(&hostname($server),$server);
1.550 foxr 337: }
1.850 albertel 338: sleep(1); # Try again later if failed connection.
1.550 foxr 339: }
340: my $answer;
341: if ($client) {
1.704 albertel 342: print $client "sethost:$server:$cmd\n";
1.550 foxr 343: $answer=<$client>;
344: if (!$answer) { $answer="con_lost"; }
345: chomp($answer);
346: } else {
347: $answer = 'con_lost'; # Failed connection.
348: }
1.1 albertel 349: return $answer;
350: }
351:
352: sub reply {
353: my ($cmd,$server)=@_;
1.838 albertel 354: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 355: my $answer=subreply($cmd,$server);
1.65 www 356: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 357: &logthis("<font color=\"blue\">WARNING:".
1.12 www 358: " $cmd to $server returned $answer</font>");
359: }
1.1 albertel 360: return $answer;
361: }
362:
363: # ----------------------------------------------------------- Send USR1 to lonc
364:
365: sub reconlonc {
1.891 albertel 366: my ($lonid) = @_;
367: my $hostname = &hostname($lonid);
368: if ($lonid) {
369: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
370: if ($hostname && -e $peerfile) {
371: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
372: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
373: Type => SOCK_STREAM,
374: Timeout => 10);
375: if ($client) {
376: print $client ("reset_retries\n");
377: my $answer=<$client>;
378: #reset just this one.
379: }
380: }
381: return;
382: }
383:
1.836 www 384: &logthis("Trying to reconnect lonc");
1.1 albertel 385: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 386: if (open(my $fh,"<$loncfile")) {
1.1 albertel 387: my $loncpid=<$fh>;
388: chomp($loncpid);
389: if (kill 0 => $loncpid) {
390: &logthis("lonc at pid $loncpid responding, sending USR1");
391: kill USR1 => $loncpid;
392: sleep 1;
1.836 www 393: } else {
1.12 www 394: &logthis(
1.672 albertel 395: "<font color=\"blue\">WARNING:".
1.12 www 396: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 397: }
398: } else {
1.836 www 399: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 400: }
401: }
402:
403: # ------------------------------------------------------ Critical communication
1.12 www 404:
1.1 albertel 405: sub critical {
406: my ($cmd,$server)=@_;
1.838 albertel 407: unless (&hostname($server)) {
1.672 albertel 408: &logthis("<font color=\"blue\">WARNING:".
1.89 www 409: " Critical message to unknown server ($server)</font>");
410: return 'no_such_host';
411: }
1.1 albertel 412: my $answer=reply($cmd,$server);
413: if ($answer eq 'con_lost') {
414: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 415: my $answer=reply($cmd,$server);
1.1 albertel 416: if ($answer eq 'con_lost') {
417: my $now=time;
418: my $middlename=$cmd;
1.5 www 419: $middlename=substr($middlename,0,16);
1.1 albertel 420: $middlename=~s/\W//g;
421: my $dfilename=
1.305 www 422: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
423: $dumpcount++;
1.1 albertel 424: {
1.448 albertel 425: my $dfh;
426: if (open($dfh,">$dfilename")) {
427: print $dfh "$cmd\n";
428: close($dfh);
429: }
1.1 albertel 430: }
431: sleep 2;
432: my $wcmd='';
433: {
1.448 albertel 434: my $dfh;
435: if (open($dfh,"<$dfilename")) {
436: $wcmd=<$dfh>;
437: close($dfh);
438: }
1.1 albertel 439: }
440: chomp($wcmd);
1.7 www 441: if ($wcmd eq $cmd) {
1.672 albertel 442: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 443: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 444: &logperm("D:$server:$cmd");
445: return 'con_delayed';
446: } else {
1.672 albertel 447: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 448: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 449: &logperm("F:$server:$cmd");
450: return 'con_failed';
451: }
452: }
453: }
454: return $answer;
1.405 albertel 455: }
456:
1.755 albertel 457: # ------------------------------------------- check if return value is an error
458:
459: sub error {
460: my ($result) = @_;
1.756 albertel 461: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 462: if ($2 == 2) { return undef; }
463: return $1;
464: }
465: return undef;
466: }
467:
1.783 albertel 468: sub convert_and_load_session_env {
469: my ($lonidsdir,$handle)=@_;
470: my @profile;
471: {
1.917 albertel 472: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
473: if (!$opened) {
1.915 albertel 474: return 0;
475: }
1.783 albertel 476: flock($idf,LOCK_SH);
477: @profile=<$idf>;
478: close($idf);
479: }
480: my %temp_env;
481: foreach my $line (@profile) {
1.786 albertel 482: if ($line !~ m/=/) {
483: return 0;
484: }
1.783 albertel 485: chomp($line);
486: my ($envname,$envvalue)=split(/=/,$line,2);
487: $temp_env{&unescape($envname)} = &unescape($envvalue);
488: }
489: unlink("$lonidsdir/$handle.id");
490: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
491: 0640)) {
492: %disk_env = %temp_env;
493: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
494: untie(%disk_env);
495: }
1.786 albertel 496: return 1;
1.783 albertel 497: }
498:
1.374 www 499: # ------------------------------------------- Transfer profile into environment
1.780 albertel 500: my $env_loaded;
501: sub transfer_profile_to_env {
1.788 albertel 502: my ($lonidsdir,$handle,$force_transfer) = @_;
503: if (!$force_transfer && $env_loaded) { return; }
1.374 www 504:
1.720 albertel 505: if (!defined($lonidsdir)) {
506: $lonidsdir = $perlvar{'lonIDsDir'};
507: }
508: if (!defined($handle)) {
509: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
510: }
511:
1.786 albertel 512: my $convert;
513: {
1.917 albertel 514: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
515: if (!$opened) {
1.915 albertel 516: return;
517: }
1.786 albertel 518: flock($idf,LOCK_SH);
519: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
520: &GDBM_READER(),0640)) {
521: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
522: untie(%disk_env);
523: } else {
524: $convert = 1;
525: }
526: }
527: if ($convert) {
528: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
529: &logthis("Failed to load session, or convert session.");
530: }
1.374 www 531: }
1.783 albertel 532:
1.786 albertel 533: my %remove;
1.783 albertel 534: while ( my $envname = each(%env) ) {
1.433 matthew 535: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
536: if ($time < time-300) {
1.783 albertel 537: $remove{$key}++;
1.433 matthew 538: }
539: }
540: }
1.783 albertel 541:
1.619 albertel 542: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 543: $env_loaded=1;
1.783 albertel 544: foreach my $expired_key (keys(%remove)) {
1.433 matthew 545: &delenv($expired_key);
1.374 www 546: }
1.1 albertel 547: }
548:
1.916 albertel 549: # ---------------------------------------------------- Check for valid session
550: sub check_for_valid_session {
551: my ($r) = @_;
552: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
553: my $lonid=$cookies{'lonID'};
554: return undef if (!$lonid);
555:
556: my $handle=&LONCAPA::clean_handle($lonid->value);
557: my $lonidsdir=$r->dir_config('lonIDsDir');
558: return undef if (!-e "$lonidsdir/$handle.id");
559:
1.917 albertel 560: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
561: return undef if (!$opened);
1.916 albertel 562:
563: flock($idf,LOCK_SH);
564: my %disk_env;
565: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
566: &GDBM_READER(),0640)) {
567: return undef;
568: }
569:
570: if (!defined($disk_env{'user.name'})
571: || !defined($disk_env{'user.domain'})) {
572: return undef;
573: }
574: return $handle;
575: }
576:
1.830 albertel 577: sub timed_flock {
578: my ($file,$lock_type) = @_;
579: my $failed=0;
580: eval {
581: local $SIG{__DIE__}='DEFAULT';
582: local $SIG{ALRM}=sub {
583: $failed=1;
584: die("failed lock");
585: };
586: alarm(13);
587: flock($file,$lock_type);
588: alarm(0);
589: };
590: if ($failed) {
591: return undef;
592: } else {
593: return 1;
594: }
595: }
596:
1.5 www 597: # ---------------------------------------------------------- Append Environment
598:
599: sub appenv {
1.949 raeburn 600: my ($newenv,$roles) = @_;
601: if (ref($newenv) eq 'HASH') {
602: foreach my $key (keys(%{$newenv})) {
603: my $refused = 0;
604: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
605: $refused = 1;
606: if (ref($roles) eq 'ARRAY') {
607: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
608: if (grep(/^\Q$role\E$/,@{$roles})) {
609: $refused = 0;
610: }
611: }
612: }
613: if ($refused) {
614: &logthis("<font color=\"blue\">WARNING: ".
615: "Attempt to modify environment ".$key." to ".$newenv->{$key}
616: .'</font>');
617: delete($newenv->{$key});
618: } else {
619: $env{$key}=$newenv->{$key};
620: }
621: }
622: my $opened = open(my $env_file,'+<',$env{'user.environment'});
623: if ($opened
624: && &timed_flock($env_file,LOCK_EX)
625: &&
626: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
627: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
628: while (my ($key,$value) = each(%{$newenv})) {
629: $disk_env{$key} = $value;
630: }
631: untie(%disk_env);
1.35 www 632: }
1.191 harris41 633: }
1.56 www 634: return 'ok';
635: }
636: # ----------------------------------------------------- Delete from Environment
637:
638: sub delenv {
1.1104 raeburn 639: my ($delthis,$regexp,$roles) = @_;
640: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
641: my $refused = 1;
642: if (ref($roles) eq 'ARRAY') {
643: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
644: if (grep(/^\Q$role\E$/,@{$roles})) {
645: $refused = 0;
646: }
647: }
648: if ($refused) {
649: &logthis("<font color=\"blue\">WARNING: ".
650: "Attempt to delete from environment ".$delthis);
651: return 'error';
652: }
1.56 www 653: }
1.917 albertel 654: my $opened = open(my $env_file,'+<',$env{'user.environment'});
655: if ($opened
1.915 albertel 656: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 657: &&
658: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
659: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 660: foreach my $key (keys(%disk_env)) {
1.987 raeburn 661: if ($regexp) {
662: if ($key=~/^$delthis/) {
663: delete($env{$key});
664: delete($disk_env{$key});
665: }
666: } else {
667: if ($key=~/^\Q$delthis\E/) {
668: delete($env{$key});
669: delete($disk_env{$key});
670: }
671: }
1.448 albertel 672: }
1.783 albertel 673: untie(%disk_env);
1.5 www 674: }
675: return 'ok';
1.369 albertel 676: }
677:
1.790 albertel 678: sub get_env_multiple {
679: my ($name) = @_;
680: my @values;
681: if (defined($env{$name})) {
682: # exists is it an array
683: if (ref($env{$name})) {
684: @values=@{ $env{$name} };
685: } else {
686: $values[0]=$env{$name};
687: }
688: }
689: return(@values);
690: }
691:
1.958 www 692: # ------------------------------------------------------------------- Locking
693:
694: sub set_lock {
695: my ($text)=@_;
696: $locknum++;
697: my $id=$$.'-'.$locknum;
698: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
699: 'session.lock.'.$id => $text});
700: return $id;
701: }
702:
703: sub get_locks {
704: my $num=0;
705: my %texts=();
706: foreach my $lock (split(/\,/,$env{'session.locks'})) {
707: if ($lock=~/\w/) {
708: $num++;
709: $texts{$lock}=$env{'session.lock.'.$lock};
710: }
711: }
712: return ($num,%texts);
713: }
714:
715: sub remove_lock {
716: my ($id)=@_;
717: my $newlocks='';
718: foreach my $lock (split(/\,/,$env{'session.locks'})) {
719: if (($lock=~/\w/) && ($lock ne $id)) {
720: $newlocks.=','.$lock;
721: }
722: }
723: &appenv({'session.locks' => $newlocks});
724: &delenv('session.lock.'.$id);
725: }
726:
727: sub remove_all_locks {
728: my $activelocks=$env{'session.locks'};
729: foreach my $lock (split(/\,/,$env{'session.locks'})) {
730: if ($lock=~/\w/) {
731: &remove_lock($lock);
732: }
733: }
734: }
735:
736:
1.369 albertel 737: # ------------------------------------------ Find out current server userload
738: sub userload {
739: my $numusers=0;
740: {
741: opendir(LONIDS,$perlvar{'lonIDsDir'});
742: my $filename;
743: my $curtime=time;
744: while ($filename=readdir(LONIDS)) {
1.925 albertel 745: next if ($filename eq '.' || $filename eq '..');
746: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 747: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 748: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 749: }
750: closedir(LONIDS);
751: }
752: my $userloadpercent=0;
753: my $maxuserload=$perlvar{'lonUserLoadLim'};
754: if ($maxuserload) {
1.371 albertel 755: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 756: }
1.372 albertel 757: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 758: return $userloadpercent;
1.283 www 759: }
760:
1.1 albertel 761: # ------------------------------ Find server with least workload from spare.tab
1.11 www 762:
1.1 albertel 763: sub spareserver {
1.1083 raeburn 764: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 765: my $spare_server;
1.370 albertel 766: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 767: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
768: : $userloadpercent;
1.1083 raeburn 769: my ($uint_dom,$remotesessions);
770: if (($udom ne '') && (&domain($udom) ne '')) {
771: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
772: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
773: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
774: $remotesessions = $udomdefaults{'remotesessions'};
775: }
1.784 albertel 776: foreach my $try_server (@{ $spareid{'primary'} }) {
1.1083 raeburn 777: if ($uint_dom) {
778: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
779: $try_server));
780: }
1.784 albertel 781: ($spare_server, $lowest_load) =
782: &compare_server_load($try_server, $spare_server, $lowest_load);
783: }
784:
785: my $found_server = ($spare_server ne '' && $lowest_load < 100);
786:
787: if (!$found_server) {
788: foreach my $try_server (@{ $spareid{'default'} }) {
1.1083 raeburn 789: if ($uint_dom) {
790: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
791: $try_server));
792: }
1.784 albertel 793: ($spare_server, $lowest_load) =
794: &compare_server_load($try_server, $spare_server, $lowest_load);
795: }
796: }
797:
798: if (!$want_server_name) {
1.968 raeburn 799: my $protocol = 'http';
800: if ($protocol{$spare_server} eq 'https') {
801: $protocol = $protocol{$spare_server};
802: }
1.1001 raeburn 803: if (defined($spare_server)) {
804: my $hostname = &hostname($spare_server);
1.1083 raeburn 805: if (defined($hostname)) {
1.1001 raeburn 806: $spare_server = $protocol.'://'.$hostname;
807: }
808: }
1.784 albertel 809: }
810: return $spare_server;
811: }
812:
813: sub compare_server_load {
814: my ($try_server, $spare_server, $lowest_load) = @_;
815:
816: my $loadans = &reply('load', $try_server);
817: my $userloadans = &reply('userload',$try_server);
818:
819: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 820: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 821: }
822:
823: my $load;
824: if ($loadans =~ /\d/) {
825: if ($userloadans =~ /\d/) {
826: #both are numbers, pick the bigger one
827: $load = ($loadans > $userloadans) ? $loadans
828: : $userloadans;
1.411 albertel 829: } else {
1.784 albertel 830: $load = $loadans;
1.411 albertel 831: }
1.784 albertel 832: } else {
833: $load = $userloadans;
834: }
835:
836: if (($load =~ /\d/) && ($load < $lowest_load)) {
837: $spare_server = $try_server;
838: $lowest_load = $load;
1.370 albertel 839: }
1.784 albertel 840: return ($spare_server,$lowest_load);
1.202 matthew 841: }
1.914 albertel 842:
843: # --------------------------- ask offload servers if user already has a session
844: sub find_existing_session {
845: my ($udom,$uname) = @_;
846: foreach my $try_server (@{ $spareid{'primary'} },
847: @{ $spareid{'default'} }) {
848: return $try_server if (&has_user_session($try_server, $udom, $uname));
849: }
850: return;
851: }
852:
853: # -------------------------------- ask if server already has a session for user
854: sub has_user_session {
855: my ($lonid,$udom,$uname) = @_;
856: my $result = &reply(join(':','userhassession',
857: map {&escape($_)} ($udom,$uname)),$lonid);
858: return 1 if ($result eq 'ok');
859:
860: return 0;
861: }
862:
1.1076 raeburn 863: # --------- determine least loaded server in a user's domain which allows login
864:
865: sub choose_server {
1.1115 raeburn 866: my ($udom,$checkloginvia) = @_;
1.1076 raeburn 867: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 868: my %servers = &get_servers($udom);
1.1076 raeburn 869: my $lowest_load = 30000;
1.1116 raeburn 870: my ($login_host,$hostname,$portal_path);
1.1076 raeburn 871: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 872: my $loginvia;
873: if ($checkloginvia) {
874: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 875: if ($loginvia) {
876: my ($server,$path) = split(/:/,$loginvia);
877: ($login_host, $lowest_load) =
878: &compare_server_load($server, $login_host, $lowest_load);
879: if ($login_host eq $server) {
880: $portal_path = $path;
881: }
882: } else {
883: ($login_host, $lowest_load) =
884: &compare_server_load($lonhost, $login_host, $lowest_load);
885: if ($login_host eq $lonhost) {
886: $portal_path = '';
887: }
888: }
889: } else {
1.1076 raeburn 890: ($login_host, $lowest_load) =
1.1116 raeburn 891: &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076 raeburn 892: }
893: }
894: if ($login_host ne '') {
1.1116 raeburn 895: $hostname = &hostname($login_host);
1.1076 raeburn 896: }
1.1116 raeburn 897: return ($login_host,$hostname,$portal_path);
1.1076 raeburn 898: }
899:
1.202 matthew 900: # --------------------------------------------- Try to change a user's password
901:
902: sub changepass {
1.799 raeburn 903: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 904: $currentpass = &escape($currentpass);
905: $newpass = &escape($newpass);
1.1030 raeburn 906: my $lonhost = $perlvar{'lonHostID'};
907: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 908: $server);
909: if (! $answer) {
910: &logthis("No reply on password change request to $server ".
911: "by $uname in domain $udom.");
912: } elsif ($answer =~ "^ok") {
913: &logthis("$uname in $udom successfully changed their password ".
914: "on $server.");
915: } elsif ($answer =~ "^pwchange_failure") {
916: &logthis("$uname in $udom was unable to change their password ".
917: "on $server. The action was blocked by either lcpasswd ".
918: "or pwchange");
919: } elsif ($answer =~ "^non_authorized") {
920: &logthis("$uname in $udom did not get their password correct when ".
921: "attempting to change it on $server.");
922: } elsif ($answer =~ "^auth_mode_error") {
923: &logthis("$uname in $udom attempted to change their password despite ".
924: "not being locally or internally authenticated on $server.");
925: } elsif ($answer =~ "^unknown_user") {
926: &logthis("$uname in $udom attempted to change their password ".
927: "on $server but were unable to because $server is not ".
928: "their home server.");
929: } elsif ($answer =~ "^refused") {
930: &logthis("$server refused to change $uname in $udom password because ".
931: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 932: } elsif ($answer =~ "invalid_client") {
933: &logthis("$server refused to change $uname in $udom password because ".
934: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 935: }
936: return $answer;
1.1 albertel 937: }
938:
1.169 harris41 939: # ----------------------- Try to determine user's current authentication scheme
940:
941: sub queryauthenticate {
942: my ($uname,$udom)=@_;
1.456 albertel 943: my $uhome=&homeserver($uname,$udom);
944: if (!$uhome) {
945: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
946: return 'no_host';
947: }
948: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
949: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
950: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 951: }
1.456 albertel 952: return $answer;
1.169 harris41 953: }
954:
1.1 albertel 955: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 956:
1.1 albertel 957: sub authenticate {
1.1073 raeburn 958: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 959: $upass=&escape($upass);
960: $uname= &LONCAPA::clean_username($uname);
1.836 www 961: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 962: my $newhome;
1.836 www 963: if ((!$uhome) || ($uhome eq 'no_host')) {
964: # Maybe the machine was offline and only re-appeared again recently?
965: &reconlonc();
966: # One more
1.952 raeburn 967: $uhome=&homeserver($uname,$udom,1);
968: if (($uhome eq 'no_host') && $checkdefauth) {
969: if (defined(&domain($udom,'primary'))) {
970: $newhome=&domain($udom,'primary');
971: }
972: if ($newhome ne '') {
973: $uhome = $newhome;
974: }
975: }
1.836 www 976: if ((!$uhome) || ($uhome eq 'no_host')) {
977: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 978: return 'no_host';
979: }
1.1 albertel 980: }
1.1073 raeburn 981: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 982: if ($answer eq 'authorized') {
1.952 raeburn 983: if ($newhome) {
984: &logthis("User $uname at $udom authorized by $uhome, but needs account");
985: return 'no_account_on_host';
986: } else {
987: &logthis("User $uname at $udom authorized by $uhome");
988: return $uhome;
989: }
1.471 albertel 990: }
991: if ($answer eq 'non_authorized') {
992: &logthis("User $uname at $udom rejected by $uhome");
993: return 'no_host';
1.9 www 994: }
1.471 albertel 995: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 996: return 'no_host';
997: }
998:
1.1073 raeburn 999: sub can_host_session {
1.1074 raeburn 1000: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1001: my $canhost = 1;
1.1074 raeburn 1002: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1003: if (ref($remotesessions) eq 'HASH') {
1004: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1005: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1006: $canhost = 0;
1007: } else {
1008: $canhost = 1;
1009: }
1010: }
1011: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1012: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1013: $canhost = 1;
1014: } else {
1015: $canhost = 0;
1016: }
1017: }
1018: if ($canhost) {
1019: if ($remotesessions->{'version'} ne '') {
1020: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1021: if ($reqmajor ne '' && $reqminor ne '') {
1022: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1023: my $major = $1;
1024: my $minor = $2;
1025: if (($major < $reqmajor ) ||
1026: (($major == $reqmajor) && ($minor < $reqminor))) {
1027: $canhost = 0;
1028: }
1029: } else {
1030: $canhost = 0;
1031: }
1032: }
1033: }
1034: }
1035: }
1036: if ($canhost) {
1037: if (ref($hostedsessions) eq 'HASH') {
1038: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1039: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'excludedomain'}})) {
1040: $canhost = 0;
1041: } else {
1042: $canhost = 1;
1043: }
1044: }
1045: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1046: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'includedomain'}})) {
1047: $canhost = 1;
1048: } else {
1049: $canhost = 0;
1050: }
1051: }
1052: }
1053: }
1054: return $canhost;
1055: }
1056:
1.1083 raeburn 1057: sub spare_can_host {
1058: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1059: my $canhost=1;
1060: my @intdoms;
1061: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1062: if (ref($internet_names) eq 'ARRAY') {
1063: @intdoms = @{$internet_names};
1064: }
1065: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1066: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1067: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1068: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1069: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1070: $canhost = &can_host_session($udom,$try_server,$remoterev,
1071: $remotesessions,
1072: $defdomdefaults{'hostedsessions'});
1073: }
1074: return $canhost;
1075: }
1076:
1.1 albertel 1077: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1078:
1.599 albertel 1079: my %homecache;
1.1 albertel 1080: sub homeserver {
1.230 stredwic 1081: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1082: my $index="$uname:$udom";
1.426 albertel 1083:
1.599 albertel 1084: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1085:
1086: my %servers = &get_servers($udom,'library');
1087: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1088: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1089: exists($badServerCache{$tryserver}));
1.841 albertel 1090:
1091: my $answer=reply("home:$udom:$uname",$tryserver);
1092: if ($answer eq 'found') {
1093: delete($badServerCache{$tryserver});
1094: return $homecache{$index}=$tryserver;
1095: } elsif ($answer eq 'no_host') {
1096: $badServerCache{$tryserver}=1;
1097: }
1.1 albertel 1098: }
1099: return 'no_host';
1.70 www 1100: }
1101:
1102: # ------------------------------------- Find the usernames behind a list of IDs
1103:
1104: sub idget {
1105: my ($udom,@ids)=@_;
1106: my %returnhash=();
1107:
1.841 albertel 1108: my %servers = &get_servers($udom,'library');
1109: foreach my $tryserver (keys(%servers)) {
1110: my $idlist=join('&',@ids);
1111: $idlist=~tr/A-Z/a-z/;
1112: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1113: my @answer=();
1114: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1115: @answer=split(/\&/,$reply);
1116: } ;
1117: my $i;
1118: for ($i=0;$i<=$#ids;$i++) {
1119: if ($answer[$i]) {
1120: $returnhash{$ids[$i]}=$answer[$i];
1121: }
1122: }
1123: }
1.70 www 1124: return %returnhash;
1125: }
1126:
1127: # ------------------------------------- Find the IDs behind a list of usernames
1128:
1129: sub idrget {
1130: my ($udom,@unames)=@_;
1131: my %returnhash=();
1.800 albertel 1132: foreach my $uname (@unames) {
1133: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1134: }
1.70 www 1135: return %returnhash;
1136: }
1137:
1138: # ------------------------------- Store away a list of names and associated IDs
1139:
1140: sub idput {
1141: my ($udom,%ids)=@_;
1142: my %servers=();
1.800 albertel 1143: foreach my $uname (keys(%ids)) {
1144: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1145: my $uhom=&homeserver($uname,$udom);
1.70 www 1146: if ($uhom ne 'no_host') {
1.800 albertel 1147: my $id=&escape($ids{$uname});
1.70 www 1148: $id=~tr/A-Z/a-z/;
1.800 albertel 1149: my $esc_unam=&escape($uname);
1.70 www 1150: if ($servers{$uhom}) {
1.800 albertel 1151: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1152: } else {
1.800 albertel 1153: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1154: }
1155: }
1.191 harris41 1156: }
1.800 albertel 1157: foreach my $server (keys(%servers)) {
1158: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1159: }
1.344 www 1160: }
1161:
1.1023 raeburn 1162: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1163: sub dump_dom {
1.1023 raeburn 1164: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 1165: if (!$udom) {
1166: $udom=$env{'user.domain'};
1167: }
1168: my %returnhash;
1.1023 raeburn 1169: if ($udom) {
1170: my $uname = &get_domainconfiguser($udom);
1171: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 1172: }
1173: return %returnhash;
1174: }
1175:
1.1023 raeburn 1176: # ------------------------------------------ get items from domain db files
1.806 raeburn 1177:
1178: sub get_dom {
1.860 raeburn 1179: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1180: my $items='';
1181: foreach my $item (@$storearr) {
1182: $items.=&escape($item).'&';
1183: }
1184: $items=~s/\&$//;
1.860 raeburn 1185: if (!$udom) {
1186: $udom=$env{'user.domain'};
1187: if (defined(&domain($udom,'primary'))) {
1188: $uhome=&domain($udom,'primary');
1189: } else {
1.874 albertel 1190: undef($uhome);
1.860 raeburn 1191: }
1192: } else {
1193: if (!$uhome) {
1194: if (defined(&domain($udom,'primary'))) {
1195: $uhome=&domain($udom,'primary');
1196: }
1197: }
1198: }
1199: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1200: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1201: my %returnhash;
1.875 albertel 1202: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1203: return %returnhash;
1204: }
1.806 raeburn 1205: my @pairs=split(/\&/,$rep);
1206: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1207: return @pairs;
1208: }
1209: my $i=0;
1210: foreach my $item (@$storearr) {
1211: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1212: $i++;
1213: }
1214: return %returnhash;
1215: } else {
1.880 banghart 1216: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1217: }
1218: }
1219:
1220: # -------------------------------------------- put items in domain db files
1221:
1222: sub put_dom {
1.860 raeburn 1223: my ($namespace,$storehash,$udom,$uhome)=@_;
1224: if (!$udom) {
1225: $udom=$env{'user.domain'};
1226: if (defined(&domain($udom,'primary'))) {
1227: $uhome=&domain($udom,'primary');
1228: } else {
1.874 albertel 1229: undef($uhome);
1.860 raeburn 1230: }
1231: } else {
1232: if (!$uhome) {
1233: if (defined(&domain($udom,'primary'))) {
1234: $uhome=&domain($udom,'primary');
1235: }
1236: }
1237: }
1238: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1239: my $items='';
1240: foreach my $item (keys(%$storehash)) {
1241: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1242: }
1243: $items=~s/\&$//;
1244: return &reply("putdom:$udom:$namespace:$items",$uhome);
1245: } else {
1.860 raeburn 1246: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1247: }
1248: }
1249:
1.1023 raeburn 1250: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1251: sub newput_dom {
1.1023 raeburn 1252: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1253: my $result;
1254: if (!$udom) {
1255: $udom=$env{'user.domain'};
1256: }
1.1023 raeburn 1257: if ($udom) {
1258: my $uname = &get_domainconfiguser($udom);
1259: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1260: }
1261: return $result;
1262: }
1263:
1.1023 raeburn 1264: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1265: sub del_dom {
1.1023 raeburn 1266: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1267: if (ref($storearr) eq 'ARRAY') {
1268: if (!$udom) {
1269: $udom=$env{'user.domain'};
1270: }
1.1023 raeburn 1271: if ($udom) {
1272: my $uname = &get_domainconfiguser($udom);
1273: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1274: }
1275: }
1276: }
1277:
1.1023 raeburn 1278: # ----------------------------------construct domainconfig user for a domain
1279: sub get_domainconfiguser {
1280: my ($udom) = @_;
1281: return $udom.'-domainconfig';
1282: }
1283:
1.837 raeburn 1284: sub retrieve_inst_usertypes {
1285: my ($udom) = @_;
1286: my (%returnhash,@order);
1.989 raeburn 1287: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1288: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1289: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1290: %returnhash = %{$domdefs{'inststatustypes'}};
1291: @order = @{$domdefs{'inststatusorder'}};
1292: } else {
1293: if (defined(&domain($udom,'primary'))) {
1294: my $uhome=&domain($udom,'primary');
1295: my $rep=&reply("inst_usertypes:$udom",$uhome);
1296: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1297: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1298: return (\%returnhash,\@order);
1299: }
1300: my ($hashitems,$orderitems) = split(/:/,$rep);
1301: my @pairs=split(/\&/,$hashitems);
1302: foreach my $item (@pairs) {
1303: my ($key,$value)=split(/=/,$item,2);
1304: $key = &unescape($key);
1305: next if ($key =~ /^error: 2 /);
1306: $returnhash{$key}=&thaw_unescape($value);
1307: }
1308: my @esc_order = split(/\&/,$orderitems);
1309: foreach my $item (@esc_order) {
1310: push(@order,&unescape($item));
1311: }
1312: } else {
1313: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1314: }
1315: }
1316: return (\%returnhash,\@order);
1317: }
1318:
1.868 raeburn 1319: sub is_domainimage {
1320: my ($url) = @_;
1321: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1322: if (&domain($1) ne '') {
1323: return '1';
1324: }
1325: }
1326: return;
1327: }
1328:
1.899 raeburn 1329: sub inst_directory_query {
1330: my ($srch) = @_;
1331: my $udom = $srch->{'srchdomain'};
1332: my %results;
1333: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1334: my $outcome;
1.899 raeburn 1335: if ($homeserver ne '') {
1.904 albertel 1336: my $queryid=&reply("querysend:instdirsearch:".
1337: &escape($srch->{'srchby'}).':'.
1338: &escape($srch->{'srchterm'}).':'.
1339: &escape($srch->{'srchtype'}),$homeserver);
1340: my $host=&hostname($homeserver);
1341: if ($queryid !~/^\Q$host\E\_/) {
1342: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1343: return;
1344: }
1345: my $response = &get_query_reply($queryid);
1346: my $maxtries = 5;
1347: my $tries = 1;
1348: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1349: $response = &get_query_reply($queryid);
1350: $tries ++;
1351: }
1352:
1353: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1354: if ($response eq 'unavailable') {
1355: $outcome = $response;
1356: } else {
1357: $outcome = 'ok';
1358: my @matches = split(/\n/,$response);
1359: foreach my $match (@matches) {
1360: my ($key,$value) = split(/=/,$match);
1361: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1362: }
1.899 raeburn 1363: }
1364: }
1365: }
1.909 raeburn 1366: return ($outcome,%results);
1.899 raeburn 1367: }
1368:
1369: sub usersearch {
1370: my ($srch) = @_;
1371: my $dom = $srch->{'srchdomain'};
1372: my %results;
1373: my %libserv = &all_library();
1374: my $query = 'usersearch';
1375: foreach my $tryserver (keys(%libserv)) {
1376: if (&host_domain($tryserver) eq $dom) {
1377: my $host=&hostname($tryserver);
1378: my $queryid=
1.911 raeburn 1379: &reply("querysend:".&escape($query).':'.
1380: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1381: &escape($srch->{'srchtype'}).':'.
1382: &escape($srch->{'srchterm'}),$tryserver);
1383: if ($queryid !~/^\Q$host\E\_/) {
1384: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1385: next;
1.899 raeburn 1386: }
1387: my $reply = &get_query_reply($queryid);
1388: my $maxtries = 1;
1389: my $tries = 1;
1390: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1391: $reply = &get_query_reply($queryid);
1392: $tries ++;
1393: }
1394: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1395: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1396: } else {
1.911 raeburn 1397: my @matches;
1398: if ($reply =~ /\n/) {
1399: @matches = split(/\n/,$reply);
1400: } else {
1401: @matches = split(/\&/,$reply);
1402: }
1.899 raeburn 1403: foreach my $match (@matches) {
1404: my ($uname,$udom,%userhash);
1.911 raeburn 1405: foreach my $entry (split(/:/,$match)) {
1406: my ($key,$value) =
1407: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1408: $userhash{$key} = $value;
1409: if ($key eq 'username') {
1410: $uname = $value;
1411: } elsif ($key eq 'domain') {
1412: $udom = $value;
1.911 raeburn 1413: }
1.899 raeburn 1414: }
1415: $results{$uname.':'.$udom} = \%userhash;
1416: }
1417: }
1418: }
1419: }
1420: return %results;
1421: }
1422:
1.912 raeburn 1423: sub get_instuser {
1424: my ($udom,$uname,$id) = @_;
1425: my $homeserver = &domain($udom,'primary');
1426: my ($outcome,%results);
1427: if ($homeserver ne '') {
1428: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1429: &escape($id).':'.&escape($udom),$homeserver);
1430: my $host=&hostname($homeserver);
1431: if ($queryid !~/^\Q$host\E\_/) {
1432: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1433: return;
1434: }
1435: my $response = &get_query_reply($queryid);
1436: my $maxtries = 5;
1437: my $tries = 1;
1438: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1439: $response = &get_query_reply($queryid);
1440: $tries ++;
1441: }
1442: if (!&error($response) && $response ne 'refused') {
1443: if ($response eq 'unavailable') {
1444: $outcome = $response;
1445: } else {
1446: $outcome = 'ok';
1447: my @matches = split(/\n/,$response);
1448: foreach my $match (@matches) {
1449: my ($key,$value) = split(/=/,$match);
1450: $results{&unescape($key)} = &thaw_unescape($value);
1451: }
1452: }
1453: }
1454: }
1455: my %userinfo;
1456: if (ref($results{$uname}) eq 'HASH') {
1457: %userinfo = %{$results{$uname}};
1458: }
1459: return ($outcome,%userinfo);
1460: }
1461:
1462: sub inst_rulecheck {
1.923 raeburn 1463: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1464: my %returnhash;
1465: if ($udom ne '') {
1466: if (ref($rules) eq 'ARRAY') {
1467: @{$rules} = map {&escape($_);} (@{$rules});
1468: my $rulestr = join(':',@{$rules});
1469: my $homeserver=&domain($udom,'primary');
1470: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1471: my $response;
1472: if ($item eq 'username') {
1473: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1474: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1475: $homeserver));
1.923 raeburn 1476: } elsif ($item eq 'id') {
1477: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1478: ':'.&escape($id).':'.$rulestr,
1479: $homeserver));
1.945 raeburn 1480: } elsif ($item eq 'selfcreate') {
1481: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1482: &escape($udom).':'.&escape($uname).
1483: ':'.$rulestr,$homeserver));
1.923 raeburn 1484: }
1.912 raeburn 1485: if ($response ne 'refused') {
1486: my @pairs=split(/\&/,$response);
1487: foreach my $item (@pairs) {
1488: my ($key,$value)=split(/=/,$item,2);
1489: $key = &unescape($key);
1490: next if ($key =~ /^error: 2 /);
1491: $returnhash{$key}=&thaw_unescape($value);
1492: }
1493: }
1494: }
1495: }
1496: }
1497: return %returnhash;
1498: }
1499:
1500: sub inst_userrules {
1.923 raeburn 1501: my ($udom,$check) = @_;
1.912 raeburn 1502: my (%ruleshash,@ruleorder);
1503: if ($udom ne '') {
1504: my $homeserver=&domain($udom,'primary');
1505: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1506: my $response;
1507: if ($check eq 'id') {
1508: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1509: $homeserver);
1.943 raeburn 1510: } elsif ($check eq 'email') {
1511: $response=&reply('instemailrules:'.&escape($udom),
1512: $homeserver);
1.923 raeburn 1513: } else {
1514: $response=&reply('instuserrules:'.&escape($udom),
1515: $homeserver);
1516: }
1.912 raeburn 1517: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1518: ($response ne 'unknown_cmd') &&
1.912 raeburn 1519: ($response ne 'no_such_host')) {
1520: my ($hashitems,$orderitems) = split(/:/,$response);
1521: my @pairs=split(/\&/,$hashitems);
1522: foreach my $item (@pairs) {
1523: my ($key,$value)=split(/=/,$item,2);
1524: $key = &unescape($key);
1525: next if ($key =~ /^error: 2 /);
1526: $ruleshash{$key}=&thaw_unescape($value);
1527: }
1528: my @esc_order = split(/\&/,$orderitems);
1529: foreach my $item (@esc_order) {
1530: push(@ruleorder,&unescape($item));
1531: }
1532: }
1533: }
1534: }
1535: return (\%ruleshash,\@ruleorder);
1536: }
1537:
1.976 raeburn 1538: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1539:
1540: sub get_domain_defaults {
1541: my ($domain) = @_;
1542: my $cachetime = 60*60*24;
1543: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1544: if (defined($cached)) {
1545: if (ref($result) eq 'HASH') {
1546: return %{$result};
1547: }
1548: }
1549: my %domdefaults;
1550: my %domconfig =
1.989 raeburn 1551: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1552: 'requestcourses','inststatus',
1.1073 raeburn 1553: 'coursedefaults','usersessions'],$domain);
1.943 raeburn 1554: if (ref($domconfig{'defaults'}) eq 'HASH') {
1555: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1556: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1557: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1558: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1559: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1560: } else {
1561: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1562: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1563: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1564: }
1.976 raeburn 1565: if (ref($domconfig{'quotas'}) eq 'HASH') {
1566: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1567: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1568: } else {
1569: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1570: }
1571: my @usertools = ('aboutme','blog','portfolio');
1572: foreach my $item (@usertools) {
1573: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1574: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1575: }
1576: }
1577: }
1.985 raeburn 1578: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1579: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1580: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1581: }
1582: }
1.989 raeburn 1583: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1584: foreach my $item ('inststatustypes','inststatusorder') {
1585: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1586: }
1587: }
1.1047 raeburn 1588: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1589: foreach my $item ('canuse_pdfforms') {
1590: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1591: }
1592: }
1.1073 raeburn 1593: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1594: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1595: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1596: }
1597: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1598: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1599: }
1600: }
1.943 raeburn 1601: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1602: $cachetime);
1603: return %domdefaults;
1604: }
1605:
1.344 www 1606: # --------------------------------------------------- Assign a key to a student
1607:
1608: sub assign_access_key {
1.364 www 1609: #
1610: # a valid key looks like uname:udom#comments
1611: # comments are being appended
1612: #
1.498 www 1613: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1614: $kdom=
1.620 albertel 1615: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1616: $knum=
1.620 albertel 1617: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1618: $cdom=
1.620 albertel 1619: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1620: $cnum=
1.620 albertel 1621: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1622: $udom=$env{'user.name'} unless (defined($udom));
1623: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1624: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1625: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1626: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1627: # assigned to this person
1628: # - this should not happen,
1.345 www 1629: # unless something went wrong
1630: # the first time around
1631: # ready to assign
1.364 www 1632: $logentry=$1.'; '.$logentry;
1.496 www 1633: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1634: $kdom,$knum) eq 'ok') {
1.345 www 1635: # key now belongs to user
1.346 www 1636: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1637: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1638: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1639: return 'ok';
1640: } else {
1641: return
1642: 'error: Count not permanently assign key, will need to be re-entered later.';
1643: }
1644: } else {
1645: return 'error: Could not assign key, try again later.';
1646: }
1.364 www 1647: } elsif (!$existing{$ckey}) {
1.345 www 1648: # the key does not exist
1649: return 'error: The key does not exist';
1650: } else {
1651: # the key is somebody else's
1652: return 'error: The key is already in use';
1653: }
1.344 www 1654: }
1655:
1.364 www 1656: # ------------------------------------------ put an additional comment on a key
1657:
1658: sub comment_access_key {
1659: #
1660: # a valid key looks like uname:udom#comments
1661: # comments are being appended
1662: #
1663: my ($ckey,$cdom,$cnum,$logentry)=@_;
1664: $cdom=
1.620 albertel 1665: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1666: $cnum=
1.620 albertel 1667: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1668: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1669: if ($existing{$ckey}) {
1670: $existing{$ckey}.='; '.$logentry;
1671: # ready to assign
1.367 www 1672: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1673: $cdom,$cnum) eq 'ok') {
1674: return 'ok';
1675: } else {
1676: return 'error: Count not store comment.';
1677: }
1678: } else {
1679: # the key does not exist
1680: return 'error: The key does not exist';
1681: }
1682: }
1683:
1.344 www 1684: # ------------------------------------------------------ Generate a set of keys
1685:
1686: sub generate_access_keys {
1.364 www 1687: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1688: $cdom=
1.620 albertel 1689: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1690: $cnum=
1.620 albertel 1691: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1692: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1693: unless (($cdom) && ($cnum)) { return 0; }
1694: if ($number>10000) { return 0; }
1695: sleep(2); # make sure don't get same seed twice
1696: srand(time()^($$+($$<<15))); # from "Programming Perl"
1697: my $total=0;
1698: for (my $i=1;$i<=$number;$i++) {
1699: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1700: sprintf("%lx",int(100000*rand)).'-'.
1701: sprintf("%lx",int(100000*rand));
1702: $newkey=~s/1/g/g; # folks mix up 1 and l
1703: $newkey=~s/0/h/g; # and also 0 and O
1704: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1705: if ($existing{$newkey}) {
1706: $i--;
1707: } else {
1.364 www 1708: if (&put('accesskeys',
1709: { $newkey => '# generated '.localtime().
1.620 albertel 1710: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1711: '; '.$logentry },
1712: $cdom,$cnum) eq 'ok') {
1.344 www 1713: $total++;
1714: }
1715: }
1716: }
1.620 albertel 1717: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1718: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1719: return $total;
1720: }
1721:
1722: # ------------------------------------------------------- Validate an accesskey
1723:
1724: sub validate_access_key {
1725: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1726: $cdom=
1.620 albertel 1727: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1728: $cnum=
1.620 albertel 1729: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1730: $udom=$env{'user.domain'} unless (defined($udom));
1731: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1732: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1733: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1734: }
1735:
1736: # ------------------------------------- Find the section of student in a course
1.652 albertel 1737: sub devalidate_getsection_cache {
1738: my ($udom,$unam,$courseid)=@_;
1739: my $hashid="$udom:$unam:$courseid";
1740: &devalidate_cache_new('getsection',$hashid);
1741: }
1.298 matthew 1742:
1.815 albertel 1743: sub courseid_to_courseurl {
1744: my ($courseid) = @_;
1745: #already url style courseid
1746: return $courseid if ($courseid =~ m{^/});
1747:
1748: if (exists($env{'course.'.$courseid.'.num'})) {
1749: my $cnum = $env{'course.'.$courseid.'.num'};
1750: my $cdom = $env{'course.'.$courseid.'.domain'};
1751: return "/$cdom/$cnum";
1752: }
1753:
1754: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1755: if (exists($courseinfo{'num'})) {
1756: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1757: }
1758:
1759: return undef;
1760: }
1761:
1.298 matthew 1762: sub getsection {
1763: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1764: my $cachetime=1800;
1.551 albertel 1765:
1766: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1767: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1768: if (defined($cached)) { return $result; }
1769:
1.298 matthew 1770: my %Pending;
1771: my %Expired;
1772: #
1773: # Each role can either have not started yet (pending), be active,
1774: # or have expired.
1775: #
1776: # If there is an active role, we are done.
1777: #
1778: # If there is more than one role which has not started yet,
1779: # choose the one which will start sooner
1780: # If there is one role which has not started yet, return it.
1781: #
1782: # If there is more than one expired role, choose the one which ended last.
1783: # If there is a role which has expired, return it.
1784: #
1.815 albertel 1785: $courseid = &courseid_to_courseurl($courseid);
1.1086 raeburn 1786: my $extra = &freeze_escape({'skipcheck' => 1});
1787: my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817 raeburn 1788: foreach my $key (keys(%roleshash)) {
1.479 albertel 1789: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1790: my $section=$1;
1791: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1792: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1793: my $now=time;
1.548 albertel 1794: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1795: $Expired{$end}=$section;
1796: next;
1797: }
1.548 albertel 1798: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1799: $Pending{$start}=$section;
1800: next;
1801: }
1.599 albertel 1802: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1803: }
1804: #
1805: # Presumedly there will be few matching roles from the above
1806: # loop and the sorting time will be negligible.
1807: if (scalar(keys(%Pending))) {
1808: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1809: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1810: }
1811: if (scalar(keys(%Expired))) {
1812: my @sorted = sort {$a <=> $b} keys(%Expired);
1813: my $time = pop(@sorted);
1.599 albertel 1814: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1815: }
1.599 albertel 1816: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1817: }
1.70 www 1818:
1.599 albertel 1819: sub save_cache {
1820: &purge_remembered();
1.722 albertel 1821: #&Apache::loncommon::validate_page();
1.620 albertel 1822: undef(%env);
1.780 albertel 1823: undef($env_loaded);
1.599 albertel 1824: }
1.452 albertel 1825:
1.599 albertel 1826: my $to_remember=-1;
1827: my %remembered;
1828: my %accessed;
1829: my $kicks=0;
1830: my $hits=0;
1.849 albertel 1831: sub make_key {
1832: my ($name,$id) = @_;
1.872 albertel 1833: if (length($id) > 65
1834: && length(&escape($id)) > 200) {
1835: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1836: }
1.849 albertel 1837: return &escape($name.':'.$id);
1838: }
1839:
1.599 albertel 1840: sub devalidate_cache_new {
1841: my ($name,$id,$debug) = @_;
1842: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1843: $id=&make_key($name,$id);
1.599 albertel 1844: $memcache->delete($id);
1845: delete($remembered{$id});
1846: delete($accessed{$id});
1847: }
1848:
1849: sub is_cached_new {
1850: my ($name,$id,$debug) = @_;
1.849 albertel 1851: $id=&make_key($name,$id);
1.599 albertel 1852: if (exists($remembered{$id})) {
1853: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1854: $accessed{$id}=[&gettimeofday()];
1855: $hits++;
1856: return ($remembered{$id},1);
1857: }
1858: my $value = $memcache->get($id);
1859: if (!(defined($value))) {
1860: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1861: return (undef,undef);
1.416 albertel 1862: }
1.599 albertel 1863: if ($value eq '__undef__') {
1864: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1865: $value=undef;
1866: }
1867: &make_room($id,$value,$debug);
1868: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1869: return ($value,1);
1870: }
1871:
1872: sub do_cache_new {
1873: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1874: $id=&make_key($name,$id);
1.599 albertel 1875: my $setvalue=$value;
1876: if (!defined($setvalue)) {
1877: $setvalue='__undef__';
1878: }
1.623 albertel 1879: if (!defined($time) ) {
1880: $time=600;
1881: }
1.599 albertel 1882: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1883: my $result = $memcache->set($id,$setvalue,$time);
1884: if (! $result) {
1.872 albertel 1885: &logthis("caching of id -> $id failed");
1.910 albertel 1886: $memcache->disconnect_all();
1.872 albertel 1887: }
1.600 albertel 1888: # need to make a copy of $value
1.919 albertel 1889: &make_room($id,$value,$debug);
1.599 albertel 1890: return $value;
1891: }
1892:
1893: sub make_room {
1894: my ($id,$value,$debug)=@_;
1.919 albertel 1895:
1896: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1897: : $value;
1.599 albertel 1898: if ($to_remember<0) { return; }
1899: $accessed{$id}=[&gettimeofday()];
1900: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1901: my $to_kick;
1902: my $max_time=0;
1903: foreach my $other (keys(%accessed)) {
1904: if (&tv_interval($accessed{$other}) > $max_time) {
1905: $to_kick=$other;
1906: $max_time=&tv_interval($accessed{$other});
1907: }
1908: }
1909: delete($remembered{$to_kick});
1910: delete($accessed{$to_kick});
1911: $kicks++;
1912: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1913: return;
1914: }
1915:
1.599 albertel 1916: sub purge_remembered {
1.604 albertel 1917: #&logthis("Tossing ".scalar(keys(%remembered)));
1918: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1919: undef(%remembered);
1920: undef(%accessed);
1.428 albertel 1921: }
1.70 www 1922: # ------------------------------------- Read an entry from a user's environment
1923:
1924: sub userenvironment {
1925: my ($udom,$unam,@what)=@_;
1.976 raeburn 1926: my $items;
1927: foreach my $item (@what) {
1928: $items.=&escape($item).'&';
1929: }
1930: $items=~s/\&$//;
1.70 www 1931: my %returnhash=();
1.1009 raeburn 1932: my $uhome = &homeserver($unam,$udom);
1933: unless ($uhome eq 'no_host') {
1934: my @answer=split(/\&/,
1935: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 1936: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
1937: return %returnhash;
1938: }
1.1009 raeburn 1939: my $i;
1940: for ($i=0;$i<=$#what;$i++) {
1941: $returnhash{$what[$i]}=&unescape($answer[$i]);
1942: }
1.70 www 1943: }
1944: return %returnhash;
1.1 albertel 1945: }
1946:
1.617 albertel 1947: # ---------------------------------------------------------- Get a studentphoto
1948: sub studentphoto {
1949: my ($udom,$unam,$ext) = @_;
1950: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1951: if (defined($env{'request.course.id'})) {
1.708 raeburn 1952: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1953: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1954: return(&retrievestudentphoto($udom,$unam,$ext));
1955: } else {
1956: my ($result,$perm_reqd)=
1.707 albertel 1957: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1958: if ($result eq 'ok') {
1959: if (!($perm_reqd eq 'yes')) {
1960: return(&retrievestudentphoto($udom,$unam,$ext));
1961: }
1962: }
1963: }
1964: }
1965: } else {
1966: my ($result,$perm_reqd) =
1.707 albertel 1967: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1968: if ($result eq 'ok') {
1969: if (!($perm_reqd eq 'yes')) {
1970: return(&retrievestudentphoto($udom,$unam,$ext));
1971: }
1972: }
1973: }
1974: return '/adm/lonKaputt/lonlogo_broken.gif';
1975: }
1976:
1977: sub retrievestudentphoto {
1978: my ($udom,$unam,$ext,$type) = @_;
1979: my $home=&Apache::lonnet::homeserver($unam,$udom);
1980: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1981: if ($ret eq 'ok') {
1982: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1983: if ($type eq 'thumbnail') {
1984: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1985: }
1986: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1987: return $tokenurl;
1988: } else {
1989: if ($type eq 'thumbnail') {
1990: return '/adm/lonKaputt/genericstudent_tn.gif';
1991: } else {
1992: return '/adm/lonKaputt/lonlogo_broken.gif';
1993: }
1.617 albertel 1994: }
1995: }
1996:
1.263 www 1997: # -------------------------------------------------------------------- New chat
1998:
1999: sub chatsend {
1.724 raeburn 2000: my ($newentry,$anon,$group)=@_;
1.620 albertel 2001: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2002: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2003: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2004: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2005: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2006: &escape($newentry)).':'.$group,$chome);
1.292 www 2007: }
2008:
2009: # ------------------------------------------ Find current version of a resource
2010:
2011: sub getversion {
2012: my $fname=&clutter(shift);
2013: unless ($fname=~/^\/res\//) { return -1; }
2014: return ¤tversion(&filelocation('',$fname));
2015: }
2016:
2017: sub currentversion {
2018: my $fname=shift;
2019: my $author=$fname;
2020: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2021: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2022: my $home=&homeserver($uname,$udom);
1.292 www 2023: if ($home eq 'no_host') {
2024: return -1;
2025: }
1.1112 www 2026: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2027: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2028: return -1;
2029: }
1.1112 www 2030: return $answer;
1.263 www 2031: }
2032:
1.1111 www 2033: #
2034: # Return special version number of resource if set by override, empty otherwise
2035: #
2036: sub usedversion {
2037: my $fname=shift;
2038: unless ($fname) { $fname=$env{'request.uri'}; }
2039: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2040: if ($urlversion) { return $urlversion; }
2041: return '';
2042: }
2043:
1.1 albertel 2044: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2045:
1.1 albertel 2046: sub subscribe {
2047: my $fname=shift;
1.761 raeburn 2048: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2049: $fname=~s/[\n\r]//g;
1.1 albertel 2050: my $author=$fname;
2051: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2052: my ($udom,$uname)=split(/\//,$author);
2053: my $home=homeserver($uname,$udom);
1.335 albertel 2054: if ($home eq 'no_host') {
2055: return 'not_found';
1.1 albertel 2056: }
2057: my $answer=reply("sub:$fname",$home);
1.64 www 2058: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2059: $answer.=' by '.$home;
2060: }
1.1 albertel 2061: return $answer;
2062: }
2063:
1.8 www 2064: # -------------------------------------------------------------- Replicate file
2065:
2066: sub repcopy {
2067: my $filename=shift;
1.23 www 2068: $filename=~s/\/+/\//g;
1.607 raeburn 2069: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
2070: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 2071: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 2072: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 2073: return &repcopy_userfile($filename);
2074: }
1.532 albertel 2075: $filename=~s/[\n\r]//g;
1.8 www 2076: my $transname="$filename.in.transfer";
1.828 www 2077: # FIXME: this should flock
1.607 raeburn 2078: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2079: my $remoteurl=subscribe($filename);
1.64 www 2080: if ($remoteurl =~ /^con_lost by/) {
2081: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2082: return 'unavailable';
1.8 www 2083: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2084: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2085: return 'not_found';
1.64 www 2086: } elsif ($remoteurl =~ /^rejected by/) {
2087: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2088: return 'forbidden';
1.20 www 2089: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2090: return 'ok';
1.8 www 2091: } else {
1.290 www 2092: my $author=$filename;
2093: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2094: my ($udom,$uname)=split(/\//,$author);
2095: my $home=homeserver($uname,$udom);
2096: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2097: my @parts=split(/\//,$filename);
2098: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2099: if ($path ne "$perlvar{'lonDocRoot'}/res") {
2100: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2101: return 'bad_request';
1.8 www 2102: }
2103: my $count;
2104: for ($count=5;$count<$#parts;$count++) {
2105: $path.="/$parts[$count]";
2106: if ((-e $path)!=1) {
2107: mkdir($path,0777);
2108: }
2109: }
2110: my $ua=new LWP::UserAgent;
2111: my $request=new HTTP::Request('GET',"$remoteurl");
2112: my $response=$ua->request($request,$transname);
2113: if ($response->is_error()) {
2114: unlink($transname);
2115: my $message=$response->status_line;
1.672 albertel 2116: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2117: ." LWP get: $message: $filename</font>");
1.607 raeburn 2118: return 'unavailable';
1.8 www 2119: } else {
1.16 www 2120: if ($remoteurl!~/\.meta$/) {
2121: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2122: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2123: if ($mresponse->is_error()) {
2124: unlink($filename.'.meta');
2125: &logthis(
1.672 albertel 2126: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2127: }
2128: }
1.8 www 2129: rename($transname,$filename);
1.607 raeburn 2130: return 'ok';
1.8 www 2131: }
1.290 www 2132: }
1.8 www 2133: }
1.330 www 2134: }
2135:
2136: # ------------------------------------------------ Get server side include body
2137: sub ssi_body {
1.381 albertel 2138: my ($filelink,%form)=@_;
1.606 matthew 2139: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2140: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2141: }
1.953 www 2142: my $output='';
2143: my $response;
1.980 raeburn 2144: if ($filelink=~/^https?\:/) {
1.954 raeburn 2145: ($output,$response)=&externalssi($filelink);
1.953 www 2146: } else {
1.1004 droeschl 2147: $filelink .= $filelink=~/\?/ ? '&' : '?';
2148: $filelink .= 'inhibitmenu=yes';
1.953 www 2149: ($output,$response)=&ssi($filelink,%form);
2150: }
1.778 albertel 2151: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2152: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2153: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2154: if (wantarray) {
2155: return ($output, $response);
2156: } else {
2157: return $output;
2158: }
1.8 www 2159: }
2160:
1.15 www 2161: # --------------------------------------------------------- Server Side Include
2162:
1.782 albertel 2163: sub absolute_url {
2164: my ($host_name) = @_;
2165: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2166: if ($host_name eq '') {
2167: $host_name = $ENV{'SERVER_NAME'};
2168: }
2169: return $protocol.$host_name;
2170: }
2171:
1.942 foxr 2172: #
2173: # Server side include.
2174: # Parameters:
2175: # fn Possibly encrypted resource name/id.
2176: # form Hash that describes how the rendering should be done
2177: # and other things.
1.944 foxr 2178: # Returns:
1.950 raeburn 2179: # Scalar context: The content of the response.
2180: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2181: #
1.15 www 2182: sub ssi {
2183:
1.944 foxr 2184: my ($fn,%form)=@_;
1.15 www 2185: my $ua=new LWP::UserAgent;
1.23 www 2186: my $request;
1.711 albertel 2187:
2188: $form{'no_update_last_known'}=1;
1.895 albertel 2189: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2190: if (%form) {
1.782 albertel 2191: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2192: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2193: } else {
1.782 albertel 2194: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2195: }
2196:
1.15 www 2197: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2198: my $response=$ua->request($request);
2199:
1.944 foxr 2200: if (wantarray) {
2201: return ($response->content, $response);
2202: } else {
2203: return $response->content;
1.942 foxr 2204: }
1.324 www 2205: }
2206:
2207: sub externalssi {
2208: my ($url)=@_;
2209: my $ua=new LWP::UserAgent;
2210: my $request=new HTTP::Request('GET',$url);
2211: my $response=$ua->request($request);
1.954 raeburn 2212: if (wantarray) {
2213: return ($response->content, $response);
2214: } else {
2215: return $response->content;
2216: }
1.15 www 2217: }
1.254 www 2218:
1.492 albertel 2219: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2220:
2221: sub allowuploaded {
2222: my ($srcurl,$url)=@_;
2223: $url=&clutter(&declutter($url));
2224: my $dir=$url;
2225: $dir=~s/\/[^\/]+$//;
2226: my %httpref=();
2227: my $httpurl=&hreflocation('',$url);
2228: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2229: &Apache::lonnet::appenv(\%httpref);
1.254 www 2230: }
1.477 raeburn 2231:
1.478 albertel 2232: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2233: # input: action, courseID, current domain, intended
1.637 raeburn 2234: # path to file, source of file, instruction to parse file for objects,
2235: # ref to hash for embedded objects,
2236: # ref to hash for codebase of java objects.
1.1095 raeburn 2237: # reference to scalar to accommodate mime type determined
2238: # from File::MMagic if $parser = parse.
1.637 raeburn 2239: #
1.485 raeburn 2240: # output: url to file (if action was uploaddoc),
2241: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2242: #
1.478 albertel 2243: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2244: # course.
1.477 raeburn 2245: #
1.478 albertel 2246: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2247: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2248: # course's home server.
1.477 raeburn 2249: #
1.478 albertel 2250: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2251: # be copied from $source (current location) to
2252: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2253: # and will then be copied to
2254: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2255: # course's home server.
1.485 raeburn 2256: #
1.481 raeburn 2257: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2258: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2259: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2260: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2261: # in course's home server.
1.637 raeburn 2262: #
1.477 raeburn 2263:
2264: sub process_coursefile {
1.1095 raeburn 2265: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2266: $mimetype)=@_;
1.477 raeburn 2267: my $fetchresult;
1.638 albertel 2268: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2269: if ($action eq 'propagate') {
1.638 albertel 2270: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2271: $home);
1.481 raeburn 2272: } else {
1.477 raeburn 2273: my $fpath = '';
2274: my $fname = $file;
1.478 albertel 2275: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2276: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2277: my $filepath = &build_filepath($fpath);
1.481 raeburn 2278: if ($action eq 'copy') {
2279: if ($source eq '') {
2280: $fetchresult = 'no source file';
2281: return $fetchresult;
2282: } else {
2283: my $destination = $filepath.'/'.$fname;
2284: rename($source,$destination);
2285: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2286: $home);
1.481 raeburn 2287: }
2288: } elsif ($action eq 'uploaddoc') {
2289: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2290: print $fh $env{'form.'.$source};
1.481 raeburn 2291: close($fh);
1.637 raeburn 2292: if ($parser eq 'parse') {
1.1024 raeburn 2293: my $mm = new File::MMagic;
1.1095 raeburn 2294: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2295: if ($type eq 'text/html') {
1.1024 raeburn 2296: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2297: unless ($parse_result eq 'ok') {
2298: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2299: }
1.637 raeburn 2300: }
1.1095 raeburn 2301: if (ref($mimetype)) {
2302: $$mimetype = $type;
2303: }
1.637 raeburn 2304: }
1.477 raeburn 2305: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2306: $home);
1.481 raeburn 2307: if ($fetchresult eq 'ok') {
2308: return '/uploaded/'.$fpath.'/'.$fname;
2309: } else {
2310: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2311: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2312: return '/adm/notfound.html';
2313: }
1.477 raeburn 2314: }
2315: }
1.485 raeburn 2316: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2317: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2318: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2319: }
2320: return $fetchresult;
2321: }
2322:
1.637 raeburn 2323: sub build_filepath {
2324: my ($fpath) = @_;
2325: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2326: unless ($fpath eq '') {
2327: my @parts=split('/',$fpath);
2328: foreach my $part (@parts) {
2329: $filepath.= '/'.$part;
2330: if ((-e $filepath)!=1) {
2331: mkdir($filepath,0777);
2332: }
2333: }
2334: }
2335: return $filepath;
2336: }
2337:
2338: sub store_edited_file {
1.638 albertel 2339: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2340: my $file = $primary_url;
2341: $file =~ s#^/uploaded/$docudom/$docuname/##;
2342: my $fpath = '';
2343: my $fname = $file;
2344: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2345: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2346: my $filepath = &build_filepath($fpath);
2347: open(my $fh,'>'.$filepath.'/'.$fname);
2348: print $fh $content;
2349: close($fh);
1.638 albertel 2350: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2351: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2352: $home);
1.637 raeburn 2353: if ($$fetchresult eq 'ok') {
2354: return '/uploaded/'.$fpath.'/'.$fname;
2355: } else {
1.638 albertel 2356: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2357: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2358: return '/adm/notfound.html';
2359: }
2360: }
2361:
1.531 albertel 2362: sub clean_filename {
1.831 albertel 2363: my ($fname,$args)=@_;
1.315 www 2364: # Replace Windows backslashes by forward slashes
1.257 www 2365: $fname=~s/\\/\//g;
1.831 albertel 2366: if (!$args->{'keep_path'}) {
2367: # Get rid of everything but the actual filename
2368: $fname=~s/^.*\/([^\/]+)$/$1/;
2369: }
1.315 www 2370: # Replace spaces by underscores
2371: $fname=~s/\s+/\_/g;
2372: # Replace all other weird characters by nothing
1.831 albertel 2373: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2374: # Replace all .\d. sequences with _\d. so they no longer look like version
2375: # numbers
2376: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2377: return $fname;
2378: }
1.1051 raeburn 2379: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2380: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2381: # image with the same aspect ratio as the original, but with dimensions which do
2382: # not exceed $resizewidth and $resizeheight.
2383:
1.984 neumanie 2384: sub resizeImage {
1.1051 raeburn 2385: my ($img_path,$resizewidth,$resizeheight) = @_;
2386: my $ima = Image::Magick->new;
2387: my $resized;
2388: if (-e $img_path) {
2389: $ima->Read($img_path);
2390: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2391: my $width = $ima->Get('width');
2392: my $height = $ima->Get('height');
2393: if ($width > $resizewidth) {
2394: my $factor = $width/$resizewidth;
2395: my $newheight = $height/$factor;
2396: $ima->Scale(width=>$resizewidth,height=>$newheight);
2397: $resized = 1;
2398: }
2399: }
2400: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2401: my $width = $ima->Get('width');
2402: my $height = $ima->Get('height');
2403: if ($height > $resizeheight) {
2404: my $factor = $height/$resizeheight;
2405: my $newwidth = $width/$factor;
2406: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2407: $resized = 1;
2408: }
2409: }
2410: if ($resized) {
2411: $ima->Write($img_path);
2412: }
2413: }
2414: return;
1.977 amueller 2415: }
2416:
1.608 albertel 2417: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2418: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 2419: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 2420: # $context - possible values: coursedoc, existingfile, overwrite,
2421: # canceloverwrite, or ''.
2422: # if 'coursedoc': upload to the current course
2423: # if 'existingfile': write file to tmp/overwrites directory
2424: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2425: # $context is passed as argument to &finishuserfileupload
1.686 albertel 2426: # $subdir - directory in userfile to store the file into
1.858 raeburn 2427: # $parser - instruction to parse file for objects ($parser = parse)
2428: # $allfiles - reference to hash for embedded objects
2429: # $codebase - reference to hash for codebase of java objects
2430: # $desuname - username for permanent storage of uploaded file
2431: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2432: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2433: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2434: # $resizewidth - width (pixels) to which to resize uploaded image
2435: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 2436: # $mimetype - reference to scalar to accommodate mime type determined
2437: # from File::MMagic if $parser = parse.
1.858 raeburn 2438: #
1.686 albertel 2439: # output: url of file in userspace, or error: <message>
2440: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2441:
1.531 albertel 2442: sub userfileupload {
1.1090 raeburn 2443: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 2444: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 2445: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2446: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2447: $fname=&clean_filename($fname);
1.1090 raeburn 2448: # See if there is anything left
1.257 www 2449: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 2450: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2451: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2452: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2453: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 2454: my $now = time;
1.1090 raeburn 2455: my $filepath;
1.1095 raeburn 2456: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 2457: $filepath = 'tmp/helprequests/'.$now;
2458: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2459: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2460: '_'.$env{'user.domain'}.'/pending';
2461: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2462: my ($docuname,$docudom);
2463: if ($destudom) {
2464: $docudom = $destudom;
2465: } else {
2466: $docudom = $env{'user.domain'};
2467: }
2468: if ($destuname) {
2469: $docuname = $destuname;
2470: } else {
2471: $docuname = $env{'user.name'};
2472: }
2473: if (exists($env{'form.group'})) {
2474: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2475: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2476: }
2477: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2478: if ($context eq 'canceloverwrite') {
2479: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2480: if (-e $tempfile) {
2481: my @info = stat($tempfile);
2482: if ($info[9] eq $env{'form.timestamp'}) {
2483: unlink($tempfile);
2484: }
2485: }
2486: return;
1.523 raeburn 2487: }
2488: }
1.1090 raeburn 2489: # Create the directory if not present
1.741 raeburn 2490: my @parts=split(/\//,$filepath);
2491: my $fullpath = $perlvar{'lonDaemons'};
2492: for (my $i=0;$i<@parts;$i++) {
2493: $fullpath .= '/'.$parts[$i];
2494: if ((-e $fullpath)!=1) {
2495: mkdir($fullpath,0777);
2496: }
2497: }
2498: open(my $fh,'>'.$fullpath.'/'.$fname);
2499: print $fh $env{'form.'.$formname};
2500: close($fh);
1.1090 raeburn 2501: if ($context eq 'existingfile') {
2502: my @info = stat($fullpath.'/'.$fname);
2503: return ($fullpath.'/'.$fname,$info[9]);
2504: } else {
2505: return $fullpath.'/'.$fname;
2506: }
1.523 raeburn 2507: }
1.995 raeburn 2508: if ($subdir eq 'scantron') {
2509: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 2510: } else {
1.995 raeburn 2511: $fname="$subdir/$fname";
2512: }
1.1090 raeburn 2513: if ($context eq 'coursedoc') {
1.638 albertel 2514: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2515: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2516: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2517: return &finishuserfileupload($docuname,$docudom,
2518: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2519: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 2520: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 2521: } else {
1.620 albertel 2522: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2523: return &process_coursefile('uploaddoc',$docuname,$docudom,
2524: $fname,$formname,$parser,
1.1095 raeburn 2525: $allfiles,$codebase,$mimetype);
1.481 raeburn 2526: }
1.719 banghart 2527: } elsif (defined($destuname)) {
2528: my $docuname=$destuname;
2529: my $docudom=$destudom;
1.860 raeburn 2530: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2531: $parser,$allfiles,$codebase,
1.1051 raeburn 2532: $thumbwidth,$thumbheight,
1.1095 raeburn 2533: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2534: } else {
1.638 albertel 2535: my $docuname=$env{'user.name'};
2536: my $docudom=$env{'user.domain'};
1.714 raeburn 2537: if (exists($env{'form.group'})) {
2538: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2539: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2540: }
1.860 raeburn 2541: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2542: $parser,$allfiles,$codebase,
1.1051 raeburn 2543: $thumbwidth,$thumbheight,
1.1095 raeburn 2544: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2545: }
1.271 www 2546: }
2547:
2548: sub finishuserfileupload {
1.860 raeburn 2549: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 2550: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 2551: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2552: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2553:
1.860 raeburn 2554: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2555: $file=$fname;
2556: if ($fname=~m|/|) {
2557: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2558: $path.=$fnamepath.'/';
2559: }
1.259 www 2560: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2561: my $count;
2562: for ($count=4;$count<=$#parts;$count++) {
2563: $filepath.="/$parts[$count]";
2564: if ((-e $filepath)!=1) {
2565: mkdir($filepath,0777);
2566: }
2567: }
1.984 neumanie 2568:
1.258 www 2569: # Save the file
2570: {
1.701 albertel 2571: if (!open(FH,'>'.$filepath.'/'.$file)) {
2572: &logthis('Failed to create '.$filepath.'/'.$file);
2573: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2574: return '/adm/notfound.html';
2575: }
1.1090 raeburn 2576: if ($context eq 'overwrite') {
1.1117 ! foxr 2577: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 2578: my $target = $filepath.'/'.$file;
2579: if (-e $source) {
2580: my @info = stat($source);
2581: if ($info[9] eq $env{'form.timestamp'}) {
2582: unless (&File::Copy::move($source,$target)) {
2583: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2584: return "Moving from $source failed";
2585: }
2586: } else {
2587: return "Temporary file: $source had unexpected date/time for last modification";
2588: }
2589: } else {
2590: return "Temporary file: $source missing";
2591: }
2592: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 2593: &logthis('Failed to write to '.$filepath.'/'.$file);
2594: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2595: return '/adm/notfound.html';
2596: }
1.570 albertel 2597: close(FH);
1.1051 raeburn 2598: if ($resizewidth && $resizeheight) {
2599: my $mm = new File::MMagic;
2600: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2601: if ($mime_type =~ m{^image/}) {
2602: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2603: }
1.977 amueller 2604: }
1.258 www 2605: }
1.637 raeburn 2606: if ($parser eq 'parse') {
1.1024 raeburn 2607: my $mm = new File::MMagic;
1.1095 raeburn 2608: my $type = $mm->checktype_filename($filepath.'/'.$file);
2609: if ($type eq 'text/html') {
1.1024 raeburn 2610: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2611: $allfiles,$codebase);
2612: unless ($parse_result eq 'ok') {
2613: &logthis('Failed to parse '.$filepath.$file.
2614: ' for embedded media: '.$parse_result);
2615: }
1.637 raeburn 2616: }
1.1095 raeburn 2617: if (ref($mimetype)) {
2618: $$mimetype = $type;
2619: }
1.637 raeburn 2620: }
1.860 raeburn 2621: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2622: my $input = $filepath.'/'.$file;
2623: my $output = $filepath.'/'.'tn-'.$file;
2624: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2625: system("convert -sample $thumbsize $input $output");
2626: if (-e $filepath.'/'.'tn-'.$file) {
2627: $fetchthumb = 1;
2628: }
2629: }
1.858 raeburn 2630:
1.259 www 2631: # Notify homeserver to grep it
2632: #
1.984 neumanie 2633: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2634: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2635: if ($fetchresult eq 'ok') {
1.860 raeburn 2636: if ($fetchthumb) {
2637: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2638: if ($thumbresult ne 'ok') {
2639: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2640: $docuhome.': '.$thumbresult);
2641: }
2642: }
1.259 www 2643: #
1.258 www 2644: # Return the URL to it
1.494 albertel 2645: return '/uploaded/'.$path.$file;
1.263 www 2646: } else {
1.494 albertel 2647: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2648: ': '.$fetchresult);
1.263 www 2649: return '/adm/notfound.html';
1.858 raeburn 2650: }
1.493 albertel 2651: }
2652:
1.637 raeburn 2653: sub extract_embedded_items {
1.961 raeburn 2654: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2655: my @state = ();
2656: my %javafiles = (
2657: codebase => '',
2658: code => '',
2659: archive => ''
2660: );
2661: my %mediafiles = (
2662: src => '',
2663: movie => '',
2664: );
1.648 raeburn 2665: my $p;
2666: if ($content) {
2667: $p = HTML::LCParser->new($content);
2668: } else {
1.961 raeburn 2669: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2670: }
1.641 albertel 2671: while (my $t=$p->get_token()) {
1.640 albertel 2672: if ($t->[0] eq 'S') {
2673: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2674: push(@state, $tagname);
1.648 raeburn 2675: if (lc($tagname) eq 'allow') {
2676: &add_filetype($allfiles,$attr->{'src'},'src');
2677: }
1.640 albertel 2678: if (lc($tagname) eq 'img') {
2679: &add_filetype($allfiles,$attr->{'src'},'src');
2680: }
1.886 albertel 2681: if (lc($tagname) eq 'a') {
2682: &add_filetype($allfiles,$attr->{'href'},'href');
2683: }
1.645 raeburn 2684: if (lc($tagname) eq 'script') {
2685: if ($attr->{'archive'} =~ /\.jar$/i) {
2686: &add_filetype($allfiles,$attr->{'archive'},'archive');
2687: } else {
2688: &add_filetype($allfiles,$attr->{'src'},'src');
2689: }
2690: }
2691: if (lc($tagname) eq 'link') {
2692: if (lc($attr->{'rel'}) eq 'stylesheet') {
2693: &add_filetype($allfiles,$attr->{'href'},'href');
2694: }
2695: }
1.640 albertel 2696: if (lc($tagname) eq 'object' ||
2697: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2698: foreach my $item (keys(%javafiles)) {
2699: $javafiles{$item} = '';
2700: }
2701: }
2702: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2703: my $name = lc($attr->{'name'});
2704: foreach my $item (keys(%javafiles)) {
2705: if ($name eq $item) {
2706: $javafiles{$item} = $attr->{'value'};
2707: last;
2708: }
2709: }
2710: foreach my $item (keys(%mediafiles)) {
2711: if ($name eq $item) {
2712: &add_filetype($allfiles, $attr->{'value'}, 'value');
2713: last;
2714: }
2715: }
2716: }
2717: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2718: foreach my $item (keys(%javafiles)) {
2719: if ($attr->{$item}) {
2720: $javafiles{$item} = $attr->{$item};
2721: last;
2722: }
2723: }
2724: foreach my $item (keys(%mediafiles)) {
2725: if ($attr->{$item}) {
2726: &add_filetype($allfiles,$attr->{$item},$item);
2727: last;
2728: }
2729: }
2730: }
2731: } elsif ($t->[0] eq 'E') {
2732: my ($tagname) = ($t->[1]);
2733: if ($javafiles{'codebase'} ne '') {
2734: $javafiles{'codebase'} .= '/';
2735: }
2736: if (lc($tagname) eq 'applet' ||
2737: lc($tagname) eq 'object' ||
2738: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2739: ) {
2740: foreach my $item (keys(%javafiles)) {
2741: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2742: my $file=$javafiles{'codebase'}.$javafiles{$item};
2743: &add_filetype($allfiles,$file,$item);
2744: }
2745: }
2746: }
2747: pop @state;
2748: }
2749: }
1.637 raeburn 2750: return 'ok';
2751: }
2752:
1.639 albertel 2753: sub add_filetype {
2754: my ($allfiles,$file,$type)=@_;
2755: if (exists($allfiles->{$file})) {
2756: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2757: push(@{$allfiles->{$file}}, &escape($type));
2758: }
2759: } else {
2760: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2761: }
2762: }
2763:
1.493 albertel 2764: sub removeuploadedurl {
1.984 neumanie 2765: my ($url)=@_;
2766: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2767: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2768: }
2769:
2770: sub removeuserfile {
2771: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2772: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2773: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2774: if ($result eq 'ok') {
1.798 raeburn 2775: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2776: my $metafile = $fname.'.meta';
2777: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2778: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2779: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2780: my $sqlresult =
1.823 albertel 2781: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2782: 'portfolio_metadata',$group,
2783: 'delete');
1.798 raeburn 2784: }
2785: }
2786: return $result;
1.257 www 2787: }
1.15 www 2788:
1.530 albertel 2789: sub mkdiruserfile {
2790: my ($docuname,$docudom,$dir)=@_;
2791: my $home=&homeserver($docuname,$docudom);
2792: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2793: }
2794:
1.531 albertel 2795: sub renameuserfile {
2796: my ($docuname,$docudom,$old,$new)=@_;
2797: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2798: my $result = &reply("renameuserfile:$docudom:$docuname:".
2799: &escape("$old").':'.&escape("$new"),$home);
2800: if ($result eq 'ok') {
2801: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2802: my $oldmeta = $old.'.meta';
2803: my $newmeta = $new.'.meta';
2804: my $metaresult =
2805: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2806: my $url = "/uploaded/$docudom/$docuname/$old";
2807: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2808: my $sqlresult =
1.823 albertel 2809: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2810: 'portfolio_metadata',$group,
2811: 'delete');
1.798 raeburn 2812: }
2813: }
2814: return $result;
1.531 albertel 2815: }
2816:
1.14 www 2817: # ------------------------------------------------------------------------- Log
2818:
2819: sub log {
2820: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2821: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2822: }
2823:
2824: # ------------------------------------------------------------------ Course Log
1.352 www 2825: #
2826: # This routine flushes several buffers of non-mission-critical nature
2827: #
1.157 www 2828:
2829: sub flushcourselogs {
1.352 www 2830: &logthis('Flushing log buffers');
2831: #
2832: # course logs
2833: # This is a log of all transactions in a course, which can be used
2834: # for data mining purposes
2835: #
2836: # It also collects the courseid database, which lists last transaction
2837: # times and course titles for all courseids
2838: #
2839: my %courseidbuffer=();
1.921 raeburn 2840: foreach my $crsid (keys(%courselogs)) {
1.352 www 2841: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2842: &escape($courselogs{$crsid}),
2843: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2844: delete $courselogs{$crsid};
2845: } else {
2846: &logthis('Failed to flush log buffer for '.$crsid);
2847: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2848: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2849: " exceeded maximum size, deleting.</font>");
2850: delete $courselogs{$crsid};
2851: }
1.352 www 2852: }
1.920 raeburn 2853: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2854: 'description' => $coursedescrbuf{$crsid},
2855: 'inst_code' => $courseinstcodebuf{$crsid},
2856: 'type' => $coursetypebuf{$crsid},
2857: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2858: };
1.191 harris41 2859: }
1.352 www 2860: #
2861: # Write course id database (reverse lookup) to homeserver of courses
2862: # Is used in pickcourse
2863: #
1.840 albertel 2864: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2865: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2866: $courseidbuffer{$crs_home},
2867: $crs_home,'timeonly');
1.352 www 2868: }
2869: #
2870: # File accesses
2871: # Writes to the dynamic metadata of resources to get hit counts, etc.
2872: #
1.449 matthew 2873: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2874: if ($entry =~ /___count$/) {
2875: my ($dom,$name);
1.807 albertel 2876: ($dom,$name,undef)=
1.811 albertel 2877: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2878: if (! defined($dom) || $dom eq '' ||
2879: ! defined($name) || $name eq '') {
1.620 albertel 2880: my $cid = $env{'request.course.id'};
2881: $dom = $env{'request.'.$cid.'.domain'};
2882: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2883: }
1.450 matthew 2884: my $value = $accesshash{$entry};
2885: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2886: my %temphash=($url => $value);
1.449 matthew 2887: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2888: if ($result eq 'ok') {
2889: delete $accesshash{$entry};
2890: } elsif ($result eq 'unknown_cmd') {
2891: # Target server has old code running on it.
1.450 matthew 2892: my %temphash=($entry => $value);
1.449 matthew 2893: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2894: delete $accesshash{$entry};
2895: }
2896: }
2897: } else {
1.811 albertel 2898: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2899: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2900: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2901: delete $accesshash{$entry};
2902: }
1.185 www 2903: }
1.191 harris41 2904: }
1.352 www 2905: #
2906: # Roles
2907: # Reverse lookup of user roles for course faculty/staff and co-authorship
2908: #
1.800 albertel 2909: foreach my $entry (keys(%userrolehash)) {
1.351 www 2910: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2911: split(/\:/,$entry);
2912: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2913: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2914: $rudom,$runame) eq 'ok') {
2915: delete $userrolehash{$entry};
2916: }
2917: }
1.662 raeburn 2918: #
2919: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2920: #
2921: my %domrolebuffer = ();
1.1000 raeburn 2922: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 2923: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2924: if ($domrolebuffer{$rudom}) {
2925: $domrolebuffer{$rudom}.='&'.&escape($entry).
2926: '='.&escape($domainrolehash{$entry});
2927: } else {
2928: $domrolebuffer{$rudom}.=&escape($entry).
2929: '='.&escape($domainrolehash{$entry});
2930: }
2931: delete $domainrolehash{$entry};
2932: }
2933: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2934: my %servers = &get_servers($dom,'library');
2935: foreach my $tryserver (keys(%servers)) {
2936: unless (&reply('domroleput:'.$dom.':'.
2937: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2938: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2939: }
1.662 raeburn 2940: }
2941: }
1.186 www 2942: $dumpcount++;
1.157 www 2943: }
2944:
2945: sub courselog {
2946: my $what=shift;
1.158 www 2947: $what=time.':'.$what;
1.620 albertel 2948: unless ($env{'request.course.id'}) { return ''; }
2949: $coursedombuf{$env{'request.course.id'}}=
2950: $env{'course.'.$env{'request.course.id'}.'.domain'};
2951: $coursenumbuf{$env{'request.course.id'}}=
2952: $env{'course.'.$env{'request.course.id'}.'.num'};
2953: $coursehombuf{$env{'request.course.id'}}=
2954: $env{'course.'.$env{'request.course.id'}.'.home'};
2955: $coursedescrbuf{$env{'request.course.id'}}=
2956: $env{'course.'.$env{'request.course.id'}.'.description'};
2957: $courseinstcodebuf{$env{'request.course.id'}}=
2958: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2959: $courseownerbuf{$env{'request.course.id'}}=
2960: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2961: $coursetypebuf{$env{'request.course.id'}}=
2962: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2963: if (defined $courselogs{$env{'request.course.id'}}) {
2964: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2965: } else {
1.620 albertel 2966: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2967: }
1.620 albertel 2968: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2969: &flushcourselogs();
2970: }
1.158 www 2971: }
2972:
2973: sub courseacclog {
2974: my $fnsymb=shift;
1.620 albertel 2975: unless ($env{'request.course.id'}) { return ''; }
2976: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2977: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2978: $what.=':POST';
1.583 matthew 2979: # FIXME: Probably ought to escape things....
1.800 albertel 2980: foreach my $key (keys(%env)) {
2981: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2982: my $formitem = $1;
2983: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2984: $what.=':'.$formitem.'='.$env{$key};
2985: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2986: $what.=':'.$formitem.'='.$env{$key};
2987: }
1.158 www 2988: }
1.191 harris41 2989: }
1.583 matthew 2990: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2991: # FIXME: We should not be depending on a form parameter that someone
2992: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2993: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2994: $what.= ':POST';
2995: # FIXME: Probably ought to escape things....
2996: foreach my $element ('courseexp','crsfulltext','crsrelated',
2997: 'crsdiscuss') {
1.620 albertel 2998: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2999: }
3000: }
1.158 www 3001: }
3002: &courselog($what);
1.149 www 3003: }
3004:
1.185 www 3005: sub countacc {
3006: my $url=&declutter(shift);
1.458 matthew 3007: return if (! defined($url) || $url eq '');
1.620 albertel 3008: unless ($env{'request.course.id'}) { return ''; }
3009: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 3010: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3011: $accesshash{$key}++;
1.185 www 3012: }
1.349 www 3013:
1.361 www 3014: sub linklog {
3015: my ($from,$to)=@_;
3016: $from=&declutter($from);
3017: $to=&declutter($to);
3018: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3019: $accesshash{$to.'___'.$from.'___goto'}=1;
3020: }
3021:
1.349 www 3022: sub userrolelog {
3023: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 3024: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 3025: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 3026: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 3027: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 3028: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3029: $userrolehash
3030: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3031: =$tend.':'.$tstart;
1.662 raeburn 3032: }
1.898 albertel 3033: if (($env{'request.role'} =~ /dc\./) &&
3034: (($trole=~/^au/) || ($trole=~/^in/) ||
3035: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 3036: ($trole=~/^cr/) || ($trole=~/^ta/) ||
3037: ($trole=~/^co/))) {
1.898 albertel 3038: $userrolehash
3039: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3040: =$tend.':'.$tstart;
3041: }
1.662 raeburn 3042: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
3043: ($trole=~/^li/) || ($trole=~/^li/) ||
3044: ($trole=~/^au/) || ($trole=~/^dg/) ||
3045: ($trole=~/^sc/)) {
3046: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3047: $domainrolehash
3048: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3049: = $tend.':'.$tstart;
3050: }
1.351 www 3051: }
3052:
1.957 raeburn 3053: sub courserolelog {
3054: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3055: if (($trole eq 'cc') || ($trole eq 'in') ||
3056: ($trole eq 'ep') || ($trole eq 'ad') ||
3057: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 3058: ($trole=~/^cr/) || ($trole eq 'gr') ||
3059: ($trole eq 'co')) {
1.957 raeburn 3060: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3061: my $cdom = $1;
3062: my $cnum = $2;
3063: my $sec = $3;
3064: my $namespace = 'rolelog';
3065: my %storehash = (
3066: role => $trole,
3067: start => $tstart,
3068: end => $tend,
3069: selfenroll => $selfenroll,
3070: context => $context,
3071: );
3072: if ($trole eq 'gr') {
3073: $namespace = 'groupslog';
3074: $storehash{'group'} = $sec;
3075: } else {
3076: $storehash{'section'} = $sec;
3077: }
3078: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 3079: if (($trole ne 'st') || ($sec ne '')) {
3080: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3081: }
1.957 raeburn 3082: }
3083: }
3084: return;
3085: }
3086:
1.351 www 3087: sub get_course_adv_roles {
1.948 raeburn 3088: my ($cid,$codes) = @_;
1.620 albertel 3089: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3090: my %coursehash=&coursedescription($cid);
1.988 raeburn 3091: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3092: my %nothide=();
1.800 albertel 3093: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3094: if ($user !~ /:/) {
3095: $nothide{join(':',split(/[\@]/,$user))}=1;
3096: } else {
3097: $nothide{$user}=1;
3098: }
1.470 www 3099: }
1.351 www 3100: my %returnhash=();
3101: my %dumphash=
3102: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3103: my $now=time;
1.997 raeburn 3104: my %privileged;
1.1000 raeburn 3105: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3106: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3107: if (($tstart) && ($tstart<0)) { next; }
3108: if (($tend) && ($tend<$now)) { next; }
3109: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3110: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3111: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 3112: unless (ref($privileged{$domain}) eq 'HASH') {
3113: my %dompersonnel =
1.998 raeburn 3114: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 3115: $privileged{$domain} = {};
3116: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 3117: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 3118: foreach my $user (keys(%{$dompersonnel{$server}})) {
3119: my ($trole,$uname,$udom) = split(/:/,$user);
3120: $privileged{$udom}{$uname} = 1;
3121: }
3122: }
3123: }
3124: }
3125: if ((exists($privileged{$domain}{$username})) &&
3126: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3127: if ($role eq 'cr') { next; }
1.948 raeburn 3128: if ($codes) {
3129: if ($section) { $role .= ':'.$section; }
3130: if ($returnhash{$role}) {
3131: $returnhash{$role}.=','.$username.':'.$domain;
3132: } else {
3133: $returnhash{$role}=$username.':'.$domain;
3134: }
1.351 www 3135: } else {
1.988 raeburn 3136: my $key=&plaintext($role,$crstype);
1.973 bisitz 3137: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3138: if ($returnhash{$key}) {
3139: $returnhash{$key}.=','.$username.':'.$domain;
3140: } else {
3141: $returnhash{$key}=$username.':'.$domain;
3142: }
1.351 www 3143: }
1.948 raeburn 3144: }
1.400 www 3145: return %returnhash;
3146: }
3147:
3148: sub get_my_roles {
1.937 raeburn 3149: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3150: unless (defined($uname)) { $uname=$env{'user.name'}; }
3151: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3152: my (%dumphash,%nothide);
1.1086 raeburn 3153: if ($context eq 'userroles') {
3154: my $extra = &freeze_escape({'skipcheck' => 1});
3155: %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858 raeburn 3156: } else {
3157: %dumphash=
1.400 www 3158: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3159: if ($hidepriv) {
3160: my %coursehash=&coursedescription($udom.'_'.$uname);
3161: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3162: if ($user !~ /:/) {
3163: $nothide{join(':',split(/[\@]/,$user))} = 1;
3164: } else {
3165: $nothide{$user} = 1;
3166: }
3167: }
3168: }
1.858 raeburn 3169: }
1.400 www 3170: my %returnhash=();
3171: my $now=time;
1.999 raeburn 3172: my %privileged;
1.800 albertel 3173: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3174: my ($role,$tend,$tstart);
3175: if ($context eq 'userroles') {
3176: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3177: } else {
3178: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3179: }
1.400 www 3180: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3181: my $status = 'active';
1.939 raeburn 3182: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3183: $status = 'previous';
3184: }
3185: if (($tstart) && ($now<$tstart)) {
3186: $status = 'future';
3187: }
3188: if (ref($types) eq 'ARRAY') {
3189: if (!grep(/^\Q$status\E$/,@{$types})) {
3190: next;
3191: }
3192: } else {
3193: if ($status ne 'active') {
3194: next;
3195: }
3196: }
1.867 raeburn 3197: my ($rolecode,$username,$domain,$section,$area);
3198: if ($context eq 'userroles') {
3199: ($area,$rolecode) = split(/_/,$entry);
3200: (undef,$domain,$username,$section) = split(/\//,$area);
3201: } else {
3202: ($role,$username,$domain,$section) = split(/\:/,$entry);
3203: }
1.832 raeburn 3204: if (ref($roledoms) eq 'ARRAY') {
3205: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3206: next;
3207: }
3208: }
3209: if (ref($roles) eq 'ARRAY') {
3210: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3211: if ($role =~ /^cr\//) {
3212: if (!grep(/^cr$/,@{$roles})) {
3213: next;
3214: }
1.1104 raeburn 3215: } elsif ($role =~ /^gr\//) {
3216: if (!grep(/^gr$/,@{$roles})) {
3217: next;
3218: }
1.922 raeburn 3219: } else {
3220: next;
3221: }
1.832 raeburn 3222: }
1.867 raeburn 3223: }
1.937 raeburn 3224: if ($hidepriv) {
1.999 raeburn 3225: if ($context eq 'userroles') {
3226: if ((&privileged($username,$domain)) &&
3227: (!$nothide{$username.':'.$domain})) {
3228: next;
3229: }
3230: } else {
3231: unless (ref($privileged{$domain}) eq 'HASH') {
3232: my %dompersonnel =
3233: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3234: $privileged{$domain} = {};
3235: if (keys(%dompersonnel)) {
3236: foreach my $server (keys(%dompersonnel)) {
3237: if (ref($dompersonnel{$server}) eq 'HASH') {
3238: foreach my $user (keys(%{$dompersonnel{$server}})) {
3239: my ($trole,$uname,$udom) = split(/:/,$user);
3240: $privileged{$udom}{$uname} = $trole;
3241: }
3242: }
3243: }
3244: }
3245: }
3246: if (exists($privileged{$domain}{$username})) {
3247: if (!$nothide{$username.':'.$domain}) {
3248: next;
3249: }
3250: }
1.937 raeburn 3251: }
3252: }
1.933 raeburn 3253: if ($withsec) {
3254: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3255: $tstart.':'.$tend;
3256: } else {
3257: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3258: }
1.832 raeburn 3259: }
1.373 www 3260: return %returnhash;
1.399 www 3261: }
3262:
3263: # ----------------------------------------------------- Frontpage Announcements
3264: #
3265: #
3266:
3267: sub postannounce {
3268: my ($server,$text)=@_;
1.844 albertel 3269: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3270: unless ($text=~/\w/) { $text=''; }
3271: return &reply('setannounce:'.&escape($text),$server);
3272: }
3273:
3274: sub getannounce {
1.448 albertel 3275:
3276: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3277: my $announcement='';
1.800 albertel 3278: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3279: close($fh);
1.399 www 3280: if ($announcement=~/\w/) {
3281: return
3282: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3283: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3284: } else {
3285: return '';
3286: }
3287: } else {
3288: return '';
3289: }
1.351 www 3290: }
1.353 www 3291:
3292: # ---------------------------------------------------------- Course ID routines
3293: # Deal with domain's nohist_courseid.db files
3294: #
3295:
3296: sub courseidput {
1.921 raeburn 3297: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3298: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3299: my $outcome;
3300: if ($caller eq 'timeonly') {
3301: my $cids = '';
3302: foreach my $item (keys(%$storehash)) {
3303: $cids.=&escape($item).'&';
3304: }
3305: $cids=~s/\&$//;
3306: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3307: $coursehome);
3308: } else {
3309: my $items = '';
3310: foreach my $item (keys(%$storehash)) {
3311: $items.= &escape($item).'='.
3312: &freeze_escape($$storehash{$item}).'&';
3313: }
3314: $items=~s/\&$//;
3315: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3316: $coursehome);
1.918 raeburn 3317: }
3318: if ($outcome eq 'unknown_cmd') {
3319: my $what;
3320: foreach my $cid (keys(%$storehash)) {
3321: $what .= &escape($cid).'=';
1.921 raeburn 3322: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3323: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3324: }
3325: $what =~ s/\:$/&/;
3326: }
3327: $what =~ s/\&$//;
3328: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3329: } else {
3330: return $outcome;
3331: }
1.353 www 3332: }
3333:
3334: sub courseiddump {
1.921 raeburn 3335: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3336: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3337: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 3338: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3339: my $as_hash = 1;
3340: my %returnhash;
3341: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3342: my %libserv = &all_library();
3343: foreach my $tryserver (keys(%libserv)) {
3344: if ( ( $hostidflag == 1
3345: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3346: || (!defined($hostidflag)) ) {
3347:
1.918 raeburn 3348: if (($domfilter eq '') ||
3349: (&host_domain($tryserver) eq $domfilter)) {
3350: my $rep =
3351: &reply('courseiddump:'.&host_domain($tryserver).':'.
3352: $sincefilter.':'.&escape($descfilter).':'.
3353: &escape($instcodefilter).':'.&escape($ownerfilter).
3354: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3355: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3356: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3357: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3358: &escape($cc_clone).':'.$cloneonly.':'.
3359: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071 raeburn 3360: &escape($creationcontext).':'.$domcloner,
3361: $tryserver);
1.918 raeburn 3362: my @pairs=split(/\&/,$rep);
3363: foreach my $item (@pairs) {
3364: my ($key,$value)=split(/\=/,$item,2);
3365: $key = &unescape($key);
3366: next if ($key =~ /^error: 2 /);
3367: my $result = &thaw_unescape($value);
3368: if (ref($result) eq 'HASH') {
3369: $returnhash{$key}=$result;
3370: } else {
1.921 raeburn 3371: my @responses = split(/:/,$value);
3372: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3373: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3374: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3375: }
1.1008 raeburn 3376: }
1.353 www 3377: }
3378: }
3379: }
3380: }
3381: return %returnhash;
3382: }
3383:
1.1055 raeburn 3384: sub courselastaccess {
3385: my ($cdom,$cnum,$hostidref) = @_;
3386: my %returnhash;
3387: if ($cdom && $cnum) {
3388: my $chome = &homeserver($cnum,$cdom);
3389: if ($chome ne 'no_host') {
3390: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3391: &extract_lastaccess(\%returnhash,$rep);
3392: }
3393: } else {
3394: if (!$cdom) { $cdom=''; }
3395: my %libserv = &all_library();
3396: foreach my $tryserver (keys(%libserv)) {
3397: if (ref($hostidref) eq 'ARRAY') {
3398: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3399: }
3400: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3401: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3402: &extract_lastaccess(\%returnhash,$rep);
3403: }
3404: }
3405: }
3406: return %returnhash;
3407: }
3408:
3409: sub extract_lastaccess {
3410: my ($returnhash,$rep) = @_;
3411: if (ref($returnhash) eq 'HASH') {
3412: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3413: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3414: $rep eq '') {
3415: my @pairs=split(/\&/,$rep);
3416: foreach my $item (@pairs) {
3417: my ($key,$value)=split(/\=/,$item,2);
3418: $key = &unescape($key);
3419: next if ($key =~ /^error: 2 /);
3420: $returnhash->{$key} = &thaw_unescape($value);
3421: }
3422: }
3423: }
3424: return;
3425: }
3426:
1.658 raeburn 3427: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3428:
3429: sub dcmailput {
1.685 raeburn 3430: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3431: my $status = &Apache::lonnet::critical(
1.740 www 3432: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3433: &escape($message),$server);
1.662 raeburn 3434: return $status;
3435: }
3436:
1.658 raeburn 3437: sub dcmaildump {
3438: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3439: my %returnhash=();
1.846 albertel 3440:
3441: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3442: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3443: &escape($enddate).':';
3444: my @esc_senders=map { &escape($_)} @$senders;
3445: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3446: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3447: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3448: if (($key) && ($value)) {
3449: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3450: }
3451: }
3452: }
3453: return %returnhash;
3454: }
1.662 raeburn 3455: # ---------------------------------------------------------- Domain roles
3456:
3457: sub get_domain_roles {
3458: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3459: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3460: $startdate = '.';
3461: }
1.1018 raeburn 3462: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3463: $enddate = '.';
3464: }
1.922 raeburn 3465: my $rolelist;
3466: if (ref($roles) eq 'ARRAY') {
3467: $rolelist = join(':',@{$roles});
3468: }
1.662 raeburn 3469: my %personnel = ();
1.841 albertel 3470:
3471: my %servers = &get_servers($dom,'library');
3472: foreach my $tryserver (keys(%servers)) {
3473: %{$personnel{$tryserver}}=();
3474: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3475: &escape($startdate).':'.
3476: &escape($enddate).':'.
3477: &escape($rolelist), $tryserver))) {
3478: my ($key,$value) = split(/\=/,$line,2);
3479: if (($key) && ($value)) {
3480: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3481: }
3482: }
1.662 raeburn 3483: }
3484: return %personnel;
3485: }
1.658 raeburn 3486:
1.1057 www 3487: # ----------------------------------------------------------- Interval timing
1.149 www 3488:
1.504 albertel 3489: sub get_first_access {
3490: my ($type,$argsymb)=@_;
1.790 albertel 3491: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3492: if ($argsymb) { $symb=$argsymb; }
3493: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3494: if ($type eq 'course') {
3495: $res='course';
3496: } elsif ($type eq 'map') {
1.588 albertel 3497: $res=&symbread($map);
3498: } else {
3499: $res=$symb;
3500: }
3501: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3502: return $times{"$courseid\0$res"};
1.504 albertel 3503: }
3504:
3505: sub set_first_access {
3506: my ($type)=@_;
1.790 albertel 3507: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3508: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3509: if ($type eq 'course') {
3510: $res='course';
3511: } elsif ($type eq 'map') {
1.588 albertel 3512: $res=&symbread($map);
3513: } else {
3514: $res=$symb;
3515: }
3516: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3517: if (!$firstaccess) {
1.588 albertel 3518: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3519: }
3520: return 'already_set';
1.504 albertel 3521: }
3522:
1.110 www 3523: # --------------------------------------------- Set Expire Date for Spreadsheet
3524:
3525: sub expirespread {
3526: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3527: my $cid=$env{'request.course.id'};
1.110 www 3528: if ($cid) {
3529: my $now=time;
3530: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3531: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3532: $env{'course.'.$cid.'.num'}.
1.110 www 3533: ':nohist_expirationdates:'.
3534: &escape($key).'='.$now,
1.620 albertel 3535: $env{'course.'.$cid.'.home'})
1.110 www 3536: }
3537: return 'ok';
1.14 www 3538: }
3539:
1.109 www 3540: # ----------------------------------------------------- Devalidate Spreadsheets
3541:
3542: sub devalidate {
1.325 www 3543: my ($symb,$uname,$udom)=@_;
1.620 albertel 3544: my $cid=$env{'request.course.id'};
1.109 www 3545: if ($cid) {
1.391 matthew 3546: # delete the stored spreadsheets for
3547: # - the student level sheet of this user in course's homespace
3548: # - the assessment level sheet for this resource
3549: # for this user in user's homespace
1.553 albertel 3550: # - current conditional state info
1.325 www 3551: my $key=$uname.':'.$udom.':';
1.109 www 3552: my $status=
1.299 matthew 3553: &del('nohist_calculatedsheets',
1.391 matthew 3554: [$key.'studentcalc:'],
1.620 albertel 3555: $env{'course.'.$cid.'.domain'},
3556: $env{'course.'.$cid.'.num'})
1.133 albertel 3557: .' '.
3558: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3559: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3560: unless ($status eq 'ok ok') {
3561: &logthis('Could not devalidate spreadsheet '.
1.325 www 3562: $uname.' at '.$udom.' for '.
1.109 www 3563: $symb.': '.$status);
1.133 albertel 3564: }
1.553 albertel 3565: &delenv('user.state.'.$cid);
1.109 www 3566: }
3567: }
3568:
1.265 albertel 3569: sub get_scalar {
3570: my ($string,$end) = @_;
3571: my $value;
3572: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3573: $value = $1;
3574: } elsif ($$string =~ s/^([^&]*?)&//) {
3575: $value = $1;
3576: }
3577: return &unescape($value);
3578: }
3579:
3580: sub array2str {
3581: my (@array) = @_;
3582: my $result=&arrayref2str(\@array);
3583: $result=~s/^__ARRAY_REF__//;
3584: $result=~s/__END_ARRAY_REF__$//;
3585: return $result;
3586: }
3587:
1.204 albertel 3588: sub arrayref2str {
3589: my ($arrayref) = @_;
1.265 albertel 3590: my $result='__ARRAY_REF__';
1.204 albertel 3591: foreach my $elem (@$arrayref) {
1.265 albertel 3592: if(ref($elem) eq 'ARRAY') {
3593: $result.=&arrayref2str($elem).'&';
3594: } elsif(ref($elem) eq 'HASH') {
3595: $result.=&hashref2str($elem).'&';
3596: } elsif(ref($elem)) {
3597: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3598: } else {
3599: $result.=&escape($elem).'&';
3600: }
3601: }
3602: $result=~s/\&$//;
1.265 albertel 3603: $result .= '__END_ARRAY_REF__';
1.204 albertel 3604: return $result;
3605: }
3606:
1.168 albertel 3607: sub hash2str {
1.204 albertel 3608: my (%hash) = @_;
3609: my $result=&hashref2str(\%hash);
1.265 albertel 3610: $result=~s/^__HASH_REF__//;
3611: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3612: return $result;
3613: }
3614:
3615: sub hashref2str {
3616: my ($hashref)=@_;
1.265 albertel 3617: my $result='__HASH_REF__';
1.800 albertel 3618: foreach my $key (sort(keys(%$hashref))) {
3619: if (ref($key) eq 'ARRAY') {
3620: $result.=&arrayref2str($key).'=';
3621: } elsif (ref($key) eq 'HASH') {
3622: $result.=&hashref2str($key).'=';
3623: } elsif (ref($key)) {
1.265 albertel 3624: $result.='=';
1.800 albertel 3625: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3626: } else {
1.800 albertel 3627: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3628: }
3629:
1.800 albertel 3630: if(ref($hashref->{$key}) eq 'ARRAY') {
3631: $result.=&arrayref2str($hashref->{$key}).'&';
3632: } elsif(ref($hashref->{$key}) eq 'HASH') {
3633: $result.=&hashref2str($hashref->{$key}).'&';
3634: } elsif(ref($hashref->{$key})) {
1.265 albertel 3635: $result.='&';
1.800 albertel 3636: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3637: } else {
1.800 albertel 3638: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3639: }
3640: }
1.168 albertel 3641: $result=~s/\&$//;
1.265 albertel 3642: $result .= '__END_HASH_REF__';
1.168 albertel 3643: return $result;
3644: }
3645:
3646: sub str2hash {
1.265 albertel 3647: my ($string)=@_;
3648: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3649: return %$hash;
3650: }
3651:
3652: sub str2hashref {
1.168 albertel 3653: my ($string) = @_;
1.265 albertel 3654:
3655: my %hash;
3656:
3657: if($string !~ /^__HASH_REF__/) {
3658: if (! ($string eq '' || !defined($string))) {
3659: $hash{'error'}='Not hash reference';
3660: }
3661: return (\%hash, $string);
3662: }
3663:
3664: $string =~ s/^__HASH_REF__//;
3665:
3666: while($string !~ /^__END_HASH_REF__/) {
3667: #key
3668: my $key='';
3669: if($string =~ /^__HASH_REF__/) {
3670: ($key, $string)=&str2hashref($string);
3671: if(defined($key->{'error'})) {
3672: $hash{'error'}='Bad data';
3673: return (\%hash, $string);
3674: }
3675: } elsif($string =~ /^__ARRAY_REF__/) {
3676: ($key, $string)=&str2arrayref($string);
3677: if($key->[0] eq 'Array reference error') {
3678: $hash{'error'}='Bad data';
3679: return (\%hash, $string);
3680: }
3681: } else {
3682: $string =~ s/^(.*?)=//;
1.267 albertel 3683: $key=&unescape($1);
1.265 albertel 3684: }
3685: $string =~ s/^=//;
3686:
3687: #value
3688: my $value='';
3689: if($string =~ /^__HASH_REF__/) {
3690: ($value, $string)=&str2hashref($string);
3691: if(defined($value->{'error'})) {
3692: $hash{'error'}='Bad data';
3693: return (\%hash, $string);
3694: }
3695: } elsif($string =~ /^__ARRAY_REF__/) {
3696: ($value, $string)=&str2arrayref($string);
3697: if($value->[0] eq 'Array reference error') {
3698: $hash{'error'}='Bad data';
3699: return (\%hash, $string);
3700: }
3701: } else {
3702: $value=&get_scalar(\$string,'__END_HASH_REF__');
3703: }
3704: $string =~ s/^&//;
3705:
3706: $hash{$key}=$value;
1.204 albertel 3707: }
1.265 albertel 3708:
3709: $string =~ s/^__END_HASH_REF__//;
3710:
3711: return (\%hash, $string);
1.204 albertel 3712: }
3713:
3714: sub str2array {
1.265 albertel 3715: my ($string)=@_;
3716: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3717: return @$array;
3718: }
3719:
3720: sub str2arrayref {
1.204 albertel 3721: my ($string) = @_;
1.265 albertel 3722: my @array;
3723:
3724: if($string !~ /^__ARRAY_REF__/) {
3725: if (! ($string eq '' || !defined($string))) {
3726: $array[0]='Array reference error';
3727: }
3728: return (\@array, $string);
3729: }
3730:
3731: $string =~ s/^__ARRAY_REF__//;
3732:
3733: while($string !~ /^__END_ARRAY_REF__/) {
3734: my $value='';
3735: if($string =~ /^__HASH_REF__/) {
3736: ($value, $string)=&str2hashref($string);
3737: if(defined($value->{'error'})) {
3738: $array[0] ='Array reference error';
3739: return (\@array, $string);
3740: }
3741: } elsif($string =~ /^__ARRAY_REF__/) {
3742: ($value, $string)=&str2arrayref($string);
3743: if($value->[0] eq 'Array reference error') {
3744: $array[0] ='Array reference error';
3745: return (\@array, $string);
3746: }
3747: } else {
3748: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3749: }
3750: $string =~ s/^&//;
3751:
3752: push(@array, $value);
1.191 harris41 3753: }
1.265 albertel 3754:
3755: $string =~ s/^__END_ARRAY_REF__//;
3756:
3757: return (\@array, $string);
1.168 albertel 3758: }
3759:
1.167 albertel 3760: # -------------------------------------------------------------------Temp Store
3761:
1.168 albertel 3762: sub tmpreset {
3763: my ($symb,$namespace,$domain,$stuname) = @_;
3764: if (!$symb) {
3765: $symb=&symbread();
1.620 albertel 3766: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3767: }
3768: $symb=escape($symb);
3769:
1.620 albertel 3770: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3771: $namespace=~s/\//\_/g;
3772: $namespace=~s/\W//g;
3773:
1.620 albertel 3774: if (!$domain) { $domain=$env{'user.domain'}; }
3775: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3776: if ($domain eq 'public' && $stuname eq 'public') {
3777: $stuname=$ENV{'REMOTE_ADDR'};
3778: }
1.1117 ! foxr 3779: my $path=LONCAPA::tempdir();
1.168 albertel 3780: my %hash;
3781: if (tie(%hash,'GDBM_File',
3782: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3783: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 3784: foreach my $key (keys(%hash)) {
1.180 albertel 3785: if ($key=~ /:$symb/) {
1.168 albertel 3786: delete($hash{$key});
3787: }
3788: }
3789: }
3790: }
3791:
1.167 albertel 3792: sub tmpstore {
1.168 albertel 3793: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3794:
3795: if (!$symb) {
3796: $symb=&symbread();
1.620 albertel 3797: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3798: }
3799: $symb=escape($symb);
3800:
3801: if (!$namespace) {
3802: # I don't think we would ever want to store this for a course.
3803: # it seems this will only be used if we don't have a course.
1.620 albertel 3804: #$namespace=$env{'request.course.id'};
1.168 albertel 3805: #if (!$namespace) {
1.620 albertel 3806: $namespace=$env{'request.state'};
1.168 albertel 3807: #}
3808: }
3809: $namespace=~s/\//\_/g;
3810: $namespace=~s/\W//g;
1.620 albertel 3811: if (!$domain) { $domain=$env{'user.domain'}; }
3812: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3813: if ($domain eq 'public' && $stuname eq 'public') {
3814: $stuname=$ENV{'REMOTE_ADDR'};
3815: }
1.168 albertel 3816: my $now=time;
3817: my %hash;
1.1117 ! foxr 3818: my $path=LONCAPA::tempdir();
1.168 albertel 3819: if (tie(%hash,'GDBM_File',
3820: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3821: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3822: $hash{"version:$symb"}++;
3823: my $version=$hash{"version:$symb"};
3824: my $allkeys='';
3825: foreach my $key (keys(%$storehash)) {
3826: $allkeys.=$key.':';
1.591 albertel 3827: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3828: }
3829: $hash{"$version:$symb:timestamp"}=$now;
3830: $allkeys.='timestamp';
3831: $hash{"$version:keys:$symb"}=$allkeys;
3832: if (untie(%hash)) {
3833: return 'ok';
3834: } else {
3835: return "error:$!";
3836: }
3837: } else {
3838: return "error:$!";
3839: }
3840: }
1.167 albertel 3841:
1.168 albertel 3842: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3843:
1.168 albertel 3844: sub tmprestore {
3845: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3846:
1.168 albertel 3847: if (!$symb) {
3848: $symb=&symbread();
1.620 albertel 3849: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3850: }
3851: $symb=escape($symb);
3852:
1.620 albertel 3853: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3854:
1.620 albertel 3855: if (!$domain) { $domain=$env{'user.domain'}; }
3856: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3857: if ($domain eq 'public' && $stuname eq 'public') {
3858: $stuname=$ENV{'REMOTE_ADDR'};
3859: }
1.168 albertel 3860: my %returnhash;
3861: $namespace=~s/\//\_/g;
3862: $namespace=~s/\W//g;
3863: my %hash;
1.1117 ! foxr 3864: my $path=LONCAPA::tempdir();
1.168 albertel 3865: if (tie(%hash,'GDBM_File',
3866: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3867: &GDBM_READER(),0640)) {
1.168 albertel 3868: my $version=$hash{"version:$symb"};
3869: $returnhash{'version'}=$version;
3870: my $scope;
3871: for ($scope=1;$scope<=$version;$scope++) {
3872: my $vkeys=$hash{"$scope:keys:$symb"};
3873: my @keys=split(/:/,$vkeys);
3874: my $key;
3875: $returnhash{"$scope:keys"}=$vkeys;
3876: foreach $key (@keys) {
1.591 albertel 3877: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3878: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3879: }
3880: }
1.168 albertel 3881: if (!(untie(%hash))) {
3882: return "error:$!";
3883: }
3884: } else {
3885: return "error:$!";
3886: }
3887: return %returnhash;
1.167 albertel 3888: }
3889:
1.9 www 3890: # ----------------------------------------------------------------------- Store
3891:
3892: sub store {
1.124 www 3893: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3894: my $home='';
3895:
1.168 albertel 3896: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3897:
1.213 www 3898: $symb=&symbclean($symb);
1.122 albertel 3899: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3900:
1.620 albertel 3901: if (!$domain) { $domain=$env{'user.domain'}; }
3902: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3903:
3904: &devalidate($symb,$stuname,$domain);
1.109 www 3905:
3906: $symb=escape($symb);
1.187 www 3907: if (!$namespace) {
1.620 albertel 3908: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3909: return '';
3910: }
3911: }
1.620 albertel 3912: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3913:
3914: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3915: $$storehash{'host'}=$perlvar{'lonHostID'};
3916:
1.12 www 3917: my $namevalue='';
1.800 albertel 3918: foreach my $key (keys(%$storehash)) {
3919: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3920: }
1.12 www 3921: $namevalue=~s/\&$//;
1.187 www 3922: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3923: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3924: }
3925:
1.47 www 3926: # -------------------------------------------------------------- Critical Store
3927:
3928: sub cstore {
1.124 www 3929: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3930: my $home='';
3931:
1.168 albertel 3932: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3933:
1.213 www 3934: $symb=&symbclean($symb);
1.122 albertel 3935: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3936:
1.620 albertel 3937: if (!$domain) { $domain=$env{'user.domain'}; }
3938: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3939:
3940: &devalidate($symb,$stuname,$domain);
1.109 www 3941:
3942: $symb=escape($symb);
1.187 www 3943: if (!$namespace) {
1.620 albertel 3944: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3945: return '';
3946: }
3947: }
1.620 albertel 3948: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3949:
3950: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3951: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3952:
1.47 www 3953: my $namevalue='';
1.800 albertel 3954: foreach my $key (keys(%$storehash)) {
3955: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3956: }
1.47 www 3957: $namevalue=~s/\&$//;
1.187 www 3958: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3959: return critical
3960: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3961: }
3962:
1.9 www 3963: # --------------------------------------------------------------------- Restore
3964:
3965: sub restore {
1.124 www 3966: my ($symb,$namespace,$domain,$stuname) = @_;
3967: my $home='';
3968:
1.168 albertel 3969: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3970:
1.122 albertel 3971: if (!$symb) {
3972: unless ($symb=escape(&symbread())) { return ''; }
3973: } else {
1.213 www 3974: $symb=&escape(&symbclean($symb));
1.122 albertel 3975: }
1.188 www 3976: if (!$namespace) {
1.620 albertel 3977: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3978: return '';
3979: }
3980: }
1.620 albertel 3981: if (!$domain) { $domain=$env{'user.domain'}; }
3982: if (!$stuname) { $stuname=$env{'user.name'}; }
3983: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3984: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3985:
1.12 www 3986: my %returnhash=();
1.800 albertel 3987: foreach my $line (split(/\&/,$answer)) {
3988: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3989: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3990: }
1.75 www 3991: my $version;
3992: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3993: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3994: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3995: }
1.75 www 3996: }
1.13 www 3997: return %returnhash;
1.34 www 3998: }
3999:
4000: # ---------------------------------------------------------- Course Description
4001:
4002: sub coursedescription {
1.731 albertel 4003: my ($courseid,$args)=@_;
1.34 www 4004: $courseid=~s/^\///;
1.49 www 4005: $courseid=~s/\_/\//g;
1.34 www 4006: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4007: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4008: my $normalid=$cdomain.'_'.$cnum;
4009: # need to always cache even if we get errors otherwise we keep
4010: # trying and trying and trying to get the course description.
4011: my %envhash=();
4012: my %returnhash=();
1.731 albertel 4013:
4014: my $expiretime=600;
4015: if ($env{'request.course.id'} eq $normalid) {
4016: $expiretime=120;
4017: }
4018:
4019: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4020: if (!$args->{'freshen_cache'}
4021: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4022: foreach my $key (keys(%env)) {
4023: next if ($key !~ /^\Q$prefix\E(.*)/);
4024: my ($setting) = $1;
4025: $returnhash{$setting} = $env{$key};
4026: }
4027: return %returnhash;
4028: }
4029:
4030: # get the data agin
4031: if (!$args->{'one_time'}) {
4032: $envhash{'course.'.$normalid.'.last_cache'}=time;
4033: }
1.811 albertel 4034:
1.34 www 4035: if ($chome ne 'no_host') {
1.302 albertel 4036: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4037: if (!exists($returnhash{'con_lost'})) {
4038: $returnhash{'home'}= $chome;
4039: $returnhash{'domain'} = $cdomain;
4040: $returnhash{'num'} = $cnum;
1.741 raeburn 4041: if (!defined($returnhash{'type'})) {
4042: $returnhash{'type'} = 'Course';
4043: }
1.130 albertel 4044: while (my ($name,$value) = each %returnhash) {
1.53 www 4045: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4046: }
1.270 www 4047: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 ! foxr 4048: $returnhash{'fn'}=LONCAPA::tempdir() .
1.620 albertel 4049: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 4050: $envhash{'course.'.$normalid.'.home'}=$chome;
4051: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4052: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4053: }
4054: }
1.731 albertel 4055: if (!$args->{'one_time'}) {
1.949 raeburn 4056: &appenv(\%envhash);
1.731 albertel 4057: }
1.302 albertel 4058: return %returnhash;
1.461 www 4059: }
4060:
1.1080 raeburn 4061: sub update_released_required {
4062: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4063: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4064: $cid = $env{'request.course.id'};
4065: $cdom = $env{'course.'.$cid.'.domain'};
4066: $cnum = $env{'course.'.$cid.'.num'};
4067: $chome = $env{'course.'.$cid.'.home'};
4068: }
4069: if ($needsrelease) {
4070: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4071: my $needsupdate;
4072: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4073: $needsupdate = 1;
4074: } else {
4075: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4076: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4077: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4078: $needsupdate = 1;
4079: }
4080: }
4081: if ($needsupdate) {
4082: my %needshash = (
4083: 'internal.releaserequired' => $needsrelease,
4084: );
4085: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4086: if ($putresult eq 'ok') {
4087: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4088: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4089: if (ref($crsinfo{$cid}) eq 'HASH') {
4090: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4091: &courseidput($cdom,\%crsinfo,$chome,'notime');
4092: }
4093: }
4094: }
4095: }
4096: return;
4097: }
4098:
1.461 www 4099: # -------------------------------------------------See if a user is privileged
4100:
4101: sub privileged {
4102: my ($username,$domain)=@_;
4103: my $rolesdump=&reply("dump:$domain:$username:roles",
4104: &homeserver($username,$domain));
1.1033 raeburn 4105: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4106: ($rolesdump =~ /^error:/)) {
4107: return 0;
4108: }
1.461 www 4109: my $now=time;
4110: if ($rolesdump ne '') {
1.800 albertel 4111: foreach my $entry (split(/&/,$rolesdump)) {
4112: if ($entry!~/^rolesdef_/) {
4113: my ($area,$role)=split(/=/,$entry);
1.461 www 4114: $area=~s/\_\w\w$//;
4115: my ($trole,$tend,$tstart)=split(/_/,$role);
4116: if (($trole eq 'dc') || ($trole eq 'su')) {
4117: my $active=1;
4118: if ($tend) {
4119: if ($tend<$now) { $active=0; }
4120: }
4121: if ($tstart) {
4122: if ($tstart>$now) { $active=0; }
4123: }
4124: if ($active) { return 1; }
4125: }
4126: }
4127: }
4128: }
4129: return 0;
1.9 www 4130: }
1.1 albertel 4131:
1.103 harris41 4132: # -------------------------------------------------------- Get user privileges
1.11 www 4133:
4134: sub rolesinit {
4135: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 4136: my $now=time;
4137: my %userroles = ('user.login.time' => $now);
1.1086 raeburn 4138: my $extra = &freeze_escape({'skipcheck' => 1});
1.1078 raeburn 4139: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033 raeburn 4140: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
1.1078 raeburn 4141: ($rolesdump =~ /^error:/)) {
1.1033 raeburn 4142: return \%userroles;
4143: }
1.11 www 4144: my %allroles=();
1.678 raeburn 4145: my %allgroups=();
1.11 www 4146:
4147: if ($rolesdump ne '') {
1.800 albertel 4148: foreach my $entry (split(/&/,$rolesdump)) {
4149: if ($entry!~/^rolesdef_/) {
4150: my ($area,$role)=split(/=/,$entry);
1.587 albertel 4151: $area=~s/\_\w\w$//;
1.678 raeburn 4152: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 4153: if ($role=~/^cr/) {
1.807 albertel 4154: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4155: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 4156: ($tend,$tstart)=split('_',$trest);
4157: } else {
4158: $trole=$role;
4159: }
1.678 raeburn 4160: } elsif ($role =~ m|^gr/|) {
4161: ($trole,$tend,$tstart) = split(/_/,$role);
1.1104 raeburn 4162: next if ($tstart eq '-1');
1.678 raeburn 4163: ($trole,$group_privs) = split(/\//,$trole);
4164: $group_privs = &unescape($group_privs);
1.587 albertel 4165: } else {
4166: ($trole,$tend,$tstart)=split(/_/,$role);
4167: }
1.743 albertel 4168: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4169: $username);
4170: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 4171: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4172: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 4173: if (($area ne '') && ($trole ne '')) {
1.347 albertel 4174: my $spec=$trole.'.'.$area;
4175: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4176: if ($trole =~ /^cr\//) {
1.567 raeburn 4177: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 4178: } elsif ($trole eq 'gr') {
4179: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 4180: } else {
1.567 raeburn 4181: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 4182: }
1.12 www 4183: }
1.662 raeburn 4184: }
1.191 harris41 4185: }
1.743 albertel 4186: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4187: $userroles{'user.adv'} = $adv;
4188: $userroles{'user.author'} = $author;
1.620 albertel 4189: $env{'user.adv'}=$adv;
1.11 www 4190: }
1.743 albertel 4191: return \%userroles;
1.11 www 4192: }
4193:
1.567 raeburn 4194: sub set_arearole {
4195: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4196: # log the associated role with the area
4197: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4198: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4199: }
4200:
4201: sub custom_roleprivs {
4202: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4203: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4204: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4205: if (&hostname($homsvr) ne '') {
1.567 raeburn 4206: my ($rdummy,$roledef)=
4207: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4208: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4209: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4210: if (defined($syspriv)) {
1.1043 raeburn 4211: if ($trest =~ /^$match_community$/) {
4212: $syspriv =~ s/bre\&S//;
4213: }
1.567 raeburn 4214: $$allroles{'cm./'}.=':'.$syspriv;
4215: $$allroles{$spec.'./'}.=':'.$syspriv;
4216: }
4217: if ($tdomain ne '') {
4218: if (defined($dompriv)) {
4219: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4220: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4221: }
4222: if (($trest ne '') && (defined($coursepriv))) {
4223: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4224: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4225: }
4226: }
4227: }
4228: }
4229: }
4230:
1.678 raeburn 4231: sub group_roleprivs {
4232: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4233: my $access = 1;
4234: my $now = time;
4235: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4236: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4237: if ($access) {
1.811 albertel 4238: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4239: $$allgroups{$course}{$group} .=':'.$group_privs;
4240: }
4241: }
1.567 raeburn 4242:
4243: sub standard_roleprivs {
4244: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4245: if (defined($pr{$trole.':s'})) {
4246: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4247: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4248: }
4249: if ($tdomain ne '') {
4250: if (defined($pr{$trole.':d'})) {
4251: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4252: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4253: }
4254: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4255: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4256: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4257: }
4258: }
4259: }
4260:
4261: sub set_userprivs {
1.1064 raeburn 4262: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4263: my $author=0;
4264: my $adv=0;
1.678 raeburn 4265: my %grouproles = ();
4266: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 4267: my @groupkeys;
1.1000 raeburn 4268: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 4269: push(@groupkeys,$role);
4270: }
4271: if (ref($groups_roles) eq 'HASH') {
4272: foreach my $key (keys(%{$groups_roles})) {
4273: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4274: push(@groupkeys,$key);
4275: }
4276: }
4277: }
4278: if (@groupkeys > 0) {
4279: foreach my $role (@groupkeys) {
4280: my ($trole,$area,$sec,$extendedarea);
4281: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4282: $trole = $1;
4283: $area = $2;
4284: $sec = $3;
4285: $extendedarea = $area.$sec;
4286: if (exists($$allgroups{$area})) {
4287: foreach my $group (keys(%{$$allgroups{$area}})) {
4288: my $spec = $trole.'.'.$extendedarea;
4289: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4290: $$allgroups{$area}{$group};
1.1064 raeburn 4291: }
1.678 raeburn 4292: }
4293: }
4294: }
4295: }
4296: }
1.800 albertel 4297: foreach my $group (keys(%grouproles)) {
4298: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4299: }
1.800 albertel 4300: foreach my $role (keys(%{$allroles})) {
4301: my %thesepriv;
1.941 raeburn 4302: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4303: foreach my $item (split(/:/,$$allroles{$role})) {
4304: if ($item ne '') {
4305: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4306: if ($restrictions eq '') {
4307: $thesepriv{$privilege}='F';
4308: } elsif ($thesepriv{$privilege} ne 'F') {
4309: $thesepriv{$privilege}.=$restrictions;
4310: }
4311: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4312: }
4313: }
4314: my $thesestr='';
1.1104 raeburn 4315: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 4316: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4317: }
4318: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4319: }
4320: return ($author,$adv);
4321: }
4322:
1.994 raeburn 4323: sub role_status {
1.1104 raeburn 4324: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4325: my @pwhere = ();
4326: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4327: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4328: unless (!defined($$role) || $$role eq '') {
4329: $$where=join('.',@pwhere);
4330: $$trolecode=$$role.'.'.$$where;
4331: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4332: $$tstatus='is';
1.1104 raeburn 4333: if ($$tstart && $$tstart>$update) {
1.994 raeburn 4334: $$tstatus='future';
1.1034 raeburn 4335: if ($$tstart<$now) {
4336: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4337: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 4338: my (%allroles,%allgroups,$group_privs,
4339: %groups_roles,@rolecodes);
1.1002 raeburn 4340: my %userroles = (
4341: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4342: );
1.1064 raeburn 4343: @rolecodes = ('cm');
1.1002 raeburn 4344: my $spec=$$role.'.'.$$where;
4345: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4346: if ($$role =~ /^cr\//) {
4347: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 4348: push(@rolecodes,'cr');
1.1002 raeburn 4349: } elsif ($$role eq 'gr') {
1.1064 raeburn 4350: push(@rolecodes,$$role);
1.1002 raeburn 4351: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4352: $env{'user.name'});
1.1064 raeburn 4353: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4354: (undef,my $group_privs) = split(/\//,$trole);
4355: $group_privs = &unescape($group_privs);
4356: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 4357: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
1.1104 raeburn 4358: &get_groups_roles($tdomain,$trest,
4359: \%course_roles,\@rolecodes,
4360: \%groups_roles);
1.1002 raeburn 4361: } else {
1.1064 raeburn 4362: push(@rolecodes,$$role);
1.1002 raeburn 4363: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4364: }
1.1064 raeburn 4365: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4366: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4367: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4368: }
4369: }
1.1034 raeburn 4370: $$tstatus = 'is';
1.1002 raeburn 4371: }
1.994 raeburn 4372: }
4373: if ($$tend) {
1.1104 raeburn 4374: if ($$tend<$update) {
1.994 raeburn 4375: $$tstatus='expired';
4376: } elsif ($$tend<$now) {
4377: $$tstatus='will_not';
4378: }
4379: }
4380: }
4381: }
4382: }
4383:
1.1104 raeburn 4384: sub get_groups_roles {
4385: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
4386: return unless((ref($cdom_courseroles) eq 'HASH') &&
4387: (ref($rolecodes) eq 'ARRAY') &&
4388: (ref($groups_roles) eq 'HASH'));
4389: if (keys(%{$cdom_courseroles}) > 0) {
4390: my ($cnum) = ($rest =~ /^($match_courseid)/);
4391: if ($cdom ne '' && $cnum ne '') {
4392: foreach my $key (keys(%{$cdom_courseroles})) {
4393: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
4394: my $crsrole = $1;
4395: my $crssec = $2;
4396: if ($crsrole =~ /^cr/) {
4397: unless (grep(/^cr$/,@{$rolecodes})) {
4398: push(@{$rolecodes},'cr');
4399: }
4400: } else {
4401: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
4402: push(@{$rolecodes},$crsrole);
4403: }
4404: }
4405: my $rolekey = "$crsrole./$cdom/$cnum";
4406: if ($crssec ne '') {
4407: $rolekey .= "/$crssec";
4408: }
4409: $rolekey .= './';
4410: $groups_roles->{$rolekey} = $rolecodes;
4411: }
4412: }
4413: }
4414: }
4415: return;
4416: }
4417:
4418: sub delete_env_groupprivs {
4419: my ($where,$courseroles,$possroles) = @_;
4420: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
4421: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
4422: unless (ref($courseroles->{$udom}) eq 'HASH') {
4423: %{$courseroles->{$udom}} =
4424: &get_my_roles('','','userroles',['active'],
4425: $possroles,[$udom],1);
4426: }
4427: if (ref($courseroles->{$udom}) eq 'HASH') {
4428: foreach my $item (keys(%{$courseroles->{$udom}})) {
4429: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
4430: my $area = '/'.$cdom.'/'.$cnum;
4431: my $privkey = "user.priv.$crsrole.$area";
4432: if ($crssec ne '') {
4433: $privkey .= '/'.$crssec;
4434: }
4435: $privkey .= ".$area/$group";
4436: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
4437: }
4438: }
4439: return;
4440: }
4441:
1.994 raeburn 4442: sub check_adhoc_privs {
1.1104 raeburn 4443: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 4444: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4445: if ($env{$cckey}) {
4446: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 4447: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4448: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 4449: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4450: }
4451: } else {
1.1088 raeburn 4452: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4453: }
4454: }
4455:
4456: sub set_adhoc_privileges {
4457: # role can be cc or ca
1.1088 raeburn 4458: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 4459: my $area = '/'.$dcdom.'/'.$pickedcourse;
4460: my $spec = $role.'.'.$area;
4461: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4462: $env{'user.name'});
4463: my %ccrole = ();
4464: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4465: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4466: &appenv(\%userroles,[$role,'cm']);
4467: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 4468: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
4469: &appenv( {'request.role' => $spec,
4470: 'request.role.domain' => $dcdom,
4471: 'request.course.sec' => ''
4472: }
4473: );
4474: my $tadv=0;
4475: if (&allowed('adv') eq 'F') { $tadv=1; }
4476: &appenv({'request.role.adv' => $tadv});
4477: }
1.994 raeburn 4478: }
4479:
1.12 www 4480: # --------------------------------------------------------------- get interface
4481:
4482: sub get {
1.131 albertel 4483: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4484: my $items='';
1.800 albertel 4485: foreach my $item (@$storearr) {
4486: $items.=&escape($item).'&';
1.191 harris41 4487: }
1.12 www 4488: $items=~s/\&$//;
1.620 albertel 4489: if (!$udomain) { $udomain=$env{'user.domain'}; }
4490: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4491: my $uhome=&homeserver($uname,$udomain);
4492:
1.133 albertel 4493: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4494: my @pairs=split(/\&/,$rep);
1.273 albertel 4495: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4496: return @pairs;
4497: }
1.15 www 4498: my %returnhash=();
1.42 www 4499: my $i=0;
1.800 albertel 4500: foreach my $item (@$storearr) {
4501: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4502: $i++;
1.191 harris41 4503: }
1.15 www 4504: return %returnhash;
1.27 www 4505: }
4506:
4507: # --------------------------------------------------------------- del interface
4508:
4509: sub del {
1.133 albertel 4510: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4511: my $items='';
1.800 albertel 4512: foreach my $item (@$storearr) {
4513: $items.=&escape($item).'&';
1.191 harris41 4514: }
1.984 neumanie 4515:
1.27 www 4516: $items=~s/\&$//;
1.620 albertel 4517: if (!$udomain) { $udomain=$env{'user.domain'}; }
4518: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4519: my $uhome=&homeserver($uname,$udomain);
4520: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4521: }
4522:
4523: # -------------------------------------------------------------- dump interface
4524:
4525: sub dump {
1.1086 raeburn 4526: my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755 albertel 4527: if (!$udomain) { $udomain=$env{'user.domain'}; }
4528: if (!$uname) { $uname=$env{'user.name'}; }
4529: my $uhome=&homeserver($uname,$udomain);
4530: if ($regexp) {
4531: $regexp=&escape($regexp);
4532: } else {
4533: $regexp='.';
4534: }
1.1086 raeburn 4535: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755 albertel 4536: my @pairs=split(/\&/,$rep);
4537: my %returnhash=();
1.1098 foxr 4538: if (!($rep =~ /^error/ )) {
4539: foreach my $item (@pairs) {
4540: my ($key,$value)=split(/=/,$item,2);
4541: $key = &unescape($key);
4542: next if ($key =~ /^error: 2 /);
4543: $returnhash{$key}=&thaw_unescape($value);
4544: }
1.755 albertel 4545: }
4546: return %returnhash;
1.407 www 4547: }
4548:
1.1098 foxr 4549:
1.717 albertel 4550: # --------------------------------------------------------- dumpstore interface
4551:
4552: sub dumpstore {
4553: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4554: if (!$udomain) { $udomain=$env{'user.domain'}; }
4555: if (!$uname) { $uname=$env{'user.name'}; }
4556: my $uhome=&homeserver($uname,$udomain);
4557: if ($regexp) {
4558: $regexp=&escape($regexp);
4559: } else {
4560: $regexp='.';
4561: }
4562: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4563: my @pairs=split(/\&/,$rep);
4564: my %returnhash=();
4565: foreach my $item (@pairs) {
4566: my ($key,$value)=split(/=/,$item,2);
4567: next if ($key =~ /^error: 2 /);
4568: $returnhash{$key}=&thaw_unescape($value);
4569: }
4570: return %returnhash;
1.717 albertel 4571: }
4572:
1.407 www 4573: # -------------------------------------------------------------- keys interface
4574:
4575: sub getkeys {
4576: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4577: if (!$udomain) { $udomain=$env{'user.domain'}; }
4578: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4579: my $uhome=&homeserver($uname,$udomain);
4580: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4581: my @keyarray=();
1.800 albertel 4582: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4583: next if ($key =~ /^error: 2 /);
1.800 albertel 4584: push(@keyarray,&unescape($key));
1.407 www 4585: }
4586: return @keyarray;
1.318 matthew 4587: }
4588:
1.319 matthew 4589: # --------------------------------------------------------------- currentdump
4590: sub currentdump {
1.328 matthew 4591: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4592: $courseid = $env{'request.course.id'} if (! defined($courseid));
4593: $sdom = $env{'user.domain'} if (! defined($sdom));
4594: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4595: my $uhome = &homeserver($sname,$sdom);
4596: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4597: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4598: #
1.318 matthew 4599: my %returnhash=();
1.319 matthew 4600: #
4601: if ($rep eq "unknown_cmd") {
4602: # an old lond will not know currentdump
4603: # Do a dump and make it look like a currentdump
1.822 albertel 4604: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4605: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4606: my %hash = @tmp;
4607: @tmp=();
1.424 matthew 4608: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4609: } else {
4610: my @pairs=split(/\&/,$rep);
1.800 albertel 4611: foreach my $pair (@pairs) {
4612: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4613: my ($symb,$param) = split(/:/,$key);
4614: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4615: &thaw_unescape($value);
1.319 matthew 4616: }
1.191 harris41 4617: }
1.12 www 4618: return %returnhash;
1.424 matthew 4619: }
4620:
4621: sub convert_dump_to_currentdump{
4622: my %hash = %{shift()};
4623: my %returnhash;
4624: # Code ripped from lond, essentially. The only difference
4625: # here is the unescaping done by lonnet::dump(). Conceivably
4626: # we might run in to problems with parameter names =~ /^v\./
4627: while (my ($key,$value) = each(%hash)) {
4628: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4629: $symb = &unescape($symb);
4630: $param = &unescape($param);
1.424 matthew 4631: next if ($v eq 'version' || $symb eq 'keys');
4632: next if (exists($returnhash{$symb}) &&
4633: exists($returnhash{$symb}->{$param}) &&
4634: $returnhash{$symb}->{'v.'.$param} > $v);
4635: $returnhash{$symb}->{$param}=$value;
4636: $returnhash{$symb}->{'v.'.$param}=$v;
4637: }
4638: #
4639: # Remove all of the keys in the hashes which keep track of
4640: # the version of the parameter.
4641: while (my ($symb,$param_hash) = each(%returnhash)) {
4642: # use a foreach because we are going to delete from the hash.
4643: foreach my $key (keys(%$param_hash)) {
4644: delete($param_hash->{$key}) if ($key =~ /^v\./);
4645: }
4646: }
4647: return \%returnhash;
1.12 www 4648: }
4649:
1.627 albertel 4650: # ------------------------------------------------------ critical inc interface
4651:
4652: sub cinc {
4653: return &inc(@_,'critical');
4654: }
4655:
1.449 matthew 4656: # --------------------------------------------------------------- inc interface
4657:
4658: sub inc {
1.627 albertel 4659: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4660: if (!$udomain) { $udomain=$env{'user.domain'}; }
4661: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4662: my $uhome=&homeserver($uname,$udomain);
4663: my $items='';
4664: if (! ref($store)) {
4665: # got a single value, so use that instead
4666: $items = &escape($store).'=&';
4667: } elsif (ref($store) eq 'SCALAR') {
4668: $items = &escape($$store).'=&';
4669: } elsif (ref($store) eq 'ARRAY') {
4670: $items = join('=&',map {&escape($_);} @{$store});
4671: } elsif (ref($store) eq 'HASH') {
4672: while (my($key,$value) = each(%{$store})) {
4673: $items.= &escape($key).'='.&escape($value).'&';
4674: }
4675: }
4676: $items=~s/\&$//;
1.627 albertel 4677: if ($critical) {
4678: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4679: } else {
4680: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4681: }
1.449 matthew 4682: }
4683:
1.12 www 4684: # --------------------------------------------------------------- put interface
4685:
4686: sub put {
1.134 albertel 4687: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4688: if (!$udomain) { $udomain=$env{'user.domain'}; }
4689: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4690: my $uhome=&homeserver($uname,$udomain);
1.12 www 4691: my $items='';
1.800 albertel 4692: foreach my $item (keys(%$storehash)) {
4693: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4694: }
1.12 www 4695: $items=~s/\&$//;
1.134 albertel 4696: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4697: }
4698:
1.631 albertel 4699: # ------------------------------------------------------------ newput interface
4700:
4701: sub newput {
4702: my ($namespace,$storehash,$udomain,$uname)=@_;
4703: if (!$udomain) { $udomain=$env{'user.domain'}; }
4704: if (!$uname) { $uname=$env{'user.name'}; }
4705: my $uhome=&homeserver($uname,$udomain);
4706: my $items='';
4707: foreach my $key (keys(%$storehash)) {
4708: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4709: }
4710: $items=~s/\&$//;
4711: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4712: }
4713:
4714: # --------------------------------------------------------- putstore interface
4715:
1.524 raeburn 4716: sub putstore {
1.715 albertel 4717: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4718: if (!$udomain) { $udomain=$env{'user.domain'}; }
4719: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4720: my $uhome=&homeserver($uname,$udomain);
4721: my $items='';
1.715 albertel 4722: foreach my $key (keys(%$storehash)) {
4723: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4724: }
1.715 albertel 4725: $items=~s/\&$//;
1.716 albertel 4726: my $esc_symb=&escape($symb);
4727: my $esc_v=&escape($version);
1.715 albertel 4728: my $reply =
1.716 albertel 4729: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4730: $uhome);
4731: if ($reply eq 'unknown_cmd') {
1.716 albertel 4732: # gfall back to way things use to be done
1.715 albertel 4733: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4734: $uname);
1.524 raeburn 4735: }
1.715 albertel 4736: return $reply;
4737: }
4738:
4739: sub old_putstore {
1.716 albertel 4740: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4741: if (!$udomain) { $udomain=$env{'user.domain'}; }
4742: if (!$uname) { $uname=$env{'user.name'}; }
4743: my $uhome=&homeserver($uname,$udomain);
4744: my %newstorehash;
1.800 albertel 4745: foreach my $item (keys(%$storehash)) {
4746: my $key = $version.':'.&escape($symb).':'.$item;
4747: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4748: }
4749: my $items='';
4750: my %allitems = ();
1.800 albertel 4751: foreach my $item (keys(%newstorehash)) {
4752: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4753: my $key = $1.':keys:'.$2;
4754: $allitems{$key} .= $3.':';
4755: }
1.800 albertel 4756: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4757: }
1.800 albertel 4758: foreach my $item (keys(%allitems)) {
4759: $allitems{$item} =~ s/\:$//;
4760: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4761: }
4762: $items=~s/\&$//;
4763: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4764: }
4765:
1.47 www 4766: # ------------------------------------------------------ critical put interface
4767:
4768: sub cput {
1.134 albertel 4769: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4770: if (!$udomain) { $udomain=$env{'user.domain'}; }
4771: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4772: my $uhome=&homeserver($uname,$udomain);
1.47 www 4773: my $items='';
1.800 albertel 4774: foreach my $item (keys(%$storehash)) {
4775: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4776: }
1.47 www 4777: $items=~s/\&$//;
1.134 albertel 4778: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4779: }
4780:
4781: # -------------------------------------------------------------- eget interface
4782:
4783: sub eget {
1.133 albertel 4784: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4785: my $items='';
1.800 albertel 4786: foreach my $item (@$storearr) {
4787: $items.=&escape($item).'&';
1.191 harris41 4788: }
1.12 www 4789: $items=~s/\&$//;
1.620 albertel 4790: if (!$udomain) { $udomain=$env{'user.domain'}; }
4791: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4792: my $uhome=&homeserver($uname,$udomain);
4793: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4794: my @pairs=split(/\&/,$rep);
4795: my %returnhash=();
1.42 www 4796: my $i=0;
1.800 albertel 4797: foreach my $item (@$storearr) {
4798: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4799: $i++;
1.191 harris41 4800: }
1.12 www 4801: return %returnhash;
4802: }
4803:
1.667 albertel 4804: # ------------------------------------------------------------ tmpput interface
4805: sub tmpput {
1.802 raeburn 4806: my ($storehash,$server,$context)=@_;
1.667 albertel 4807: my $items='';
1.800 albertel 4808: foreach my $item (keys(%$storehash)) {
4809: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4810: }
4811: $items=~s/\&$//;
1.802 raeburn 4812: if (defined($context)) {
4813: $items .= ':'.&escape($context);
4814: }
1.667 albertel 4815: return &reply("tmpput:$items",$server);
4816: }
4817:
4818: # ------------------------------------------------------------ tmpget interface
4819: sub tmpget {
1.688 albertel 4820: my ($token,$server)=@_;
4821: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4822: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4823: my %returnhash;
4824: foreach my $item (split(/\&/,$rep)) {
4825: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4826: next if ($key =~ /^error: 2 /);
1.667 albertel 4827: $returnhash{&unescape($key)}=&thaw_unescape($value);
4828: }
4829: return %returnhash;
4830: }
4831:
1.1113 raeburn 4832: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 4833: sub tmpdel {
4834: my ($token,$server)=@_;
4835: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4836: return &reply("tmpdel:$token",$server);
4837: }
4838:
1.765 albertel 4839: # -------------------------------------------------- portfolio access checking
4840:
4841: sub portfolio_access {
1.766 albertel 4842: my ($requrl) = @_;
1.765 albertel 4843: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4844: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4845: if ($result) {
4846: my %setters;
4847: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4848: my ($startblock,$endblock) =
4849: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4850: if ($startblock && $endblock) {
4851: return 'B';
4852: }
4853: } else {
4854: my ($startblock,$endblock) =
4855: &Apache::loncommon::blockcheck(\%setters,'port');
4856: if ($startblock && $endblock) {
4857: return 'B';
4858: }
4859: }
4860: }
1.765 albertel 4861: if ($result eq 'ok') {
1.766 albertel 4862: return 'F';
1.765 albertel 4863: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4864: return 'A';
1.765 albertel 4865: }
1.766 albertel 4866: return '';
1.765 albertel 4867: }
4868:
4869: sub get_portfolio_access {
1.767 albertel 4870: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4871:
4872: if (!ref($access_hash)) {
4873: my $current_perms = &get_portfile_permissions($udom,$unum);
4874: my %access_controls = &get_access_controls($current_perms,$group,
4875: $file_name);
4876: $access_hash = $access_controls{$file_name};
4877: }
4878:
1.765 albertel 4879: my ($public,$guest,@domains,@users,@courses,@groups);
4880: my $now = time;
4881: if (ref($access_hash) eq 'HASH') {
4882: foreach my $key (keys(%{$access_hash})) {
4883: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4884: if ($start > $now) {
4885: next;
4886: }
4887: if ($end && $end<$now) {
4888: next;
4889: }
4890: if ($scope eq 'public') {
4891: $public = $key;
4892: last;
4893: } elsif ($scope eq 'guest') {
4894: $guest = $key;
4895: } elsif ($scope eq 'domains') {
4896: push(@domains,$key);
4897: } elsif ($scope eq 'users') {
4898: push(@users,$key);
4899: } elsif ($scope eq 'course') {
4900: push(@courses,$key);
4901: } elsif ($scope eq 'group') {
4902: push(@groups,$key);
4903: }
4904: }
4905: if ($public) {
4906: return 'ok';
4907: }
4908: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4909: if ($guest) {
4910: return $guest;
4911: }
4912: } else {
4913: if (@domains > 0) {
4914: foreach my $domkey (@domains) {
4915: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4916: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4917: return 'ok';
4918: }
4919: }
4920: }
4921: }
4922: if (@users > 0) {
4923: foreach my $userkey (@users) {
1.865 raeburn 4924: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4925: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4926: if (ref($item) eq 'HASH') {
4927: if (($item->{'uname'} eq $env{'user.name'}) &&
4928: ($item->{'udom'} eq $env{'user.domain'})) {
4929: return 'ok';
4930: }
4931: }
4932: }
4933: }
1.765 albertel 4934: }
4935: }
4936: my %roleshash;
4937: my @courses_and_groups = @courses;
4938: push(@courses_and_groups,@groups);
4939: if (@courses_and_groups > 0) {
4940: my (%allgroups,%allroles);
4941: my ($start,$end,$role,$sec,$group);
4942: foreach my $envkey (%env) {
1.1060 raeburn 4943: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4944: my $cid = $2.'_'.$3;
4945: if ($1 eq 'gr') {
4946: $group = $4;
4947: $allgroups{$cid}{$group} = $env{$envkey};
4948: } else {
4949: if ($4 eq '') {
4950: $sec = 'none';
4951: } else {
4952: $sec = $4;
4953: }
4954: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4955: }
1.811 albertel 4956: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4957: my $cid = $2.'_'.$3;
4958: if ($4 eq '') {
4959: $sec = 'none';
4960: } else {
4961: $sec = $4;
4962: }
4963: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4964: }
4965: }
4966: if (keys(%allroles) == 0) {
4967: return;
4968: }
4969: foreach my $key (@courses_and_groups) {
4970: my %content = %{$$access_hash{$key}};
4971: my $cnum = $content{'number'};
4972: my $cdom = $content{'domain'};
4973: my $cid = $cdom.'_'.$cnum;
4974: if (!exists($allroles{$cid})) {
4975: next;
4976: }
4977: foreach my $role_id (keys(%{$content{'roles'}})) {
4978: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4979: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4980: my @status = @{$content{'roles'}{$role_id}{'access'}};
4981: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4982: foreach my $role (keys(%{$allroles{$cid}})) {
4983: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4984: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4985: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4986: if (grep/^all$/,@sections) {
4987: return 'ok';
4988: } else {
4989: if (grep/^$sec$/,@sections) {
4990: return 'ok';
4991: }
4992: }
4993: }
4994: }
4995: if (keys(%{$allgroups{$cid}}) == 0) {
4996: if (grep/^none$/,@groups) {
4997: return 'ok';
4998: }
4999: } else {
5000: if (grep/^all$/,@groups) {
5001: return 'ok';
5002: }
5003: foreach my $group (keys(%{$allgroups{$cid}})) {
5004: if (grep/^$group$/,@groups) {
5005: return 'ok';
5006: }
5007: }
5008: }
5009: }
5010: }
5011: }
5012: }
5013: }
5014: if ($guest) {
5015: return $guest;
5016: }
5017: }
5018: }
5019: return;
5020: }
5021:
5022: sub course_group_datechecker {
5023: my ($dates,$now,$status) = @_;
5024: my ($start,$end) = split(/\./,$dates);
5025: if (!$start && !$end) {
5026: return 'ok';
5027: }
5028: if (grep/^active$/,@{$status}) {
5029: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5030: return 'ok';
5031: }
5032: }
5033: if (grep/^previous$/,@{$status}) {
5034: if ($end > $now ) {
5035: return 'ok';
5036: }
5037: }
5038: if (grep/^future$/,@{$status}) {
5039: if ($start > $now) {
5040: return 'ok';
5041: }
5042: }
5043: return;
5044: }
5045:
5046: sub parse_portfolio_url {
5047: my ($url) = @_;
5048:
5049: my ($type,$udom,$unum,$group,$file_name);
5050:
1.823 albertel 5051: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 5052: $type = 1;
5053: $udom = $1;
5054: $unum = $2;
5055: $file_name = $3;
1.823 albertel 5056: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 5057: $type = 2;
5058: $udom = $1;
5059: $unum = $2;
5060: $group = $3;
5061: $file_name = $3.'/'.$4;
5062: }
5063: if (wantarray) {
5064: return ($type,$udom,$unum,$file_name,$group);
5065: }
5066: return $type;
5067: }
5068:
5069: sub is_portfolio_url {
5070: my ($url) = @_;
5071: return scalar(&parse_portfolio_url($url));
5072: }
5073:
1.798 raeburn 5074: sub is_portfolio_file {
5075: my ($file) = @_;
1.820 raeburn 5076: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 5077: return 1;
5078: }
5079: return;
5080: }
5081:
1.976 raeburn 5082: sub usertools_access {
1.1084 raeburn 5083: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 5084: my ($access,%tools);
5085: if ($context eq '') {
5086: $context = 'tools';
5087: }
5088: if ($context eq 'requestcourses') {
5089: %tools = (
5090: official => 1,
5091: unofficial => 1,
1.1006 raeburn 5092: community => 1,
1.985 raeburn 5093: );
5094: } else {
5095: %tools = (
5096: aboutme => 1,
5097: blog => 1,
5098: portfolio => 1,
5099: );
5100: }
1.976 raeburn 5101: return if (!defined($tools{$tool}));
5102:
5103: if ((!defined($udom)) || (!defined($uname))) {
5104: $udom = $env{'user.domain'};
5105: $uname = $env{'user.name'};
5106: }
5107:
1.978 raeburn 5108: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5109: if ($action ne 'reload') {
1.985 raeburn 5110: if ($context eq 'requestcourses') {
5111: return $env{'environment.canrequest.'.$tool};
5112: } else {
5113: return $env{'environment.availabletools.'.$tool};
5114: }
5115: }
1.976 raeburn 5116: }
5117:
5118: my ($toolstatus,$inststatus);
5119:
1.985 raeburn 5120: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5121: ($action ne 'reload')) {
5122: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 5123: $inststatus = $env{'environment.inststatus'};
5124: } else {
1.1084 raeburn 5125: if (ref($userenvref) eq 'HASH') {
5126: $toolstatus = $userenvref->{$context.'.'.$tool};
5127: $inststatus = $userenvref->{'inststatus'};
5128: } else {
5129: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5130: $toolstatus = $userenv{$context.'.'.$tool};
5131: $inststatus = $userenv{'inststatus'};
5132: }
1.976 raeburn 5133: }
5134:
5135: if ($toolstatus ne '') {
5136: if ($toolstatus) {
5137: $access = 1;
5138: } else {
5139: $access = 0;
5140: }
5141: return $access;
5142: }
5143:
1.1084 raeburn 5144: my ($is_adv,%domdef);
5145: if (ref($is_advref) eq 'HASH') {
5146: $is_adv = $is_advref->{'is_adv'};
5147: } else {
5148: $is_adv = &is_advanced_user($udom,$uname);
5149: }
5150: if (ref($domdefref) eq 'HASH') {
5151: %domdef = %{$domdefref};
5152: } else {
5153: %domdef = &get_domain_defaults($udom);
5154: }
1.976 raeburn 5155: if (ref($domdef{$tool}) eq 'HASH') {
5156: if ($is_adv) {
5157: if ($domdef{$tool}{'_LC_adv'} ne '') {
5158: if ($domdef{$tool}{'_LC_adv'}) {
5159: $access = 1;
5160: } else {
5161: $access = 0;
5162: }
5163: return $access;
5164: }
5165: }
5166: if ($inststatus ne '') {
5167: my ($hasaccess,$hasnoaccess);
5168: foreach my $affiliation (split(/:/,$inststatus)) {
5169: if ($domdef{$tool}{$affiliation} ne '') {
5170: if ($domdef{$tool}{$affiliation}) {
5171: $hasaccess = 1;
5172: } else {
5173: $hasnoaccess = 1;
5174: }
5175: }
5176: }
5177: if ($hasaccess || $hasnoaccess) {
5178: if ($hasaccess) {
5179: $access = 1;
5180: } elsif ($hasnoaccess) {
5181: $access = 0;
5182: }
5183: return $access;
5184: }
5185: } else {
5186: if ($domdef{$tool}{'default'} ne '') {
5187: if ($domdef{$tool}{'default'}) {
5188: $access = 1;
5189: } elsif ($domdef{$tool}{'default'} == 0) {
5190: $access = 0;
5191: }
5192: return $access;
5193: }
5194: }
5195: } else {
1.985 raeburn 5196: if ($context eq 'tools') {
5197: $access = 1;
5198: } else {
5199: $access = 0;
5200: }
1.976 raeburn 5201: return $access;
5202: }
5203: }
5204:
1.1050 raeburn 5205: sub is_course_owner {
5206: my ($cdom,$cnum,$udom,$uname) = @_;
5207: if (($udom eq '') || ($uname eq '')) {
5208: $udom = $env{'user.domain'};
5209: $uname = $env{'user.name'};
5210: }
5211: unless (($udom eq '') || ($uname eq '')) {
5212: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5213: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5214: return 1;
5215: } else {
5216: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5217: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5218: return 1;
5219: }
5220: }
5221: }
5222: }
5223: return;
5224: }
5225:
1.976 raeburn 5226: sub is_advanced_user {
5227: my ($udom,$uname) = @_;
1.1085 raeburn 5228: if ($udom ne '' && $uname ne '') {
5229: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5230: return $env{'user.adv'};
5231: }
5232: }
1.976 raeburn 5233: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5234: my %allroles;
5235: my $is_adv;
5236: foreach my $role (keys(%roleshash)) {
5237: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5238: my $area = '/'.$tdomain.'/'.$trest;
5239: if ($sec ne '') {
5240: $area .= '/'.$sec;
5241: }
5242: if (($area ne '') && ($trole ne '')) {
5243: my $spec=$trole.'.'.$area;
5244: if ($trole =~ /^cr\//) {
5245: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5246: } elsif ($trole ne 'gr') {
5247: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5248: }
5249: }
5250: }
5251: foreach my $role (keys(%allroles)) {
5252: last if ($is_adv);
5253: foreach my $item (split(/:/,$allroles{$role})) {
5254: if ($item ne '') {
5255: my ($privilege,$restrictions)=split(/&/,$item);
5256: if ($privilege eq 'adv') {
5257: $is_adv = 1;
5258: last;
5259: }
5260: }
5261: }
5262: }
5263: return $is_adv;
5264: }
1.798 raeburn 5265:
1.1035 raeburn 5266: sub check_can_request {
1.1036 raeburn 5267: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5268: my $canreq = 0;
5269: my ($types,$typename) = &Apache::loncommon::course_types();
5270: my @options = ('approval','validate','autolimit');
5271: my $optregex = join('|',@options);
5272: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5273: foreach my $type (@{$types}) {
5274: if (&usertools_access($env{'user.name'},
5275: $env{'user.domain'},
5276: $type,undef,'requestcourses')) {
5277: $canreq ++;
1.1036 raeburn 5278: if (ref($request_domains) eq 'HASH') {
5279: push(@{$request_domains->{$type}},$env{'user.domain'});
5280: }
1.1035 raeburn 5281: if ($dom eq $env{'user.domain'}) {
5282: $can_request->{$type} = 1;
5283: }
5284: }
5285: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5286: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5287: if (@curr > 0) {
1.1036 raeburn 5288: foreach my $item (@curr) {
5289: if (ref($request_domains) eq 'HASH') {
5290: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5291: if ($otherdom ne '') {
5292: if (ref($request_domains->{$type}) eq 'ARRAY') {
5293: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5294: push(@{$request_domains->{$type}},$otherdom);
5295: }
5296: } else {
5297: push(@{$request_domains->{$type}},$otherdom);
5298: }
5299: }
5300: }
5301: }
5302: unless($dom eq $env{'user.domain'}) {
5303: $canreq ++;
1.1035 raeburn 5304: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5305: $can_request->{$type} = 1;
5306: }
5307: }
5308: }
5309: }
5310: }
5311: }
5312: return $canreq;
5313: }
5314:
1.341 www 5315: # ---------------------------------------------- Custom access rule evaluation
5316:
5317: sub customaccess {
5318: my ($priv,$uri)=@_;
1.807 albertel 5319: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5320: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5321: $udom = &LONCAPA::clean_domain($udom);
5322: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5323: my $access=0;
1.800 albertel 5324: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5325: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5326: if ($type eq 'user') {
5327: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5328: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5329: if ($tdom) {
5330: if ($tdom ne $env{'user.domain'}) { next; }
5331: }
1.896 albertel 5332: if ($tuname) {
5333: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5334: }
5335: $access=($effect eq 'allow');
5336: last;
5337: }
5338: } else {
5339: if ($role) {
5340: if ($role ne $urole) { next; }
5341: }
5342: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5343: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5344: if ($tdom) {
5345: if ($tdom ne $udom) { next; }
5346: }
5347: if ($tcrs) {
5348: if ($tcrs ne $ucrs) { next; }
5349: }
5350: if ($tsec) {
5351: if ($tsec ne $usec) { next; }
5352: }
5353: $access=($effect eq 'allow');
5354: last;
5355: }
5356: if ($realm eq '' && $role eq '') {
5357: $access=($effect eq 'allow');
5358: }
1.402 bowersj2 5359: }
1.341 www 5360: }
5361: return $access;
5362: }
5363:
1.103 harris41 5364: # ------------------------------------------------- Check for a user privilege
1.12 www 5365:
5366: sub allowed {
1.810 raeburn 5367: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5368: my $ver_orguri=$uri;
1.439 www 5369: $uri=&deversion($uri);
1.152 www 5370: my $orguri=$uri;
1.52 www 5371: $uri=&declutter($uri);
1.809 raeburn 5372:
1.810 raeburn 5373: if ($priv eq 'evb') {
5374: # Evade communication block restrictions for specified role in a course
5375: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5376: return $1;
5377: } else {
5378: return;
5379: }
5380: }
5381:
1.620 albertel 5382: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5383: # Free bre access to adm and meta resources
1.775 albertel 5384: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5385: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5386: && ($priv eq 'bre')) {
1.14 www 5387: return 'F';
1.159 www 5388: }
5389:
1.545 banghart 5390: # Free bre access to user's own portfolio contents
1.714 raeburn 5391: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5392: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5393: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5394: my %setters;
5395: my ($startblock,$endblock) =
5396: &Apache::loncommon::blockcheck(\%setters,'port');
5397: if ($startblock && $endblock) {
5398: return 'B';
5399: } else {
5400: return 'F';
5401: }
1.545 banghart 5402: }
5403:
1.762 raeburn 5404: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5405: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5406: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5407: if (exists($env{'request.course.id'})) {
5408: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5409: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5410: if (($domain eq $cdom) && ($name eq $cnum)) {
5411: my $courseprivid=$env{'request.course.id'};
5412: $courseprivid=~s/\_/\//;
5413: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5414: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5415: return $1;
1.762 raeburn 5416: } else {
5417: if ($env{'request.course.sec'}) {
5418: $courseprivid.='/'.$env{'request.course.sec'};
5419: }
5420: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5421: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5422: return $2;
5423: }
1.714 raeburn 5424: }
5425: }
5426: }
5427: }
5428:
1.159 www 5429: # Free bre to public access
5430:
5431: if ($priv eq 'bre') {
1.238 www 5432: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5433: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5434: return 'F';
5435: }
1.238 www 5436: if ($copyright eq 'priv') {
5437: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5438: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5439: return '';
5440: }
5441: }
5442: if ($copyright eq 'domain') {
5443: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5444: unless (($env{'user.domain'} eq $1) ||
5445: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5446: return '';
5447: }
1.262 matthew 5448: }
1.620 albertel 5449: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5450: # Library role, so allow browsing of resources in this domain.
5451: return 'F';
1.238 www 5452: }
1.341 www 5453: if ($copyright eq 'custom') {
5454: unless (&customaccess($priv,$uri)) { return ''; }
5455: }
1.14 www 5456: }
1.264 matthew 5457: # Domain coordinator is trying to create a course
1.620 albertel 5458: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5459: # uri is the requested domain in this case.
5460: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5461: # a role of dc for the domain in question.
1.620 albertel 5462: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5463: }
1.29 www 5464:
1.52 www 5465: my $thisallowed='';
5466: my $statecond=0;
5467: my $courseprivid='';
5468:
1.1039 raeburn 5469: my $ownaccess;
1.1043 raeburn 5470: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5471: if (($priv eq 'bro') && ($env{'user.author'})) {
5472: if ($uri eq '') {
5473: $ownaccess = 1;
5474: } else {
5475: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5476: my $udom = $env{'user.domain'};
5477: my $uname = $env{'user.name'};
5478: if ($uri =~ m{^\Q$udom\E/?$}) {
5479: $ownaccess = 1;
1.1040 raeburn 5480: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5481: unless ($uri =~ m{\.\./}) {
5482: $ownaccess = 1;
5483: }
5484: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5485: my $now = time;
5486: if ($uri =~ m{^([^/]+)/?$}) {
5487: my $adom = $1;
5488: foreach my $key (keys(%env)) {
1.1042 raeburn 5489: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5490: my ($start,$end) = split('.',$env{$key});
5491: if (($now >= $start) && (!$end || $end < $now)) {
5492: $ownaccess = 1;
5493: last;
5494: }
5495: }
5496: }
5497: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5498: my $adom = $1;
5499: my $aname = $2;
1.1042 raeburn 5500: foreach my $role ('ca','aa') {
5501: if ($env{"user.role.$role./$adom/$aname"}) {
5502: my ($start,$end) =
5503: split('.',$env{"user.role.$role./$adom/$aname"});
5504: if (($now >= $start) && (!$end || $end < $now)) {
5505: $ownaccess = 1;
5506: last;
5507: }
1.1039 raeburn 5508: }
5509: }
5510: }
5511: }
5512: }
5513: }
5514: }
5515:
1.52 www 5516: # Course
5517:
1.620 albertel 5518: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5519: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5520: $thisallowed.=$1;
5521: }
1.52 www 5522: }
1.29 www 5523:
1.52 www 5524: # Domain
5525:
1.620 albertel 5526: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5527: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5528: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5529: $thisallowed.=$1;
5530: }
1.12 www 5531: }
1.52 www 5532:
5533: # Course: uri itself is a course
1.66 www 5534: my $courseuri=$uri;
5535: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5536: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5537:
1.620 albertel 5538: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5539: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5540: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5541: $thisallowed.=$1;
5542: }
1.12 www 5543: }
1.29 www 5544:
1.665 albertel 5545: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5546: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5547: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5548: $thisallowed='';
1.671 raeburn 5549: my ($match)=&is_on_map($uri);
5550: if ($match) {
5551: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5552: =~/\Q$priv\E\&([^\:]*)/) {
5553: $thisallowed.=$1;
5554: }
5555: } else {
1.705 albertel 5556: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5557: if ($refuri) {
5558: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5559: $thisallowed='F';
1.671 raeburn 5560: } else {
5561: $refuri=&declutter($refuri);
5562: my ($match) = &is_on_map($refuri);
5563: if ($match) {
5564: $thisallowed='F';
5565: }
1.669 raeburn 5566: }
1.671 raeburn 5567: }
5568: }
1.314 www 5569: }
1.492 albertel 5570:
1.766 albertel 5571: if ($priv eq 'bre'
5572: && $thisallowed ne 'F'
5573: && $thisallowed ne '2'
5574: && &is_portfolio_url($uri)) {
5575: $thisallowed = &portfolio_access($uri);
5576: }
5577:
1.52 www 5578: # Full access at system, domain or course-wide level? Exit.
1.29 www 5579: if ($thisallowed=~/F/) {
5580: return 'F';
5581: }
5582:
1.52 www 5583: # If this is generating or modifying users, exit with special codes
1.29 www 5584:
1.643 www 5585: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5586: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5587: my ($audom,$auname)=split('/',$uri);
1.643 www 5588: # no author name given, so this just checks on the general right to make a co-author in this domain
5589: unless ($auname) { return $thisallowed; }
5590: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5591: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5592: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5593: ($audom ne $env{'request.role.domain'}))) { return ''; }
5594: }
1.52 www 5595: return $thisallowed;
5596: }
5597: #
1.103 harris41 5598: # Gathered so far: system, domain and course wide privileges
1.52 www 5599: #
5600: # Course: See if uri or referer is an individual resource that is part of
5601: # the course
5602:
1.620 albertel 5603: if ($env{'request.course.id'}) {
1.232 www 5604:
1.620 albertel 5605: $courseprivid=$env{'request.course.id'};
5606: if ($env{'request.course.sec'}) {
5607: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5608: }
5609: $courseprivid=~s/\_/\//;
5610: my $checkreferer=1;
1.232 www 5611: my ($match,$cond)=&is_on_map($uri);
5612: if ($match) {
5613: $statecond=$cond;
1.620 albertel 5614: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5615: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5616: $thisallowed.=$1;
5617: $checkreferer=0;
5618: }
1.29 www 5619: }
1.83 www 5620:
1.148 www 5621: if ($checkreferer) {
1.620 albertel 5622: my $refuri=$env{'httpref.'.$orguri};
1.148 www 5623: unless ($refuri) {
1.800 albertel 5624: foreach my $key (keys(%env)) {
5625: if ($key=~/^httpref\..*\*/) {
5626: my $pattern=$key;
1.156 www 5627: $pattern=~s/^httpref\.\/res\///;
1.148 www 5628: $pattern=~s/\*/\[\^\/\]\+/g;
5629: $pattern=~s/\//\\\//g;
1.152 www 5630: if ($orguri=~/$pattern/) {
1.800 albertel 5631: $refuri=$env{$key};
1.148 www 5632: }
5633: }
1.191 harris41 5634: }
1.148 www 5635: }
1.232 www 5636:
1.148 www 5637: if ($refuri) {
1.152 www 5638: $refuri=&declutter($refuri);
1.232 www 5639: my ($match,$cond)=&is_on_map($refuri);
5640: if ($match) {
5641: my $refstatecond=$cond;
1.620 albertel 5642: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5643: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5644: $thisallowed.=$1;
1.53 www 5645: $uri=$refuri;
5646: $statecond=$refstatecond;
1.52 www 5647: }
5648: }
1.148 www 5649: }
1.29 www 5650: }
1.52 www 5651: }
1.29 www 5652:
1.52 www 5653: #
1.103 harris41 5654: # Gathered now: all privileges that could apply, and condition number
1.52 www 5655: #
5656: #
5657: # Full or no access?
5658: #
1.29 www 5659:
1.52 www 5660: if ($thisallowed=~/F/) {
5661: return 'F';
5662: }
1.29 www 5663:
1.52 www 5664: unless ($thisallowed) {
5665: return '';
5666: }
1.29 www 5667:
1.52 www 5668: # Restrictions exist, deal with them
5669: #
5670: # C:according to course preferences
5671: # R:according to resource settings
5672: # L:unless locked
5673: # X:according to user session state
5674: #
5675:
5676: # Possibly locked functionality, check all courses
1.54 www 5677: # Locks might take effect only after 10 minutes cache expiration for other
5678: # courses, and 2 minutes for current course
1.52 www 5679:
5680: my $envkey;
5681: if ($thisallowed=~/L/) {
1.1000 raeburn 5682: foreach $envkey (keys(%env)) {
1.54 www 5683: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5684: my $courseid=$2;
5685: my $roleid=$1.'.'.$2;
1.92 www 5686: $courseid=~s/^\///;
1.54 www 5687: my $expiretime=600;
1.620 albertel 5688: if ($env{'request.role'} eq $roleid) {
1.54 www 5689: $expiretime=120;
5690: }
5691: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5692: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 5693: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 5694: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 5695: }
1.620 albertel 5696: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5697: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5698: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5699: &log($env{'user.domain'},$env{'user.name'},
5700: $env{'user.home'},
1.57 www 5701: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 5702: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5703: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5704: return '';
5705: }
5706: }
1.620 albertel 5707: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5708: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5709: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5710: &log($env{'user.domain'},$env{'user.name'},
5711: $env{'user.home'},
1.57 www 5712: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 5713: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5714: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5715: return '';
5716: }
5717: }
5718: }
1.29 www 5719: }
1.52 www 5720: }
5721:
5722: #
5723: # Rest of the restrictions depend on selected course
5724: #
5725:
1.620 albertel 5726: unless ($env{'request.course.id'}) {
1.766 albertel 5727: if ($thisallowed eq 'A') {
5728: return 'A';
1.814 raeburn 5729: } elsif ($thisallowed eq 'B') {
5730: return 'B';
1.766 albertel 5731: } else {
5732: return '1';
5733: }
1.52 www 5734: }
1.29 www 5735:
1.52 www 5736: #
5737: # Now user is definitely in a course
5738: #
1.53 www 5739:
5740:
5741: # Course preferences
5742:
5743: if ($thisallowed=~/C/) {
1.620 albertel 5744: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5745: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5746: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 5747: =~/\Q$rolecode\E/) {
1.1103 raeburn 5748: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 5749: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5750: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5751: $env{'request.course.id'});
5752: }
1.237 www 5753: return '';
5754: }
5755:
1.620 albertel 5756: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 5757: =~/\Q$unamedom\E/) {
1.1103 raeburn 5758: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 5759: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5760: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5761: $env{'request.course.id'});
5762: }
1.54 www 5763: return '';
5764: }
1.53 www 5765: }
5766:
5767: # Resource preferences
5768:
5769: if ($thisallowed=~/R/) {
1.620 albertel 5770: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 5771: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 5772: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 5773: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5774: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5775: }
5776: return '';
1.54 www 5777: }
1.53 www 5778: }
1.30 www 5779:
1.246 www 5780: # Restricted by state or randomout?
1.30 www 5781:
1.52 www 5782: if ($thisallowed=~/X/) {
1.620 albertel 5783: if ($env{'acc.randomout'}) {
1.579 albertel 5784: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 5785: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 5786: return '';
5787: }
1.247 www 5788: }
5789: if (&condval($statecond)) {
1.52 www 5790: return '2';
5791: } else {
5792: return '';
5793: }
5794: }
1.30 www 5795:
1.766 albertel 5796: if ($thisallowed eq 'A') {
5797: return 'A';
1.814 raeburn 5798: } elsif ($thisallowed eq 'B') {
5799: return 'B';
1.766 albertel 5800: }
1.52 www 5801: return 'F';
1.232 www 5802: }
5803:
1.710 albertel 5804: sub split_uri_for_cond {
5805: my $uri=&deversion(&declutter(shift));
5806: my @uriparts=split(/\//,$uri);
5807: my $filename=pop(@uriparts);
5808: my $pathname=join('/',@uriparts);
5809: return ($pathname,$filename);
5810: }
1.232 www 5811: # --------------------------------------------------- Is a resource on the map?
5812:
5813: sub is_on_map {
1.710 albertel 5814: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5815: #Trying to find the conditional for the file
1.620 albertel 5816: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5817: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5818: if ($match) {
1.289 bowersj2 5819: return (1,$1);
5820: } else {
1.434 www 5821: return (0,0);
1.289 bowersj2 5822: }
1.12 www 5823: }
5824:
1.427 www 5825: # --------------------------------------------------------- Get symb from alias
5826:
5827: sub get_symb_from_alias {
5828: my $symb=shift;
5829: my ($map,$resid,$url)=&decode_symb($symb);
5830: # Already is a symb
5831: if ($url) { return $symb; }
5832: # Must be an alias
5833: my $aliassymb='';
5834: my %bighash;
1.620 albertel 5835: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5836: &GDBM_READER(),0640)) {
5837: my $rid=$bighash{'mapalias_'.$symb};
5838: if ($rid) {
5839: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5840: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5841: $resid,$bighash{'src_'.$rid});
1.427 www 5842: }
5843: untie %bighash;
5844: }
5845: return $aliassymb;
5846: }
5847:
1.12 www 5848: # ----------------------------------------------------------------- Define Role
5849:
5850: sub definerole {
5851: if (allowed('mcr','/')) {
5852: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5853: foreach my $role (split(':',$sysrole)) {
5854: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5855: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5856: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5857: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5858: return "refused:s:$crole&$cqual";
5859: }
5860: }
1.191 harris41 5861: }
1.800 albertel 5862: foreach my $role (split(':',$domrole)) {
5863: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5864: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5865: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5866: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5867: return "refused:d:$crole&$cqual";
5868: }
5869: }
1.191 harris41 5870: }
1.800 albertel 5871: foreach my $role (split(':',$courole)) {
5872: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5873: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5874: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5875: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5876: return "refused:c:$crole&$cqual";
5877: }
5878: }
1.191 harris41 5879: }
1.620 albertel 5880: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5881: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5882: "rolesdef_$rolename=".
5883: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5884: return reply($command,$env{'user.home'});
1.12 www 5885: } else {
5886: return 'refused';
5887: }
1.105 harris41 5888: }
5889:
5890: # ---------------- Make a metadata query against the network of library servers
5891:
5892: sub metadata_query {
1.244 matthew 5893: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5894: my %rhash;
1.845 albertel 5895: my %libserv = &all_library();
1.244 matthew 5896: my @server_list = (defined($server_array) ? @$server_array
5897: : keys(%libserv) );
5898: for my $server (@server_list) {
1.118 harris41 5899: unless ($custom or $customshow) {
5900: my $reply=&reply("querysend:".&escape($query),$server);
5901: $rhash{$server}=$reply;
5902: }
5903: else {
5904: my $reply=&reply("querysend:".&escape($query).':'.
5905: &escape($custom).':'.&escape($customshow),
5906: $server);
5907: $rhash{$server}=$reply;
5908: }
1.112 harris41 5909: }
1.118 harris41 5910: return \%rhash;
1.240 www 5911: }
5912:
5913: # ----------------------------------------- Send log queries and wait for reply
5914:
5915: sub log_query {
5916: my ($uname,$udom,$query,%filters)=@_;
5917: my $uhome=&homeserver($uname,$udom);
5918: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5919: my $uhost=&hostname($uhome);
1.800 albertel 5920: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5921: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5922: $uhome);
1.479 albertel 5923: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5924: return get_query_reply($queryid);
5925: }
5926:
1.818 raeburn 5927: # -------------------------- Update MySQL table for portfolio file
5928:
5929: sub update_portfolio_table {
1.821 raeburn 5930: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5931: if ($group ne '') {
5932: $file_name =~s /^\Q$group\E//;
5933: }
1.818 raeburn 5934: my $homeserver = &homeserver($uname,$udom);
5935: my $queryid=
1.821 raeburn 5936: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5937: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5938: my $reply = &get_query_reply($queryid);
5939: return $reply;
5940: }
5941:
1.899 raeburn 5942: # -------------------------- Update MySQL allusers table
5943:
5944: sub update_allusers_table {
5945: my ($uname,$udom,$names) = @_;
5946: my $homeserver = &homeserver($uname,$udom);
5947: my $queryid=
5948: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5949: 'lastname='.&escape($names->{'lastname'}).'%%'.
5950: 'firstname='.&escape($names->{'firstname'}).'%%'.
5951: 'middlename='.&escape($names->{'middlename'}).'%%'.
5952: 'generation='.&escape($names->{'generation'}).'%%'.
5953: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5954: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 5955: return;
1.899 raeburn 5956: }
5957:
1.508 raeburn 5958: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5959:
5960: sub fetch_enrollment_query {
1.511 raeburn 5961: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5962: my $homeserver;
1.547 raeburn 5963: my $maxtries = 1;
1.508 raeburn 5964: if ($context eq 'automated') {
5965: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 5966: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 5967: } else {
5968: $homeserver = &homeserver($cnum,$dom);
5969: }
1.838 albertel 5970: my $host=&hostname($homeserver);
1.506 raeburn 5971: my $cmd = '';
1.1000 raeburn 5972: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 5973: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 5974: }
5975: $cmd =~ s/%%$//;
5976: $cmd = &escape($cmd);
5977: my $query = 'fetchenrollment';
1.620 albertel 5978: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 5979: unless ($queryid=~/^\Q$host\E\_/) {
5980: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5981: return 'error: '.$queryid;
5982: }
1.506 raeburn 5983: my $reply = &get_query_reply($queryid);
1.547 raeburn 5984: my $tries = 1;
5985: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5986: $reply = &get_query_reply($queryid);
5987: $tries ++;
5988: }
1.526 raeburn 5989: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 5990: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 5991: } else {
1.901 albertel 5992: my @responses = split(/:/,$reply);
1.515 raeburn 5993: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 5994: foreach my $line (@responses) {
5995: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 5996: $$replyref{$key} = $value;
5997: }
5998: } else {
1.1117 ! foxr 5999: my $pathname = LONCAPA::tempdir();
1.800 albertel 6000: foreach my $line (@responses) {
6001: my ($key,$value) = split(/=/,$line);
1.506 raeburn 6002: $$replyref{$key} = $value;
6003: if ($value > 0) {
1.800 albertel 6004: foreach my $item (@{$$affiliatesref{$key}}) {
6005: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 6006: my $destname = $pathname.'/'.$filename;
6007: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 6008: if ($xml_classlist =~ /^error/) {
6009: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6010: } else {
1.506 raeburn 6011: if ( open(FILE,">$destname") ) {
6012: print FILE &unescape($xml_classlist);
6013: close(FILE);
1.526 raeburn 6014: } else {
6015: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 6016: }
6017: }
6018: }
6019: }
6020: }
6021: }
6022: return 'ok';
6023: }
6024: return 'error';
6025: }
6026:
1.242 www 6027: sub get_query_reply {
6028: my $queryid=shift;
1.1117 ! foxr 6029: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 6030: my $reply='';
6031: for (1..100) {
6032: sleep 2;
6033: if (-e $replyfile.'.end') {
1.448 albertel 6034: if (open(my $fh,$replyfile)) {
1.904 albertel 6035: $reply = join('',<$fh>);
6036: close($fh);
1.240 www 6037: } else { return 'error: reply_file_error'; }
1.242 www 6038: return &unescape($reply);
6039: }
1.240 www 6040: }
1.242 www 6041: return 'timeout:'.$queryid;
1.240 www 6042: }
6043:
6044: sub courselog_query {
1.241 www 6045: #
6046: # possible filters:
6047: # url: url or symb
6048: # username
6049: # domain
6050: # action: view, submit, grade
6051: # start: timestamp
6052: # end: timestamp
6053: #
1.240 www 6054: my (%filters)=@_;
1.620 albertel 6055: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 6056: if ($filters{'url'}) {
6057: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6058: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6059: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6060: }
1.620 albertel 6061: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6062: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 6063: return &log_query($cname,$cdom,'courselog',%filters);
6064: }
6065:
6066: sub userlog_query {
1.858 raeburn 6067: #
6068: # possible filters:
6069: # action: log check role
6070: # start: timestamp
6071: # end: timestamp
6072: #
1.240 www 6073: my ($uname,$udom,%filters)=@_;
6074: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 6075: }
6076:
1.506 raeburn 6077: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6078:
6079: sub auto_run {
1.508 raeburn 6080: my ($cnum,$cdom) = @_;
1.876 raeburn 6081: my $response = 0;
6082: my $settings;
6083: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6084: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6085: $settings = $domconfig{'autoenroll'};
6086: if ($settings->{'run'} eq '1') {
6087: $response = 1;
6088: }
6089: } else {
1.934 raeburn 6090: my $homeserver;
6091: if (&is_course($cdom,$cnum)) {
6092: $homeserver = &homeserver($cnum,$cdom);
6093: } else {
6094: $homeserver = &domain($cdom,'primary');
6095: }
6096: if ($homeserver ne 'no_host') {
6097: $response = &reply('autorun:'.$cdom,$homeserver);
6098: }
1.876 raeburn 6099: }
1.506 raeburn 6100: return $response;
6101: }
1.776 albertel 6102:
1.506 raeburn 6103: sub auto_get_sections {
1.508 raeburn 6104: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 6105: my $homeserver;
6106: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6107: $homeserver = &homeserver($cnum,$cdom);
6108: }
6109: if (!defined($homeserver)) {
6110: if ($cdom =~ /^$match_domain$/) {
6111: $homeserver = &domain($cdom,'primary');
6112: }
6113: }
6114: my @secs;
6115: if (defined($homeserver)) {
6116: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6117: unless ($response eq 'refused') {
6118: @secs = split(/:/,$response);
6119: }
1.506 raeburn 6120: }
6121: return @secs;
6122: }
1.776 albertel 6123:
1.506 raeburn 6124: sub auto_new_course {
1.1099 raeburn 6125: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 6126: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 6127: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 6128: return $response;
6129: }
1.776 albertel 6130:
1.506 raeburn 6131: sub auto_validate_courseID {
1.508 raeburn 6132: my ($cnum,$cdom,$inst_course_id) = @_;
6133: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 6134: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 6135: return $response;
6136: }
1.776 albertel 6137:
1.1007 raeburn 6138: sub auto_validate_instcode {
1.1020 raeburn 6139: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 6140: my ($homeserver,$response);
6141: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6142: $homeserver = &homeserver($cnum,$cdom);
6143: }
6144: if (!defined($homeserver)) {
6145: if ($cdom =~ /^$match_domain$/) {
6146: $homeserver = &domain($cdom,'primary');
6147: }
6148: }
1.1065 raeburn 6149: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6150: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 6151: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6152: return ($outcome,$description);
1.1007 raeburn 6153: }
6154:
1.506 raeburn 6155: sub auto_create_password {
1.873 raeburn 6156: my ($cnum,$cdom,$authparam,$udom) = @_;
6157: my ($homeserver,$response);
1.506 raeburn 6158: my $create_passwd = 0;
6159: my $authchk = '';
1.873 raeburn 6160: if ($udom =~ /^$match_domain$/) {
6161: $homeserver = &domain($udom,'primary');
6162: }
6163: if ($homeserver eq '') {
6164: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6165: $homeserver = &homeserver($cnum,$cdom);
6166: }
6167: }
6168: if ($homeserver eq '') {
6169: $authchk = 'nodomain';
1.506 raeburn 6170: } else {
1.873 raeburn 6171: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6172: if ($response eq 'refused') {
6173: $authchk = 'refused';
6174: } else {
1.901 albertel 6175: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 6176: }
1.506 raeburn 6177: }
6178: return ($authparam,$create_passwd,$authchk);
6179: }
6180:
1.706 raeburn 6181: sub auto_photo_permission {
6182: my ($cnum,$cdom,$students) = @_;
6183: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 6184: my ($outcome,$perm_reqd,$conditions) =
6185: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 6186: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6187: return (undef,undef);
6188: }
1.706 raeburn 6189: return ($outcome,$perm_reqd,$conditions);
6190: }
6191:
6192: sub auto_checkphotos {
6193: my ($uname,$udom,$pid) = @_;
6194: my $homeserver = &homeserver($uname,$udom);
6195: my ($result,$resulttype);
6196: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 6197: &escape($uname).':'.&escape($pid),
6198: $homeserver));
1.709 albertel 6199: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6200: return (undef,undef);
6201: }
1.706 raeburn 6202: if ($outcome) {
6203: ($result,$resulttype) = split(/:/,$outcome);
6204: }
6205: return ($result,$resulttype);
6206: }
6207:
6208: sub auto_photochoice {
6209: my ($cnum,$cdom) = @_;
6210: my $homeserver = &homeserver($cnum,$cdom);
6211: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 6212: &escape($cdom),
6213: $homeserver)));
1.709 albertel 6214: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6215: return (undef,undef);
6216: }
1.706 raeburn 6217: return ($update,$comment);
6218: }
6219:
6220: sub auto_photoupdate {
6221: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6222: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 6223: my $host=&hostname($homeserver);
1.706 raeburn 6224: my $cmd = '';
6225: my $maxtries = 1;
1.800 albertel 6226: foreach my $affiliate (keys(%{$affiliatesref})) {
6227: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 6228: }
6229: $cmd =~ s/%%$//;
6230: $cmd = &escape($cmd);
6231: my $query = 'institutionalphotos';
6232: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6233: unless ($queryid=~/^\Q$host\E\_/) {
6234: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6235: return 'error: '.$queryid;
6236: }
6237: my $reply = &get_query_reply($queryid);
6238: my $tries = 1;
6239: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6240: $reply = &get_query_reply($queryid);
6241: $tries ++;
6242: }
6243: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6244: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6245: } else {
6246: my @responses = split(/:/,$reply);
6247: my $outcome = shift(@responses);
6248: foreach my $item (@responses) {
6249: my ($key,$value) = split(/=/,$item);
6250: $$photo{$key} = $value;
6251: }
6252: return $outcome;
6253: }
6254: return 'error';
6255: }
6256:
1.521 raeburn 6257: sub auto_instcode_format {
1.793 albertel 6258: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6259: $cat_order) = @_;
1.521 raeburn 6260: my $courses = '';
1.772 raeburn 6261: my @homeservers;
1.521 raeburn 6262: if ($caller eq 'global') {
1.841 albertel 6263: my %servers = &get_servers($codedom,'library');
6264: foreach my $tryserver (keys(%servers)) {
6265: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6266: push(@homeservers,$tryserver);
6267: }
1.584 raeburn 6268: }
1.1022 raeburn 6269: } elsif ($caller eq 'requests') {
6270: if ($codedom =~ /^$match_domain$/) {
6271: my $chome = &domain($codedom,'primary');
6272: unless ($chome eq 'no_host') {
6273: push(@homeservers,$chome);
6274: }
6275: }
1.521 raeburn 6276: } else {
1.772 raeburn 6277: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 6278: }
1.793 albertel 6279: foreach my $code (keys(%{$instcodes})) {
6280: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 6281: }
6282: chop($courses);
1.772 raeburn 6283: my $ok_response = 0;
6284: my $response;
6285: while (@homeservers > 0 && $ok_response == 0) {
6286: my $server = shift(@homeservers);
6287: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6288: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6289: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 6290: split(/:/,$response);
1.772 raeburn 6291: %{$codes} = (%{$codes},&str2hash($codes_str));
6292: push(@{$codetitles},&str2array($codetitles_str));
6293: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6294: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6295: $ok_response = 1;
6296: }
6297: }
6298: if ($ok_response) {
1.521 raeburn 6299: return 'ok';
1.772 raeburn 6300: } else {
6301: return $response;
1.521 raeburn 6302: }
6303: }
6304:
1.792 raeburn 6305: sub auto_instcode_defaults {
6306: my ($domain,$returnhash,$code_order) = @_;
6307: my @homeservers;
1.841 albertel 6308:
6309: my %servers = &get_servers($domain,'library');
6310: foreach my $tryserver (keys(%servers)) {
6311: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6312: push(@homeservers,$tryserver);
6313: }
1.792 raeburn 6314: }
1.841 albertel 6315:
1.792 raeburn 6316: my $response;
1.841 albertel 6317: foreach my $server (@homeservers) {
1.792 raeburn 6318: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 6319: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6320:
6321: foreach my $pair (split(/\&/,$response)) {
6322: my ($name,$value)=split(/\=/,$pair);
6323: if ($name eq 'code_order') {
6324: @{$code_order} = split(/\&/,&unescape($value));
6325: } else {
6326: $returnhash->{&unescape($name)}=&unescape($value);
6327: }
6328: }
6329: return 'ok';
1.792 raeburn 6330: }
1.841 albertel 6331:
6332: return $response;
1.1003 raeburn 6333: }
6334:
6335: sub auto_possible_instcodes {
1.1007 raeburn 6336: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6337: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6338: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6339: return;
6340: }
1.1003 raeburn 6341: my (@homeservers,$uhome);
6342: if (defined(&domain($domain,'primary'))) {
6343: $uhome=&domain($domain,'primary');
6344: push(@homeservers,&domain($domain,'primary'));
6345: } else {
6346: my %servers = &get_servers($domain,'library');
6347: foreach my $tryserver (keys(%servers)) {
6348: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6349: push(@homeservers,$tryserver);
6350: }
6351: }
6352: }
6353: my $response;
6354: foreach my $server (@homeservers) {
6355: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6356: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 6357: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6358: split(':',$response);
6359: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6360: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 6361: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 6362: my ($name,$value)=split('=',$item);
6363: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6364: }
6365: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 6366: my ($name,$value)=split('=',$item);
6367: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6368: }
6369: return 'ok';
6370: }
6371: return $response;
6372: }
1.792 raeburn 6373:
1.1010 raeburn 6374: sub auto_courserequest_checks {
6375: my ($dom) = @_;
1.1020 raeburn 6376: my ($homeserver,%validations);
6377: if ($dom =~ /^$match_domain$/) {
6378: $homeserver = &domain($dom,'primary');
6379: }
6380: unless ($homeserver eq 'no_host') {
6381: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6382: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6383: my @items = split(/&/,$response);
6384: foreach my $item (@items) {
6385: my ($key,$value) = split('=',$item);
6386: $validations{&unescape($key)} = &thaw_unescape($value);
6387: }
6388: }
6389: }
1.1010 raeburn 6390: return %validations;
6391: }
6392:
1.1020 raeburn 6393: sub auto_courserequest_validation {
6394: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6395: my ($homeserver,$response);
6396: if ($dom =~ /^$match_domain$/) {
6397: $homeserver = &domain($dom,'primary');
6398: }
6399: unless ($homeserver eq 'no_host') {
1.1021 raeburn 6400:
1.1020 raeburn 6401: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 6402: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 6403: ':'.&escape($instcode).':'.&escape($instseclist),
6404: $homeserver));
6405: }
6406: return $response;
6407: }
6408:
1.777 albertel 6409: sub auto_validate_class_sec {
1.918 raeburn 6410: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 6411: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 6412: my $ownerlist;
6413: if (ref($owners) eq 'ARRAY') {
6414: $ownerlist = join(',',@{$owners});
6415: } else {
6416: $ownerlist = $owners;
6417: }
1.773 raeburn 6418: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 6419: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 6420: return $response;
6421: }
6422:
1.679 raeburn 6423: # ------------------------------------------------------- Course Group routines
6424:
6425: sub get_coursegroups {
1.809 raeburn 6426: my ($cdom,$cnum,$group,$namespace) = @_;
6427: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 6428: }
6429:
1.679 raeburn 6430: sub modify_coursegroup {
6431: my ($cdom,$cnum,$groupsettings) = @_;
6432: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6433: }
6434:
1.809 raeburn 6435: sub toggle_coursegroup_status {
6436: my ($cdom,$cnum,$group,$action) = @_;
6437: my ($from_namespace,$to_namespace);
6438: if ($action eq 'delete') {
6439: $from_namespace = 'coursegroups';
6440: $to_namespace = 'deleted_groups';
6441: } else {
6442: $from_namespace = 'deleted_groups';
6443: $to_namespace = 'coursegroups';
6444: }
6445: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6446: if (my $tmp = &error(%curr_group)) {
6447: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6448: return ('read error',$tmp);
6449: } else {
6450: my %savedsettings = %curr_group;
1.809 raeburn 6451: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6452: my $deloutcome;
6453: if ($result eq 'ok') {
1.809 raeburn 6454: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6455: } else {
6456: return ('write error',$result);
6457: }
6458: if ($deloutcome eq 'ok') {
6459: return 'ok';
6460: } else {
6461: return ('delete error',$deloutcome);
6462: }
6463: }
6464: }
6465:
1.679 raeburn 6466: sub modify_group_roles {
1.957 raeburn 6467: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6468: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6469: my $role = 'gr/'.&escape($userprivs);
6470: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6471: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6472: if ($result eq 'ok') {
6473: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6474: }
1.679 raeburn 6475: return $result;
6476: }
6477:
6478: sub modify_coursegroup_membership {
6479: my ($cdom,$cnum,$membership) = @_;
6480: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6481: return $result;
6482: }
6483:
1.682 raeburn 6484: sub get_active_groups {
6485: my ($udom,$uname,$cdom,$cnum) = @_;
6486: my $now = time;
6487: my %groups = ();
6488: foreach my $key (keys(%env)) {
1.811 albertel 6489: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6490: my ($start,$end) = split(/\./,$env{$key});
6491: if (($end!=0) && ($end<$now)) { next; }
6492: if (($start!=0) && ($start>$now)) { next; }
6493: if ($1 eq $cdom && $2 eq $cnum) {
6494: $groups{$3} = $env{$key} ;
6495: }
6496: }
6497: }
6498: return %groups;
6499: }
6500:
1.683 raeburn 6501: sub get_group_membership {
6502: my ($cdom,$cnum,$group) = @_;
6503: return(&dump('groupmembership',$cdom,$cnum,$group));
6504: }
6505:
6506: sub get_users_groups {
6507: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6508: my @usersgroups;
1.683 raeburn 6509: my $cachetime=1800;
6510:
6511: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6512: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6513: if (defined($cached)) {
1.734 albertel 6514: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6515: } else {
6516: $grouplist = '';
1.816 raeburn 6517: my $courseurl = &courseid_to_courseurl($courseid);
1.1086 raeburn 6518: my $extra = &freeze_escape({'skipcheck' => 1});
6519: my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817 raeburn 6520: my $access_end = $env{'course.'.$courseid.
6521: '.default_enrollment_end_date'};
6522: my $now = time;
6523: foreach my $key (keys(%roleshash)) {
6524: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6525: my $group = $1;
6526: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6527: my $start = $2;
6528: my $end = $1;
6529: if ($start == -1) { next; } # deleted from group
6530: if (($start!=0) && ($start>$now)) { next; }
6531: if (($end!=0) && ($end<$now)) {
6532: if ($access_end && $access_end < $now) {
6533: if ($access_end - $end < 86400) {
6534: push(@usersgroups,$group);
1.733 raeburn 6535: }
6536: }
1.817 raeburn 6537: next;
1.733 raeburn 6538: }
1.817 raeburn 6539: push(@usersgroups,$group);
1.683 raeburn 6540: }
6541: }
6542: }
1.817 raeburn 6543: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6544: $grouplist = join(':',@usersgroups);
6545: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6546: }
1.733 raeburn 6547: return @usersgroups;
1.683 raeburn 6548: }
6549:
6550: sub devalidate_getgroups_cache {
6551: my ($udom,$uname,$cdom,$cnum)=@_;
6552: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6553:
1.683 raeburn 6554: my $hashid="$udom:$uname:$courseid";
6555: &devalidate_cache_new('getgroups',$hashid);
6556: }
6557:
1.12 www 6558: # ------------------------------------------------------------------ Plain Text
6559:
6560: sub plaintext {
1.988 raeburn 6561: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6562: if ($short =~ m{^cr/}) {
1.758 albertel 6563: return (split('/',$short))[-1];
6564: }
1.742 raeburn 6565: if (!defined($cid)) {
6566: $cid = $env{'request.course.id'};
6567: }
6568: my %rolenames = (
1.1008 raeburn 6569: Course => 'std',
6570: Community => 'alt1',
1.742 raeburn 6571: );
1.1037 raeburn 6572: if ($cid ne '') {
6573: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6574: unless ($forcedefault) {
6575: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6576: &Apache::lonlocal::mt_escape(\$roletext);
6577: return &Apache::lonlocal::mt($roletext);
6578: }
6579: }
6580: }
6581: if ((defined($type)) && (defined($rolenames{$type})) &&
6582: (defined($rolenames{$type})) &&
6583: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6584: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6585: } elsif ($cid ne '') {
6586: my $crstype = $env{'course.'.$cid.'.type'};
6587: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6588: (defined($prp{$short}{$rolenames{$crstype}}))) {
6589: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6590: }
1.742 raeburn 6591: }
1.1037 raeburn 6592: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 6593: }
6594:
6595: # ----------------------------------------------------------------- Assign Role
6596:
6597: sub assignrole {
1.957 raeburn 6598: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6599: $context)=@_;
1.21 www 6600: my $mrole;
6601: if ($role =~ /^cr\//) {
1.393 www 6602: my $cwosec=$url;
1.811 albertel 6603: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 6604: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 6605: my $refused = 1;
6606: if ($context eq 'requestcourses') {
6607: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6608: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6609: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6610: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6611: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6612: if ($crsenv{'internal.courseowner'} eq
6613: $env{'user.name'}.':'.$env{'user.domain'}) {
6614: $refused = '';
6615: }
6616: }
6617: }
6618: }
6619: }
6620: if ($refused) {
6621: &logthis('Refused custom assignrole: '.
6622: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6623: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6624: return 'refused';
6625: }
1.104 www 6626: }
1.21 www 6627: $mrole='cr';
1.678 raeburn 6628: } elsif ($role =~ /^gr\//) {
6629: my $cwogrp=$url;
1.811 albertel 6630: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 6631: unless (&allowed('mdg',$cwogrp)) {
6632: &logthis('Refused group assignrole: '.
6633: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6634: $env{'user.name'}.' at '.$env{'user.domain'});
6635: return 'refused';
6636: }
6637: $mrole='gr';
1.21 www 6638: } else {
1.82 www 6639: my $cwosec=$url;
1.811 albertel 6640: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 6641: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6642: my $refused;
6643: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6644: if (!(&allowed('c'.$role,$url))) {
6645: $refused = 1;
6646: }
6647: } else {
6648: $refused = 1;
6649: }
1.947 raeburn 6650: if ($refused) {
1.1045 raeburn 6651: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6652: if (!$selfenroll && $context eq 'course') {
6653: my %crsenv;
6654: if ($role eq 'cc' || $role eq 'co') {
6655: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6656: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
6657: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
6658: if ($crsenv{'internal.courseowner'} eq
6659: $env{'user.name'}.':'.$env{'user.domain'}) {
6660: $refused = '';
6661: }
6662: }
6663: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
6664: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
6665: if ($crsenv{'internal.courseowner'} eq
6666: $env{'user.name'}.':'.$env{'user.domain'}) {
6667: $refused = '';
6668: }
6669: }
6670: }
6671: }
6672: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 6673: $refused = '';
1.1017 raeburn 6674: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 6675: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 6676: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 6677: my $wrongcc;
6678: if ($cnum =~ /^$match_community$/) {
6679: $wrongcc = 1 if ($role eq 'cc');
6680: } else {
6681: $wrongcc = 1 if ($role eq 'co');
6682: }
6683: unless ($wrongcc) {
6684: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6685: if ($crsenv{'internal.courseowner'} eq
6686: $env{'user.name'}.':'.$env{'user.domain'}) {
6687: $refused = '';
6688: }
1.1017 raeburn 6689: }
6690: }
6691: }
6692: if ($refused) {
1.947 raeburn 6693: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6694: ' '.$role.' '.$end.' '.$start.' by '.
6695: $env{'user.name'}.' at '.$env{'user.domain'});
6696: return 'refused';
6697: }
1.932 raeburn 6698: }
1.104 www 6699: }
1.21 www 6700: $mrole=$role;
6701: }
1.620 albertel 6702: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6703: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 6704: if ($end) { $command.='_'.$end; }
1.21 www 6705: if ($start) {
6706: if ($end) {
1.81 www 6707: $command.='_'.$start;
1.21 www 6708: } else {
1.81 www 6709: $command.='_0_'.$start;
1.21 www 6710: }
6711: }
1.739 raeburn 6712: my $origstart = $start;
6713: my $origend = $end;
1.957 raeburn 6714: my $delflag;
1.357 www 6715: # actually delete
6716: if ($deleteflag) {
1.373 www 6717: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 6718: # modify command to delete the role
1.620 albertel 6719: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 6720: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 6721: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 6722: # set start and finish to negative values for userrolelog
6723: $start=-1;
6724: $end=-1;
1.957 raeburn 6725: $delflag = 1;
1.357 www 6726: }
6727: }
6728: # send command
1.349 www 6729: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 6730: # log new user role if status is ok
1.349 www 6731: if ($answer eq 'ok') {
1.663 raeburn 6732: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 6733: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 6734: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 6735: unless ($role =~ /^gr/) {
6736: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 6737: $origstart,$selfenroll,$context);
1.739 raeburn 6738: }
1.1053 raeburn 6739: if ($role eq 'cc') {
6740: &autoupdate_coowners($url,$end,$start,$uname,$udom);
6741: }
1.349 www 6742: }
6743: return $answer;
1.169 harris41 6744: }
6745:
1.1053 raeburn 6746: sub autoupdate_coowners {
6747: my ($url,$end,$start,$uname,$udom) = @_;
6748: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
6749: if (($cdom ne '') && ($cnum ne '')) {
6750: my $now = time;
6751: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
6752: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
6753: my %coursehash = &coursedescription($cdom.'_'.$cnum);
6754: my $instcode = $coursehash{'internal.coursecode'};
6755: if ($instcode ne '') {
1.1056 raeburn 6756: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
6757: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 6758: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 6759: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
6760: if ($result eq 'valid') {
6761: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 6762: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6763: push(@newcoowners,$coowner);
6764: }
6765: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
6766: push(@newcoowners,$uname.':'.$udom);
6767: }
6768: @newcoowners = sort(@newcoowners);
6769: } else {
6770: push(@newcoowners,$uname.':'.$udom);
6771: }
6772: } else {
6773: if ($coursehash{'internal.co-owners'}) {
6774: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6775: unless ($coowner eq $uname.':'.$udom) {
6776: push(@newcoowners,$coowner);
6777: }
6778: }
6779: unless (@newcoowners > 0) {
6780: $delcoowners = 1;
6781: $coowners = '';
6782: }
6783: }
6784: }
6785: if (@newcoowners || $delcoowners) {
6786: &store_coowners($cdom,$cnum,$coursehash{'home'},
6787: $delcoowners,@newcoowners);
6788: }
6789: }
6790: }
6791: }
6792: }
6793: }
6794: }
6795:
6796: sub store_coowners {
6797: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
6798: my $cid = $cdom.'_'.$cnum;
6799: my ($coowners,$delresult,$putresult);
6800: if (@newcoowners) {
6801: $coowners = join(',',@newcoowners);
6802: my %coownershash = (
6803: 'internal.co-owners' => $coowners,
6804: );
6805: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
6806: if ($putresult eq 'ok') {
6807: if ($env{'course.'.$cid.'.num'} eq $cnum) {
6808: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
6809: }
6810: }
6811: }
6812: if ($delcoowners) {
6813: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
6814: if ($delresult eq 'ok') {
6815: if ($env{'course.'.$cid.'.internal.co-owners'}) {
6816: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
6817: }
6818: }
6819: }
6820: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
6821: my %crsinfo =
6822: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6823: if (ref($crsinfo{$cid}) eq 'HASH') {
6824: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
6825: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
6826: }
6827: }
6828: }
6829:
1.169 harris41 6830: # -------------------------------------------------- Modify user authentication
1.197 www 6831: # Overrides without validation
6832:
1.169 harris41 6833: sub modifyuserauth {
6834: my ($udom,$uname,$umode,$upass)=@_;
6835: my $uhome=&homeserver($uname,$udom);
1.197 www 6836: unless (&allowed('mau',$udom)) { return 'refused'; }
6837: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 6838: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6839: ' in domain '.$env{'request.role.domain'});
1.169 harris41 6840: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6841: &escape($upass),$uhome);
1.620 albertel 6842: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 6843: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6844: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6845: &log($udom,,$uname,$uhome,
1.620 albertel 6846: 'Authentication changed by '.$env{'user.domain'}.', '.
6847: $env{'user.name'}.', '.$umode.
1.197 www 6848: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 6849: unless ($reply eq 'ok') {
1.197 www 6850: &logthis('Authentication mode error: '.$reply);
1.169 harris41 6851: return 'error: '.$reply;
6852: }
1.170 harris41 6853: return 'ok';
1.80 www 6854: }
6855:
1.81 www 6856: # --------------------------------------------------------------- Modify a user
1.80 www 6857:
1.81 www 6858: sub modifyuser {
1.206 matthew 6859: my ($udom, $uname, $uid,
6860: $umode, $upass, $first,
6861: $middle, $last, $gene,
1.1058 raeburn 6862: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 6863: $udom= &LONCAPA::clean_domain($udom);
6864: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 6865: my $showcandelete = 'none';
6866: if (ref($candelete) eq 'ARRAY') {
6867: if (@{$candelete} > 0) {
6868: $showcandelete = join(', ',@{$candelete});
6869: }
6870: }
1.81 www 6871: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 6872: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 6873: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 6874: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6875: ' desiredhome not specified').
1.620 albertel 6876: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6877: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 6878: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 6879: my $newuser;
6880: if ($uhome eq 'no_host') {
6881: $newuser = 1;
6882: }
1.80 www 6883: # ----------------------------------------------------------------- Create User
1.406 albertel 6884: if (($uhome eq 'no_host') &&
6885: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 6886: my $unhome='';
1.844 albertel 6887: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 6888: $unhome = $desiredhome;
1.620 albertel 6889: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6890: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 6891: } else { # load balancing routine for determining $unhome
1.81 www 6892: my $loadm=10000000;
1.841 albertel 6893: my %servers = &get_servers($udom,'library');
6894: foreach my $tryserver (keys(%servers)) {
6895: my $answer=reply('load',$tryserver);
6896: if (($answer=~/\d+/) && ($answer<$loadm)) {
6897: $loadm=$answer;
6898: $unhome=$tryserver;
6899: }
1.80 www 6900: }
6901: }
6902: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 6903: return 'error: unable to find a home server for '.$uname.
6904: ' in domain '.$udom;
1.80 www 6905: }
6906: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6907: &escape($upass),$unhome);
6908: unless ($reply eq 'ok') {
6909: return 'error: '.$reply;
6910: }
1.230 stredwic 6911: $uhome=&homeserver($uname,$udom,'true');
1.80 www 6912: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 6913: return 'error: unable verify users home machine.';
1.80 www 6914: }
1.209 matthew 6915: } # End of creation of new user
1.80 www 6916: # ---------------------------------------------------------------------- Add ID
6917: if ($uid) {
6918: $uid=~tr/A-Z/a-z/;
6919: my %uidhash=&idrget($udom,$uname);
1.196 www 6920: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6921: && (!$forceid)) {
1.80 www 6922: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 6923: return 'error: user id "'.$uid.'" does not match '.
6924: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 6925: }
6926: } else {
6927: &idput($udom,($uname => $uid));
6928: }
6929: }
6930: # -------------------------------------------------------------- Add names, etc
1.313 matthew 6931: my @tmp=&get('environment',
1.899 raeburn 6932: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 6933: 'permanentemail','inststatus'],
1.134 albertel 6934: $udom,$uname);
1.1075 raeburn 6935: my (%names,%oldnames);
1.313 matthew 6936: if ($tmp[0] =~ m/^error:.*/) {
6937: %names=();
6938: } else {
6939: %names = @tmp;
1.1075 raeburn 6940: %oldnames = %names;
1.313 matthew 6941: }
1.388 www 6942: #
1.1058 raeburn 6943: # If name, email and/or uid are blank (e.g., because an uploaded file
6944: # of users did not contain them), do not overwrite existing values
6945: # unless field is in $candelete array ref.
6946: #
6947:
6948: my @fields = ('firstname','middlename','lastname','generation',
6949: 'permanentemail','id');
6950: my %newvalues;
6951: if (ref($candelete) eq 'ARRAY') {
6952: foreach my $field (@fields) {
6953: if (grep(/^\Q$field\E$/,@{$candelete})) {
6954: if ($field eq 'firstname') {
6955: $names{$field} = $first;
6956: } elsif ($field eq 'middlename') {
6957: $names{$field} = $middle;
6958: } elsif ($field eq 'lastname') {
6959: $names{$field} = $last;
6960: } elsif ($field eq 'generation') {
6961: $names{$field} = $gene;
6962: } elsif ($field eq 'permanentemail') {
6963: $names{$field} = $email;
6964: } elsif ($field eq 'id') {
6965: $names{$field} = $uid;
6966: }
6967: }
6968: }
6969: }
1.388 www 6970: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 6971: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 6972: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 6973: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 6974: if ($email) {
6975: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 6976: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 6977: }
1.899 raeburn 6978: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 6979: if (defined($inststatus)) {
6980: $names{'inststatus'} = '';
6981: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
6982: if (ref($usertypes) eq 'HASH') {
6983: my @okstatuses;
6984: foreach my $item (split(/:/,$inststatus)) {
6985: if (defined($usertypes->{$item})) {
6986: push(@okstatuses,$item);
6987: }
6988: }
6989: if (@okstatuses) {
6990: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
6991: }
6992: }
6993: }
1.1075 raeburn 6994: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 6995: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 6996: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 6997: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
6998: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
6999: } else {
7000: $logmsg .= ' during self creation';
7001: }
1.1075 raeburn 7002: my $changed;
7003: if ($newuser) {
7004: $changed = 1;
7005: } else {
7006: foreach my $field (@fields) {
7007: if ($names{$field} ne $oldnames{$field}) {
7008: $changed = 1;
7009: last;
7010: }
7011: }
7012: }
7013: unless ($changed) {
7014: $logmsg = 'No changes in user information needed for: '.$logmsg;
7015: &logthis($logmsg);
7016: return 'ok';
7017: }
7018: my $reply = &put('environment', \%names, $udom,$uname);
7019: if ($reply ne 'ok') {
7020: return 'error: '.$reply;
7021: }
1.1087 raeburn 7022: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7023: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7024: }
1.1075 raeburn 7025: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7026: &devalidate_cache_new('namescache',$uname.':'.$udom);
7027: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 7028: &logthis($logmsg);
1.134 albertel 7029: return 'ok';
1.80 www 7030: }
7031:
1.81 www 7032: # -------------------------------------------------------------- Modify student
1.80 www 7033:
1.81 www 7034: sub modifystudent {
7035: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 7036: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 7037: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 7038: if (!$cid) {
1.620 albertel 7039: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7040: return 'not_in_class';
7041: }
1.80 www 7042: }
7043: # --------------------------------------------------------------- Make the user
1.81 www 7044: my $reply=&modifyuser
1.209 matthew 7045: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 7046: $desiredhome,$email,$inststatus);
1.80 www 7047: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 7048: # This will cause &modify_student_enrollment to get the uid from the
7049: # students environment
7050: $uid = undef if (!$forceid);
1.455 albertel 7051: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 7052: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 7053: return $reply;
7054: }
7055:
7056: sub modify_student_enrollment {
1.957 raeburn 7057: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 7058: my ($cdom,$cnum,$chome);
7059: if (!$cid) {
1.620 albertel 7060: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7061: return 'not_in_class';
7062: }
1.620 albertel 7063: $cdom=$env{'course.'.$cid.'.domain'};
7064: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 7065: } else {
7066: ($cdom,$cnum)=split(/_/,$cid);
7067: }
1.620 albertel 7068: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 7069: if (!$chome) {
1.457 raeburn 7070: $chome=&homeserver($cnum,$cdom);
1.297 matthew 7071: }
1.455 albertel 7072: if (!$chome) { return 'unknown_course'; }
1.297 matthew 7073: # Make sure the user exists
1.81 www 7074: my $uhome=&homeserver($uname,$udom);
7075: if (($uhome eq '') || ($uhome eq 'no_host')) {
7076: return 'error: no such user';
7077: }
1.297 matthew 7078: # Get student data if we were not given enough information
7079: if (!defined($first) || $first eq '' ||
7080: !defined($last) || $last eq '' ||
7081: !defined($uid) || $uid eq '' ||
7082: !defined($middle) || $middle eq '' ||
7083: !defined($gene) || $gene eq '') {
1.294 matthew 7084: # They did not supply us with enough data to enroll the student, so
7085: # we need to pick up more information.
1.297 matthew 7086: my %tmp = &get('environment',
1.294 matthew 7087: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 7088: ,$udom,$uname);
7089:
1.800 albertel 7090: #foreach my $key (keys(%tmp)) {
7091: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 7092: #}
1.294 matthew 7093: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7094: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7095: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 7096: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 7097: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7098: }
1.556 albertel 7099: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 7100: my $reply=cput('classlist',
7101: {"$uname:$udom" =>
1.515 raeburn 7102: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 7103: $cdom,$cnum);
1.81 www 7104: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
7105: return 'error: '.$reply;
1.652 albertel 7106: } else {
7107: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 7108: }
1.297 matthew 7109: # Add student role to user
1.83 www 7110: my $uurl='/'.$cid;
1.81 www 7111: $uurl=~s/\_/\//g;
7112: if ($usec) {
7113: $uurl.='/'.$usec;
7114: }
1.957 raeburn 7115: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 7116: }
7117:
1.556 albertel 7118: sub format_name {
7119: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7120: my $name;
7121: if ($first ne 'lastname') {
7122: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7123: } else {
7124: if ($lastname=~/\S/) {
7125: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7126: $name=~s/\s+,/,/;
7127: } else {
7128: $name.= $firstname.' '.$middlename.' '.$generation;
7129: }
7130: }
7131: $name=~s/^\s+//;
7132: $name=~s/\s+$//;
7133: $name=~s/\s+/ /g;
7134: return $name;
7135: }
7136:
1.84 www 7137: # ------------------------------------------------- Write to course preferences
7138:
7139: sub writecoursepref {
7140: my ($courseid,%prefs)=@_;
7141: $courseid=~s/^\///;
7142: $courseid=~s/\_/\//g;
7143: my ($cdomain,$cnum)=split(/\//,$courseid);
7144: my $chome=homeserver($cnum,$cdomain);
7145: if (($chome eq '') || ($chome eq 'no_host')) {
7146: return 'error: no such course';
7147: }
7148: my $cstring='';
1.800 albertel 7149: foreach my $pref (keys(%prefs)) {
7150: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 7151: }
1.84 www 7152: $cstring=~s/\&$//;
7153: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7154: }
7155:
7156: # ---------------------------------------------------------- Make/modify course
7157:
7158: sub createcourse {
1.741 raeburn 7159: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 7160: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 7161: $url=&declutter($url);
7162: my $cid='';
1.1028 raeburn 7163: if ($context eq 'requestcourses') {
7164: my $can_create = 0;
7165: my ($ownername,$ownerdom) = split(':',$course_owner);
7166: if ($udom eq $ownerdom) {
7167: if (&usertools_access($ownername,$ownerdom,$category,undef,
7168: $context)) {
7169: $can_create = 1;
7170: }
7171: } else {
7172: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7173: $category);
7174: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7175: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7176: if (@curr > 0) {
7177: my @options = qw(approval validate autolimit);
7178: my $optregex = join('|',@options);
7179: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7180: $can_create = 1;
7181: }
7182: }
7183: }
7184: }
7185: if ($can_create) {
7186: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7187: unless (&allowed('ccc',$udom)) {
7188: return 'refused';
7189: }
1.1017 raeburn 7190: }
7191: } else {
7192: return 'refused';
7193: }
1.1028 raeburn 7194: } elsif (!&allowed('ccc',$udom)) {
7195: return 'refused';
1.84 www 7196: }
1.1011 raeburn 7197: # --------------------------------------------------------------- Get Unique ID
7198: my $uname;
7199: if ($cnum =~ /^$match_courseid$/) {
7200: my $chome=&homeserver($cnum,$udom,'true');
7201: if (($chome eq '') || ($chome eq 'no_host')) {
7202: $uname = $cnum;
7203: } else {
1.1038 raeburn 7204: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7205: }
7206: } else {
1.1038 raeburn 7207: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7208: }
7209: return $uname if ($uname =~ /^error/);
7210: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 7211: if (!defined($course_server)) {
7212: if (defined(&domain($udom,'primary'))) {
7213: $course_server = &domain($udom,'primary');
7214: } else {
7215: $course_server = $env{'user.home'};
7216: }
7217: }
7218: my %host_servers =
7219: &Apache::lonnet::get_servers($udom,'library');
7220: unless ($host_servers{$course_server}) {
7221: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 7222: }
1.84 www 7223: # ------------------------------------------------------------- Make the course
7224: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 7225: $course_server);
1.84 www 7226: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 7227: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 7228: if (($uhome eq '') || ($uhome eq 'no_host')) {
7229: return 'error: no such course';
7230: }
1.271 www 7231: # ----------------------------------------------------------------- Course made
1.516 raeburn 7232: # log existence
1.1029 raeburn 7233: my $now = time;
1.918 raeburn 7234: my $newcourse = {
7235: $udom.'_'.$uname => {
1.921 raeburn 7236: description => $description,
7237: inst_code => $inst_code,
7238: owner => $course_owner,
7239: type => $crstype,
1.1029 raeburn 7240: creator => $env{'user.name'}.':'.
7241: $env{'user.domain'},
7242: created => $now,
7243: context => $context,
1.918 raeburn 7244: },
7245: };
1.921 raeburn 7246: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 7247: # set toplevel url
1.271 www 7248: my $topurl=$url;
7249: unless ($nonstandard) {
7250: # ------------------------------------------ For standard courses, make top url
7251: my $mapurl=&clutter($url);
1.278 www 7252: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 7253: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 7254: <map>
7255: <resource id="1" type="start"></resource>
7256: <resource id="2" src="$mapurl"></resource>
7257: <resource id="3" type="finish"></resource>
7258: <link index="1" from="1" to="2"></link>
7259: <link index="2" from="2" to="3"></link>
7260: </map>
7261: ENDINITMAP
7262: $topurl=&declutter(
1.638 albertel 7263: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 7264: );
7265: }
7266: # ----------------------------------------------------------- Write preferences
1.84 www 7267: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 7268: ('description' => $description,
7269: 'url' => $topurl,
7270: 'internal.creator' => $env{'user.name'}.':'.
7271: $env{'user.domain'},
7272: 'internal.created' => $now,
7273: 'internal.creationcontext' => $context)
7274: );
1.84 www 7275: return '/'.$udom.'/'.$uname;
7276: }
7277:
1.1011 raeburn 7278: # ------------------------------------------------------------------- Create ID
7279: sub generate_coursenum {
1.1038 raeburn 7280: my ($udom,$crstype) = @_;
1.1011 raeburn 7281: my $domdesc = &domain($udom);
7282: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 7283: my $first;
7284: if ($crstype eq 'Community') {
7285: $first = '0';
7286: } else {
7287: $first = int(1+rand(9));
7288: }
7289: my $uname=$first.
1.1011 raeburn 7290: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7291: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7292: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7293: # ----------------------------------------------- Make sure that does not exist
7294: my $uhome=&homeserver($uname,$udom,'true');
7295: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 7296: if ($crstype eq 'Community') {
7297: $first = '0';
7298: } else {
7299: $first = int(1+rand(9));
7300: }
7301: $uname=$first.
1.1011 raeburn 7302: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7303: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7304: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7305: $uhome=&homeserver($uname,$udom,'true');
7306: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7307: return 'error: unable to generate unique course-ID';
7308: }
7309: }
7310: return $uname;
7311: }
7312:
1.813 albertel 7313: sub is_course {
7314: my ($cdom,$cnum) = @_;
7315: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 7316: undef,'.');
1.813 albertel 7317: if (exists($courses{$cdom.'_'.$cnum})) {
7318: return 1;
7319: }
7320: return 0;
7321: }
7322:
1.1015 raeburn 7323: sub store_userdata {
7324: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 7325: my $result;
1.1016 raeburn 7326: if ($datakey ne '') {
1.1013 raeburn 7327: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 7328: if ($udom eq '' || $uname eq '') {
7329: $udom = $env{'user.domain'};
7330: $uname = $env{'user.name'};
7331: }
7332: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 7333: if (($uhome eq '') || ($uhome eq 'no_host')) {
7334: $result = 'error: no_host';
7335: } else {
7336: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7337: $storehash->{'host'} = $perlvar{'lonHostID'};
7338:
7339: my $namevalue='';
7340: foreach my $key (keys(%{$storehash})) {
7341: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7342: }
7343: $namevalue=~s/\&$//;
1.1105 raeburn 7344: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
7345: $namevalue,$uhome);
1.1013 raeburn 7346: }
7347: } else {
7348: $result = 'error: data to store was not a hash reference';
7349: }
7350: } else {
7351: $result= 'error: invalid requestkey';
7352: }
7353: return $result;
7354: }
7355:
1.21 www 7356: # ---------------------------------------------------------- Assign Custom Role
7357:
7358: sub assigncustomrole {
1.957 raeburn 7359: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7360: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 7361: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 7362: }
7363:
7364: # ----------------------------------------------------------------- Revoke Role
7365:
7366: sub revokerole {
1.957 raeburn 7367: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7368: my $now=time;
1.965 raeburn 7369: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 7370: }
7371:
7372: # ---------------------------------------------------------- Revoke Custom Role
7373:
7374: sub revokecustomrole {
1.957 raeburn 7375: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7376: my $now=time;
1.357 www 7377: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 7378: $deleteflag,$selfenroll,$context);
1.17 www 7379: }
7380:
1.533 banghart 7381: # ------------------------------------------------------------ Disk usage
1.535 albertel 7382: sub diskusage {
1.955 raeburn 7383: my ($udom,$uname,$directorypath,$getpropath)=@_;
7384: $directorypath =~ s/\/$//;
7385: my $listing=&reply('du2:'.&escape($directorypath).':'
7386: .&escape($getpropath).':'.&escape($uname).':'
7387: .&escape($udom),homeserver($uname,$udom));
7388: if ($listing eq 'unknown_cmd') {
7389: if ($getpropath) {
7390: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7391: }
7392: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7393: }
1.514 albertel 7394: return $listing;
1.512 banghart 7395: }
7396:
1.566 banghart 7397: sub is_locked {
1.1096 raeburn 7398: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 7399: my @check;
7400: my $is_locked;
1.1093 raeburn 7401: push (@check,$file_name);
1.613 albertel 7402: my %locked = &get('file_permissions',\@check,
1.620 albertel 7403: $env{'user.domain'},$env{'user.name'});
1.615 albertel 7404: my ($tmp)=keys(%locked);
7405: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 7406:
1.566 banghart 7407: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 7408: $is_locked = 'false';
7409: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 7410: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 7411: $is_locked = 'true';
1.1096 raeburn 7412: if (ref($which) eq 'ARRAY') {
7413: push(@{$which},$entry);
7414: } else {
7415: last;
7416: }
1.745 raeburn 7417: }
7418: }
1.566 banghart 7419: } else {
7420: $is_locked = 'false';
7421: }
1.1093 raeburn 7422: return $is_locked;
1.566 banghart 7423: }
7424:
1.759 albertel 7425: sub declutter_portfile {
7426: my ($file) = @_;
1.833 albertel 7427: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 7428: return $file;
7429: }
7430:
1.559 banghart 7431: # ------------------------------------------------------------- Mark as Read Only
7432:
7433: sub mark_as_readonly {
7434: my ($domain,$user,$files,$what) = @_;
1.613 albertel 7435: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7436: my ($tmp)=keys(%current_permissions);
7437: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 7438: foreach my $file (@{$files}) {
1.759 albertel 7439: $file = &declutter_portfile($file);
1.561 banghart 7440: push(@{$current_permissions{$file}},$what);
1.559 banghart 7441: }
1.613 albertel 7442: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7443: return;
7444: }
7445:
1.572 banghart 7446: # ------------------------------------------------------------Save Selected Files
7447:
7448: sub save_selected_files {
7449: my ($user, $path, @files) = @_;
7450: my $filename = $user."savedfiles";
1.573 banghart 7451: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 7452: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 7453: foreach my $file (@files) {
1.620 albertel 7454: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 7455: }
7456: foreach my $file (@other_files) {
1.574 banghart 7457: print (OUT $file."\n");
1.572 banghart 7458: }
1.574 banghart 7459: close (OUT);
1.572 banghart 7460: return 'ok';
7461: }
7462:
1.574 banghart 7463: sub clear_selected_files {
7464: my ($user) = @_;
7465: my $filename = $user."savedfiles";
1.1117 ! foxr 7466: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 7467: print (OUT undef);
7468: close (OUT);
7469: return ("ok");
7470: }
7471:
1.572 banghart 7472: sub files_in_path {
7473: my ($user, $path) = @_;
7474: my $filename = $user."savedfiles";
7475: my %return_files;
1.1117 ! foxr 7476: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 7477: while (my $line_in = <IN>) {
1.574 banghart 7478: chomp ($line_in);
7479: my @paths_and_file = split (m!/!, $line_in);
7480: my $file_part = pop (@paths_and_file);
7481: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7482: $path_part.='/';
7483: my $path_and_file = $path_part.$file_part;
7484: if ($path_part eq $path) {
7485: $return_files{$file_part}= 'selected';
7486: }
7487: }
1.574 banghart 7488: close (IN);
7489: return (\%return_files);
1.572 banghart 7490: }
7491:
7492: # called in portfolio select mode, to show files selected NOT in current directory
7493: sub files_not_in_path {
7494: my ($user, $path) = @_;
7495: my $filename = $user."savedfiles";
7496: my @return_files;
7497: my $path_part;
1.1117 ! foxr 7498: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 7499: while (my $line = <IN>) {
1.572 banghart 7500: #ok, I know it's clunky, but I want it to work
1.800 albertel 7501: my @paths_and_file = split(m|/|, $line);
7502: my $file_part = pop(@paths_and_file);
7503: chomp($file_part);
7504: my $path_part = join('/', @paths_and_file);
1.572 banghart 7505: $path_part .= '/';
7506: my $path_and_file = $path_part.$file_part;
7507: if ($path_part ne $path) {
1.800 albertel 7508: push(@return_files, ($path_and_file));
1.572 banghart 7509: }
7510: }
1.800 albertel 7511: close(OUT);
1.574 banghart 7512: return (@return_files);
1.572 banghart 7513: }
7514:
1.745 raeburn 7515: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7516:
1.745 raeburn 7517: sub get_portfile_permissions {
7518: my ($domain,$user) = @_;
1.613 albertel 7519: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7520: my ($tmp)=keys(%current_permissions);
7521: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7522: return \%current_permissions;
7523: }
7524:
7525: #---------------------------------------------Get portfolio file access controls
7526:
1.749 raeburn 7527: sub get_access_controls {
1.745 raeburn 7528: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7529: my %access;
7530: my $real_file = $file;
7531: $file =~ s/\.meta$//;
1.745 raeburn 7532: if (defined($file)) {
1.749 raeburn 7533: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7534: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7535: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7536: }
7537: }
1.745 raeburn 7538: } else {
1.749 raeburn 7539: foreach my $key (keys(%{$current_permissions})) {
7540: if ($key =~ /\0accesscontrol$/) {
7541: if (defined($group)) {
7542: if ($key !~ m-^\Q$group\E/-) {
7543: next;
7544: }
7545: }
7546: my ($fullpath) = split(/\0/,$key);
7547: if (ref($$current_permissions{$key}) eq 'HASH') {
7548: foreach my $control (keys(%{$$current_permissions{$key}})) {
7549: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7550: }
7551: }
7552: }
7553: }
7554: }
7555: return %access;
7556: }
7557:
7558: sub modify_access_controls {
7559: my ($file_name,$changes,$domain,$user)=@_;
7560: my ($outcome,$deloutcome);
7561: my %store_permissions;
7562: my %new_values;
7563: my %new_control;
7564: my %translation;
7565: my @deletions = ();
7566: my $now = time;
7567: if (exists($$changes{'activate'})) {
7568: if (ref($$changes{'activate'}) eq 'HASH') {
7569: my @newitems = sort(keys(%{$$changes{'activate'}}));
7570: my $numnew = scalar(@newitems);
7571: for (my $i=0; $i<$numnew; $i++) {
7572: my $newkey = $newitems[$i];
7573: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 7574: if ($newkey =~ /^\d+:/) {
7575: $newkey =~ s/^(\d+)/$newid/;
7576: $translation{$1} = $newid;
7577: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7578: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7579: $translation{$1} = $newid;
7580: }
1.749 raeburn 7581: $new_values{$file_name."\0".$newkey} =
7582: $$changes{'activate'}{$newitems[$i]};
7583: $new_control{$newkey} = $now;
7584: }
7585: }
7586: }
7587: my %todelete;
7588: my %changed_items;
7589: foreach my $action ('delete','update') {
7590: if (exists($$changes{$action})) {
7591: if (ref($$changes{$action}) eq 'HASH') {
7592: foreach my $key (keys(%{$$changes{$action}})) {
7593: my ($itemnum) = ($key =~ /^([^:]+):/);
7594: if ($action eq 'delete') {
7595: $todelete{$itemnum} = 1;
7596: } else {
7597: $changed_items{$itemnum} = $key;
7598: }
7599: }
1.745 raeburn 7600: }
7601: }
1.749 raeburn 7602: }
7603: # get lock on access controls for file.
7604: my $lockhash = {
7605: $file_name."\0".'locked_access_records' => $env{'user.name'}.
7606: ':'.$env{'user.domain'},
7607: };
7608: my $tries = 0;
7609: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7610:
7611: while (($gotlock ne 'ok') && $tries <3) {
7612: $tries ++;
7613: sleep 1;
7614: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7615: }
7616: if ($gotlock eq 'ok') {
7617: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
7618: my ($tmp)=keys(%curr_permissions);
7619: if ($tmp=~/^error:/) { undef(%curr_permissions); }
7620: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
7621: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
7622: if (ref($curr_controls) eq 'HASH') {
7623: foreach my $control_item (keys(%{$curr_controls})) {
7624: my ($itemnum) = ($control_item =~ /^([^:]+):/);
7625: if (defined($todelete{$itemnum})) {
7626: push(@deletions,$file_name."\0".$control_item);
7627: } else {
7628: if (defined($changed_items{$itemnum})) {
7629: $new_control{$changed_items{$itemnum}} = $now;
7630: push(@deletions,$file_name."\0".$control_item);
7631: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
7632: } else {
7633: $new_control{$control_item} = $$curr_controls{$control_item};
7634: }
7635: }
1.745 raeburn 7636: }
7637: }
7638: }
1.970 raeburn 7639: my ($group);
7640: if (&is_course($domain,$user)) {
7641: ($group,my $file) = split(/\//,$file_name,2);
7642: }
1.749 raeburn 7643: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
7644: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
7645: $outcome = &put('file_permissions',\%new_values,$domain,$user);
7646: # remove lock
7647: my @del_lock = ($file_name."\0".'locked_access_records');
7648: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 7649: my $sqlresult =
1.970 raeburn 7650: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 7651: $group);
1.749 raeburn 7652: } else {
7653: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 7654: }
1.749 raeburn 7655: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 7656: }
7657:
1.827 raeburn 7658: sub make_public_indefinitely {
7659: my ($requrl) = @_;
7660: my $now = time;
7661: my $action = 'activate';
7662: my $aclnum = 0;
7663: if (&is_portfolio_url($requrl)) {
7664: my (undef,$udom,$unum,$file_name,$group) =
7665: &parse_portfolio_url($requrl);
7666: my $current_perms = &get_portfile_permissions($udom,$unum);
7667: my %access_controls = &get_access_controls($current_perms,
7668: $group,$file_name);
7669: foreach my $key (keys(%{$access_controls{$file_name}})) {
7670: my ($num,$scope,$end,$start) =
7671: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7672: if ($scope eq 'public') {
7673: if ($start <= $now && $end == 0) {
7674: $action = 'none';
7675: } else {
7676: $action = 'update';
7677: $aclnum = $num;
7678: }
7679: last;
7680: }
7681: }
7682: if ($action eq 'none') {
7683: return 'ok';
7684: } else {
7685: my %changes;
7686: my $newend = 0;
7687: my $newstart = $now;
7688: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
7689: $changes{$action}{$newkey} = {
7690: type => 'public',
7691: time => {
7692: start => $newstart,
7693: end => $newend,
7694: },
7695: };
7696: my ($outcome,$deloutcome,$new_values,$translation) =
7697: &modify_access_controls($file_name,\%changes,$udom,$unum);
7698: return $outcome;
7699: }
7700: } else {
7701: return 'invalid';
7702: }
7703: }
7704:
1.745 raeburn 7705: #------------------------------------------------------Get Marked as Read Only
7706:
7707: sub get_marked_as_readonly {
7708: my ($domain,$user,$what,$group) = @_;
7709: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 7710: my @readonly_files;
1.629 banghart 7711: my $cmp1=$what;
7712: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 7713: while (my ($file_name,$value) = each(%{$current_permissions})) {
7714: if (defined($group)) {
7715: if ($file_name !~ m-^\Q$group\E/-) {
7716: next;
7717: }
7718: }
1.561 banghart 7719: if (ref($value) eq "ARRAY"){
7720: foreach my $stored_what (@{$value}) {
1.629 banghart 7721: my $cmp2=$stored_what;
1.759 albertel 7722: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 7723: $cmp2=join('',@{$stored_what});
1.745 raeburn 7724: }
1.629 banghart 7725: if ($cmp1 eq $cmp2) {
1.561 banghart 7726: push(@readonly_files, $file_name);
1.745 raeburn 7727: last;
1.563 banghart 7728: } elsif (!defined($what)) {
7729: push(@readonly_files, $file_name);
1.745 raeburn 7730: last;
1.561 banghart 7731: }
7732: }
1.745 raeburn 7733: }
1.561 banghart 7734: }
7735: return @readonly_files;
7736: }
1.577 banghart 7737: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 7738:
1.577 banghart 7739: sub get_marked_as_readonly_hash {
1.745 raeburn 7740: my ($current_permissions,$group,$what) = @_;
1.577 banghart 7741: my %readonly_files;
1.745 raeburn 7742: while (my ($file_name,$value) = each(%{$current_permissions})) {
7743: if (defined($group)) {
7744: if ($file_name !~ m-^\Q$group\E/-) {
7745: next;
7746: }
7747: }
1.577 banghart 7748: if (ref($value) eq "ARRAY"){
7749: foreach my $stored_what (@{$value}) {
1.745 raeburn 7750: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 7751: foreach my $lock_descriptor(@{$stored_what}) {
7752: if ($lock_descriptor eq 'graded') {
7753: $readonly_files{$file_name} = 'graded';
7754: } elsif ($lock_descriptor eq 'handback') {
7755: $readonly_files{$file_name} = 'handback';
7756: } else {
7757: if (!exists($readonly_files{$file_name})) {
7758: $readonly_files{$file_name} = 'locked';
7759: }
7760: }
1.745 raeburn 7761: }
1.750 banghart 7762: }
1.577 banghart 7763: }
7764: }
7765: }
7766: return %readonly_files;
7767: }
1.559 banghart 7768: # ------------------------------------------------------------ Unmark as Read Only
7769:
7770: sub unmark_as_readonly {
1.629 banghart 7771: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7772: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 7773: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 7774: $file_name = &declutter_portfile($file_name);
1.634 albertel 7775: my $symb_crs = $what;
7776: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 7777: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 7778: my ($tmp)=keys(%current_permissions);
7779: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7780: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 7781: foreach my $file (@readonly_files) {
1.759 albertel 7782: my $clean_file = &declutter_portfile($file);
7783: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 7784: my $current_locks = $current_permissions{$file};
1.563 banghart 7785: my @new_locks;
7786: my @del_keys;
7787: if (ref($current_locks) eq "ARRAY"){
7788: foreach my $locker (@{$current_locks}) {
1.632 albertel 7789: my $compare=$locker;
1.749 raeburn 7790: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 7791: $compare=join('',@{$locker});
1.746 raeburn 7792: if ($compare ne $symb_crs) {
7793: push(@new_locks, $locker);
7794: }
1.563 banghart 7795: }
7796: }
1.650 albertel 7797: if (scalar(@new_locks) > 0) {
1.563 banghart 7798: $current_permissions{$file} = \@new_locks;
7799: } else {
7800: push(@del_keys, $file);
1.613 albertel 7801: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 7802: delete($current_permissions{$file});
1.563 banghart 7803: }
7804: }
1.561 banghart 7805: }
1.613 albertel 7806: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7807: return;
7808: }
1.512 banghart 7809:
1.17 www 7810: # ------------------------------------------------------------ Directory lister
7811:
7812: sub dirlist {
1.955 raeburn 7813: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 7814: $uri=~s/^\///;
7815: $uri=~s/\/$//;
1.253 stredwic 7816: my ($udom, $uname);
1.955 raeburn 7817: if ($getuserdir) {
1.253 stredwic 7818: $udom = $userdomain;
7819: $uname = $username;
1.955 raeburn 7820: } else {
7821: (undef,$udom,$uname)=split(/\//,$uri);
7822: if(defined($userdomain)) {
7823: $udom = $userdomain;
7824: }
7825: if(defined($username)) {
7826: $uname = $username;
7827: }
1.253 stredwic 7828: }
1.955 raeburn 7829: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 7830:
1.955 raeburn 7831: $dirRoot = $perlvar{'lonDocRoot'};
7832: if (defined($getpropath)) {
7833: $dirRoot = &propath($udom,$uname);
1.253 stredwic 7834: $dirRoot =~ s/\/$//;
1.955 raeburn 7835: } elsif (defined($getuserdir)) {
7836: my $subdir=$uname.'__';
7837: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7838: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7839: ."/$udom/$subdir/$uname";
7840: } elsif (defined($alternateRoot)) {
7841: $dirRoot = $alternateRoot;
1.751 banghart 7842: }
1.253 stredwic 7843:
7844: if($udom) {
7845: if($uname) {
1.955 raeburn 7846: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 7847: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 7848: .':'.&escape($uname).':'.&escape($udom),
7849: &homeserver($uname,$udom));
7850: if ($listing eq 'unknown_cmd') {
7851: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7852: &homeserver($uname,$udom));
7853: } else {
7854: @listing_results = map { &unescape($_); } split(/:/,$listing);
7855: }
1.605 matthew 7856: if ($listing eq 'unknown_cmd') {
1.800 albertel 7857: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7858: &homeserver($uname,$udom));
1.605 matthew 7859: @listing_results = split(/:/,$listing);
7860: } else {
7861: @listing_results = map { &unescape($_); } split(/:/,$listing);
7862: }
7863: return @listing_results;
1.955 raeburn 7864: } elsif(!$alternateRoot) {
1.800 albertel 7865: my %allusers;
1.841 albertel 7866: my %servers = &get_servers($udom,'library');
1.955 raeburn 7867: foreach my $tryserver (keys(%servers)) {
7868: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7869: &escape($udom),$tryserver);
7870: if ($listing eq 'unknown_cmd') {
7871: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7872: $udom, $tryserver);
7873: } else {
7874: @listing_results = map { &unescape($_); } split(/:/,$listing);
7875: }
1.841 albertel 7876: if ($listing eq 'unknown_cmd') {
7877: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7878: $udom, $tryserver);
7879: @listing_results = split(/:/,$listing);
7880: } else {
7881: @listing_results =
7882: map { &unescape($_); } split(/:/,$listing);
7883: }
7884: if ($listing_results[0] ne 'no_such_dir' &&
7885: $listing_results[0] ne 'empty' &&
7886: $listing_results[0] ne 'con_lost') {
7887: foreach my $line (@listing_results) {
7888: my ($entry) = split(/&/,$line,2);
7889: $allusers{$entry} = 1;
7890: }
7891: }
1.253 stredwic 7892: }
7893: my $alluserstr='';
1.800 albertel 7894: foreach my $user (sort(keys(%allusers))) {
7895: $alluserstr.=$user.'&user:';
1.253 stredwic 7896: }
7897: $alluserstr=~s/:$//;
7898: return split(/:/,$alluserstr);
7899: } else {
1.800 albertel 7900: return ('missing user name');
1.253 stredwic 7901: }
1.955 raeburn 7902: } elsif(!defined($getpropath)) {
1.841 albertel 7903: my @all_domains = sort(&all_domains());
1.955 raeburn 7904: foreach my $domain (@all_domains) {
7905: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7906: }
7907: return @all_domains;
7908: } else {
1.800 albertel 7909: return ('missing domain');
1.275 stredwic 7910: }
7911: }
7912:
7913: # --------------------------------------------- GetFileTimestamp
7914: # This function utilizes dirlist and returns the date stamp for
7915: # when it was last modified. It will also return an error of -1
7916: # if an error occurs
7917:
7918: sub GetFileTimestamp {
1.955 raeburn 7919: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 7920: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7921: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 7922: my ($fileStat) =
7923: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7924: undef,$getuserdir);
1.275 stredwic 7925: my @stats = split('&', $fileStat);
7926: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 7927: # @stats contains first the filename, then the stat output
7928: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 7929: } else {
7930: return -1;
1.253 stredwic 7931: }
1.26 www 7932: }
7933:
1.712 albertel 7934: sub stat_file {
7935: my ($uri) = @_;
1.787 albertel 7936: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 7937:
1.955 raeburn 7938: my ($udom,$uname,$file);
1.712 albertel 7939: if ($uri =~ m-^/(uploaded|editupload)/-) {
7940: ($udom,$uname,$file) =
1.811 albertel 7941: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 7942: $file = 'userfiles/'.$file;
7943: }
7944: if ($uri =~ m-^/res/-) {
7945: ($udom,$uname) =
1.807 albertel 7946: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 7947: $file = $uri;
7948: }
7949:
7950: if (!$udom || !$uname || !$file) {
7951: # unable to handle the uri
7952: return ();
7953: }
1.956 raeburn 7954: my $getpropath;
7955: if ($file =~ /^userfiles\//) {
7956: $getpropath = 1;
7957: }
1.955 raeburn 7958: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 7959: my @stats = split('&', $result);
1.721 banghart 7960:
1.712 albertel 7961: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7962: shift(@stats); #filename is first
7963: return @stats;
7964: }
7965: return ();
7966: }
7967:
1.26 www 7968: # -------------------------------------------------------- Value of a Condition
7969:
1.713 albertel 7970: # gets the value of a specific preevaluated condition
7971: # stored in the string $env{user.state.<cid>}
7972: # or looks up a condition reference in the bighash and if if hasn't
7973: # already been evaluated recurses into docondval to get the value of
7974: # the condition, then memoizing it to
7975: # $env{user.state.<cid>.<condition>}
1.40 www 7976: sub directcondval {
7977: my $number=shift;
1.620 albertel 7978: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 7979: &Apache::lonuserstate::evalstate();
7980: }
1.713 albertel 7981: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
7982: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
7983: } elsif ($number =~ /^_/) {
7984: my $sub_condition;
7985: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7986: &GDBM_READER(),0640)) {
7987: $sub_condition=$bighash{'conditions'.$number};
7988: untie(%bighash);
7989: }
7990: my $value = &docondval($sub_condition);
1.949 raeburn 7991: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 7992: return $value;
7993: }
1.620 albertel 7994: if ($env{'user.state.'.$env{'request.course.id'}}) {
7995: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 7996: } else {
7997: return 2;
7998: }
7999: }
8000:
1.713 albertel 8001: # get the collection of conditions for this resource
1.26 www 8002: sub condval {
8003: my $condidx=shift;
1.54 www 8004: my $allpathcond='';
1.713 albertel 8005: foreach my $cond (split(/\|/,$condidx)) {
8006: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8007: $allpathcond.=
8008: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8009: }
1.191 harris41 8010: }
1.54 www 8011: $allpathcond=~s/\|$//;
1.713 albertel 8012: return &docondval($allpathcond);
8013: }
8014:
8015: #evaluates an expression of conditions
8016: sub docondval {
8017: my ($allpathcond) = @_;
8018: my $result=0;
8019: if ($env{'request.course.id'}
8020: && defined($allpathcond)) {
8021: my $operand='|';
8022: my @stack;
8023: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8024: if ($chunk eq '(') {
8025: push @stack,($operand,$result);
8026: } elsif ($chunk eq ')') {
8027: my $before=pop @stack;
8028: if (pop @stack eq '&') {
8029: $result=$result>$before?$before:$result;
8030: } else {
8031: $result=$result>$before?$result:$before;
8032: }
8033: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8034: $operand=$chunk;
8035: } else {
8036: my $new=directcondval($chunk);
8037: if ($operand eq '&') {
8038: $result=$result>$new?$new:$result;
8039: } else {
8040: $result=$result>$new?$result:$new;
8041: }
8042: }
8043: }
1.26 www 8044: }
8045: return $result;
1.421 albertel 8046: }
8047:
8048: # ---------------------------------------------------- Devalidate courseresdata
8049:
8050: sub devalidatecourseresdata {
8051: my ($coursenum,$coursedomain)=@_;
8052: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8053: &devalidate_cache_new('courseres',$hashid);
1.28 www 8054: }
8055:
1.763 www 8056:
1.200 www 8057: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 8058: #
8059: # Parameters:
8060: # $coursenum - Number of the course.
8061: # $coursedomain - Domain at which the course was created.
8062: # Returns:
8063: # A hash of the course parameters along (I think) with timestamps
8064: # and version info.
1.877 foxr 8065:
1.624 albertel 8066: sub get_courseresdata {
8067: my ($coursenum,$coursedomain)=@_;
1.200 www 8068: my $coursehom=&homeserver($coursenum,$coursedomain);
8069: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8070: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 8071: my %dumpreply;
1.417 albertel 8072: unless (defined($cached)) {
1.624 albertel 8073: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 8074: $result=\%dumpreply;
1.251 albertel 8075: my ($tmp) = keys(%dumpreply);
8076: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 8077: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 8078: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8079: return $tmp;
1.416 albertel 8080: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 8081: $result=undef;
1.599 albertel 8082: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 8083: }
8084: }
1.624 albertel 8085: return $result;
8086: }
8087:
1.633 albertel 8088: sub devalidateuserresdata {
8089: my ($uname,$udom)=@_;
8090: my $hashid="$udom:$uname";
8091: &devalidate_cache_new('userres',$hashid);
8092: }
8093:
1.624 albertel 8094: sub get_userresdata {
8095: my ($uname,$udom)=@_;
8096: #most student don\'t have any data set, check if there is some data
8097: if (&EXT_cache_status($udom,$uname)) { return undef; }
8098:
8099: my $hashid="$udom:$uname";
8100: my ($result,$cached)=&is_cached_new('userres',$hashid);
8101: if (!defined($cached)) {
8102: my %resourcedata=&dump('resourcedata',$udom,$uname);
8103: $result=\%resourcedata;
8104: &do_cache_new('userres',$hashid,$result,600);
8105: }
8106: my ($tmp)=keys(%$result);
8107: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8108: return $result;
8109: }
8110: #error 2 occurs when the .db doesn't exist
8111: if ($tmp!~/error: 2 /) {
1.672 albertel 8112: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 8113: " Trying to get resource data for ".
8114: $uname." at ".$udom.": ".
8115: $tmp."</font>");
8116: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 8117: #&EXT_cache_set($udom,$uname);
8118: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 8119: undef($tmp); # not really an error so don't send it back
1.624 albertel 8120: }
8121: return $tmp;
8122: }
1.879 foxr 8123: #----------------------------------------------- resdata - return resource data
8124: # Purpose:
8125: # Return resource data for either users or for a course.
8126: # Parameters:
8127: # $name - Course/user name.
8128: # $domain - Name of the domain the user/course is registered on.
8129: # $type - Type of thing $name is (must be 'course' or 'user'
8130: # @which - Array of names of resources desired.
8131: # Returns:
8132: # The value of the first reasource in @which that is found in the
8133: # resource hash.
8134: # Exceptional Conditions:
8135: # If the $type passed in is not valid (not the string 'course' or
8136: # 'user', an undefined reference is returned.
8137: # If none of the resources are found, an undef is returned
1.624 albertel 8138: sub resdata {
8139: my ($name,$domain,$type,@which)=@_;
8140: my $result;
8141: if ($type eq 'course') {
8142: $result=&get_courseresdata($name,$domain);
8143: } elsif ($type eq 'user') {
8144: $result=&get_userresdata($name,$domain);
8145: }
8146: if (!ref($result)) { return $result; }
1.251 albertel 8147: foreach my $item (@which) {
1.927 albertel 8148: if (defined($result->{$item->[0]})) {
8149: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 8150: }
1.250 albertel 8151: }
1.291 albertel 8152: return undef;
1.200 www 8153: }
8154:
1.379 matthew 8155: #
8156: # EXT resource caching routines
8157: #
8158:
8159: sub clear_EXT_cache_status {
1.383 albertel 8160: &delenv('cache.EXT.');
1.379 matthew 8161: }
8162:
8163: sub EXT_cache_status {
8164: my ($target_domain,$target_user) = @_;
1.383 albertel 8165: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 8166: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 8167: # We know already the user has no data
8168: return 1;
8169: } else {
8170: return 0;
8171: }
8172: }
8173:
8174: sub EXT_cache_set {
8175: my ($target_domain,$target_user) = @_;
1.383 albertel 8176: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 8177: #&appenv({$cachename => time});
1.379 matthew 8178: }
8179:
1.28 www 8180: # --------------------------------------------------------- Value of a Variable
1.58 www 8181: sub EXT {
1.715 albertel 8182:
1.395 albertel 8183: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 8184: unless ($varname) { return ''; }
1.218 albertel 8185: #get real user name/domain, courseid and symb
8186: my $courseid;
1.359 albertel 8187: my $publicuser;
1.427 www 8188: if ($symbparm) {
8189: $symbparm=&get_symb_from_alias($symbparm);
8190: }
1.218 albertel 8191: if (!($uname && $udom)) {
1.790 albertel 8192: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 8193: if (!$symbparm) { $symbparm=$cursymb; }
8194: } else {
1.620 albertel 8195: $courseid=$env{'request.course.id'};
1.218 albertel 8196: }
1.48 www 8197: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8198: my $rest;
1.320 albertel 8199: if (defined($therest[0])) {
1.48 www 8200: $rest=join('.',@therest);
8201: } else {
8202: $rest='';
8203: }
1.320 albertel 8204:
1.57 www 8205: my $qualifierrest=$qualifier;
8206: if ($rest) { $qualifierrest.='.'.$rest; }
8207: my $spacequalifierrest=$space;
8208: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 8209: if ($realm eq 'user') {
1.48 www 8210: # --------------------------------------------------------------- user.resource
8211: if ($space eq 'resource') {
1.651 albertel 8212: if ( (defined($Apache::lonhomework::parsing_a_problem)
8213: || defined($Apache::lonhomework::parsing_a_task))
8214: &&
1.744 albertel 8215: ($symbparm eq &symbread()) ) {
8216: # if we are in the middle of processing the resource the
8217: # get the value we are planning on committing
8218: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8219: return $Apache::lonhomework::results{$qualifierrest};
8220: } else {
8221: return $Apache::lonhomework::history{$qualifierrest};
8222: }
1.335 albertel 8223: } else {
1.359 albertel 8224: my %restored;
1.620 albertel 8225: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 8226: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8227: } else {
8228: %restored=&restore($symbparm,$courseid,$udom,$uname);
8229: }
1.335 albertel 8230: return $restored{$qualifierrest};
8231: }
1.48 www 8232: # ----------------------------------------------------------------- user.access
8233: } elsif ($space eq 'access') {
1.218 albertel 8234: # FIXME - not supporting calls for a specific user
1.48 www 8235: return &allowed($qualifier,$rest);
8236: # ------------------------------------------ user.preferences, user.environment
8237: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 8238: if (($uname eq $env{'user.name'}) &&
8239: ($udom eq $env{'user.domain'})) {
8240: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 8241: } else {
1.359 albertel 8242: my %returnhash;
8243: if (!$publicuser) {
8244: %returnhash=&userenvironment($udom,$uname,
8245: $qualifierrest);
8246: }
1.218 albertel 8247: return $returnhash{$qualifierrest};
8248: }
1.48 www 8249: # ----------------------------------------------------------------- user.course
8250: } elsif ($space eq 'course') {
1.218 albertel 8251: # FIXME - not supporting calls for a specific user
1.620 albertel 8252: return $env{join('.',('request.course',$qualifier))};
1.48 www 8253: # ------------------------------------------------------------------- user.role
8254: } elsif ($space eq 'role') {
1.218 albertel 8255: # FIXME - not supporting calls for a specific user
1.620 albertel 8256: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 8257: if ($qualifier eq 'value') {
8258: return $role;
8259: } elsif ($qualifier eq 'extent') {
8260: return $where;
8261: }
8262: # ----------------------------------------------------------------- user.domain
8263: } elsif ($space eq 'domain') {
1.218 albertel 8264: return $udom;
1.48 www 8265: # ------------------------------------------------------------------- user.name
8266: } elsif ($space eq 'name') {
1.218 albertel 8267: return $uname;
1.48 www 8268: # ---------------------------------------------------- Any other user namespace
1.29 www 8269: } else {
1.359 albertel 8270: my %reply;
8271: if (!$publicuser) {
8272: %reply=&get($space,[$qualifierrest],$udom,$uname);
8273: }
8274: return $reply{$qualifierrest};
1.48 www 8275: }
1.236 www 8276: } elsif ($realm eq 'query') {
8277: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 8278: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8279: [$spacequalifierrest]);
1.620 albertel 8280: return $env{'form.'.$spacequalifierrest};
1.236 www 8281: } elsif ($realm eq 'request') {
1.48 www 8282: # ------------------------------------------------------------- request.browser
8283: if ($space eq 'browser') {
1.430 www 8284: if ($qualifier eq 'textremote') {
1.676 albertel 8285: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 8286: return 1;
8287: } else {
8288: return 0;
8289: }
8290: } else {
1.620 albertel 8291: return $env{'browser.'.$qualifier};
1.430 www 8292: }
1.57 www 8293: # ------------------------------------------------------------ request.filename
8294: } else {
1.620 albertel 8295: return $env{'request.'.$spacequalifierrest};
1.29 www 8296: }
1.28 www 8297: } elsif ($realm eq 'course') {
1.48 www 8298: # ---------------------------------------------------------- course.description
1.620 albertel 8299: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 8300: } elsif ($realm eq 'resource') {
1.165 www 8301:
1.620 albertel 8302: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 8303: if (!$symbparm) { $symbparm=&symbread(); }
8304: }
1.693 albertel 8305:
8306: if ($space eq 'title') {
8307: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8308: return &gettitle($symbparm);
8309: }
8310:
8311: if ($space eq 'map') {
8312: my ($map) = &decode_symb($symbparm);
8313: return &symbread($map);
8314: }
1.905 albertel 8315: if ($space eq 'filename') {
8316: if ($symbparm) {
8317: return &clutter((&decode_symb($symbparm))[2]);
8318: }
8319: return &hreflocation('',$env{'request.filename'});
8320: }
1.693 albertel 8321:
8322: my ($section, $group, @groups);
1.593 albertel 8323: my ($courselevelm,$courselevel);
1.539 albertel 8324: if ($symbparm && defined($courseid) &&
1.620 albertel 8325: $courseid eq $env{'request.course.id'}) {
1.165 www 8326:
1.218 albertel 8327: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 8328:
1.60 www 8329: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 8330: my $symbp=$symbparm;
1.735 albertel 8331: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 8332:
8333: my $symbparm=$symbp.'.'.$spacequalifierrest;
8334: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8335:
1.620 albertel 8336: if (($env{'user.name'} eq $uname) &&
8337: ($env{'user.domain'} eq $udom)) {
8338: $section=$env{'request.course.sec'};
1.733 raeburn 8339: @groups = split(/:/,$env{'request.course.groups'});
8340: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 8341: } else {
1.539 albertel 8342: if (! defined($usection)) {
1.551 albertel 8343: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 8344: } else {
8345: $section = $usection;
8346: }
1.733 raeburn 8347: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 8348: }
8349:
8350: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8351: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8352: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8353:
1.593 albertel 8354: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 8355: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 8356: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 8357:
1.60 www 8358: # ----------------------------------------------------------- first, check user
1.624 albertel 8359:
8360: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 8361: ([$courselevelr,'resource'],
8362: [$courselevelm,'map' ],
8363: [$courselevel, 'course' ]));
1.931 albertel 8364: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 8365:
1.594 albertel 8366: # ------------------------------------------------ second, check some of course
1.684 raeburn 8367: my $coursereply;
1.691 raeburn 8368: if (@groups > 0) {
8369: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8370: $mapparm,$spacequalifierrest);
1.927 albertel 8371: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 8372: }
1.96 www 8373:
1.684 raeburn 8374: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 8375: $env{'course.'.$courseid.'.domain'},
8376: 'course',
8377: ([$seclevelr, 'resource'],
8378: [$seclevelm, 'map' ],
8379: [$seclevel, 'course' ],
8380: [$courselevelr,'resource']));
8381: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 8382:
1.60 www 8383: # ------------------------------------------------------ third, check map parms
1.218 albertel 8384: my %parmhash=();
8385: my $thisparm='';
8386: if (tie(%parmhash,'GDBM_File',
1.620 albertel 8387: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 8388: &GDBM_READER(),0640)) {
1.218 albertel 8389: $thisparm=$parmhash{$symbparm};
8390: untie(%parmhash);
8391: }
1.927 albertel 8392: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 8393: }
1.594 albertel 8394: # ------------------------------------------ fourth, look in resource metadata
1.71 www 8395:
1.218 albertel 8396: $spacequalifierrest=~s/\./\_/;
1.282 albertel 8397: my $filename;
8398: if (!$symbparm) { $symbparm=&symbread(); }
8399: if ($symbparm) {
1.409 www 8400: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 8401: } else {
1.620 albertel 8402: $filename=$env{'request.filename'};
1.282 albertel 8403: }
8404: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 8405: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 8406: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 8407: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 8408:
1.927 albertel 8409: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 8410: if ($symbparm && defined($courseid) &&
1.620 albertel 8411: $courseid eq $env{'request.course.id'}) {
1.624 albertel 8412: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8413: $env{'course.'.$courseid.'.domain'},
8414: 'course',
1.927 albertel 8415: ([$courselevelm,'map' ],
8416: [$courselevel, 'course']));
8417: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 8418: }
1.145 www 8419: # ------------------------------------------------------------------ Cascade up
1.218 albertel 8420: unless ($space eq '0') {
1.336 albertel 8421: my @parts=split(/_/,$space);
8422: my $id=pop(@parts);
8423: my $part=join('_',@parts);
8424: if ($part eq '') { $part='0'; }
1.927 albertel 8425: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 8426: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 8427: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 8428: }
1.395 albertel 8429: if ($recurse) { return undef; }
8430: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 8431: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 8432: # ---------------------------------------------------- Any other user namespace
8433: } elsif ($realm eq 'environment') {
8434: # ----------------------------------------------------------------- environment
1.620 albertel 8435: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8436: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 8437: } else {
1.770 albertel 8438: if ($uname eq 'anonymous' && $udom eq '') {
8439: return '';
8440: }
1.219 albertel 8441: my %returnhash=&userenvironment($udom,$uname,
8442: $spacequalifierrest);
8443: return $returnhash{$spacequalifierrest};
8444: }
1.28 www 8445: } elsif ($realm eq 'system') {
1.48 www 8446: # ----------------------------------------------------------------- system.time
8447: if ($space eq 'time') {
8448: return time;
8449: }
1.696 albertel 8450: } elsif ($realm eq 'server') {
8451: # ----------------------------------------------------------------- system.time
8452: if ($space eq 'name') {
8453: return $ENV{'SERVER_NAME'};
8454: }
1.28 www 8455: }
1.48 www 8456: return '';
1.61 www 8457: }
8458:
1.927 albertel 8459: sub get_reply {
8460: my ($reply_value) = @_;
1.940 raeburn 8461: if (ref($reply_value) eq 'ARRAY') {
8462: if (wantarray) {
8463: return @$reply_value;
8464: }
8465: return $reply_value->[0];
8466: } else {
8467: return $reply_value;
1.927 albertel 8468: }
8469: }
8470:
1.691 raeburn 8471: sub check_group_parms {
8472: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8473: my @groupitems = ();
8474: my $resultitem;
1.927 albertel 8475: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8476: foreach my $group (@{$groups}) {
8477: foreach my $level (@levels) {
1.927 albertel 8478: my $item = $courseid.'.['.$group.'].'.$level->[0];
8479: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8480: }
8481: }
8482: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8483: $env{'course.'.$courseid.'.domain'},
8484: 'course',@groupitems);
8485: return $coursereply;
8486: }
8487:
8488: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8489: my ($courseid,@groups) = @_;
8490: @groups = sort(@groups);
1.691 raeburn 8491: return @groups;
8492: }
8493:
1.395 albertel 8494: sub packages_tab_default {
8495: my ($uri,$varname)=@_;
8496: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8497:
8498: my (@extension,@specifics,$do_default);
8499: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8500: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8501: if ($pack_type eq 'default') {
8502: $do_default=1;
8503: } elsif ($pack_type eq 'extension') {
8504: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8505: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8506: # only look at packages defaults for packages that this id is
1.738 albertel 8507: push(@specifics,[$package,$pack_type,$pack_part]);
8508: }
8509: }
8510: # first look for a package that matches the requested part id
8511: foreach my $package (@specifics) {
8512: my (undef,$pack_type,$pack_part)=@{$package};
8513: next if ($pack_part ne $part);
8514: if (defined($packagetab{"$pack_type&$name&default"})) {
8515: return $packagetab{"$pack_type&$name&default"};
8516: }
8517: }
8518: # look for any possible matching non extension_ package
8519: foreach my $package (@specifics) {
8520: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8521: if (defined($packagetab{"$pack_type&$name&default"})) {
8522: return $packagetab{"$pack_type&$name&default"};
8523: }
1.585 albertel 8524: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8525: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8526: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8527: }
8528: }
1.738 albertel 8529: # look for any posible extension_ match
8530: foreach my $package (@extension) {
8531: my ($package,$pack_type)=@{$package};
8532: if (defined($packagetab{"$pack_type&$name&default"})) {
8533: return $packagetab{"$pack_type&$name&default"};
8534: }
8535: if (defined($packagetab{$package."&$name&default"})) {
8536: return $packagetab{$package."&$name&default"};
8537: }
8538: }
8539: # look for a global default setting
8540: if ($do_default && defined($packagetab{"default&$name&default"})) {
8541: return $packagetab{"default&$name&default"};
8542: }
1.395 albertel 8543: return undef;
8544: }
8545:
1.334 albertel 8546: sub add_prefix_and_part {
8547: my ($prefix,$part)=@_;
8548: my $keyroot;
8549: if (defined($prefix) && $prefix !~ /^__/) {
8550: # prefix that has a part already
8551: $keyroot=$prefix;
8552: } elsif (defined($prefix)) {
8553: # prefix that is missing a part
8554: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8555: } else {
8556: # no prefix at all
8557: if (defined($part)) { $keyroot='_'.$part; }
8558: }
8559: return $keyroot;
8560: }
8561:
1.71 www 8562: # ---------------------------------------------------------------- Get metadata
8563:
1.599 albertel 8564: my %metaentry;
1.1070 www 8565: my %importedpartids;
1.71 www 8566: sub metadata {
1.176 www 8567: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 8568: $uri=&declutter($uri);
1.288 albertel 8569: # if it is a non metadata possible uri return quickly
1.529 albertel 8570: if (($uri eq '') ||
8571: (($uri =~ m|^/*adm/|) &&
1.698 albertel 8572: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108 raeburn 8573: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 8574: return undef;
8575: }
8576: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8577: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 8578: return undef;
1.288 albertel 8579: }
1.73 www 8580: my $filename=$uri;
8581: $uri=~s/\.meta$//;
1.172 www 8582: #
8583: # Is the metadata already cached?
1.177 www 8584: # Look at timestamp of caching
1.172 www 8585: # Everything is cached by the main uri, libraries are never directly cached
8586: #
1.428 albertel 8587: if (!defined($liburi)) {
1.599 albertel 8588: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 8589: if (defined($cached)) { return $result->{':'.$what}; }
8590: }
8591: {
1.1069 www 8592: # Imported parts would go here
1.1070 www 8593: my %importedids=();
8594: my @origfileimportpartids=();
1.1069 www 8595: my $importedparts=0;
1.172 www 8596: #
8597: # Is this a recursive call for a library?
8598: #
1.599 albertel 8599: # if (! exists($metacache{$uri})) {
8600: # $metacache{$uri}={};
8601: # }
1.924 albertel 8602: my $cachetime = 60*60;
1.171 www 8603: if ($liburi) {
8604: $liburi=&declutter($liburi);
8605: $filename=$liburi;
1.401 bowersj2 8606: } else {
1.599 albertel 8607: &devalidate_cache_new('meta',$uri);
8608: undef(%metaentry);
1.401 bowersj2 8609: }
1.140 www 8610: my %metathesekeys=();
1.73 www 8611: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 8612: my $metastring;
1.924 albertel 8613: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 8614: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 8615: $metastring =
1.929 albertel 8616: &Apache::lonnet::ssi_body($which,
1.924 albertel 8617: ('grade_target' => 'meta'));
8618: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 8619: } elsif (($uri !~ m -^(editupload)/-) &&
8620: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 8621: my $file=&filelocation('',&clutter($filename));
1.599 albertel 8622: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 8623: $metastring=&getfile($file);
1.489 albertel 8624: }
1.208 albertel 8625: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 8626: my $token;
1.140 www 8627: undef %metathesekeys;
1.71 www 8628: while ($token=$parser->get_token) {
1.339 albertel 8629: if ($token->[0] eq 'S') {
8630: if (defined($token->[2]->{'package'})) {
1.172 www 8631: #
8632: # This is a package - get package info
8633: #
1.339 albertel 8634: my $package=$token->[2]->{'package'};
8635: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8636: if (defined($token->[2]->{'id'})) {
8637: $keyroot.='_'.$token->[2]->{'id'};
8638: }
1.599 albertel 8639: if ($metaentry{':packages'}) {
8640: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 8641: } else {
1.599 albertel 8642: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 8643: }
1.736 albertel 8644: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 8645: my $part=$keyroot;
8646: $part=~s/^\_//;
1.736 albertel 8647: if ($pack_entry=~/^\Q$package\E\&/ ||
8648: $pack_entry=~/^\Q$package\E_0\&/) {
8649: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 8650: # ignore package.tab specified default values
8651: # here &package_tab_default() will fetch those
8652: if ($subp eq 'default') { next; }
1.736 albertel 8653: my $value=$packagetab{$pack_entry};
1.432 albertel 8654: my $unikey;
8655: if ($pack =~ /_0$/) {
8656: $unikey='parameter_0_'.$name;
8657: $part=0;
8658: } else {
8659: $unikey='parameter'.$keyroot.'_'.$name;
8660: }
1.339 albertel 8661: if ($subp eq 'display') {
8662: $value.=' [Part: '.$part.']';
8663: }
1.599 albertel 8664: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 8665: $metathesekeys{$unikey}=1;
1.599 albertel 8666: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8667: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 8668: }
1.599 albertel 8669: if (defined($metaentry{':'.$unikey.'.default'})) {
8670: $metaentry{':'.$unikey}=
8671: $metaentry{':'.$unikey.'.default'};
1.356 albertel 8672: }
1.339 albertel 8673: }
8674: }
8675: } else {
1.172 www 8676: #
8677: # This is not a package - some other kind of start tag
1.339 albertel 8678: #
8679: my $entry=$token->[1];
1.1068 www 8680: my $unikey='';
1.175 www 8681:
1.339 albertel 8682: if ($entry eq 'import') {
1.175 www 8683: #
8684: # Importing a library here
1.339 albertel 8685: #
1.1067 www 8686: my $location=$parser->get_text('/import');
8687: my $dir=$filename;
8688: $dir=~s|[^/]*$||;
8689: $location=&filelocation($dir,$location);
1.1069 www 8690:
1.1068 www 8691: my $importmode=$token->[2]->{'importmode'};
8692: if ($importmode eq 'problem') {
1.1069 www 8693: # Import as problem/response
1.1068 www 8694: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8695: } elsif ($importmode eq 'part') {
8696: # Import as part(s)
1.1069 www 8697: $importedparts=1;
8698: # We need to get the original file and the imported file to get the part order correct
8699: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
8700: # Load and inspect original file
1.1070 www 8701: if ($#origfileimportpartids<0) {
8702: undef(%importedpartids);
8703: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
8704: my $origfile=&getfile($origfilelocation);
8705: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
8706: }
8707:
1.1069 www 8708: # Load and inspect imported file
8709: my $impfile=&getfile($location);
8710: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
8711: if ($#impfilepartids>=0) {
8712: # This problem had parts
1.1070 www 8713: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 8714: } else {
8715: # Importing by turning a single problem into a problem part
8716: # It gets the import-tags ID as part-ID
8717: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 8718: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 8719: }
1.1068 www 8720: } else {
8721: # Normal import
8722: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8723: if (defined($token->[2]->{'id'})) {
8724: $unikey.='_'.$token->[2]->{'id'};
8725: }
1.1067 www 8726: }
8727:
1.339 albertel 8728: if ($depthcount<20) {
1.736 albertel 8729: my $metadata =
8730: &metadata($uri,'keys', $location,$unikey,
8731: $depthcount+1);
8732: foreach my $meta (split(',',$metadata)) {
8733: $metaentry{':'.$meta}=$metaentry{':'.$meta};
8734: $metathesekeys{$meta}=1;
1.339 albertel 8735: }
1.1068 www 8736:
8737: }
1.1067 www 8738: } else {
8739: #
8740: # Not importing, some other kind of non-package, non-library start tag
8741: #
8742: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
8743: if (defined($token->[2]->{'id'})) {
8744: $unikey.='_'.$token->[2]->{'id'};
8745: }
1.339 albertel 8746: if (defined($token->[2]->{'name'})) {
8747: $unikey.='_'.$token->[2]->{'name'};
8748: }
8749: $metathesekeys{$unikey}=1;
1.736 albertel 8750: foreach my $param (@{$token->[3]}) {
8751: $metaentry{':'.$unikey.'.'.$param} =
8752: $token->[2]->{$param};
1.339 albertel 8753: }
8754: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 8755: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 8756: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
8757: # only ws inside the tag, and not in default, so use default
8758: # as value
1.599 albertel 8759: $metaentry{':'.$unikey}=$default;
1.908 albertel 8760: } elsif ( $internaltext =~ /\S/ ) {
8761: # something interesting inside the tag
8762: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 8763: } else {
1.908 albertel 8764: # no interesting values, don't set a default
1.339 albertel 8765: }
1.172 www 8766: # end of not-a-package not-a-library import
1.339 albertel 8767: }
1.172 www 8768: # end of not-a-package start tag
1.339 albertel 8769: }
1.172 www 8770: # the next is the end of "start tag"
1.339 albertel 8771: }
8772: }
1.483 albertel 8773: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 8774: $extension = lc($extension);
8775: if ($extension eq 'htm') { $extension='html'; }
8776:
1.737 albertel 8777: foreach my $key (keys(%packagetab)) {
1.483 albertel 8778: #no specific packages #how's our extension
8779: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 8780: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 8781: \%metathesekeys);
8782: }
1.883 albertel 8783:
8784: if (!exists($metaentry{':packages'})
8785: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 8786: foreach my $key (keys(%packagetab)) {
1.483 albertel 8787: #no specific packages well let's get default then
8788: if ($key!~/^default&/) { next; }
1.488 albertel 8789: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 8790: \%metathesekeys);
8791: }
8792: }
1.338 www 8793: # are there custom rights to evaluate
1.599 albertel 8794: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 8795:
1.338 www 8796: #
8797: # Importing a rights file here
1.339 albertel 8798: #
8799: unless ($depthcount) {
1.599 albertel 8800: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 8801: my $dir=$filename;
8802: $dir=~s|[^/]*$||;
8803: $location=&filelocation($dir,$location);
1.736 albertel 8804: my $rights_metadata =
8805: &metadata($uri,'keys',$location,'_rights',
8806: $depthcount+1);
8807: foreach my $rights (split(',',$rights_metadata)) {
8808: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8809: $metathesekeys{$rights}=1;
1.339 albertel 8810: }
8811: }
8812: }
1.737 albertel 8813: # uniqifiy package listing
8814: my %seen;
8815: my @uniq_packages =
8816: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8817: $metaentry{':packages'} = join(',',@uniq_packages);
8818:
1.1070 www 8819: if ($importedparts) {
8820: # We had imported parts and need to rebuild partorder
8821: $metaentry{':partorder'}='';
8822: $metathesekeys{'partorder'}=1;
8823: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
8824: if ($origfileimportpartids[$index] eq 'part') {
8825: # original part, part of the problem
8826: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
8827: } else {
8828: # we have imported parts at this position
8829: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
8830: }
8831: }
8832: $metaentry{':partorder'}=~s/^\,//;
8833: }
8834:
1.737 albertel 8835: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 8836: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8837: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 8838: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 8839: # this is the end of "was not already recently cached
1.71 www 8840: }
1.599 albertel 8841: return $metaentry{':'.$what};
1.261 albertel 8842: }
8843:
1.488 albertel 8844: sub metadata_create_package_def {
1.483 albertel 8845: my ($uri,$key,$package,$metathesekeys)=@_;
8846: my ($pack,$name,$subp)=split(/\&/,$key);
8847: if ($subp eq 'default') { next; }
8848:
1.599 albertel 8849: if (defined($metaentry{':packages'})) {
8850: $metaentry{':packages'}.=','.$package;
1.483 albertel 8851: } else {
1.599 albertel 8852: $metaentry{':packages'}=$package;
1.483 albertel 8853: }
8854: my $value=$packagetab{$key};
8855: my $unikey;
8856: $unikey='parameter_0_'.$name;
1.599 albertel 8857: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 8858: $$metathesekeys{$unikey}=1;
1.599 albertel 8859: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8860: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 8861: }
1.599 albertel 8862: if (defined($metaentry{':'.$unikey.'.default'})) {
8863: $metaentry{':'.$unikey}=
8864: $metaentry{':'.$unikey.'.default'};
1.483 albertel 8865: }
8866: }
8867:
1.261 albertel 8868: sub metadata_generate_part0 {
8869: my ($metadata,$metacache,$uri) = @_;
8870: my %allnames;
1.737 albertel 8871: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 8872: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 8873: my $part=$$metacache{':'.$metakey.'.part'};
8874: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 8875: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 8876: $allnames{$name}=$part;
8877: }
8878: }
8879: }
8880: foreach my $name (keys(%allnames)) {
8881: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 8882: my $key=":parameter_0_$name";
1.261 albertel 8883: $$metacache{"$key.part"}='0';
8884: $$metacache{"$key.name"}=$name;
1.428 albertel 8885: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 8886: $allnames{$name}.'_'.$name.
8887: '.type'};
1.428 albertel 8888: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 8889: '.display'};
1.644 www 8890: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 8891: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 8892: $$metacache{"$key.display"}=$olddis;
8893: }
1.71 www 8894: }
8895:
1.764 albertel 8896: # ------------------------------------------------------ Devalidate title cache
8897:
8898: sub devalidate_title_cache {
8899: my ($url)=@_;
8900: if (!$env{'request.course.id'}) { return; }
8901: my $symb=&symbread($url);
8902: if (!$symb) { return; }
8903: my $key=$env{'request.course.id'}."\0".$symb;
8904: &devalidate_cache_new('title',$key);
8905: }
8906:
1.1014 droeschl 8907: # ------------------------------------------------- Get the title of a course
8908:
8909: sub current_course_title {
8910: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8911: }
1.301 www 8912: # ------------------------------------------------- Get the title of a resource
8913:
8914: sub gettitle {
8915: my $urlsymb=shift;
8916: my $symb=&symbread($urlsymb);
1.534 albertel 8917: if ($symb) {
1.620 albertel 8918: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 8919: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 8920: if (defined($cached)) {
8921: return $result;
8922: }
1.534 albertel 8923: my ($map,$resid,$url)=&decode_symb($symb);
8924: my $title='';
1.907 albertel 8925: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8926: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8927: } else {
8928: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8929: &GDBM_READER(),0640)) {
8930: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8931: $title=$bighash{'title_'.$mapid.'.'.$resid};
8932: untie(%bighash);
8933: }
1.534 albertel 8934: }
8935: $title=~s/\&colon\;/\:/gs;
8936: if ($title) {
1.599 albertel 8937: return &do_cache_new('title',$key,$title,600);
1.534 albertel 8938: }
8939: $urlsymb=$url;
8940: }
8941: my $title=&metadata($urlsymb,'title');
8942: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8943: return $title;
1.301 www 8944: }
1.613 albertel 8945:
1.614 albertel 8946: sub get_slot {
8947: my ($which,$cnum,$cdom)=@_;
8948: if (!$cnum || !$cdom) {
1.790 albertel 8949: (undef,my $courseid)=&whichuser();
1.620 albertel 8950: $cdom=$env{'course.'.$courseid.'.domain'};
8951: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 8952: }
1.703 albertel 8953: my $key=join("\0",'slots',$cdom,$cnum,$which);
8954: my %slotinfo;
8955: if (exists($remembered{$key})) {
8956: $slotinfo{$which} = $remembered{$key};
8957: } else {
8958: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8959: &Apache::lonhomework::showhash(%slotinfo);
8960: my ($tmp)=keys(%slotinfo);
8961: if ($tmp=~/^error:/) { return (); }
8962: $remembered{$key} = $slotinfo{$which};
8963: }
1.616 albertel 8964: if (ref($slotinfo{$which}) eq 'HASH') {
8965: return %{$slotinfo{$which}};
8966: }
8967: return $slotinfo{$which};
1.614 albertel 8968: }
1.31 www 8969: # ------------------------------------------------- Update symbolic store links
8970:
8971: sub symblist {
8972: my ($mapname,%newhash)=@_;
1.438 www 8973: $mapname=&deversion(&declutter($mapname));
1.31 www 8974: my %hash;
1.620 albertel 8975: if (($env{'request.course.fn'}) && (%newhash)) {
8976: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8977: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 8978: foreach my $url (keys(%newhash)) {
1.711 albertel 8979: next if ($url eq 'last_known'
8980: && $env{'form.no_update_last_known'});
8981: $hash{declutter($url)}=&encode_symb($mapname,
8982: $newhash{$url}->[1],
8983: $newhash{$url}->[0]);
1.191 harris41 8984: }
1.31 www 8985: if (untie(%hash)) {
8986: return 'ok';
8987: }
8988: }
8989: }
8990: return 'error';
1.212 www 8991: }
8992:
8993: # --------------------------------------------------------------- Verify a symb
8994:
8995: sub symbverify {
1.510 www 8996: my ($symb,$thisurl)=@_;
8997: my $thisfn=$thisurl;
1.439 www 8998: $thisfn=&declutter($thisfn);
1.215 www 8999: # direct jump to resource in page or to a sequence - will construct own symbs
9000: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
9001: # check URL part
1.409 www 9002: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 9003:
1.431 www 9004: unless ($url eq $thisfn) { return 0; }
1.213 www 9005:
1.216 www 9006: $symb=&symbclean($symb);
1.510 www 9007: $thisurl=&deversion($thisurl);
1.439 www 9008: $thisfn=&deversion($thisfn);
1.213 www 9009:
9010: my %bighash;
9011: my $okay=0;
1.431 www 9012:
1.620 albertel 9013: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9014: &GDBM_READER(),0640)) {
1.1032 raeburn 9015: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
9016: $thisurl =~ s/\?.+$//;
9017: }
1.510 www 9018: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102 raeburn 9019: unless ($ids) {
9020: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
9021: $ids=$bighash{$idkey};
1.216 www 9022: }
9023: if ($ids) {
9024: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 9025: foreach my $id (split(/\,/,$ids)) {
9026: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 9027: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
9028: $symb =~ s/\?.+$//;
9029: }
1.216 www 9030: if (
9031: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
9032: eq $symb) {
1.620 albertel 9033: if (($env{'request.role.adv'}) ||
1.1101 raeburn 9034: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
9035: ($thisurl eq '/adm/navmaps')) {
1.582 albertel 9036: $okay=1;
9037: }
9038: }
1.216 www 9039: }
9040: }
1.213 www 9041: untie(%bighash);
9042: }
9043: return $okay;
1.31 www 9044: }
9045:
1.210 www 9046: # --------------------------------------------------------------- Clean-up symb
9047:
9048: sub symbclean {
9049: my $symb=shift;
1.568 albertel 9050: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 9051: # remove version from map
9052: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 9053:
1.210 www 9054: # remove version from URL
9055: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 9056:
1.507 www 9057: # remove wrapper
9058:
1.510 www 9059: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 9060: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 9061: return $symb;
1.409 www 9062: }
9063:
9064: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 9065:
9066: sub encode_symb {
9067: my ($map,$resid,$url)=@_;
9068: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
9069: }
1.409 www 9070:
9071: sub decode_symb {
1.568 albertel 9072: my $symb=shift;
9073: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9074: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 9075: return (&fixversion($map),$resid,&fixversion($url));
9076: }
9077:
9078: sub fixversion {
9079: my $fn=shift;
1.609 banghart 9080: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 9081: my %bighash;
9082: my $uri=&clutter($fn);
1.620 albertel 9083: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 9084: # is this cached?
1.599 albertel 9085: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 9086: if (defined($cached)) { return $result; }
9087: # unfortunately not cached, or expired
1.620 albertel 9088: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 9089: &GDBM_READER(),0640)) {
9090: if ($bighash{'version_'.$uri}) {
9091: my $version=$bighash{'version_'.$uri};
1.444 www 9092: unless (($version eq 'mostrecent') ||
9093: ($version==&getversion($uri))) {
1.440 www 9094: $uri=~s/\.(\w+)$/\.$version\.$1/;
9095: }
9096: }
9097: untie %bighash;
1.413 www 9098: }
1.599 albertel 9099: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 9100: }
9101:
9102: sub deversion {
9103: my $url=shift;
9104: $url=~s/\.\d+\.(\w+)$/\.$1/;
9105: return $url;
1.210 www 9106: }
9107:
1.31 www 9108: # ------------------------------------------------------ Return symb list entry
9109:
9110: sub symbread {
1.249 www 9111: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 9112: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 9113: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 9114: # no filename provided? try from environment
1.44 www 9115: unless ($thisfn) {
1.620 albertel 9116: if ($env{'request.symb'}) {
9117: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 9118: }
1.620 albertel 9119: $thisfn=$env{'request.filename'};
1.44 www 9120: }
1.569 albertel 9121: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 9122: # is that filename actually a symb? Verify, clean, and return
9123: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 9124: if (&symbverify($thisfn,$1)) {
1.620 albertel 9125: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 9126: }
1.242 www 9127: }
1.44 www 9128: $thisfn=declutter($thisfn);
1.31 www 9129: my %hash;
1.37 www 9130: my %bighash;
9131: my $syval='';
1.620 albertel 9132: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 9133: my $targetfn = $thisfn;
1.609 banghart 9134: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 9135: $targetfn = 'adm/wrapper/'.$thisfn;
9136: }
1.687 albertel 9137: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9138: $targetfn=$1;
9139: }
1.620 albertel 9140: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9141: &GDBM_READER(),0640)) {
1.481 raeburn 9142: $syval=$hash{$targetfn};
1.37 www 9143: untie(%hash);
9144: }
9145: # ---------------------------------------------------------- There was an entry
9146: if ($syval) {
1.601 albertel 9147: #unless ($syval=~/\_\d+$/) {
1.620 albertel 9148: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 9149: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9150: #return $env{$cache_str}='';
1.601 albertel 9151: #}
9152: #$syval.=$1;
9153: #}
1.37 www 9154: } else {
9155: # ------------------------------------------------------- Was not in symb table
1.620 albertel 9156: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9157: &GDBM_READER(),0640)) {
1.37 www 9158: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 9159: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 9160: unless ($ids) {
9161: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 9162: }
9163: unless ($ids) {
9164: # alias?
9165: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 9166: }
1.37 www 9167: if ($ids) {
9168: # ------------------------------------------------------------------- Has ID(s)
9169: my @possibilities=split(/\,/,$ids);
1.39 www 9170: if ($#possibilities==0) {
9171: # ----------------------------------------------- There is only one possibility
1.37 www 9172: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 9173: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9174: $resid,$thisfn);
1.249 www 9175: } elsif (!$donotrecurse) {
1.39 www 9176: # ------------------------------------------ There is more than one possibility
9177: my $realpossible=0;
1.800 albertel 9178: foreach my $id (@possibilities) {
9179: my $file=$bighash{'src_'.$id};
1.39 www 9180: if (&allowed('bre',$file)) {
1.800 albertel 9181: my ($mapid,$resid)=split(/\./,$id);
1.39 www 9182: if ($bighash{'map_type_'.$mapid} ne 'page') {
9183: $realpossible++;
1.626 albertel 9184: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9185: $resid,$thisfn);
1.39 www 9186: }
9187: }
1.191 harris41 9188: }
1.39 www 9189: if ($realpossible!=1) { $syval=''; }
1.249 www 9190: } else {
9191: $syval='';
1.37 www 9192: }
9193: }
9194: untie(%bighash)
1.481 raeburn 9195: }
1.31 www 9196: }
1.62 www 9197: if ($syval) {
1.620 albertel 9198: return $env{$cache_str}=$syval;
1.62 www 9199: }
1.31 www 9200: }
1.949 raeburn 9201: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9202: return $env{$cache_str}='';
1.31 www 9203: }
9204:
9205: # ---------------------------------------------------------- Return random seed
9206:
1.32 www 9207: sub numval {
9208: my $txt=shift;
9209: $txt=~tr/A-J/0-9/;
9210: $txt=~tr/a-j/0-9/;
9211: $txt=~tr/K-T/0-9/;
9212: $txt=~tr/k-t/0-9/;
9213: $txt=~tr/U-Z/0-5/;
9214: $txt=~tr/u-z/0-5/;
9215: $txt=~s/\D//g;
1.564 albertel 9216: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 9217: return int($txt);
1.368 albertel 9218: }
9219:
1.484 albertel 9220: sub numval2 {
9221: my $txt=shift;
9222: $txt=~tr/A-J/0-9/;
9223: $txt=~tr/a-j/0-9/;
9224: $txt=~tr/K-T/0-9/;
9225: $txt=~tr/k-t/0-9/;
9226: $txt=~tr/U-Z/0-5/;
9227: $txt=~tr/u-z/0-5/;
9228: $txt=~s/\D//g;
9229: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9230: my $total;
9231: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 9232: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 9233: return int($total);
9234: }
9235:
1.575 albertel 9236: sub numval3 {
9237: use integer;
9238: my $txt=shift;
9239: $txt=~tr/A-J/0-9/;
9240: $txt=~tr/a-j/0-9/;
9241: $txt=~tr/K-T/0-9/;
9242: $txt=~tr/k-t/0-9/;
9243: $txt=~tr/U-Z/0-5/;
9244: $txt=~tr/u-z/0-5/;
9245: $txt=~s/\D//g;
9246: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9247: my $total;
9248: foreach my $val (@txts) { $total+=$val; }
9249: if ($_64bit) { $total=(($total<<32)>>32); }
9250: return $total;
9251: }
9252:
1.675 albertel 9253: sub digest {
9254: my ($data)=@_;
9255: my $digest=&Digest::MD5::md5($data);
9256: my ($a,$b,$c,$d)=unpack("iiii",$digest);
9257: my ($e,$f);
9258: {
9259: use integer;
9260: $e=($a+$b);
9261: $f=($c+$d);
9262: if ($_64bit) {
9263: $e=(($e<<32)>>32);
9264: $f=(($f<<32)>>32);
9265: }
9266: }
9267: if (wantarray) {
9268: return ($e,$f);
9269: } else {
9270: my $g;
9271: {
9272: use integer;
9273: $g=($e+$f);
9274: if ($_64bit) {
9275: $g=(($g<<32)>>32);
9276: }
9277: }
9278: return $g;
9279: }
9280: }
9281:
1.368 albertel 9282: sub latest_rnd_algorithm_id {
1.675 albertel 9283: return '64bit5';
1.366 albertel 9284: }
1.32 www 9285:
1.503 albertel 9286: sub get_rand_alg {
9287: my ($courseid)=@_;
1.790 albertel 9288: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 9289: if ($courseid) {
1.620 albertel 9290: return $env{"course.$courseid.rndseed"};
1.503 albertel 9291: }
9292: return &latest_rnd_algorithm_id();
9293: }
9294:
1.562 albertel 9295: sub validCODE {
9296: my ($CODE)=@_;
9297: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9298: return 0;
9299: }
9300:
1.491 albertel 9301: sub getCODE {
1.620 albertel 9302: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 9303: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9304: defined($Apache::lonhomework::parsing_a_task) ) &&
9305: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 9306: return $Apache::lonhomework::history{'resource.CODE'};
9307: }
9308: return undef;
9309: }
9310:
1.31 www 9311: sub rndseed {
1.155 albertel 9312: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 9313: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 9314: if (!defined($symb)) {
1.366 albertel 9315: unless ($symb=$wsymb) { return time; }
9316: }
9317: if (!$courseid) { $courseid=$wcourseid; }
9318: if (!$domain) { $domain=$wdomain; }
9319: if (!$username) { $username=$wusername }
1.503 albertel 9320: my $which=&get_rand_alg();
1.1110 www 9321:
1.491 albertel 9322: if (defined(&getCODE())) {
1.675 albertel 9323: if ($which eq '64bit5') {
9324: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9325: } elsif ($which eq '64bit4') {
1.575 albertel 9326: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9327: } else {
9328: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9329: }
1.675 albertel 9330: } elsif ($which eq '64bit5') {
9331: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 9332: } elsif ($which eq '64bit4') {
9333: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 9334: } elsif ($which eq '64bit3') {
9335: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 9336: } elsif ($which eq '64bit2') {
9337: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 9338: } elsif ($which eq '64bit') {
9339: return &rndseed_64bit($symb,$courseid,$domain,$username);
9340: }
9341: return &rndseed_32bit($symb,$courseid,$domain,$username);
9342: }
9343:
9344: sub rndseed_32bit {
9345: my ($symb,$courseid,$domain,$username)=@_;
9346: {
9347: use integer;
9348: my $symbchck=unpack("%32C*",$symb) << 27;
9349: my $symbseed=numval($symb) << 22;
9350: my $namechck=unpack("%32C*",$username) << 17;
9351: my $nameseed=numval($username) << 12;
9352: my $domainseed=unpack("%32C*",$domain) << 7;
9353: my $courseseed=unpack("%32C*",$courseid);
9354: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 9355: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9356: #&logthis("rndseed :$num:$symb");
1.564 albertel 9357: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 9358: return $num;
9359: }
9360: }
9361:
9362: sub rndseed_64bit {
9363: my ($symb,$courseid,$domain,$username)=@_;
9364: {
9365: use integer;
9366: my $symbchck=unpack("%32S*",$symb) << 21;
9367: my $symbseed=numval($symb) << 10;
9368: my $namechck=unpack("%32S*",$username);
9369:
9370: my $nameseed=numval($username) << 21;
9371: my $domainseed=unpack("%32S*",$domain) << 10;
9372: my $courseseed=unpack("%32S*",$courseid);
9373:
9374: my $num1=$symbchck+$symbseed+$namechck;
9375: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9376: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9377: #&logthis("rndseed :$num:$symb");
1.564 albertel 9378: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 9379: return "$num1,$num2";
1.155 albertel 9380: }
1.366 albertel 9381: }
9382:
1.443 albertel 9383: sub rndseed_64bit2 {
9384: my ($symb,$courseid,$domain,$username)=@_;
9385: {
9386: use integer;
9387: # strings need to be an even # of cahracters long, it it is odd the
9388: # last characters gets thrown away
9389: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9390: my $symbseed=numval($symb) << 10;
9391: my $namechck=unpack("%32S*",$username.' ');
9392:
9393: my $nameseed=numval($username) << 21;
1.501 albertel 9394: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9395: my $courseseed=unpack("%32S*",$courseid.' ');
9396:
9397: my $num1=$symbchck+$symbseed+$namechck;
9398: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9399: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9400: #&logthis("rndseed :$num:$symb");
1.803 albertel 9401: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 9402: return "$num1,$num2";
9403: }
9404: }
9405:
9406: sub rndseed_64bit3 {
9407: my ($symb,$courseid,$domain,$username)=@_;
9408: {
9409: use integer;
9410: # strings need to be an even # of cahracters long, it it is odd the
9411: # last characters gets thrown away
9412: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9413: my $symbseed=numval2($symb) << 10;
9414: my $namechck=unpack("%32S*",$username.' ');
9415:
9416: my $nameseed=numval2($username) << 21;
1.443 albertel 9417: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9418: my $courseseed=unpack("%32S*",$courseid.' ');
9419:
9420: my $num1=$symbchck+$symbseed+$namechck;
9421: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9422: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9423: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 9424: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 9425:
1.503 albertel 9426: return "$num1:$num2";
1.443 albertel 9427: }
9428: }
9429:
1.575 albertel 9430: sub rndseed_64bit4 {
9431: my ($symb,$courseid,$domain,$username)=@_;
9432: {
9433: use integer;
9434: # strings need to be an even # of cahracters long, it it is odd the
9435: # last characters gets thrown away
9436: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9437: my $symbseed=numval3($symb) << 10;
9438: my $namechck=unpack("%32S*",$username.' ');
9439:
9440: my $nameseed=numval3($username) << 21;
9441: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9442: my $courseseed=unpack("%32S*",$courseid.' ');
9443:
9444: my $num1=$symbchck+$symbseed+$namechck;
9445: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9446: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9447: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 9448: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 9449:
1.575 albertel 9450: return "$num1:$num2";
9451: }
9452: }
9453:
1.675 albertel 9454: sub rndseed_64bit5 {
9455: my ($symb,$courseid,$domain,$username)=@_;
9456: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9457: return "$num1:$num2";
9458: }
9459:
1.366 albertel 9460: sub rndseed_CODE_64bit {
9461: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 9462: {
1.366 albertel 9463: use integer;
1.443 albertel 9464: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 9465: my $symbseed=numval2($symb);
1.491 albertel 9466: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9467: my $CODEseed=numval(&getCODE());
1.443 albertel 9468: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 9469: my $num1=$symbseed+$CODEchck;
9470: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9471: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9472: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 9473: if ($_64bit) { $num1=(($num1<<32)>>32); }
9474: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 9475: return "$num1:$num2";
1.366 albertel 9476: }
9477: }
9478:
1.575 albertel 9479: sub rndseed_CODE_64bit4 {
9480: my ($symb,$courseid,$domain,$username)=@_;
9481: {
9482: use integer;
9483: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9484: my $symbseed=numval3($symb);
9485: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9486: my $CODEseed=numval3(&getCODE());
9487: my $courseseed=unpack("%32S*",$courseid.' ');
9488: my $num1=$symbseed+$CODEchck;
9489: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9490: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9491: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 9492: if ($_64bit) { $num1=(($num1<<32)>>32); }
9493: if ($_64bit) { $num2=(($num2<<32)>>32); }
9494: return "$num1:$num2";
9495: }
9496: }
9497:
1.675 albertel 9498: sub rndseed_CODE_64bit5 {
9499: my ($symb,$courseid,$domain,$username)=@_;
9500: my $code = &getCODE();
9501: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9502: return "$num1:$num2";
9503: }
9504:
1.366 albertel 9505: sub setup_random_from_rndseed {
9506: my ($rndseed)=@_;
1.503 albertel 9507: if ($rndseed =~/([,:])/) {
9508: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 9509: &Math::Random::random_set_seed(abs($num1),abs($num2));
9510: } else {
9511: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 9512: }
1.36 albertel 9513: }
9514:
1.474 albertel 9515: sub latest_receipt_algorithm_id {
1.835 albertel 9516: return 'receipt3';
1.474 albertel 9517: }
9518:
1.480 www 9519: sub recunique {
9520: my $fucourseid=shift;
9521: my $unique;
1.835 albertel 9522: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9523: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9524: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 9525: } else {
9526: $unique=$perlvar{'lonReceipt'};
9527: }
9528: return unpack("%32C*",$unique);
9529: }
9530:
9531: sub recprefix {
9532: my $fucourseid=shift;
9533: my $prefix;
1.835 albertel 9534: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9535: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9536: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 9537: } else {
9538: $prefix=$perlvar{'lonHostID'};
9539: }
9540: return unpack("%32C*",$prefix);
9541: }
9542:
1.76 www 9543: sub ireceipt {
1.474 albertel 9544: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 9545:
9546: my $return =&recprefix($fucourseid).'-';
9547:
9548: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9549: $env{'request.state'} eq 'construct') {
9550: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9551: return $return;
9552: }
9553:
1.76 www 9554: my $cuname=unpack("%32C*",$funame);
9555: my $cudom=unpack("%32C*",$fudom);
9556: my $cucourseid=unpack("%32C*",$fucourseid);
9557: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 9558: my $cunique=&recunique($fucourseid);
1.474 albertel 9559: my $cpart=unpack("%32S*",$part);
1.835 albertel 9560: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
9561:
1.790 albertel 9562: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 9563:
9564: $return.= ($cunique%$cuname+
9565: $cunique%$cudom+
9566: $cusymb%$cuname+
9567: $cusymb%$cudom+
9568: $cucourseid%$cuname+
9569: $cucourseid%$cudom+
9570: $cpart%$cuname+
9571: $cpart%$cudom);
9572: } else {
9573: $return.= ($cunique%$cuname+
9574: $cunique%$cudom+
9575: $cusymb%$cuname+
9576: $cusymb%$cudom+
9577: $cucourseid%$cuname+
9578: $cucourseid%$cudom);
9579: }
9580: return $return;
1.76 www 9581: }
9582:
9583: sub receipt {
1.474 albertel 9584: my ($part)=@_;
1.790 albertel 9585: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 9586: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 9587: }
1.260 ng 9588:
1.790 albertel 9589: sub whichuser {
9590: my ($passedsymb)=@_;
9591: my ($symb,$courseid,$domain,$name,$publicuser);
9592: if (defined($env{'form.grade_symb'})) {
9593: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
9594: my $allowed=&allowed('vgr',$tmp_courseid);
9595: if (!$allowed &&
9596: exists($env{'request.course.sec'}) &&
9597: $env{'request.course.sec'} !~ /^\s*$/) {
9598: $allowed=&allowed('vgr',$tmp_courseid.
9599: '/'.$env{'request.course.sec'});
9600: }
9601: if ($allowed) {
9602: ($symb)=&get_env_multiple('form.grade_symb');
9603: $courseid=$tmp_courseid;
9604: ($domain)=&get_env_multiple('form.grade_domain');
9605: ($name)=&get_env_multiple('form.grade_username');
9606: return ($symb,$courseid,$domain,$name,$publicuser);
9607: }
9608: }
9609: if (!$passedsymb) {
9610: $symb=&symbread();
9611: } else {
9612: $symb=$passedsymb;
9613: }
9614: $courseid=$env{'request.course.id'};
9615: $domain=$env{'user.domain'};
9616: $name=$env{'user.name'};
9617: if ($name eq 'public' && $domain eq 'public') {
9618: if (!defined($env{'form.username'})) {
9619: $env{'form.username'}.=time.rand(10000000);
9620: }
9621: $name.=$env{'form.username'};
9622: }
9623: return ($symb,$courseid,$domain,$name,$publicuser);
9624:
9625: }
9626:
1.36 albertel 9627: # ------------------------------------------------------------ Serves up a file
1.472 albertel 9628: # returns either the contents of the file or
9629: # -1 if the file doesn't exist
1.481 raeburn 9630: #
9631: # if the target is a file that was uploaded via DOCS,
9632: # a check will be made to see if a current copy exists on the local server,
9633: # if it does this will be served, otherwise a copy will be retrieved from
9634: # the home server for the course and stored in /home/httpd/html/userfiles on
9635: # the local server.
1.472 albertel 9636:
1.36 albertel 9637: sub getfile {
1.538 albertel 9638: my ($file) = @_;
1.609 banghart 9639: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 9640: &repcopy($file);
9641: return &readfile($file);
9642: }
9643:
9644: sub repcopy_userfile {
9645: my ($file)=@_;
1.609 banghart 9646: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 9647: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 9648: my ($cdom,$cnum,$filename) =
1.811 albertel 9649: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 9650: my $uri="/uploaded/$cdom/$cnum/$filename";
9651: if (-e "$file") {
1.828 www 9652: # we already have a local copy, check it out
1.538 albertel 9653: my @fileinfo = stat($file);
1.828 www 9654: my $rtncode;
9655: my $info;
1.538 albertel 9656: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 9657: if ($lwpresp ne 'ok') {
1.828 www 9658: # there is no such file anymore, even though we had a local copy
1.482 albertel 9659: if ($rtncode eq '404') {
1.538 albertel 9660: unlink($file);
1.482 albertel 9661: }
9662: return -1;
9663: }
9664: if ($info < $fileinfo[9]) {
1.828 www 9665: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 9666: return 'ok';
1.828 www 9667: } else {
9668: # the file is outdated, get rid of it
9669: unlink($file);
1.482 albertel 9670: }
1.828 www 9671: }
9672: # one way or the other, at this point, we don't have the file
9673: # construct the correct path for the file
9674: my @parts = ($cdom,$cnum);
9675: if ($filename =~ m|^(.+)/[^/]+$|) {
9676: push @parts, split(/\//,$1);
9677: }
9678: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
9679: foreach my $part (@parts) {
9680: $path .= '/'.$part;
9681: if (!-e $path) {
9682: mkdir($path,0770);
1.482 albertel 9683: }
9684: }
1.828 www 9685: # now the path exists for sure
9686: # get a user agent
9687: my $ua=new LWP::UserAgent;
9688: my $transferfile=$file.'.in.transfer';
9689: # FIXME: this should flock
9690: if (-e $transferfile) { return 'ok'; }
9691: my $request;
9692: $uri=~s/^\///;
1.980 raeburn 9693: my $homeserver = &homeserver($cnum,$cdom);
9694: my $protocol = $protocol{$homeserver};
9695: $protocol = 'http' if ($protocol ne 'https');
9696: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 9697: my $response=$ua->request($request,$transferfile);
9698: # did it work?
9699: if ($response->is_error()) {
9700: unlink($transferfile);
9701: &logthis("Userfile repcopy failed for $uri");
9702: return -1;
9703: }
9704: # worked, rename the transfer file
9705: rename($transferfile,$file);
1.607 raeburn 9706: return 'ok';
1.481 raeburn 9707: }
9708:
1.517 albertel 9709: sub tokenwrapper {
9710: my $uri=shift;
1.980 raeburn 9711: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 9712: $uri=~s|^/||;
1.620 albertel 9713: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 9714: my $token=$1;
1.552 albertel 9715: my (undef,$udom,$uname,$file)=split('/',$uri,4);
9716: if ($udom && $uname && $file) {
9717: $file=~s|(\?\.*)*$||;
1.949 raeburn 9718: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 9719: my $homeserver = &homeserver($uname,$udom);
9720: my $protocol = $protocol{$homeserver};
9721: $protocol = 'http' if ($protocol ne 'https');
9722: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 9723: (($uri=~/\?/)?'&':'?').'token='.$token.
9724: '&tokenissued='.$perlvar{'lonHostID'};
9725: } else {
9726: return '/adm/notfound.html';
9727: }
9728: }
9729:
1.828 www 9730: # call with reqtype HEAD: get last modification time
9731: # call with reqtype GET: get the file contents
9732: # Do not call this with reqtype GET for large files! It loads everything into memory
9733: #
1.481 raeburn 9734: sub getuploaded {
9735: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
9736: $uri=~s/^\///;
1.980 raeburn 9737: my $homeserver = &homeserver($cnum,$cdom);
9738: my $protocol = $protocol{$homeserver};
9739: $protocol = 'http' if ($protocol ne 'https');
9740: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 9741: my $ua=new LWP::UserAgent;
9742: my $request=new HTTP::Request($reqtype,$uri);
9743: my $response=$ua->request($request);
9744: $$rtncode = $response->code;
1.482 albertel 9745: if (! $response->is_success()) {
9746: return 'failed';
9747: }
9748: if ($reqtype eq 'HEAD') {
1.486 www 9749: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 9750: } elsif ($reqtype eq 'GET') {
9751: $$info = $response->content;
1.472 albertel 9752: }
1.482 albertel 9753: return 'ok';
1.36 albertel 9754: }
9755:
1.481 raeburn 9756: sub readfile {
9757: my $file = shift;
9758: if ( (! -e $file ) || ($file eq '') ) { return -1; };
9759: my $fh;
9760: open($fh,"<$file");
9761: my $a='';
1.800 albertel 9762: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 9763: return $a;
9764: }
9765:
1.36 albertel 9766: sub filelocation {
1.590 banghart 9767: my ($dir,$file) = @_;
9768: my $location;
9769: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 9770:
9771: if ($file =~ m-^/adm/-) {
9772: $file=~s-^/adm/wrapper/-/-;
9773: $file=~s-^/adm/coursedocs/showdoc/-/-;
9774: }
1.882 albertel 9775:
1.590 banghart 9776: if ($file=~m:^/~:) { # is a contruction space reference
9777: $location = $file;
9778: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 9779: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 9780: # is a correct contruction space reference
9781: $location = $file;
1.956 raeburn 9782: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
9783: $location = $file;
1.609 banghart 9784: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 9785: my ($udom,$uname,$filename)=
1.811 albertel 9786: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 9787: my $home=&homeserver($uname,$udom);
9788: my $is_me=0;
9789: my @ids=¤t_machine_ids();
9790: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
9791: if ($is_me) {
1.1117 ! foxr 9792: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 9793: } else {
9794: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
9795: $udom.'/'.$uname.'/'.$filename;
9796: }
1.882 albertel 9797: } elsif ($file =~ m-^/adm/-) {
9798: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 9799: } else {
9800: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9801: $file=~s:^/res/:/:;
9802: if ( !( $file =~ m:^/:) ) {
9803: $location = $dir. '/'.$file;
9804: } else {
9805: $location = '/home/httpd/html/res'.$file;
9806: }
1.59 albertel 9807: }
1.590 banghart 9808: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 9809: while ($location=~m{/\.\./}) {
9810: if ($location =~ m{/[^/]+/\.\./}) {
9811: $location=~ s{/[^/]+/\.\./}{/}g;
9812: } else {
9813: $location=~ s{/\.\./}{/}g;
9814: }
9815: } #remove dir/..
1.590 banghart 9816: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9817: return $location;
1.46 www 9818: }
1.36 albertel 9819:
1.46 www 9820: sub hreflocation {
9821: my ($dir,$file)=@_;
1.980 raeburn 9822: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 9823: $file=filelocation($dir,$file);
1.700 albertel 9824: } elsif ($file=~m-^/adm/-) {
9825: $file=~s-^/adm/wrapper/-/-;
9826: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 9827: }
9828: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9829: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 9830: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9831: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 9832: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 9833: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 9834: -/uploaded/$1/$2/-x;
1.46 www 9835: }
1.913 albertel 9836: if ($file=~ m{^/userfiles/}) {
9837: $file =~ s{^/userfiles/}{/uploaded/};
9838: }
1.462 albertel 9839: return $file;
1.465 albertel 9840: }
9841:
9842: sub current_machine_domains {
1.853 albertel 9843: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9844: }
9845:
9846: sub machine_domains {
9847: my ($hostname) = @_;
1.465 albertel 9848: my @domains;
1.838 albertel 9849: my %hostname = &all_hostnames();
1.465 albertel 9850: while( my($id, $name) = each(%hostname)) {
1.467 matthew 9851: # &logthis("-$id-$name-$hostname-");
1.465 albertel 9852: if ($hostname eq $name) {
1.844 albertel 9853: push(@domains,&host_domain($id));
1.465 albertel 9854: }
9855: }
9856: return @domains;
9857: }
9858:
9859: sub current_machine_ids {
1.853 albertel 9860: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9861: }
9862:
9863: sub machine_ids {
9864: my ($hostname) = @_;
9865: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 9866: my @ids;
1.888 albertel 9867: my %name_to_host = &all_names();
1.889 albertel 9868: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9869: return @{ $name_to_host{$hostname} };
9870: }
9871: return;
1.31 www 9872: }
9873:
1.824 raeburn 9874: sub additional_machine_domains {
9875: my @domains;
9876: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9877: while( my $line = <$fh>) {
9878: $line =~ s/\s//g;
9879: push(@domains,$line);
9880: }
9881: return @domains;
9882: }
9883:
9884: sub default_login_domain {
9885: my $domain = $perlvar{'lonDefDomain'};
9886: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9887: foreach my $posdom (¤t_machine_domains(),
9888: &additional_machine_domains()) {
9889: if (lc($posdom) eq lc($testdomain)) {
9890: $domain=$posdom;
9891: last;
9892: }
9893: }
9894: return $domain;
9895: }
9896:
1.31 www 9897: # ------------------------------------------------------------- Declutters URLs
9898:
9899: sub declutter {
9900: my $thisfn=shift;
1.569 albertel 9901: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 9902: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 9903: $thisfn=~s/^\///;
1.697 albertel 9904: $thisfn=~s|^adm/wrapper/||;
9905: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 9906: $thisfn=~s/^res\///;
1.1032 raeburn 9907: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
9908: $thisfn=~s/\?.+$//;
9909: }
1.268 www 9910: return $thisfn;
9911: }
9912:
9913: # ------------------------------------------------------------- Clutter up URLs
9914:
9915: sub clutter {
9916: my $thisfn='/'.&declutter(shift);
1.887 albertel 9917: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 9918: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 9919: $thisfn='/res'.$thisfn;
9920: }
1.1031 raeburn 9921: if ($thisfn !~m|^/adm|) {
9922: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 9923: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 9924: } else {
9925: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9926: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 9927: if ($embstyle eq 'ssi'
9928: || ($embstyle eq 'hdn')
9929: || ($embstyle eq 'rat')
9930: || ($embstyle eq 'prv')
9931: || ($embstyle eq 'ign')) {
9932: #do nothing with these
9933: } elsif (($embstyle eq 'img')
1.695 albertel 9934: || ($embstyle eq 'emb')
9935: || ($embstyle eq 'wrp')) {
9936: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 9937: } elsif ($embstyle eq 'unk'
9938: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 9939: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 9940: } else {
1.718 www 9941: # &logthis("Got a blank emb style");
1.695 albertel 9942: }
1.694 albertel 9943: }
9944: }
1.31 www 9945: return $thisfn;
1.12 www 9946: }
9947:
1.787 albertel 9948: sub clutter_with_no_wrapper {
9949: my $uri = &clutter(shift);
9950: if ($uri =~ m-^/adm/-) {
9951: $uri =~ s-^/adm/wrapper/-/-;
9952: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9953: }
9954: return $uri;
9955: }
9956:
1.557 albertel 9957: sub freeze_escape {
9958: my ($value)=@_;
9959: if (ref($value)) {
9960: $value=&nfreeze($value);
9961: return '__FROZEN__'.&escape($value);
9962: }
9963: return &escape($value);
9964: }
9965:
1.11 www 9966:
1.557 albertel 9967: sub thaw_unescape {
9968: my ($value)=@_;
9969: if ($value =~ /^__FROZEN__/) {
9970: substr($value,0,10,undef);
9971: $value=&unescape($value);
9972: return &thaw($value);
9973: }
9974: return &unescape($value);
9975: }
9976:
1.436 albertel 9977: sub correct_line_ends {
9978: my ($result)=@_;
9979: $$result =~s/\r\n/\n/mg;
9980: $$result =~s/\r/\n/mg;
1.415 albertel 9981: }
1.1 albertel 9982: # ================================================================ Main Program
9983:
1.184 www 9984: sub goodbye {
1.204 albertel 9985: &logthis("Starting Shut down");
1.443 albertel 9986: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 9987: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 9988: #converted
1.599 albertel 9989: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 9990: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9991: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9992: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 9993: #1.1 only
1.870 albertel 9994: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9995: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
9996: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
9997: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
9998: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 9999: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10000: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 10001: &flushcourselogs();
10002: &logthis("Shutting down");
10003: }
10004:
1.852 albertel 10005: sub get_dns {
1.869 albertel 10006: my ($url,$func,$ignore_cache) = @_;
10007: if (!$ignore_cache) {
10008: my ($content,$cached)=
10009: &Apache::lonnet::is_cached_new('dns',$url);
10010: if ($cached) {
10011: &$func($content);
10012: return;
10013: }
10014: }
10015:
10016: my %alldns;
1.852 albertel 10017: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10018: foreach my $dns (<$config>) {
10019: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 10020: my $line = $1;
10021: my ($host,$protocol) = split(/:/,$line);
10022: if ($protocol ne 'https') {
10023: $protocol = 'http';
10024: }
10025: $alldns{$host} = $protocol;
1.869 albertel 10026: }
10027: while (%alldns) {
10028: my ($dns) = keys(%alldns);
1.852 albertel 10029: my $ua=new LWP::UserAgent;
1.979 raeburn 10030: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 10031: my $response=$ua->request($request);
1.979 raeburn 10032: delete($alldns{$dns});
1.852 albertel 10033: next if ($response->is_error());
10034: my @content = split("\n",$response->content);
1.869 albertel 10035: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 10036: &$func(\@content);
1.869 albertel 10037: return;
1.852 albertel 10038: }
10039: close($config);
1.871 albertel 10040: my $which = (split('/',$url))[3];
10041: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10042: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 10043: my @content = <$config>;
10044: &$func(\@content);
10045: return;
1.852 albertel 10046: }
1.327 albertel 10047: # ------------------------------------------------------------ Read domain file
10048: {
1.852 albertel 10049: my $loaded;
1.846 albertel 10050: my %domain;
10051:
1.852 albertel 10052: sub parse_domain_tab {
10053: my ($lines) = @_;
10054: foreach my $line (@$lines) {
10055: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 10056:
1.846 albertel 10057: chomp($line);
1.852 albertel 10058: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 10059: my %this_domain;
10060: foreach my $field ('description', 'auth_def', 'auth_arg_def',
10061: 'lang_def', 'city', 'longi', 'lati',
10062: 'primary') {
10063: $this_domain{$field} = shift(@elements);
10064: }
10065: $domain{$name} = \%this_domain;
1.852 albertel 10066: }
10067: }
1.864 albertel 10068:
10069: sub reset_domain_info {
10070: undef($loaded);
10071: undef(%domain);
10072: }
10073:
1.852 albertel 10074: sub load_domain_tab {
1.869 albertel 10075: my ($ignore_cache) = @_;
10076: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 10077: my $fh;
10078: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10079: my @lines = <$fh>;
10080: &parse_domain_tab(\@lines);
1.448 albertel 10081: }
1.852 albertel 10082: close($fh);
10083: $loaded = 1;
1.327 albertel 10084: }
1.846 albertel 10085:
10086: sub domain {
1.852 albertel 10087: &load_domain_tab() if (!$loaded);
10088:
1.846 albertel 10089: my ($name,$what) = @_;
10090: return if ( !exists($domain{$name}) );
10091:
10092: if (!$what) {
10093: return $domain{$name}{'description'};
10094: }
10095: return $domain{$name}{$what};
10096: }
1.974 raeburn 10097:
10098: sub domain_info {
10099: &load_domain_tab() if (!$loaded);
10100: return %domain;
10101: }
10102:
1.327 albertel 10103: }
10104:
10105:
1.1 albertel 10106: # ------------------------------------------------------------- Read hosts file
10107: {
1.838 albertel 10108: my %hostname;
1.844 albertel 10109: my %hostdom;
1.845 albertel 10110: my %libserv;
1.852 albertel 10111: my $loaded;
1.888 albertel 10112: my %name_to_host;
1.1074 raeburn 10113: my %internetdom;
1.1107 raeburn 10114: my %LC_dns_serv;
1.852 albertel 10115:
10116: sub parse_hosts_tab {
10117: my ($file) = @_;
10118: foreach my $configline (@$file) {
10119: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 10120: chomp($configline);
10121: if ($configline =~ /^\^/) {
10122: if ($configline =~ /^\^([\w.\-]+)/) {
10123: $LC_dns_serv{$1} = 1;
10124: }
10125: next;
10126: }
1.1074 raeburn 10127: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 10128: $name=~s/\s//g;
10129: if ($id && $domain && $role && $name) {
10130: $hostname{$id}=$name;
1.888 albertel 10131: push(@{$name_to_host{$name}}, $id);
1.852 albertel 10132: $hostdom{$id}=$domain;
10133: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 10134: if (defined($protocol)) {
10135: if ($protocol eq 'https') {
10136: $protocol{$id} = $protocol;
10137: } else {
10138: $protocol{$id} = 'http';
10139: }
1.968 raeburn 10140: } else {
1.969 raeburn 10141: $protocol{$id} = 'http';
1.968 raeburn 10142: }
1.1074 raeburn 10143: if (defined($intdom)) {
10144: $internetdom{$id} = $intdom;
10145: }
1.852 albertel 10146: }
10147: }
10148: }
1.864 albertel 10149:
10150: sub reset_hosts_info {
1.897 albertel 10151: &purge_remembered();
1.864 albertel 10152: &reset_domain_info();
10153: &reset_hosts_ip_info();
1.892 albertel 10154: undef(%name_to_host);
1.864 albertel 10155: undef(%hostname);
10156: undef(%hostdom);
10157: undef(%libserv);
10158: undef($loaded);
10159: }
1.1 albertel 10160:
1.852 albertel 10161: sub load_hosts_tab {
1.869 albertel 10162: my ($ignore_cache) = @_;
10163: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 10164: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10165: my @config = <$config>;
10166: &parse_hosts_tab(\@config);
10167: close($config);
10168: $loaded=1;
1.1 albertel 10169: }
1.852 albertel 10170:
1.838 albertel 10171: sub hostname {
1.852 albertel 10172: &load_hosts_tab() if (!$loaded);
10173:
1.838 albertel 10174: my ($lonid) = @_;
10175: return $hostname{$lonid};
10176: }
1.845 albertel 10177:
1.838 albertel 10178: sub all_hostnames {
1.852 albertel 10179: &load_hosts_tab() if (!$loaded);
10180:
1.838 albertel 10181: return %hostname;
10182: }
1.845 albertel 10183:
1.888 albertel 10184: sub all_names {
10185: &load_hosts_tab() if (!$loaded);
10186:
10187: return %name_to_host;
10188: }
10189:
1.974 raeburn 10190: sub all_host_domain {
10191: &load_hosts_tab() if (!$loaded);
10192: return %hostdom;
10193: }
10194:
1.845 albertel 10195: sub is_library {
1.852 albertel 10196: &load_hosts_tab() if (!$loaded);
10197:
1.845 albertel 10198: return exists($libserv{$_[0]});
10199: }
10200:
10201: sub all_library {
1.852 albertel 10202: &load_hosts_tab() if (!$loaded);
10203:
1.845 albertel 10204: return %libserv;
10205: }
10206:
1.1062 droeschl 10207: sub unique_library {
10208: #2x reverse removes all hostnames that appear more than once
10209: my %unique = reverse &all_library();
10210: return reverse %unique;
10211: }
10212:
1.841 albertel 10213: sub get_servers {
1.852 albertel 10214: &load_hosts_tab() if (!$loaded);
10215:
1.841 albertel 10216: my ($domain,$type) = @_;
10217: my %possible_hosts = ($type eq 'library') ? %libserv
10218: : %hostname;
10219: my %result;
1.842 albertel 10220: if (ref($domain) eq 'ARRAY') {
10221: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 10222: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 10223: $result{$host} = $hostname;
10224: }
10225: }
10226: } else {
10227: while ( my ($host,$hostname) = each(%possible_hosts)) {
10228: if ($hostdom{$host} eq $domain) {
10229: $result{$host} = $hostname;
10230: }
1.841 albertel 10231: }
10232: }
10233: return %result;
10234: }
1.845 albertel 10235:
1.1062 droeschl 10236: sub get_unique_servers {
10237: my %unique = reverse &get_servers(@_);
10238: return reverse %unique;
10239: }
10240:
1.844 albertel 10241: sub host_domain {
1.852 albertel 10242: &load_hosts_tab() if (!$loaded);
10243:
1.844 albertel 10244: my ($lonid) = @_;
10245: return $hostdom{$lonid};
10246: }
10247:
1.841 albertel 10248: sub all_domains {
1.852 albertel 10249: &load_hosts_tab() if (!$loaded);
10250:
1.841 albertel 10251: my %seen;
10252: my @uniq = grep(!$seen{$_}++, values(%hostdom));
10253: return @uniq;
10254: }
1.1074 raeburn 10255:
10256: sub internet_dom {
10257: &load_hosts_tab() if (!$loaded);
10258:
10259: my ($lonid) = @_;
10260: return $internetdom{$lonid};
10261: }
1.1107 raeburn 10262:
10263: sub is_LC_dns {
10264: &load_hosts_tab() if (!$loaded);
10265:
10266: my ($hostname) = @_;
10267: return exists($LC_dns_serv{$hostname});
10268: }
10269:
1.1 albertel 10270: }
10271:
1.847 albertel 10272: {
10273: my %iphost;
1.856 albertel 10274: my %name_to_ip;
10275: my %lonid_to_ip;
1.869 albertel 10276:
1.847 albertel 10277: sub get_hosts_from_ip {
10278: my ($ip) = @_;
10279: my %iphosts = &get_iphost();
10280: if (ref($iphosts{$ip})) {
10281: return @{$iphosts{$ip}};
10282: }
10283: return;
1.839 albertel 10284: }
1.864 albertel 10285:
10286: sub reset_hosts_ip_info {
10287: undef(%iphost);
10288: undef(%name_to_ip);
10289: undef(%lonid_to_ip);
10290: }
1.856 albertel 10291:
10292: sub get_host_ip {
10293: my ($lonid) = @_;
10294: if (exists($lonid_to_ip{$lonid})) {
10295: return $lonid_to_ip{$lonid};
10296: }
10297: my $name=&hostname($lonid);
10298: my $ip = gethostbyname($name);
10299: return if (!$ip || length($ip) ne 4);
10300: $ip=inet_ntoa($ip);
10301: $name_to_ip{$name} = $ip;
10302: $lonid_to_ip{$lonid} = $ip;
10303: return $ip;
10304: }
1.847 albertel 10305:
10306: sub get_iphost {
1.869 albertel 10307: my ($ignore_cache) = @_;
1.894 albertel 10308:
1.869 albertel 10309: if (!$ignore_cache) {
10310: if (%iphost) {
10311: return %iphost;
10312: }
10313: my ($ip_info,$cached)=
10314: &Apache::lonnet::is_cached_new('iphost','iphost');
10315: if ($cached) {
10316: %iphost = %{$ip_info->[0]};
10317: %name_to_ip = %{$ip_info->[1]};
10318: %lonid_to_ip = %{$ip_info->[2]};
10319: return %iphost;
10320: }
10321: }
1.894 albertel 10322:
10323: # get yesterday's info for fallback
10324: my %old_name_to_ip;
10325: my ($ip_info,$cached)=
10326: &Apache::lonnet::is_cached_new('iphost','iphost');
10327: if ($cached) {
10328: %old_name_to_ip = %{$ip_info->[1]};
10329: }
10330:
1.888 albertel 10331: my %name_to_host = &all_names();
10332: foreach my $name (keys(%name_to_host)) {
1.847 albertel 10333: my $ip;
10334: if (!exists($name_to_ip{$name})) {
10335: $ip = gethostbyname($name);
10336: if (!$ip || length($ip) ne 4) {
1.894 albertel 10337: if (defined($old_name_to_ip{$name})) {
10338: $ip = $old_name_to_ip{$name};
10339: &logthis("Can't find $name defaulting to old $ip");
10340: } else {
10341: &logthis("Name $name no IP found");
10342: next;
10343: }
10344: } else {
10345: $ip=inet_ntoa($ip);
1.847 albertel 10346: }
10347: $name_to_ip{$name} = $ip;
10348: } else {
10349: $ip = $name_to_ip{$name};
1.653 albertel 10350: }
1.888 albertel 10351: foreach my $id (@{ $name_to_host{$name} }) {
10352: $lonid_to_ip{$id} = $ip;
10353: }
10354: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 10355: }
1.869 albertel 10356: &Apache::lonnet::do_cache_new('iphost','iphost',
10357: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 10358: 48*60*60);
1.869 albertel 10359:
1.847 albertel 10360: return %iphost;
1.598 albertel 10361: }
10362:
1.992 raeburn 10363: #
10364: # Given a DNS returns the loncapa host name for that DNS
10365: #
10366: sub host_from_dns {
10367: my ($dns) = @_;
10368: my @hosts;
10369: my $ip;
10370:
1.993 raeburn 10371: if (exists($name_to_ip{$dns})) {
1.992 raeburn 10372: $ip = $name_to_ip{$dns};
10373: }
10374: if (!$ip) {
10375: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10376: if (length($ip) == 4) {
10377: $ip = &IO::Socket::inet_ntoa($ip);
10378: }
10379: }
10380: if ($ip) {
10381: @hosts = get_hosts_from_ip($ip);
10382: return $hosts[0];
10383: }
10384: return undef;
1.986 foxr 10385: }
1.992 raeburn 10386:
1.1074 raeburn 10387: sub get_internet_names {
10388: my ($lonid) = @_;
10389: return if ($lonid eq '');
10390: my ($idnref,$cached)=
10391: &Apache::lonnet::is_cached_new('internetnames',$lonid);
10392: if ($cached) {
10393: return $idnref;
10394: }
10395: my $ip = &get_host_ip($lonid);
10396: my @hosts = &get_hosts_from_ip($ip);
10397: my %iphost = &get_iphost();
10398: my (@idns,%seen);
10399: foreach my $id (@hosts) {
10400: my $dom = &host_domain($id);
10401: my $prim_id = &domain($dom,'primary');
10402: my $prim_ip = &get_host_ip($prim_id);
10403: next if ($seen{$prim_ip});
10404: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10405: foreach my $id (@{$iphost{$prim_ip}}) {
10406: my $intdom = &internet_dom($id);
10407: unless (grep(/^\Q$intdom\E$/,@idns)) {
10408: push(@idns,$intdom);
10409: }
10410: }
10411: }
10412: $seen{$prim_ip} = 1;
10413: }
10414: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10415: }
10416:
1.986 foxr 10417: }
10418:
1.1079 raeburn 10419: sub all_loncaparevs {
10420: return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10);
10421: }
10422:
1.862 albertel 10423: BEGIN {
10424:
10425: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10426: unless ($readit) {
10427: {
10428: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10429: %perlvar = (%perlvar,%{$configvars});
10430: }
10431:
10432:
1.1 albertel 10433: # ------------------------------------------------------ Read spare server file
10434: {
1.448 albertel 10435: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 10436:
10437: while (my $configline=<$config>) {
10438: chomp($configline);
1.284 matthew 10439: if ($configline) {
1.784 albertel 10440: my ($host,$type) = split(':',$configline,2);
1.785 albertel 10441: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 10442: push(@{ $spareid{$type} }, $host);
1.1 albertel 10443: }
10444: }
1.448 albertel 10445: close($config);
1.1 albertel 10446: }
1.11 www 10447: # ------------------------------------------------------------ Read permissions
10448: {
1.448 albertel 10449: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 10450:
10451: while (my $configline=<$config>) {
1.448 albertel 10452: chomp($configline);
10453: if ($configline) {
10454: my ($role,$perm)=split(/ /,$configline);
10455: if ($perm ne '') { $pr{$role}=$perm; }
10456: }
1.11 www 10457: }
1.448 albertel 10458: close($config);
1.11 www 10459: }
10460:
10461: # -------------------------------------------- Read plain texts for permissions
10462: {
1.448 albertel 10463: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 10464:
10465: while (my $configline=<$config>) {
1.448 albertel 10466: chomp($configline);
10467: if ($configline) {
1.742 raeburn 10468: my ($short,@plain)=split(/:/,$configline);
10469: %{$prp{$short}} = ();
10470: if (@plain > 0) {
10471: $prp{$short}{'std'} = $plain[0];
10472: for (my $i=1; $i<@plain; $i++) {
10473: $prp{$short}{'alt'.$i} = $plain[$i];
10474: }
10475: }
1.448 albertel 10476: }
1.135 www 10477: }
1.448 albertel 10478: close($config);
1.135 www 10479: }
10480:
10481: # ---------------------------------------------------------- Read package table
10482: {
1.448 albertel 10483: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 10484:
10485: while (my $configline=<$config>) {
1.483 albertel 10486: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 10487: chomp($configline);
10488: my ($short,$plain)=split(/:/,$configline);
10489: my ($pack,$name)=split(/\&/,$short);
10490: if ($plain ne '') {
10491: $packagetab{$pack.'&'.$name.'&name'}=$name;
10492: $packagetab{$short}=$plain;
10493: }
1.11 www 10494: }
1.448 albertel 10495: close($config);
1.329 matthew 10496: }
10497:
1.1073 raeburn 10498: # ---------------------------------------------------------- Read loncaparev table
10499: {
10500: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10501: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10502: while (my $configline=<$config>) {
10503: chomp($configline);
10504: my ($hostid,$loncaparev)=split(/:/,$configline);
10505: $loncaparevs{$hostid}=$loncaparev;
10506: }
10507: close($config);
10508: }
10509: }
10510: }
10511:
1.1074 raeburn 10512: # ---------------------------------------------------------- Read serverhostID table
10513: {
10514: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10515: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10516: while (my $configline=<$config>) {
10517: chomp($configline);
10518: my ($name,$id)=split(/:/,$configline);
10519: $serverhomeIDs{$name}=$id;
10520: }
10521: close($config);
10522: }
10523: }
10524: }
10525:
1.1079 raeburn 10526: {
10527: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
10528: if (-e $file) {
10529: my $parser = HTML::LCParser->new($file);
10530: while (my $token = $parser->get_token()) {
10531: if ($token->[0] eq 'S') {
10532: my $item = $token->[1];
10533: my $name = $token->[2]{'name'};
10534: my $value = $token->[2]{'value'};
10535: if ($item ne '' && $name ne '' && $value ne '') {
10536: my $release = $parser->get_text();
10537: $release =~ s/(^\s*|\s*$ )//gx;
10538: $needsrelease{$item.':'.$name.':'.$value} = $release;
10539: }
10540: }
10541: }
10542: }
1.1073 raeburn 10543: }
10544:
1.329 matthew 10545: # ------------- set up temporary directory
10546: {
1.1117 ! foxr 10547: $tmpdir = LONCAPA::tempdir();
1.329 matthew 10548:
1.11 www 10549: }
10550:
1.794 albertel 10551: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
10552: 'compress_threshold'=> 20_000,
10553: });
1.185 www 10554:
1.281 www 10555: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 10556: $dumpcount=0;
1.958 www 10557: $locknum=0;
1.22 www 10558:
1.163 harris41 10559: &logtouch();
1.672 albertel 10560: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 10561: $readit=1;
1.564 albertel 10562: {
10563: use integer;
10564: my $test=(2**32)+1;
1.568 albertel 10565: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 10566: &logthis(" Detected 64bit platform ($_64bit)");
10567: }
1.195 www 10568: }
1.1 albertel 10569: }
1.179 www 10570:
1.1 albertel 10571: 1;
1.191 harris41 10572: __END__
10573:
1.243 albertel 10574: =pod
10575:
1.191 harris41 10576: =head1 NAME
10577:
1.243 albertel 10578: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 10579:
10580: =head1 SYNOPSIS
10581:
1.243 albertel 10582: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 10583:
10584: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
10585:
1.243 albertel 10586: Common parameters:
10587:
10588: =over 4
10589:
10590: =item *
10591:
10592: $uname : an internal username (if $cname expecting a course Id specifically)
10593:
10594: =item *
10595:
10596: $udom : a domain (if $cdom expecting a course's domain specifically)
10597:
10598: =item *
10599:
10600: $symb : a resource instance identifier
10601:
10602: =item *
10603:
10604: $namespace : the name of a .db file that contains the data needed or
10605: being set.
10606:
10607: =back
10608:
1.394 bowersj2 10609: =head1 OVERVIEW
1.191 harris41 10610:
1.394 bowersj2 10611: lonnet provides subroutines which interact with the
10612: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
10613: about classes, users, and resources.
1.243 albertel 10614:
10615: For many of these objects you can also use this to store data about
10616: them or modify them in various ways.
1.191 harris41 10617:
1.394 bowersj2 10618: =head2 Symbs
1.191 harris41 10619:
1.394 bowersj2 10620: To identify a specific instance of a resource, LON-CAPA uses symbols
10621: or "symbs"X<symb>. These identifiers are built from the URL of the
10622: map, the resource number of the resource in the map, and the URL of
10623: the resource itself. The latter is somewhat redundant, but might help
10624: if maps change.
10625:
10626: An example is
10627:
10628: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
10629:
10630: The respective map entry is
10631:
10632: <resource id="19" src="/res/msu/korte/tests/part12.problem"
10633: title="Problem 2">
10634: </resource>
10635:
10636: Symbs are used by the random number generator, as well as to store and
10637: restore data specific to a certain instance of for example a problem.
10638:
10639: =head2 Storing And Retrieving Data
10640:
10641: X<store()>X<cstore()>X<restore()>Three of the most important functions
10642: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10643: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10644: is is the non-critical message twin of cstore. These functions are for
10645: handlers to store a perl hash to a user's permanent data space in an
10646: easy manner, and to retrieve it again on another call. It is expected
10647: that a handler would use this once at the beginning to retrieve data,
10648: and then again once at the end to send only the new data back.
10649:
10650: The data is stored in the user's data directory on the user's
10651: homeserver under the ID of the course.
10652:
10653: The hash that is returned by restore will have all of the previous
10654: value for all of the elements of the hash.
10655:
10656: Example:
10657:
10658: #creating a hash
10659: my %hash;
10660: $hash{'foo'}='bar';
10661:
10662: #storing it
10663: &Apache::lonnet::cstore(\%hash);
10664:
10665: #changing a value
10666: $hash{'foo'}='notbar';
10667:
10668: #adding a new value
10669: $hash{'bar'}='foo';
10670: &Apache::lonnet::cstore(\%hash);
10671:
10672: #retrieving the hash
10673: my %history=&Apache::lonnet::restore();
10674:
10675: #print the hash
10676: foreach my $key (sort(keys(%history))) {
10677: print("\%history{$key} = $history{$key}");
10678: }
10679:
10680: Will print out:
1.191 harris41 10681:
1.394 bowersj2 10682: %history{1:foo} = bar
10683: %history{1:keys} = foo:timestamp
10684: %history{1:timestamp} = 990455579
10685: %history{2:bar} = foo
10686: %history{2:foo} = notbar
10687: %history{2:keys} = foo:bar:timestamp
10688: %history{2:timestamp} = 990455580
10689: %history{bar} = foo
10690: %history{foo} = notbar
10691: %history{timestamp} = 990455580
10692: %history{version} = 2
10693:
10694: Note that the special hash entries C<keys>, C<version> and
10695: C<timestamp> were added to the hash. C<version> will be equal to the
10696: total number of versions of the data that have been stored. The
10697: C<timestamp> attribute will be the UNIX time the hash was
10698: stored. C<keys> is available in every historical section to list which
10699: keys were added or changed at a specific historical revision of a
10700: hash.
10701:
10702: B<Warning>: do not store the hash that restore returns directly. This
10703: will cause a mess since it will restore the historical keys as if the
10704: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 10705:
1.394 bowersj2 10706: Calling convention:
1.191 harris41 10707:
1.394 bowersj2 10708: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10709: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 10710:
1.394 bowersj2 10711: For more detailed information, see lonnet specific documentation.
1.191 harris41 10712:
1.394 bowersj2 10713: =head1 RETURN MESSAGES
1.191 harris41 10714:
1.394 bowersj2 10715: =over 4
1.191 harris41 10716:
1.394 bowersj2 10717: =item * B<con_lost>: unable to contact remote host
1.191 harris41 10718:
1.394 bowersj2 10719: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10720: when the connection is brought back up
1.191 harris41 10721:
1.394 bowersj2 10722: =item * B<con_failed>: unable to contact remote host and unable to save message
10723: for later delivery
1.191 harris41 10724:
1.967 bisitz 10725: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 10726:
1.394 bowersj2 10727: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 10728: that was requested
1.191 harris41 10729:
1.243 albertel 10730: =back
1.191 harris41 10731:
1.243 albertel 10732: =head1 PUBLIC SUBROUTINES
1.191 harris41 10733:
1.243 albertel 10734: =head2 Session Environment Functions
1.191 harris41 10735:
1.243 albertel 10736: =over 4
1.191 harris41 10737:
1.394 bowersj2 10738: =item *
10739: X<appenv()>
1.949 raeburn 10740: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 10741: the user envirnoment file, and will be restored for each access this
1.620 albertel 10742: user makes during this session, also modifies the %env for the current
1.949 raeburn 10743: process. Optional rolesarrayref - if defined contains a reference to an array
10744: of roles which are exempt from the restriction on modifying user.role entries
10745: in the user's environment.db and in %env.
1.191 harris41 10746:
10747: =item *
1.394 bowersj2 10748: X<delenv()>
1.987 raeburn 10749: B<delenv($delthis,$regexp)>: removes all items from the session
10750: environment file that begin with $delthis. If the
10751: optional second arg - $regexp - is true, $delthis is treated as a
10752: regular expression, otherwise \Q$delthis\E is used.
10753: The values are also deleted from the current processes %env.
1.191 harris41 10754:
1.795 albertel 10755: =item * get_env_multiple($name)
10756:
10757: gets $name from the %env hash, it seemlessly handles the cases where multiple
10758: values may be defined and end up as an array ref.
10759:
10760: returns an array of values
10761:
1.243 albertel 10762: =back
10763:
10764: =head2 User Information
1.191 harris41 10765:
1.243 albertel 10766: =over 4
1.191 harris41 10767:
10768: =item *
1.394 bowersj2 10769: X<queryauthenticate()>
10770: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 10771: authentication scheme
10772:
10773: =item *
1.394 bowersj2 10774: X<authenticate()>
1.1073 raeburn 10775: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 10776: authenticate user from domain's lib servers (first use the current
10777: one). C<$upass> should be the users password.
1.1073 raeburn 10778: $checkdefauth is optional (value is 1 if a check should be made to
10779: authenticate user using default authentication method, and allow
10780: account creation if username does not have account in the domain).
10781: $clientcancheckhost is optional (value is 1 if checking whether the
10782: server can host will occur on the client side in lonauth.pm).
1.191 harris41 10783:
10784: =item *
1.394 bowersj2 10785: X<homeserver()>
10786: B<homeserver($uname,$udom)>: find the server which has
10787: the user's directory and files (there must be only one), this caches
10788: the answer, and also caches if there is a borken connection.
1.191 harris41 10789:
10790: =item *
1.394 bowersj2 10791: X<idget()>
10792: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10793: (IDs are a unique resource in a domain, there must be only 1 ID per
10794: username, and only 1 username per ID in a specific domain) (returns
10795: hash: id=>name,id=>name)
1.191 harris41 10796:
10797: =item *
1.394 bowersj2 10798: X<idrget()>
10799: B<idrget($udom,@unames)>: find the IDs behind a list of
10800: usernames (returns hash: name=>id,name=>id)
1.191 harris41 10801:
10802: =item *
1.394 bowersj2 10803: X<idput()>
10804: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 10805:
10806: =item *
1.394 bowersj2 10807: X<rolesinit()>
10808: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 10809:
10810: =item *
1.551 albertel 10811: X<getsection()>
10812: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 10813: course $cname, return section name/number or '' for "not in course"
10814: and '-1' for "no section"
10815:
10816: =item *
1.394 bowersj2 10817: X<userenvironment()>
10818: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 10819: passed in @what from the requested user's environment, returns a hash
10820:
1.858 raeburn 10821: =item *
10822: X<userlog_query()>
1.859 albertel 10823: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10824: activity.log file. %filters defines filters applied when parsing the
10825: log file. These can be start or end timestamps, or the type of action
10826: - log to look for Login or Logout events, check for Checkin or
10827: Checkout, role for role selection. The response is in the form
10828: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
10829: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 10830:
1.243 albertel 10831: =back
10832:
10833: =head2 User Roles
10834:
10835: =over 4
10836:
10837: =item *
10838:
1.810 raeburn 10839: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 10840: F: full access
10841: U,I,K: authentication modes (cxx only)
10842: '': forbidden
10843: 1: user needs to choose course
10844: 2: browse allowed
1.766 albertel 10845: A: passphrase authentication needed
1.243 albertel 10846:
10847: =item *
10848:
10849: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10850: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10851: and course level
10852:
10853: =item *
10854:
1.988 raeburn 10855: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
10856: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 10857: $type is Course (default) or Community.
1.988 raeburn 10858: If $forcedefault evaluates to true, text returned will be default
10859: text for $type. Otherwise, if this is a course, the text returned
10860: will be a custom name for the role (if defined in the course's
10861: environment). If no custom name is defined the default is returned.
10862:
1.832 raeburn 10863: =item *
10864:
1.935 raeburn 10865: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 10866: All arguments are optional. Returns a hash of a roles, either for
10867: co-author/assistant author roles for a user's Construction Space
1.906 albertel 10868: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 10869: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10870: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10871: For each key, value is set to colon-separated start and end times for
10872: the role. If no username and domain are specified, will default to
1.934 raeburn 10873: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 10874: of role statuses (active, future or previous), roles
10875: (e.g., cc,in, st etc.) and domains of the roles which can be used
10876: to restrict the list of roles reported. If no array ref is
10877: provided for types, will default to return only active roles.
1.834 albertel 10878:
1.243 albertel 10879: =back
10880:
10881: =head2 User Modification
10882:
10883: =over 4
10884:
10885: =item *
10886:
1.957 raeburn 10887: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 10888: user for the level given by URL. Optional start and end dates (leave empty
10889: string or zero for "no date")
1.191 harris41 10890:
10891: =item *
10892:
1.243 albertel 10893: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10894: change a users, password, possible return values are: ok,
10895: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10896: refused
1.191 harris41 10897:
10898: =item *
10899:
1.243 albertel 10900: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 10901:
10902: =item *
10903:
1.1058 raeburn 10904: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
10905: $forceid,$desiredhome,$email,$inststatus,$candelete) :
10906:
10907: will update user information (firstname,middlename,lastname,generation,
10908: permanentemail), and if forceid is true, student/employee ID also.
10909: A user's institutional affiliation(s) can also be updated.
10910: User information fields will not be overwritten with empty entries
10911: unless the field is included in the $candelete array reference.
10912: This array is included when a single user is modified via "Manage Users",
10913: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 10914:
10915: =item *
10916:
1.286 matthew 10917: modifystudent
10918:
1.957 raeburn 10919: modify a student's enrollment and identification information.
1.286 matthew 10920: The course id is resolved based on the current users environment.
10921: This means the envoking user must be a course coordinator or otherwise
10922: associated with a course.
10923:
1.297 matthew 10924: This call is essentially a wrapper for lonnet::modifyuser and
10925: lonnet::modify_student_enrollment
1.286 matthew 10926:
10927: Inputs:
10928:
10929: =over 4
10930:
1.957 raeburn 10931: =item B<$udom> Student's loncapa domain
1.286 matthew 10932:
1.957 raeburn 10933: =item B<$uname> Student's loncapa login name
1.286 matthew 10934:
1.964 bisitz 10935: =item B<$uid> Student/Employee ID
1.286 matthew 10936:
1.957 raeburn 10937: =item B<$umode> Student's authentication mode
1.286 matthew 10938:
1.957 raeburn 10939: =item B<$upass> Student's password
1.286 matthew 10940:
1.957 raeburn 10941: =item B<$first> Student's first name
1.286 matthew 10942:
1.957 raeburn 10943: =item B<$middle> Student's middle name
1.286 matthew 10944:
1.957 raeburn 10945: =item B<$last> Student's last name
1.286 matthew 10946:
1.957 raeburn 10947: =item B<$gene> Student's generation
1.286 matthew 10948:
1.957 raeburn 10949: =item B<$usec> Student's section in course
1.286 matthew 10950:
10951: =item B<$end> Unix time of the roles expiration
10952:
10953: =item B<$start> Unix time of the roles start date
10954:
10955: =item B<$forceid> If defined, allow $uid to be changed
10956:
10957: =item B<$desiredhome> server to use as home server for student
10958:
1.957 raeburn 10959: =item B<$email> Student's permanent e-mail address
10960:
10961: =item B<$type> Type of enrollment (auto or manual)
10962:
1.963 raeburn 10963: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10964:
10965: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 10966:
1.963 raeburn 10967: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 10968:
1.963 raeburn 10969: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 10970:
1.963 raeburn 10971: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 10972:
1.286 matthew 10973: =back
1.297 matthew 10974:
10975: =item *
10976:
10977: modify_student_enrollment
10978:
10979: Change a students enrollment status in a class. The environment variable
10980: 'role.request.course' must be defined for this function to proceed.
10981:
10982: Inputs:
10983:
10984: =over 4
10985:
10986: =item $udom, students domain
10987:
10988: =item $uname, students name
10989:
10990: =item $uid, students user id
10991:
10992: =item $first, students first name
10993:
10994: =item $middle
10995:
10996: =item $last
10997:
10998: =item $gene
10999:
11000: =item $usec
11001:
11002: =item $end
11003:
11004: =item $start
11005:
1.957 raeburn 11006: =item $type
11007:
11008: =item $locktype
11009:
11010: =item $cid
11011:
11012: =item $selfenroll
11013:
11014: =item $context
11015:
1.297 matthew 11016: =back
11017:
1.191 harris41 11018:
11019: =item *
11020:
1.243 albertel 11021: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11022: custom role; give a custom role to a user for the level given by URL. Specify
11023: name and domain of role author, and role name
1.191 harris41 11024:
11025: =item *
11026:
1.243 albertel 11027: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 11028:
11029: =item *
11030:
1.243 albertel 11031: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11032:
11033: =back
11034:
11035: =head2 Course Infomation
11036:
11037: =over 4
1.191 harris41 11038:
11039: =item *
11040:
1.631 albertel 11041: coursedescription($courseid) : returns a hash of information about the
11042: specified course id, including all environment settings for the
11043: course, the description of the course will be in the hash under the
11044: key 'description'
1.191 harris41 11045:
11046: =item *
11047:
1.624 albertel 11048: resdata($name,$domain,$type,@which) : request for current parameter
11049: setting for a specific $type, where $type is either 'course' or 'user',
11050: @what should be a list of parameters to ask about. This routine caches
11051: answers for 5 minutes.
1.243 albertel 11052:
1.877 foxr 11053: =item *
11054:
11055: get_courseresdata($courseid, $domain) : dump the entire course resource
11056: data base, returning a hash that is keyed by the resource name and has
11057: values that are the resource value. I believe that the timestamps and
11058: versions are also returned.
11059:
11060:
1.243 albertel 11061: =back
11062:
11063: =head2 Course Modification
11064:
11065: =over 4
1.191 harris41 11066:
11067: =item *
11068:
1.243 albertel 11069: writecoursepref($courseid,%prefs) : write preferences (environment
11070: database) for a course
1.191 harris41 11071:
11072: =item *
11073:
1.1011 raeburn 11074: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11075:
11076: =item *
11077:
1.1038 raeburn 11078: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 11079:
11080: =back
11081:
11082: =head2 Resource Subroutines
11083:
11084: =over 4
1.191 harris41 11085:
11086: =item *
11087:
1.243 albertel 11088: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 11089:
11090: =item *
11091:
1.243 albertel 11092: repcopy($filename) : subscribes to the requested file, and attempts to
11093: replicate from the owning library server, Might return
1.607 raeburn 11094: 'unavailable', 'not_found', 'forbidden', 'ok', or
11095: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 11096: resource. Expects the local filesystem pathname
11097: (/home/httpd/html/res/....)
11098:
11099: =back
11100:
11101: =head2 Resource Information
11102:
11103: =over 4
1.191 harris41 11104:
11105: =item *
11106:
1.243 albertel 11107: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
11108: a vairety of different possible values, $varname should be a request
11109: string, and the other parameters can be used to specify who and what
11110: one is asking about.
11111:
11112: Possible values for $varname are environment.lastname (or other item
11113: from the envirnment hash), user.name (or someother aspect about the
11114: user), resource.0.maxtries (or some other part and parameter of a
11115: resource)
1.204 albertel 11116:
11117: =item *
11118:
1.243 albertel 11119: directcondval($number) : get current value of a condition; reads from a state
11120: string
1.204 albertel 11121:
11122: =item *
11123:
1.243 albertel 11124: condval($condidx) : value of condition index based on state
1.204 albertel 11125:
11126: =item *
11127:
1.243 albertel 11128: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11129: resource's metadata, $what should be either a specific key, or either
11130: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11131: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11132:
11133: this function automatically caches all requests
1.191 harris41 11134:
11135: =item *
11136:
1.243 albertel 11137: metadata_query($query,$custom,$customshow) : make a metadata query against the
11138: network of library servers; returns file handle of where SQL and regex results
11139: will be stored for query
1.191 harris41 11140:
11141: =item *
11142:
1.243 albertel 11143: symbread($filename) : return symbolic list entry (filename argument optional);
11144: returns the data handle
1.191 harris41 11145:
11146: =item *
11147:
1.243 albertel 11148: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 11149: a possible symb for the URL in $thisfn, and if is an encryypted
11150: resource that the user accessed using /enc/ returns a 1 on success, 0
11151: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 11152: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 11153:
1.191 harris41 11154:
11155: =item *
11156:
1.243 albertel 11157: symbclean($symb) : removes versions numbers from a symb, returns the
11158: cleaned symb
1.191 harris41 11159:
11160: =item *
11161:
1.243 albertel 11162: is_on_map($uri) : checks if the $uri is somewhere on the current
11163: course map, user must be in a course for it to work.
1.191 harris41 11164:
11165: =item *
11166:
1.243 albertel 11167: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 11168:
11169: =item *
11170:
1.243 albertel 11171: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11172: a random seed, all arguments are optional, if they aren't sent it uses the
11173: environment to derive them. Note: if symb isn't sent and it can't get one
11174: from &symbread it will use the current time as its return value
1.191 harris41 11175:
11176: =item *
11177:
1.243 albertel 11178: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11179: unfakeable, receipt
1.191 harris41 11180:
11181: =item *
11182:
1.620 albertel 11183: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 11184:
11185: =item *
11186:
1.243 albertel 11187: countacc($url) : count the number of accesses to a given URL
1.191 harris41 11188:
11189: =item *
11190:
1.243 albertel 11191: 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
1.191 harris41 11192:
11193: =item *
11194:
1.243 albertel 11195: 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)
1.191 harris41 11196:
11197: =item *
11198:
1.243 albertel 11199: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 11200:
11201: =item *
11202:
1.243 albertel 11203: devalidate($symb) : devalidate temporary spreadsheet calculations,
11204: forcing spreadsheet to reevaluate the resource scores next time.
11205:
11206: =back
11207:
11208: =head2 Storing/Retreiving Data
11209:
11210: =over 4
1.191 harris41 11211:
11212: =item *
11213:
1.243 albertel 11214: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11215: for this url; hashref needs to be given and should be a \%hashname; the
11216: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 11217: be derived from the env
1.191 harris41 11218:
11219: =item *
11220:
1.243 albertel 11221: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11222: uses critical subroutine
1.191 harris41 11223:
11224: =item *
11225:
1.243 albertel 11226: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11227: all args are optional
1.191 harris41 11228:
11229: =item *
11230:
1.717 albertel 11231: dumpstore($namespace,$udom,$uname,$regexp,$range) :
11232: dumps the complete (or key matching regexp) namespace into a hash
11233: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11234: normally &store()ed into
11235:
11236: $range should be either an integer '100' (give me the first 100
11237: matching records)
11238: or be two integers sperated by a - with no spaces
11239: '30-50' (give me the 30th through the 50th matching
11240: records)
11241:
11242:
11243: =item *
11244:
11245: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11246: replaces a &store() version of data with a replacement set of data
11247: for a particular resource in a namespace passed in the $storehash hash
11248: reference
11249:
11250: =item *
11251:
1.243 albertel 11252: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11253: works very similar to store/cstore, but all data is stored in a
11254: temporary location and can be reset using tmpreset, $storehash should
11255: be a hash reference, returns nothing on success
1.191 harris41 11256:
11257: =item *
11258:
1.243 albertel 11259: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11260: similar to restore, but all data is stored in a temporary location and
11261: can be reset using tmpreset. Returns a hash of values on success,
11262: error string otherwise.
1.191 harris41 11263:
11264: =item *
11265:
1.243 albertel 11266: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11267: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 11268:
11269: =item *
11270:
1.243 albertel 11271: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11272: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 11273:
11274: =item *
11275:
1.243 albertel 11276: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11277: namesp ($udom and $uname are optional)
1.191 harris41 11278:
11279: =item *
11280:
1.702 albertel 11281: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 11282: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 11283: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 11284:
1.702 albertel 11285: $range should be either an integer '100' (give me the first 100
11286: matching records)
11287: or be two integers sperated by a - with no spaces
11288: '30-50' (give me the 30th through the 50th matching
11289: records)
1.449 matthew 11290: =item *
11291:
11292: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11293: $store can be a scalar, an array reference, or if the amount to be
11294: incremented is > 1, a hash reference.
11295:
11296: ($udom and $uname are optional)
1.191 harris41 11297:
11298: =item *
11299:
1.243 albertel 11300: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11301: ($udom and $uname are optional)
1.191 harris41 11302:
11303: =item *
11304:
1.243 albertel 11305: cput($namespace,$storehash,$udom,$uname) : critical put
11306: ($udom and $uname are optional)
1.191 harris41 11307:
11308: =item *
11309:
1.748 albertel 11310: newput($namespace,$storehash,$udom,$uname) :
11311:
11312: Attempts to store the items in the $storehash, but only if they don't
11313: currently exist, if this succeeds you can be certain that you have
11314: successfully created a new key value pair in the $namespace db.
11315:
11316:
11317: Args:
11318: $namespace: name of database to store values to
11319: $storehash: hashref to store to the db
11320: $udom: (optional) domain of user containing the db
11321: $uname: (optional) name of user caontaining the db
11322:
11323: Returns:
11324: 'ok' -> succeeded in storing all keys of $storehash
11325: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11326: least <key> already existed in the db (other
11327: requested keys may also already exist)
1.967 bisitz 11328: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 11329: 'con_lost' -> unable to contact request server
11330: 'refused' -> action was not allowed by remote machine
11331:
11332:
11333: =item *
11334:
1.243 albertel 11335: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11336: reference filled in from namesp (encrypts the return communication)
11337: ($udom and $uname are optional)
1.191 harris41 11338:
11339: =item *
11340:
1.243 albertel 11341: log($udom,$name,$home,$message) : write to permanent log for user; use
11342: critical subroutine
11343:
1.806 raeburn 11344: =item *
11345:
1.860 raeburn 11346: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11347: array reference filled in from namespace found in domain level on either
11348: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 11349:
11350: =item *
11351:
1.860 raeburn 11352: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11353: domain level either on specified domain server ($uhome) or primary domain
11354: server ($udom and $uhome are optional)
1.806 raeburn 11355:
1.943 raeburn 11356: =item *
11357:
11358: get_domain_defaults($target_domain) : returns hash with defaults for
11359: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11360: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11361: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11362: Values are retrieved from cache (if current), or from domain's configuration.db
11363: (if available), or lastly from values in lonTabs/dns_domain,tab,
11364: or lonTabs/domain.tab.
11365:
11366: %domdefaults = &get_auth_defaults($target_domain);
11367:
1.243 albertel 11368: =back
11369:
11370: =head2 Network Status Functions
11371:
11372: =over 4
1.191 harris41 11373:
11374: =item *
11375:
11376: dirlist($uri) : return directory list based on URI
11377:
11378: =item *
11379:
1.243 albertel 11380: spareserver() : find server with least workload from spare.tab
11381:
1.986 foxr 11382:
11383: =item *
11384:
11385: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11386: if there is no corresponding loncapa host.
11387:
1.243 albertel 11388: =back
11389:
1.986 foxr 11390:
1.243 albertel 11391: =head2 Apache Request
11392:
11393: =over 4
1.191 harris41 11394:
11395: =item *
11396:
1.243 albertel 11397: ssi($url,%hash) : server side include, does a complete request cycle on url to
11398: localhost, posts hash
11399:
11400: =back
11401:
11402: =head2 Data to String to Data
11403:
11404: =over 4
1.191 harris41 11405:
11406: =item *
11407:
1.243 albertel 11408: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11409: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 11410:
11411: =item *
11412:
1.243 albertel 11413: hashref2str($hashref) : convert a hashref into a string complete with
11414: escaping and '=' and '&' separators, supports elements that are
11415: arrayrefs and hashrefs
1.191 harris41 11416:
11417: =item *
11418:
1.243 albertel 11419: arrayref2str($arrayref) : convert an arrayref into a string complete
11420: with escaping and '&' separators, supports elements that are arrayrefs
11421: and hashrefs
1.191 harris41 11422:
11423: =item *
11424:
1.243 albertel 11425: str2hash($string) : convert string to hash using unescaping and
11426: splitting on '=' and '&', supports elements that are arrayrefs and
11427: hashrefs
1.191 harris41 11428:
11429: =item *
11430:
1.243 albertel 11431: str2array($string) : convert string to hash using unescaping and
11432: splitting on '&', supports elements that are arrayrefs and hashrefs
11433:
11434: =back
11435:
11436: =head2 Logging Routines
11437:
11438: =over 4
11439:
11440: These routines allow one to make log messages in the lonnet.log and
11441: lonnet.perm logfiles.
1.191 harris41 11442:
11443: =item *
11444:
1.243 albertel 11445: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 11446:
11447: =item *
11448:
1.243 albertel 11449: logthis() : append message to the normal lonnet.log file, it gets
11450: preiodically rolled over and deleted.
1.191 harris41 11451:
11452: =item *
11453:
1.243 albertel 11454: logperm() : append a permanent message to lonnet.perm.log, this log
11455: file never gets deleted by any automated portion of the system, only
11456: messages of critical importance should go in here.
11457:
11458: =back
11459:
11460: =head2 General File Helper Routines
11461:
11462: =over 4
1.191 harris41 11463:
11464: =item *
11465:
1.481 raeburn 11466: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
11467: (a) files in /uploaded
11468: (i) If a local copy of the file exists -
11469: compares modification date of local copy with last-modified date for
11470: definitive version stored on home server for course. If local copy is
11471: stale, requests a new version from the home server and stores it.
11472: If the original has been removed from the home server, then local copy
11473: is unlinked.
11474: (ii) If local copy does not exist -
11475: requests the file from the home server and stores it.
11476:
11477: If $caller is 'uploadrep':
11478: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
11479: for request for files originally uploaded via DOCS.
11480: - returns 'ok' if fresh local copy now available, -1 otherwise.
11481:
11482: Otherwise:
11483: This indicates a call from the content generation phase of the request.
11484: - returns the entire contents of the file or -1.
11485:
11486: (b) files in /res
11487: - returns the entire contents of a file or -1;
11488: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 11489:
1.712 albertel 11490:
11491: =item *
11492:
11493: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
11494: reference
11495:
11496: returns either a stat() list of data about the file or an empty list
11497: if the file doesn't exist or couldn't find out about it (connection
11498: problems or user unknown)
11499:
1.191 harris41 11500: =item *
11501:
1.243 albertel 11502: filelocation($dir,$file) : returns file system location of a file
11503: based on URI; meant to be "fairly clean" absolute reference, $dir is a
11504: directory that relative $file lookups are to looked in ($dir of /a/dir
11505: and a file of ../bob will become /a/bob)
1.191 harris41 11506:
11507: =item *
11508:
11509: hreflocation($dir,$file) : returns file system location or a URL; same as
11510: filelocation except for hrefs
11511:
11512: =item *
11513:
11514: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
11515:
1.243 albertel 11516: =back
11517:
1.608 albertel 11518: =head2 Usererfile file routines (/uploaded*)
11519:
11520: =over 4
11521:
11522: =item *
11523:
11524: userfileupload(): main rotine for putting a file in a user or course's
11525: filespace, arguments are,
11526:
1.620 albertel 11527: formname - required - this is the name of the element in $env where the
1.608 albertel 11528: filename, and the contents of the file to create/modifed exist
1.620 albertel 11529: the filename is in $env{'form.'.$formname.'.filename'} and the
11530: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 11531: context - if coursedoc, store the file in the course of the active role
11532: of the current user;
11533: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
11534: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 11535: subdir - required - subdirectory to put the file in under ../userfiles/
11536: if undefined, it will be placed in "unknown"
11537:
11538: (This routine calls clean_filename() to remove any dangerous
11539: characters from the filename, and then calls finuserfileupload() to
11540: complete the transaction)
11541:
11542: returns either the url of the uploaded file (/uploaded/....) if successful
11543: and /adm/notfound.html if unsuccessful
11544:
11545: =item *
11546:
11547: clean_filename(): routine for cleaing a filename up for storage in
11548: userfile space, argument is:
11549:
11550: filename - proposed filename
11551:
11552: returns: the new clean filename
11553:
11554: =item *
11555:
1.1090 raeburn 11556: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 11557: userspace, probably shouldn't be called directly
11558:
11559: docuname: username or courseid of destination for the file
11560: docudom: domain of user/course of destination for the file
11561: formname: same as for userfileupload()
1.1090 raeburn 11562: fname: filename (including subdirectories) for the file
11563: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
11564: allfiles: reference to hash used to store objects found by parser
11565: codebase: reference to hash used for codebases of java objects found by parser
11566: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
11567: thumbheight: height (pixels) of thumbnail to be created for uploaded image
11568: resizewidth: width to be used to resize image using resizeImage from ImageMagick
11569: resizeheight: height to be used to resize image using resizeImage from ImageMagick
11570: context: if 'overwrite', will move the uploaded file from its temporary location to
11571: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 11572: mimetype: reference to scalar to accommodate mime type determined
11573: from File::MMagic if $parser = parse.
1.608 albertel 11574:
11575: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 11576: and /adm/notfound.html if unsuccessful (or an error message if context
11577: was 'overwrite').
11578:
1.608 albertel 11579:
11580: =item *
11581:
11582: renameuserfile(): renames an existing userfile to a new name
11583:
11584: Args:
11585: docuname: username or courseid of destination for the file
11586: docudom: domain of user/course of destination for the file
11587: old: current file name (including any subdirs under userfiles)
11588: new: desired file name (including any subdirs under userfiles)
11589:
11590: =item *
11591:
11592: mkdiruserfile(): creates a directory is a userfiles dir
11593:
11594: Args:
11595: docuname: username or courseid of destination for the file
11596: docudom: domain of user/course of destination for the file
11597: dir: dir to create (including any subdirs under userfiles)
11598:
11599: =item *
11600:
11601: removeuserfile(): removes a file that exists in userfiles
11602:
11603: Args:
11604: docuname: username or courseid of destination for the file
11605: docudom: domain of user/course of destination for the file
11606: fname: filname to delete (including any subdirs under userfiles)
11607:
11608: =item *
11609:
11610: removeuploadedurl(): convience function for removeuserfile()
11611:
11612: Args:
11613: url: a full /uploaded/... url to delete
11614:
1.747 albertel 11615: =item *
11616:
11617: get_portfile_permissions():
11618: Args:
11619: domain: domain of user or course contain the portfolio files
11620: user: name of user or num of course contain the portfolio files
11621: Returns:
11622: hashref of a dump of the proper file_permissions.db
11623:
11624:
11625: =item *
11626:
11627: get_access_controls():
11628:
11629: Args:
11630: current_permissions: the hash ref returned from get_portfile_permissions()
11631: group: (optional) the group you want the files associated with
11632: file: (optional) the file you want access info on
11633:
11634: Returns:
1.749 raeburn 11635: a hash (keys are file names) of hashes containing
11636: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
11637: values are XML containing access control settings (see below)
1.747 albertel 11638:
11639: Internal notes:
11640:
1.749 raeburn 11641: access controls are stored in file_permissions.db as key=value pairs.
11642: key -> path to file/file_name\0uniqueID:scope_end_start
11643: where scope -> public,guest,course,group,domains or users.
11644: end -> UNIX time for end of access (0 -> no end date)
11645: start -> UNIX time for start of access
11646:
11647: value -> XML description of access control
11648: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
11649: <start></start>
11650: <end></end>
11651:
11652: <password></password> for scope type = guest
11653:
11654: <domain></domain> for scope type = course or group
11655: <number></number>
11656: <roles id="">
11657: <role></role>
11658: <access></access>
11659: <section></section>
11660: <group></group>
11661: </roles>
11662:
11663: <dom></dom> for scope type = domains
11664:
11665: <users> for scope type = users
11666: <user>
11667: <uname></uname>
11668: <udom></udom>
11669: </user>
11670: </users>
11671: </scope>
11672:
11673: Access data is also aggregated for each file in an additional key=value pair:
11674: key -> path to file/file_name\0accesscontrol
11675: value -> reference to hash
11676: hash contains key = value pairs
11677: where key = uniqueID:scope_end_start
11678: value = UNIX time record was last updated
11679:
11680: Used to improve speed of look-ups of access controls for each file.
11681:
11682: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11683:
11684: modify_access_controls():
11685:
11686: Modifies access controls for a portfolio file
11687: Args
11688: 1. file name
11689: 2. reference to hash of required changes,
11690: 3. domain
11691: 4. username
11692: where domain,username are the domain of the portfolio owner
11693: (either a user or a course)
11694:
11695: Returns:
11696: 1. result of additions or updates ('ok' or 'error', with error message).
11697: 2. result of deletions ('ok' or 'error', with error message).
11698: 3. reference to hash of any new or updated access controls.
11699: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11700: key = integer (inbound ID)
11701: value = uniqueID
1.747 albertel 11702:
1.608 albertel 11703: =back
11704:
1.243 albertel 11705: =head2 HTTP Helper Routines
11706:
11707: =over 4
11708:
1.191 harris41 11709: =item *
11710:
11711: escape() : unpack non-word characters into CGI-compatible hex codes
11712:
11713: =item *
11714:
11715: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11716:
1.243 albertel 11717: =back
11718:
11719: =head1 PRIVATE SUBROUTINES
11720:
11721: =head2 Underlying communication routines (Shouldn't call)
11722:
11723: =over 4
11724:
11725: =item *
11726:
11727: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11728:
11729: =item *
11730:
11731: reply() : uses subreply to send a message to remote machine, logs all failures
11732:
11733: =item *
11734:
11735: critical() : passes a critical message to another server; if cannot
11736: get through then place message in connection buffer directory and
11737: returns con_delayed, if incapable of saving message, returns
11738: con_failed
11739:
11740: =item *
11741:
11742: reconlonc() : tries to reconnect lonc client processes.
11743:
11744: =back
11745:
11746: =head2 Resource Access Logging
11747:
11748: =over 4
11749:
11750: =item *
11751:
11752: flushcourselogs() : flush (save) buffer logs and access logs
11753:
11754: =item *
11755:
11756: courselog($what) : save message for course in hash
11757:
11758: =item *
11759:
11760: courseacclog($what) : save message for course using &courselog(). Perform
11761: special processing for specific resource types (problems, exams, quizzes, etc).
11762:
1.191 harris41 11763: =item *
11764:
11765: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11766: as a PerlChildExitHandler
1.243 albertel 11767:
11768: =back
11769:
11770: =head2 Other
11771:
11772: =over 4
11773:
11774: =item *
11775:
11776: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 11777:
11778: =back
11779:
11780: =cut
1.877 foxr 11781:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>